From 0d048b8704c0709506d3d14a26d540a4b8eb470e Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 01:08:51 -0500 Subject: Init Original: https://github.com/denoland/deno_std/commit/60735e18043b54f51cf794ebe152459d5e066e6d --- http.ts | 42 ++++++++++++++++++++++++++++++++++++++++++ http_test.ts | 4 ++++ 2 files changed, 46 insertions(+) create mode 100644 http.ts create mode 100644 http_test.ts diff --git a/http.ts b/http.ts new file mode 100644 index 000000000..d4c496e15 --- /dev/null +++ b/http.ts @@ -0,0 +1,42 @@ +import * as deno from "deno"; + +class Server { + _closing = false; + + constructor(readonly listener: deno.Listener) {} + + async serveConn(conn: deno.Conn) { + const buffer = new Uint8Array(1024); + try { + while (true) { + const r = await conn.read(buffer); + if (r.eof) { + break; + } + const response = new TextEncoder().encode( + "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" + ); + await conn.write(response); + } + } finally { + conn.close(); + } + } + + async serve() { + while (!this._closing) { + const conn = await this.listener.accept(); + this.serveConn(conn); + } + } + + close() { + this._closing = true; + } +} + +export function listen(addr: string): Server { + const listener = deno.listen("tcp", addr); + const s = new Server(listener); + return s; +} diff --git a/http_test.ts b/http_test.ts new file mode 100644 index 000000000..32c868ad5 --- /dev/null +++ b/http_test.ts @@ -0,0 +1,4 @@ +import { listen } from "./server.ts"; + +const s = listen("0.0.0.0:4500"); +s.serve(); -- cgit v1.2.3 From abe47d10c97f5cff671d3565a5a985c2ef203d4d Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 10:18:48 -0500 Subject: Fix test Original: https://github.com/denoland/deno_std/commit/52ff748cfbc5f23b267dc5901c96508aee02d199 --- http_test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/http_test.ts b/http_test.ts index 32c868ad5..6fbac9a4a 100644 --- a/http_test.ts +++ b/http_test.ts @@ -1,4 +1,6 @@ -import { listen } from "./server.ts"; +//import { listen } from "./server.ts"; +import { test } from "http://deno.land/x/testing/testing.ts"; -const s = listen("0.0.0.0:4500"); -s.serve(); +test(function basic() { + console.log("ok"); +}); -- cgit v1.2.3 From 8610e3578c923be2b7d758e75ea370801abf8574 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 13:16:07 -0500 Subject: First pass at bufio. Original: https://github.com/denoland/deno_std/commit/c5cc6959705c310f4f7a864d77aae54171707c04 --- buffer.ts | 229 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ buffer_test.ts | 185 ++++++++++++++++++++++++++++++++++++++++++++++ bufio.ts | 92 +++++++++++++++++++++++ bufio_test.ts | 32 ++++++++ file_server.ts | 18 +++++ http.ts | 62 ++++++++++++---- util.ts | 6 ++ 7 files changed, 608 insertions(+), 16 deletions(-) create mode 100644 buffer.ts create mode 100644 buffer_test.ts create mode 100644 bufio.ts create mode 100644 bufio_test.ts create mode 100644 file_server.ts create mode 100644 util.ts diff --git a/buffer.ts b/buffer.ts new file mode 100644 index 000000000..1c4d68e98 --- /dev/null +++ b/buffer.ts @@ -0,0 +1,229 @@ +// This code has been ported almost directly from Go's src/bytes/buffer.go +// Copyright 2009 The Go Authors. All rights reserved. BSD license. +// https://github.com/golang/go/blob/master/LICENSE + +//import * as io from "./io"; +import { Reader, Writer, ReadResult } from "deno"; +import { assert } from "./util.ts"; + +// MIN_READ is the minimum ArrayBuffer size passed to a read call by +// buffer.ReadFrom. As long as the Buffer has at least MIN_READ bytes beyond +// what is required to hold the contents of r, readFrom() will not grow the +// underlying buffer. +const MIN_READ = 512; +const MAX_SIZE = 2 ** 32 - 2; + +// `off` is the offset into `dst` where it will at which to begin writing values +// from `src`. +// Returns the number of bytes copied. +function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number { + const r = dst.byteLength - off; + if (src.byteLength > r) { + src = src.subarray(0, r); + } + dst.set(src, off); + return src.byteLength; +} + +/** A Buffer is a variable-sized buffer of bytes with read() and write() + * methods. Based on https://golang.org/pkg/bytes/#Buffer + */ +export class Buffer implements Reader, Writer { + private buf: Uint8Array; // contents are the bytes buf[off : len(buf)] + private off = 0; // read at buf[off], write at buf[buf.byteLength] + + constructor(ab?: ArrayBuffer) { + if (ab == null) { + this.buf = new Uint8Array(0); + } else { + this.buf = new Uint8Array(ab); + } + } + + /** bytes() returns a slice holding the unread portion of the buffer. + * The slice is valid for use only until the next buffer modification (that + * is, only until the next call to a method like read(), write(), reset(), or + * truncate()). The slice aliases the buffer content at least until the next + * buffer modification, so immediate changes to the slice will affect the + * result of future reads. + */ + bytes(): Uint8Array { + return this.buf.subarray(this.off); + } + + /** toString() returns the contents of the unread portion of the buffer + * as a string. Warning - if multibyte characters are present when data is + * flowing through the buffer, this method may result in incorrect strings + * due to a character being split. + */ + toString(): string { + const decoder = new TextDecoder(); + return decoder.decode(this.buf.subarray(this.off)); + } + + /** empty() returns whether the unread portion of the buffer is empty. */ + empty() { + return this.buf.byteLength <= this.off; + } + + /** length is a getter that returns the number of bytes of the unread + * portion of the buffer + */ + get length() { + return this.buf.byteLength - this.off; + } + + /** Returns the capacity of the buffer's underlying byte slice, that is, + * the total space allocated for the buffer's data. + */ + get capacity(): number { + return this.buf.buffer.byteLength; + } + + /** truncate() discards all but the first n unread bytes from the buffer but + * continues to use the same allocated storage. It throws if n is negative or + * greater than the length of the buffer. + */ + truncate(n: number): void { + if (n === 0) { + this.reset(); + return; + } + if (n < 0 || n > this.length) { + throw Error("bytes.Buffer: truncation out of range"); + } + this._reslice(this.off + n); + } + + /** reset() resets the buffer to be empty, but it retains the underlying + * storage for use by future writes. reset() is the same as truncate(0) + */ + reset(): void { + this._reslice(0); + this.off = 0; + } + + /** _tryGrowByReslice() is a version of grow for the fast-case + * where the internal buffer only needs to be resliced. It returns the index + * where bytes should be written and whether it succeeded. + * It returns -1 if a reslice was not needed. + */ + private _tryGrowByReslice(n: number): number { + const l = this.buf.byteLength; + if (n <= this.capacity - l) { + this._reslice(l + n); + return l; + } + return -1; + } + + private _reslice(len: number): void { + assert(len <= this.buf.buffer.byteLength); + this.buf = new Uint8Array(this.buf.buffer, 0, len); + } + + /** read() reads the next len(p) bytes from the buffer or until the buffer + * is drained. The return value n is the number of bytes read. If the + * buffer has no data to return, eof in the response will be true. + */ + async read(p: ArrayBufferView): Promise { + if (!(p instanceof Uint8Array)) { + throw Error("Only Uint8Array supported"); + } + if (this.empty()) { + // Buffer is empty, reset to recover space. + this.reset(); + if (p.byteLength === 0) { + // TODO This edge case should be tested by porting TestReadEmptyAtEOF + // from the Go tests. + return { nread: 0, eof: false }; + } + return { nread: 0, eof: true }; + } + const nread = copyBytes(p, this.buf.subarray(this.off)); + this.off += nread; + return { nread, eof: false }; + } + + async write(p: ArrayBufferView): Promise { + const m = this._grow(p.byteLength); + if (!(p instanceof Uint8Array)) { + throw Error("Only Uint8Array supported"); + } + return copyBytes(this.buf, p, m); + } + + /** _grow() grows the buffer to guarantee space for n more bytes. + * It returns the index where bytes should be written. + * If the buffer can't grow it will throw with ErrTooLarge. + */ + private _grow(n: number): number { + const m = this.length; + // If buffer is empty, reset to recover space. + if (m === 0 && this.off !== 0) { + this.reset(); + } + // Fast: Try to grow by means of a reslice. + const i = this._tryGrowByReslice(n); + if (i >= 0) { + return i; + } + const c = this.capacity; + if (n <= Math.floor(c / 2) - m) { + // We can slide things down instead of allocating a new + // ArrayBuffer. We only need m+n <= c to slide, but + // we instead let capacity get twice as large so we + // don't spend all our time copying. + copyBytes(this.buf, this.buf.subarray(this.off)); + } else if (c > MAX_SIZE - c - n) { + throw Error("ErrTooLarge"); // TODO DenoError(TooLarge) + } else { + // Not enough space anywhere, we need to allocate. + const buf = new Uint8Array(2 * c + n); + copyBytes(buf, this.buf.subarray(this.off)); + this.buf = buf; + } + // Restore this.off and len(this.buf). + this.off = 0; + this._reslice(m + n); + return m; + } + + /** grow() grows the buffer's capacity, if necessary, to guarantee space for + * another n bytes. After grow(n), at least n bytes can be written to the + * buffer without another allocation. If n is negative, grow() will panic. If + * the buffer can't grow it will throw ErrTooLarge. + * Based on https://golang.org/pkg/bytes/#Buffer.Grow + */ + grow(n: number): void { + if (n < 0) { + throw Error("Buffer.grow: negative count"); + } + const m = this._grow(n); + this._reslice(m); + } + + /** readFrom() reads data from r until EOF and appends it to the buffer, + * growing the buffer as needed. It returns the number of bytes read. If the + * buffer becomes too large, readFrom will panic with ErrTooLarge. + * Based on https://golang.org/pkg/bytes/#Buffer.ReadFrom + */ + async readFrom(r: Reader): Promise { + let n = 0; + while (true) { + try { + const i = this._grow(MIN_READ); + this._reslice(i); + const fub = new Uint8Array(this.buf.buffer, i); + const { nread, eof } = await r.read(fub); + this._reslice(i + nread); + n += nread; + if (eof) { + return n; + } + } catch (e) { + return n; + } + } + } +} diff --git a/buffer_test.ts b/buffer_test.ts new file mode 100644 index 000000000..c614b2e03 --- /dev/null +++ b/buffer_test.ts @@ -0,0 +1,185 @@ +// This code has been ported almost directly from Go's src/bytes/buffer_test.go +// Copyright 2009 The Go Authors. All rights reserved. BSD license. +// https://github.com/golang/go/blob/master/LICENSE +import { test, assert, assertEqual } from "./test_util.ts"; +import { Buffer } from "deno"; + +// N controls how many iterations of certain checks are performed. +const N = 100; +let testBytes: Uint8Array | null; +let testString: string | null; + +function init() { + if (testBytes == null) { + testBytes = new Uint8Array(N); + for (let i = 0; i < N; i++) { + testBytes[i] = "a".charCodeAt(0) + (i % 26); + } + const decoder = new TextDecoder(); + testString = decoder.decode(testBytes); + } +} + +function check(buf: Buffer, s: string) { + const bytes = buf.bytes(); + assertEqual(buf.length, bytes.byteLength); + const decoder = new TextDecoder(); + const bytesStr = decoder.decode(bytes); + assertEqual(bytesStr, s); + assertEqual(buf.length, buf.toString().length); + assertEqual(buf.length, s.length); +} + +// Fill buf through n writes of byte slice fub. +// The initial contents of buf corresponds to the string s; +// the result is the final contents of buf returned as a string. +async function fillBytes( + buf: Buffer, + s: string, + n: number, + fub: Uint8Array +): Promise { + check(buf, s); + for (; n > 0; n--) { + let m = await buf.write(fub); + assertEqual(m, fub.byteLength); + const decoder = new TextDecoder(); + s += decoder.decode(fub); + check(buf, s); + } + return s; +} + +// Empty buf through repeated reads into fub. +// The initial contents of buf corresponds to the string s. +async function empty(buf: Buffer, s: string, fub: Uint8Array): Promise { + check(buf, s); + while (true) { + const r = await buf.read(fub); + if (r.nread == 0) { + break; + } + s = s.slice(r.nread); + check(buf, s); + } + check(buf, ""); +} + +test(function bufferNewBuffer() { + init(); + const buf = new Buffer(testBytes.buffer as ArrayBuffer); + check(buf, testString); +}); + +test(async function bufferBasicOperations() { + init(); + let buf = new Buffer(); + for (let i = 0; i < 5; i++) { + check(buf, ""); + + buf.reset(); + check(buf, ""); + + buf.truncate(0); + check(buf, ""); + + let n = await buf.write(testBytes.subarray(0, 1)); + assertEqual(n, 1); + check(buf, "a"); + + n = await buf.write(testBytes.subarray(1, 2)); + assertEqual(n, 1); + check(buf, "ab"); + + n = await buf.write(testBytes.subarray(2, 26)); + assertEqual(n, 24); + check(buf, testString.slice(0, 26)); + + buf.truncate(26); + check(buf, testString.slice(0, 26)); + + buf.truncate(20); + check(buf, testString.slice(0, 20)); + + await empty(buf, testString.slice(0, 20), new Uint8Array(5)); + await empty(buf, "", new Uint8Array(100)); + + // TODO buf.writeByte() + // TODO buf.readByte() + } +}); + +test(async function bufferLargeByteWrites() { + init(); + const buf = new Buffer(); + const limit = 9; + for (let i = 3; i < limit; i += 3) { + const s = await fillBytes(buf, "", 5, testBytes); + await empty(buf, s, new Uint8Array(Math.floor(testString.length / i))); + } + check(buf, ""); +}); + +test(async function bufferLargeByteReads() { + init(); + const buf = new Buffer(); + for (let i = 3; i < 30; i += 3) { + const n = Math.floor(testBytes.byteLength / i); + const s = await fillBytes(buf, "", 5, testBytes.subarray(0, n)); + await empty(buf, s, new Uint8Array(testString.length)); + } + check(buf, ""); +}); + +test(function bufferCapWithPreallocatedSlice() { + const buf = new Buffer(new ArrayBuffer(10)); + assertEqual(buf.capacity, 10); +}); + +test(async function bufferReadFrom() { + init(); + const buf = new Buffer(); + for (let i = 3; i < 30; i += 3) { + const s = await fillBytes( + buf, + "", + 5, + testBytes.subarray(0, Math.floor(testBytes.byteLength / i)) + ); + const b = new Buffer(); + await b.readFrom(buf); + const fub = new Uint8Array(testString.length); + await empty(b, s, fub); + } +}); + +function repeat(c: string, bytes: number): Uint8Array { + assertEqual(c.length, 1); + const ui8 = new Uint8Array(bytes); + ui8.fill(c.charCodeAt(0)); + return ui8; +} + +test(async function bufferTestGrow() { + const tmp = new Uint8Array(72); + for (let startLen of [0, 100, 1000, 10000, 100000]) { + const xBytes = repeat("x", startLen); + for (let growLen of [0, 100, 1000, 10000, 100000]) { + const buf = new Buffer(xBytes.buffer as ArrayBuffer); + // If we read, this affects buf.off, which is good to test. + const { nread, eof } = await buf.read(tmp); + buf.grow(growLen); + const yBytes = repeat("y", growLen); + await buf.write(yBytes); + // Check that buffer has correct data. + assertEqual( + buf.bytes().subarray(0, startLen - nread), + xBytes.subarray(nread) + ); + assertEqual( + buf.bytes().subarray(startLen - nread, startLen - nread + growLen), + yBytes + ); + } + } +}); diff --git a/bufio.ts b/bufio.ts new file mode 100644 index 000000000..dc1a2095d --- /dev/null +++ b/bufio.ts @@ -0,0 +1,92 @@ +import * as deno from "deno"; + +const DEFAULT_BUF_SIZE = 4096; +const MIN_BUF_SIZE = 16; +const MAX_CONSECUTIVE_EMPTY_READS = 100; + +export class Reader implements deno.Reader { + private buf: Uint8Array; + private rd: deno.Reader; // Reader provided by caller. + private r = 0; // buf read position. + private w = 0; // buf write position. + private lastByte: number; + private lastCharSize: number; + + constructor(rd: deno.Reader, size = DEFAULT_BUF_SIZE) { + if (size < MIN_BUF_SIZE) { + size = MIN_BUF_SIZE; + } + this._reset(new Uint8Array(size), rd) + } + + /** Returns the size of the underlying buffer in bytes. */ + get byteLength(): number { + return this.buf.byteLength; + } + + // Reads a new chunk into the buffer. + // Returns true if EOF, false on successful read. + async _fill(): Promise { + // Slide existing data to beginning. + if (this.r > 0) { + this.buf.copyWithin(0, this.r, this.w); + this.w -= this.r; + this.r = 0; + } + + if (this.w >= this.buf.byteLength) { + throw Error("bufio: tried to fill full buffer"); + } + + // Read new data: try a limited number of times. + for (let i = MAX_CONSECUTIVE_EMPTY_READS; i > 0; i--) { + const { nread, eof } = await this.rd.read(this.buf.subarray(this.w)); + if (nread < 0) { + throw Error("negative read"); + } + this.w += nread; + if (eof) { + return true; + } + if (nread > 0) { + return false; + } + } + throw Error("No Progress"); + } + + /** Discards any buffered data, resets all state, and switches + * the buffered reader to read from r. + */ + reset(r: deno.Reader): void { + this._reset(this.buf, r); + } + + private _reset(buf: Uint8Array, rd: deno.Reader): void { + this.buf = buf; + this.rd = rd; + this.lastByte = -1; + this.lastCharSize = -1; + } + + async read(p: ArrayBufferView): Promise { + throw Error("not implemented"); + return { nread: 0, eof: false }; + } + + /** Returns the next byte [0, 255] or -1 if EOF. */ + async readByte(): Promise { + while (this.r === this.w) { + const eof = await this._fill(); // buffer is empty. + if (eof) { + return -1; + } + } + const c = this.buf[this.r]; + this.r++; + this.lastByte = c; + return c; + } +} + + diff --git a/bufio_test.ts b/bufio_test.ts new file mode 100644 index 000000000..a66052ba1 --- /dev/null +++ b/bufio_test.ts @@ -0,0 +1,32 @@ +import * as deno from "deno"; +import { test, assertEqual } from "http://deno.land/x/testing/testing.ts"; +import * as bufio from "./bufio.ts"; +import { Buffer } from "./buffer.ts"; + +async function readBytes(buf: bufio.Reader): Promise { + const b = new Uint8Array(1000); + let nb = 0; + while (true) { + let c = await buf.readByte(); + if (c < 0) { + break; // EOF + } + b[nb] = c; + nb++; + } + const decoder = new TextDecoder(); + return decoder.decode(b.subarray(0, nb)); +} + +function stringsReader(s: string): deno.Reader { + const encoder = new TextEncoder(); + const ui8 = encoder.encode(s); + return new Buffer(ui8.buffer as ArrayBuffer); +} + +test(async function bufioReaderSimple() { + const data = "hello world"; + const b = new bufio.Reader(stringsReader(data)); + const s = await readBytes(b); + assertEqual(s, data); +}); diff --git a/file_server.ts b/file_server.ts new file mode 100644 index 000000000..9d3d5366e --- /dev/null +++ b/file_server.ts @@ -0,0 +1,18 @@ +import { listenAndServe } from "./http.ts"; +import { open, cwd } from "deno"; + +const addr = "0.0.0.0:4500"; +const d = cwd(); + +listenAndServe(addr, async (req) => { + const filename = d + "/" + req.url; + let res; + try { + res = { status: 200, body: open(filename) }; + } catch(e) { + res = { status: 500, body: "bad" }; + } + req.respond(res); +}); + +console.log(`HTTP server listening on http://${addr}/`); diff --git a/http.ts b/http.ts index d4c496e15..c8b7d8d90 100644 --- a/http.ts +++ b/http.ts @@ -1,38 +1,67 @@ import * as deno from "deno"; +import * as bufio from "./bufio.ts"; +import { TextProtoReader } from "./textproto.ts"; + +type Handler = (req: ServerRequest) => Promise; class Server { _closing = false; constructor(readonly listener: deno.Listener) {} - async serveConn(conn: deno.Conn) { + async serve(handler: Handler) { + while (!this._closing) { + const c = await this.listener.accept(); + const sc = new ServerConn(c); + sc.serve(handler); + } + } + + close() { + this._closing = true; + this.listener.close(); + } +} + +class ServerConn { + constructor(readonly c: deno.Conn) { + // TODO Use memory pool to obtain bufr and bufw. + this.bufr = new bufio.Reader(c); + this.bufw = new bufio.Writer(c); + } + + async serve(handler: Handler): Promise { const buffer = new Uint8Array(1024); try { while (true) { - const r = await conn.read(buffer); - if (r.eof) { - break; - } + const req = readRequest(this.bufr); + + /* const response = new TextEncoder().encode( "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" ); - await conn.write(response); + await this.c.write(response); + */ } } finally { - conn.close(); + this.c.close(); } } +} - async serve() { - while (!this._closing) { - const conn = await this.listener.accept(); - this.serveConn(conn); - } - } +function readRequest(b: bufio.Reader): ServerRequest { + const tp = new TextProtoReader(b); + const req = new ServerRequest(); - close() { - this._closing = true; - } + // First line: GET /index.html HTTP/1.0 + const s = await tp.readLine(); + const [ method, url, proto ] = parseRequestLine(s); + console.log("readRequest", method, url); +} + +// Returns [method, url, proto] +function parseRequestLine(line: string): [ string, string, string ] { + return line.split(" ", 3); } export function listen(addr: string): Server { @@ -40,3 +69,4 @@ export function listen(addr: string): Server { const s = new Server(listener); return s; } + diff --git a/util.ts b/util.ts new file mode 100644 index 000000000..decf4d043 --- /dev/null +++ b/util.ts @@ -0,0 +1,6 @@ + +export function assert(cond: boolean, msg = "assert") { + if (!cond) { + throw Error(msg); + } +} -- cgit v1.2.3 From 280856f8d81c4b2e53fa8022aafae5a7c008747f Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 14:17:36 -0500 Subject: First pass at bufio.read tests. Original: https://github.com/denoland/deno_std/commit/1eb57aa3948caf88e9064defc15e076b8a46fbd2 --- buffer.ts | 14 +--------- buffer_test.ts | 10 +++++--- bufio.ts | 72 +++++++++++++++++++++++++++++++++++++++++++++++----- bufio_test.ts | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ file_server.ts | 4 +-- http.ts | 5 ++-- util.ts | 13 +++++++++- 7 files changed, 170 insertions(+), 28 deletions(-) diff --git a/buffer.ts b/buffer.ts index 1c4d68e98..a795bc842 100644 --- a/buffer.ts +++ b/buffer.ts @@ -4,7 +4,7 @@ //import * as io from "./io"; import { Reader, Writer, ReadResult } from "deno"; -import { assert } from "./util.ts"; +import { assert, copyBytes } from "./util.ts"; // MIN_READ is the minimum ArrayBuffer size passed to a read call by // buffer.ReadFrom. As long as the Buffer has at least MIN_READ bytes beyond @@ -13,18 +13,6 @@ import { assert } from "./util.ts"; const MIN_READ = 512; const MAX_SIZE = 2 ** 32 - 2; -// `off` is the offset into `dst` where it will at which to begin writing values -// from `src`. -// Returns the number of bytes copied. -function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number { - const r = dst.byteLength - off; - if (src.byteLength > r) { - src = src.subarray(0, r); - } - dst.set(src, off); - return src.byteLength; -} - /** A Buffer is a variable-sized buffer of bytes with read() and write() * methods. Based on https://golang.org/pkg/bytes/#Buffer */ diff --git a/buffer_test.ts b/buffer_test.ts index c614b2e03..8365b29bd 100644 --- a/buffer_test.ts +++ b/buffer_test.ts @@ -1,8 +1,12 @@ // This code has been ported almost directly from Go's src/bytes/buffer_test.go // Copyright 2009 The Go Authors. All rights reserved. BSD license. // https://github.com/golang/go/blob/master/LICENSE -import { test, assert, assertEqual } from "./test_util.ts"; -import { Buffer } from "deno"; +import { + test, + assert, + assertEqual +} from "http://deno.land/x/testing/testing.ts"; +import { Buffer } from "./buffer.ts"; // N controls how many iterations of certain checks are performed. const N = 100; @@ -13,7 +17,7 @@ function init() { if (testBytes == null) { testBytes = new Uint8Array(N); for (let i = 0; i < N; i++) { - testBytes[i] = "a".charCodeAt(0) + (i % 26); + testBytes[i] = "a".charCodeAt(0) + i % 26; } const decoder = new TextDecoder(); testString = decoder.decode(testBytes); diff --git a/bufio.ts b/bufio.ts index dc1a2095d..805a8136e 100644 --- a/bufio.ts +++ b/bufio.ts @@ -1,9 +1,22 @@ +// Ported to Deno from: +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + import * as deno from "deno"; +import { assert, copyBytes } from "./util.ts"; const DEFAULT_BUF_SIZE = 4096; const MIN_BUF_SIZE = 16; const MAX_CONSECUTIVE_EMPTY_READS = 100; +export class ErrNegativeRead extends Error { + constructor() { + super("bufio: reader returned negative count from Read"); + this.name = "ErrNegativeRead"; + } +} + export class Reader implements deno.Reader { private buf: Uint8Array; private rd: deno.Reader; // Reader provided by caller. @@ -16,7 +29,7 @@ export class Reader implements deno.Reader { if (size < MIN_BUF_SIZE) { size = MIN_BUF_SIZE; } - this._reset(new Uint8Array(size), rd) + this._reset(new Uint8Array(size), rd); } /** Returns the size of the underlying buffer in bytes. */ @@ -42,7 +55,7 @@ export class Reader implements deno.Reader { for (let i = MAX_CONSECUTIVE_EMPTY_READS; i > 0; i--) { const { nread, eof } = await this.rd.read(this.buf.subarray(this.w)); if (nread < 0) { - throw Error("negative read"); + throw new ErrNegativeRead(); } this.w += nread; if (eof) { @@ -69,9 +82,58 @@ export class Reader implements deno.Reader { this.lastCharSize = -1; } + /** reads data into p. + * It returns the number of bytes read into p. + * The bytes are taken from at most one Read on the underlying Reader, + * hence n may be less than len(p). + * At EOF, the count will be zero and err will be io.EOF. + * To read exactly len(p) bytes, use io.ReadFull(b, p). + */ async read(p: ArrayBufferView): Promise { - throw Error("not implemented"); - return { nread: 0, eof: false }; + let rr: deno.ReadResult = { nread: p.byteLength, eof: false }; + if (rr.nread === 0) { + return rr; + } + + if (this.r === this.w) { + /* + if (this.err != null) { + throw this.readErr(); + } + */ + if (p.byteLength >= this.buf.byteLength) { + // Large read, empty buffer. + // Read directly into p to avoid copy. + rr = await this.rd.read(p); + if (rr.nread < 0) { + throw new ErrNegativeRead(); + } + if (rr.nread > 0) { + this.lastByte = p[rr.nread - 1]; + // this.lastRuneSize = -1; + } + return rr; + } + // One read. + // Do not use this.fill, which will loop. + this.r = 0; + this.w = 0; + rr = await this.rd.read(this.buf); + if (rr.nread < 0) { + throw new ErrNegativeRead(); + } + if (rr.nread === 0) { + return rr; + } + this.w += rr.nread; + } + + // copy as much as we can + rr.nread = copyBytes(p as Uint8Array, this.buf.subarray(this.r, this.w), 0); + this.r += rr.nread; + this.lastByte = this.buf[this.r - 1]; + // this.lastRuneSize = -1; + return rr; } /** Returns the next byte [0, 255] or -1 if EOF. */ @@ -88,5 +150,3 @@ export class Reader implements deno.Reader { return c; } } - - diff --git a/bufio_test.ts b/bufio_test.ts index a66052ba1..1600852af 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -1,3 +1,8 @@ +// Ported to Deno from: +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + import * as deno from "deno"; import { test, assertEqual } from "http://deno.land/x/testing/testing.ts"; import * as bufio from "./bufio.ts"; @@ -30,3 +35,78 @@ test(async function bufioReaderSimple() { const s = await readBytes(b); assertEqual(s, data); }); + +type ReadMaker = { name: string; fn: (r: deno.Reader) => deno.Reader }; + +const readMakers: ReadMaker[] = [ + { name: "full", fn: r => r } + /* + { name: "byte", fn(r) => new iotest.OneByteReader(r) }, + { name: "half", fn(r) => new iotest.HalfReader(r) }, + { name: "data+err", r => new iotest.DataErrReader(r) }, + { name: "timeout", r => new iotest.TimeoutReader(r) }, + */ +]; + +// Call read to accumulate the text of a file +async function reads(buf: bufio.Reader, m: number): Promise { + const b = new Uint8Array(1000); + let nb = 0; + while (true) { + const { nread, eof } = await buf.read(b.subarray(nb, nb + m)); + nb += nread; + if (eof) { + break; + } + } + const decoder = new TextDecoder(); + return decoder.decode(b.subarray(0, nb)); +} + +type BufReader = { name: string; fn: (r: bufio.Reader) => Promise }; + +const bufreaders: BufReader[] = [ + { name: "1", fn: (b: bufio.Reader) => reads(b, 1) } +]; + +const MIN_READ_BUFFER_SIZE = 16; +const bufsizes: number[] = [ + 0, + MIN_READ_BUFFER_SIZE, + 23, + 32, + 46, + 64, + 93, + 128, + 1024, + 4096 +]; + +test(async function bufioReader() { + const texts = new Array(31); + let str = ""; + let all = ""; + for (let i = 0; i < texts.length - 1; i++) { + texts[i] = str + "\n"; + all += texts[i]; + str += String.fromCharCode(i % 26 + 97); + } + texts[texts.length - 1] = all; + + for (let text of texts) { + for (let readmaker of readMakers) { + for (let bufreader of bufreaders) { + for (let bufsize of bufsizes) { + const read = readmaker.fn(stringsReader(text)); + const buf = new bufio.Reader(read, bufsize); + const s = await bufreader.fn(buf); + const debugStr = + `reader=${readmaker.name} ` + + `fn=${bufreader.name} bufsize=${bufsize} want=${text} got=${s}`; + assertEqual(s, text, debugStr); + } + } + } + } +}); diff --git a/file_server.ts b/file_server.ts index 9d3d5366e..d5deccf3c 100644 --- a/file_server.ts +++ b/file_server.ts @@ -4,12 +4,12 @@ import { open, cwd } from "deno"; const addr = "0.0.0.0:4500"; const d = cwd(); -listenAndServe(addr, async (req) => { +listenAndServe(addr, async req => { const filename = d + "/" + req.url; let res; try { res = { status: 200, body: open(filename) }; - } catch(e) { + } catch (e) { res = { status: 500, body: "bad" }; } req.respond(res); diff --git a/http.ts b/http.ts index c8b7d8d90..4c209153a 100644 --- a/http.ts +++ b/http.ts @@ -55,12 +55,12 @@ function readRequest(b: bufio.Reader): ServerRequest { // First line: GET /index.html HTTP/1.0 const s = await tp.readLine(); - const [ method, url, proto ] = parseRequestLine(s); + const [method, url, proto] = parseRequestLine(s); console.log("readRequest", method, url); } // Returns [method, url, proto] -function parseRequestLine(line: string): [ string, string, string ] { +function parseRequestLine(line: string): [string, string, string] { return line.split(" ", 3); } @@ -69,4 +69,3 @@ export function listen(addr: string): Server { const s = new Server(listener); return s; } - diff --git a/util.ts b/util.ts index decf4d043..84ef8b5a8 100644 --- a/util.ts +++ b/util.ts @@ -1,6 +1,17 @@ - export function assert(cond: boolean, msg = "assert") { if (!cond) { throw Error(msg); } } + +// `off` is the offset into `dst` where it will at which to begin writing values +// from `src`. +// Returns the number of bytes copied. +export function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number { + const r = dst.byteLength - off; + if (src.byteLength > r) { + src = src.subarray(0, r); + } + dst.set(src, off); + return src.byteLength; +} -- cgit v1.2.3 From 77b1b40bd108c41938a2c639f80c7de83a8cf80f Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 14:23:06 -0500 Subject: Add travis script Original: https://github.com/denoland/deno_std/commit/7117998ab8f8695c8983c1961c038e59473268e3 --- .travis.yml | 15 +++++++++++++++ test.ts | 3 +++ 2 files changed, 18 insertions(+) create mode 100644 .travis.yml create mode 100644 test.ts diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..1a75f9cbd --- /dev/null +++ b/.travis.yml @@ -0,0 +1,15 @@ +language: python + +os: + - linux + +python: + - "2.7" + +install: +- |- + curl -sSf https://raw.githubusercontent.com/denoland/deno_install/master/install.py | python + export PATH="$HOME/.deno/bin:$PATH" + +script: + - deno test.ts diff --git a/test.ts b/test.ts new file mode 100644 index 000000000..4e65e4c39 --- /dev/null +++ b/test.ts @@ -0,0 +1,3 @@ +import "./buffer_test.ts"; +import "./bufio_test.ts"; +// TODO import "./http_test.ts"; -- cgit v1.2.3 From 9e3cde22d798e4834ff8480d9a4debd7cc056585 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 14:28:47 -0500 Subject: Add Readme Original: https://github.com/denoland/deno_std/commit/be1eb62bdc04c7af4f1f63b4b01b26c23d62f3c9 --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..f27d51a8b --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +# Deno Networking Libraries + +[![Build Status](https://travis-ci.com/denoland/net.svg?branch=master)](https://travis-ci.com/denoland/net) + + +Usage: +```typescript +import { Reader } from "https://deno.land/x/net/bufio.ts"; +// TODO Example. +``` -- cgit v1.2.3 From 9b014313dbec50da61213b5797d54ba1a5b4a530 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 20:28:01 -0500 Subject: Add bufio tests. Original: https://github.com/denoland/deno_std/commit/aa9e3df0d21e927ec86209c8cc81d5f1a27a0736 --- bufio.ts | 55 +++++++++++++++++++++++++++++++++++++++++++---------- bufio_test.ts | 34 +++++++++++++++++++++++++-------- iotest.ts | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 132 insertions(+), 18 deletions(-) create mode 100644 iotest.ts diff --git a/bufio.ts b/bufio.ts index 805a8136e..c1fcf9c47 100644 --- a/bufio.ts +++ b/bufio.ts @@ -24,6 +24,7 @@ export class Reader implements deno.Reader { private w = 0; // buf write position. private lastByte: number; private lastCharSize: number; + private err: null | Error; constructor(rd: deno.Reader, size = DEFAULT_BUF_SIZE) { if (size < MIN_BUF_SIZE) { @@ -37,9 +38,15 @@ export class Reader implements deno.Reader { return this.buf.byteLength; } + private _readErr(): Error { + const err = this.err; + this.err = null; + return err; + } + // Reads a new chunk into the buffer. // Returns true if EOF, false on successful read. - async _fill(): Promise { + private async _fill(): Promise { // Slide existing data to beginning. if (this.r > 0) { this.buf.copyWithin(0, this.r, this.w); @@ -53,15 +60,21 @@ export class Reader implements deno.Reader { // Read new data: try a limited number of times. for (let i = MAX_CONSECUTIVE_EMPTY_READS; i > 0; i--) { - const { nread, eof } = await this.rd.read(this.buf.subarray(this.w)); - if (nread < 0) { + let rr: deno.ReadResult; + try { + rr = await this.rd.read(this.buf.subarray(this.w)); + } catch (e) { + this.err = e; + return false; + } + if (rr.nread < 0) { throw new ErrNegativeRead(); } - this.w += nread; - if (eof) { + this.w += rr.nread; + if (rr.eof) { return true; } - if (nread > 0) { + if (rr.nread > 0) { return false; } } @@ -92,15 +105,16 @@ export class Reader implements deno.Reader { async read(p: ArrayBufferView): Promise { let rr: deno.ReadResult = { nread: p.byteLength, eof: false }; if (rr.nread === 0) { + if (this.err) { + throw this._readErr(); + } return rr; } if (this.r === this.w) { - /* - if (this.err != null) { - throw this.readErr(); + if (this.err) { + throw this._readErr(); } - */ if (p.byteLength >= this.buf.byteLength) { // Large read, empty buffer. // Read directly into p to avoid copy. @@ -112,6 +126,9 @@ export class Reader implements deno.Reader { this.lastByte = p[rr.nread - 1]; // this.lastRuneSize = -1; } + if (this.err) { + throw this._readErr(); + } return rr; } // One read. @@ -123,6 +140,9 @@ export class Reader implements deno.Reader { throw new ErrNegativeRead(); } if (rr.nread === 0) { + if (this.err) { + throw this._readErr(); + } return rr; } this.w += rr.nread; @@ -140,6 +160,9 @@ export class Reader implements deno.Reader { async readByte(): Promise { while (this.r === this.w) { const eof = await this._fill(); // buffer is empty. + if (this.err != null) { + throw this._readErr(); + } if (eof) { return -1; } @@ -149,4 +172,16 @@ export class Reader implements deno.Reader { this.lastByte = c; return c; } + + /** readString() reads until the first occurrence of delim in the input, + * returning a string containing the data up to and including the delimiter. + * If ReadString encounters an error before finding a delimiter, + * it returns the data read before the error and the error itself (often io.EOF). + * ReadString returns err != nil if and only if the returned data does not end in + * delim. + * For simple uses, a Scanner may be more convenient. + */ + async readString(delim: string): Promise { + throw new Error("Not implemented"); + } } diff --git a/bufio_test.ts b/bufio_test.ts index 1600852af..dc16f5e69 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -7,6 +7,7 @@ import * as deno from "deno"; import { test, assertEqual } from "http://deno.land/x/testing/testing.ts"; import * as bufio from "./bufio.ts"; import { Buffer } from "./buffer.ts"; +import * as iotest from "./iotest.ts"; async function readBytes(buf: bufio.Reader): Promise { const b = new Uint8Array(1000); @@ -39,15 +40,25 @@ test(async function bufioReaderSimple() { type ReadMaker = { name: string; fn: (r: deno.Reader) => deno.Reader }; const readMakers: ReadMaker[] = [ - { name: "full", fn: r => r } - /* - { name: "byte", fn(r) => new iotest.OneByteReader(r) }, - { name: "half", fn(r) => new iotest.HalfReader(r) }, - { name: "data+err", r => new iotest.DataErrReader(r) }, - { name: "timeout", r => new iotest.TimeoutReader(r) }, - */ + { name: "full", fn: r => r }, + { name: "byte", fn: r => new iotest.OneByteReader(r) }, + { name: "half", fn: r => new iotest.HalfReader(r) } + // TODO { name: "data+err", r => new iotest.DataErrReader(r) }, + // { name: "timeout", fn: r => new iotest.TimeoutReader(r) }, ]; +function readLines(b: bufio.Reader): string { + let s = ""; + while (true) { + let s1 = b.readString("\n"); + if (s1 == null) { + break; // EOF + } + s += s1; + } + return s; +} + // Call read to accumulate the text of a file async function reads(buf: bufio.Reader, m: number): Promise { const b = new Uint8Array(1000); @@ -66,7 +77,14 @@ async function reads(buf: bufio.Reader, m: number): Promise { type BufReader = { name: string; fn: (r: bufio.Reader) => Promise }; const bufreaders: BufReader[] = [ - { name: "1", fn: (b: bufio.Reader) => reads(b, 1) } + { name: "1", fn: (b: bufio.Reader) => reads(b, 1) }, + { name: "2", fn: (b: bufio.Reader) => reads(b, 2) }, + { name: "3", fn: (b: bufio.Reader) => reads(b, 3) }, + { name: "4", fn: (b: bufio.Reader) => reads(b, 4) }, + { name: "5", fn: (b: bufio.Reader) => reads(b, 5) }, + { name: "7", fn: (b: bufio.Reader) => reads(b, 7) }, + { name: "bytes", fn: readBytes } + // { name: "lines", fn: readLines }, ]; const MIN_READ_BUFFER_SIZE = 16; diff --git a/iotest.ts b/iotest.ts new file mode 100644 index 000000000..e2498e155 --- /dev/null +++ b/iotest.ts @@ -0,0 +1,61 @@ +// Ported to Deno from +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { Reader, ReadResult } from "deno"; + +/** OneByteReader returns a Reader that implements + * each non-empty Read by reading one byte from r. + */ +export class OneByteReader implements Reader { + constructor(readonly r: Reader) {} + + async read(p: ArrayBufferView): Promise { + if (p.byteLength === 0) { + return { nread: 0, eof: false }; + } + if (!(p instanceof Uint8Array)) { + throw Error("expected Uint8Array"); + } + return this.r.read(p.subarray(0, 1)); + } +} + +/** HalfReader returns a Reader that implements Read + * by reading half as many requested bytes from r. + */ +export class HalfReader implements Reader { + constructor(readonly r: Reader) {} + + async read(p: ArrayBufferView): Promise { + if (!(p instanceof Uint8Array)) { + throw Error("expected Uint8Array"); + } + const half = Math.floor((p.byteLength + 1) / 2); + return this.r.read(p.subarray(0, half)); + } +} + +export class ErrTimeout extends Error { + constructor() { + super("timeout"); + this.name = "ErrTimeout"; + } +} + +/** TimeoutReader returns ErrTimeout on the second read + * with no data. Subsequent calls to read succeed. + */ +export class TimeoutReader implements Reader { + count = 0; + constructor(readonly r: Reader) {} + + async read(p: ArrayBufferView): Promise { + this.count++; + if (this.count === 2) { + throw new ErrTimeout(); + } + return this.r.read(p); + } +} -- cgit v1.2.3 From 8396619721bed2eaa78cab17754b63b567accfef Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 21:01:32 -0500 Subject: Rename bufio.Reader to BufReader Original: https://github.com/denoland/deno_std/commit/6b886836c03ad0641aa0522ce1a765935884952e --- Makefile | 4 ++++ bufio.ts | 23 ++++++++++++++--------- bufio_test.ts | 36 ++++++++++++++++++------------------ 3 files changed, 36 insertions(+), 27 deletions(-) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..b94f157cc --- /dev/null +++ b/Makefile @@ -0,0 +1,4 @@ +test: + deno test.ts + +.PHONY: test diff --git a/bufio.ts b/bufio.ts index c1fcf9c47..06f2eb432 100644 --- a/bufio.ts +++ b/bufio.ts @@ -3,7 +3,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -import * as deno from "deno"; +import { Reader, ReadResult } from "deno"; import { assert, copyBytes } from "./util.ts"; const DEFAULT_BUF_SIZE = 4096; @@ -17,16 +17,17 @@ export class ErrNegativeRead extends Error { } } -export class Reader implements deno.Reader { +/** BufReader implements buffering for a Reader object. */ +export class BufReader implements Reader { private buf: Uint8Array; - private rd: deno.Reader; // Reader provided by caller. + private rd: Reader; // Reader provided by caller. private r = 0; // buf read position. private w = 0; // buf write position. private lastByte: number; private lastCharSize: number; private err: null | Error; - constructor(rd: deno.Reader, size = DEFAULT_BUF_SIZE) { + constructor(rd: Reader, size = DEFAULT_BUF_SIZE) { if (size < MIN_BUF_SIZE) { size = MIN_BUF_SIZE; } @@ -38,6 +39,10 @@ export class Reader implements deno.Reader { return this.buf.byteLength; } + buffered(): number { + return this.w - this.r; + } + private _readErr(): Error { const err = this.err; this.err = null; @@ -60,7 +65,7 @@ export class Reader implements deno.Reader { // Read new data: try a limited number of times. for (let i = MAX_CONSECUTIVE_EMPTY_READS; i > 0; i--) { - let rr: deno.ReadResult; + let rr: ReadResult; try { rr = await this.rd.read(this.buf.subarray(this.w)); } catch (e) { @@ -84,11 +89,11 @@ export class Reader implements deno.Reader { /** Discards any buffered data, resets all state, and switches * the buffered reader to read from r. */ - reset(r: deno.Reader): void { + reset(r: Reader): void { this._reset(this.buf, r); } - private _reset(buf: Uint8Array, rd: deno.Reader): void { + private _reset(buf: Uint8Array, rd: Reader): void { this.buf = buf; this.rd = rd; this.lastByte = -1; @@ -102,8 +107,8 @@ export class Reader implements deno.Reader { * At EOF, the count will be zero and err will be io.EOF. * To read exactly len(p) bytes, use io.ReadFull(b, p). */ - async read(p: ArrayBufferView): Promise { - let rr: deno.ReadResult = { nread: p.byteLength, eof: false }; + async read(p: ArrayBufferView): Promise { + let rr: ReadResult = { nread: p.byteLength, eof: false }; if (rr.nread === 0) { if (this.err) { throw this._readErr(); diff --git a/bufio_test.ts b/bufio_test.ts index dc16f5e69..85be74fdc 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -5,11 +5,11 @@ import * as deno from "deno"; import { test, assertEqual } from "http://deno.land/x/testing/testing.ts"; -import * as bufio from "./bufio.ts"; +import { BufReader } from "./bufio.ts"; import { Buffer } from "./buffer.ts"; import * as iotest from "./iotest.ts"; -async function readBytes(buf: bufio.Reader): Promise { +async function readBytes(buf: BufReader): Promise { const b = new Uint8Array(1000); let nb = 0; while (true) { @@ -32,7 +32,7 @@ function stringsReader(s: string): deno.Reader { test(async function bufioReaderSimple() { const data = "hello world"; - const b = new bufio.Reader(stringsReader(data)); + const b = new BufReader(stringsReader(data)); const s = await readBytes(b); assertEqual(s, data); }); @@ -42,15 +42,15 @@ type ReadMaker = { name: string; fn: (r: deno.Reader) => deno.Reader }; const readMakers: ReadMaker[] = [ { name: "full", fn: r => r }, { name: "byte", fn: r => new iotest.OneByteReader(r) }, - { name: "half", fn: r => new iotest.HalfReader(r) } + { name: "half", fn: r => new iotest.HalfReader(r) }, // TODO { name: "data+err", r => new iotest.DataErrReader(r) }, // { name: "timeout", fn: r => new iotest.TimeoutReader(r) }, ]; -function readLines(b: bufio.Reader): string { +function readLines(b: BufReader): string { let s = ""; while (true) { - let s1 = b.readString("\n"); + let s1 = b.readString('\n'); if (s1 == null) { break; // EOF } @@ -60,7 +60,7 @@ function readLines(b: bufio.Reader): string { } // Call read to accumulate the text of a file -async function reads(buf: bufio.Reader, m: number): Promise { +async function reads(buf: BufReader, m: number): Promise { const b = new Uint8Array(1000); let nb = 0; while (true) { @@ -74,16 +74,16 @@ async function reads(buf: bufio.Reader, m: number): Promise { return decoder.decode(b.subarray(0, nb)); } -type BufReader = { name: string; fn: (r: bufio.Reader) => Promise }; +type NamedBufReader = { name: string; fn: (r: BufReader) => Promise }; -const bufreaders: BufReader[] = [ - { name: "1", fn: (b: bufio.Reader) => reads(b, 1) }, - { name: "2", fn: (b: bufio.Reader) => reads(b, 2) }, - { name: "3", fn: (b: bufio.Reader) => reads(b, 3) }, - { name: "4", fn: (b: bufio.Reader) => reads(b, 4) }, - { name: "5", fn: (b: bufio.Reader) => reads(b, 5) }, - { name: "7", fn: (b: bufio.Reader) => reads(b, 7) }, - { name: "bytes", fn: readBytes } +const bufreaders: NamedBufReader[] = [ + { name: "1", fn: (b: BufReader) => reads(b, 1) }, + { name: "2", fn: (b: BufReader) => reads(b, 2) }, + { name: "3", fn: (b: BufReader) => reads(b, 3) }, + { name: "4", fn: (b: BufReader) => reads(b, 4) }, + { name: "5", fn: (b: BufReader) => reads(b, 5) }, + { name: "7", fn: (b: BufReader) => reads(b, 7) }, + { name: "bytes", fn: readBytes }, // { name: "lines", fn: readLines }, ]; @@ -101,7 +101,7 @@ const bufsizes: number[] = [ 4096 ]; -test(async function bufioReader() { +test(async function bufioBufReader() { const texts = new Array(31); let str = ""; let all = ""; @@ -117,7 +117,7 @@ test(async function bufioReader() { for (let bufreader of bufreaders) { for (let bufsize of bufsizes) { const read = readmaker.fn(stringsReader(text)); - const buf = new bufio.Reader(read, bufsize); + const buf = new BufReader(read, bufsize); const s = await bufreader.fn(buf); const debugStr = `reader=${readmaker.name} ` + -- cgit v1.2.3 From 423424f1daa3ca35f2ac63d2c0e40b99e938ec46 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 23:19:08 -0500 Subject: Add BufReader.readSlice() Original: https://github.com/denoland/deno_std/commit/e37b949e2c4523911e071086c1cf4ea4f33dc6af --- Makefile | 5 +- bufio.ts | 148 ++++++++++++++++++++++++++++++++++++++++++++++++++-------- bufio_test.ts | 26 +++++++++-- util.ts | 4 ++ 4 files changed, 159 insertions(+), 24 deletions(-) diff --git a/Makefile b/Makefile index b94f157cc..4b8488093 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,7 @@ test: deno test.ts -.PHONY: test +fmt: + prettier *.ts --write + +.PHONY: test fmt diff --git a/bufio.ts b/bufio.ts index 06f2eb432..e57193734 100644 --- a/bufio.ts +++ b/bufio.ts @@ -4,17 +4,18 @@ // license that can be found in the LICENSE file. import { Reader, ReadResult } from "deno"; -import { assert, copyBytes } from "./util.ts"; +import { assert, charCode, copyBytes } from "./util.ts"; const DEFAULT_BUF_SIZE = 4096; const MIN_BUF_SIZE = 16; const MAX_CONSECUTIVE_EMPTY_READS = 100; +const CR = charCode("\r"); +const LF = charCode("\n"); -export class ErrNegativeRead extends Error { - constructor() { - super("bufio: reader returned negative count from Read"); - this.name = "ErrNegativeRead"; - } +export enum BufState { + Ok, + EOF, + BufferFull } /** BufReader implements buffering for a Reader object. */ @@ -51,7 +52,7 @@ export class BufReader implements Reader { // Reads a new chunk into the buffer. // Returns true if EOF, false on successful read. - private async _fill(): Promise { + private async _fill(): Promise { // Slide existing data to beginning. if (this.r > 0) { this.buf.copyWithin(0, this.r, this.w); @@ -70,17 +71,15 @@ export class BufReader implements Reader { rr = await this.rd.read(this.buf.subarray(this.w)); } catch (e) { this.err = e; - return false; - } - if (rr.nread < 0) { - throw new ErrNegativeRead(); + return BufState.Ok; } + assert(rr.nread >= 0, "negative read"); this.w += rr.nread; if (rr.eof) { - return true; + return BufState.EOF; } if (rr.nread > 0) { - return false; + return BufState.Ok; } } throw Error("No Progress"); @@ -124,9 +123,7 @@ export class BufReader implements Reader { // Large read, empty buffer. // Read directly into p to avoid copy. rr = await this.rd.read(p); - if (rr.nread < 0) { - throw new ErrNegativeRead(); - } + assert(rr.nread >= 0, "negative read"); if (rr.nread > 0) { this.lastByte = p[rr.nread - 1]; // this.lastRuneSize = -1; @@ -140,10 +137,12 @@ export class BufReader implements Reader { // Do not use this.fill, which will loop. this.r = 0; this.w = 0; - rr = await this.rd.read(this.buf); - if (rr.nread < 0) { - throw new ErrNegativeRead(); + try { + rr = await this.rd.read(this.buf); + } catch (e) { + this.err = e; } + assert(rr.nread >= 0, "negative read"); if (rr.nread === 0) { if (this.err) { throw this._readErr(); @@ -189,4 +188,115 @@ export class BufReader implements Reader { async readString(delim: string): Promise { throw new Error("Not implemented"); } + + /** readLine() is a low-level line-reading primitive. Most callers should use + * readBytes('\n') or readString('\n') instead or use a Scanner. + * + * readLine tries to return a single line, not including the end-of-line bytes. + * If the line was too long for the buffer then isPrefix is set and the + * beginning of the line is returned. The rest of the line will be returned + * from future calls. isPrefix will be false when returning the last fragment + * of the line. The returned buffer is only valid until the next call to + * ReadLine. ReadLine either returns a non-nil line or it returns an error, + * never both. + * + * The text returned from ReadLine does not include the line end ("\r\n" or "\n"). + * No indication or error is given if the input ends without a final line end. + * Calling UnreadByte after ReadLine will always unread the last byte read + * (possibly a character belonging to the line end) even if that byte is not + * part of the line returned by ReadLine. + */ + async readLine(): Promise<{ + line?: Uint8Array; + isPrefix: boolean; + state: BufState; + }> { + let line: Uint8Array; + let state: BufState; + try { + [line, state] = await this.readSlice(LF); + } catch (err) { + this.err = err; + } + + if (state === BufState.BufferFull) { + // Handle the case where "\r\n" straddles the buffer. + if (line.byteLength > 0 && line[line.byteLength - 1] === CR) { + // Put the '\r' back on buf and drop it from line. + // Let the next call to ReadLine check for "\r\n". + assert(this.r > 0, "bufio: tried to rewind past start of buffer"); + this.r--; + line = line.subarray(0, line.byteLength - 1); + } + return { line, isPrefix: true, state }; + } + + if (line.byteLength === 0) { + return { line, isPrefix: false, state }; + } + + if (line[line.byteLength - 1] == LF) { + let drop = 1; + if (line.byteLength > 1 && line[line.byteLength - 2] === CR) { + drop = 2; + } + line = line.subarray(0, line.byteLength - drop); + } + return { line, isPrefix: false, state }; + } + + /** readSlice() reads until the first occurrence of delim in the input, + * returning a slice pointing at the bytes in the buffer. The bytes stop + * being valid at the next read. If readSlice() encounters an error before + * finding a delimiter, it returns all the data in the buffer and the error + * itself (often io.EOF). readSlice() fails with error ErrBufferFull if the + * buffer fills without a delim. Because the data returned from readSlice() + * will be overwritten by the next I/O operation, most clients should use + * readBytes() or readString() instead. readSlice() returns err != nil if and + * only if line does not end in delim. + */ + async readSlice(delim: number): Promise<[Uint8Array, BufState]> { + let s = 0; // search start index + let line: Uint8Array; + let state = BufState.Ok; + while (true) { + // Search buffer. + let i = this.buf.subarray(this.r + s, this.w).indexOf(delim); + if (i >= 0) { + i += s; + line = this.buf.subarray(this.r, this.r + i + 1); + this.r += i + 1; + break; + } + + // Pending error? + if (this.err) { + line = this.buf.subarray(this.r, this.w); + this.r = this.w; + throw this._readErr(); + break; + } + + // Buffer full? + if (this.buffered() >= this.buf.byteLength) { + this.r = this.w; + line = this.buf; + state = BufState.BufferFull; + break; + } + + s = this.w - this.r; // do not rescan area we scanned before + + await this._fill(); // buffer is not full + } + + // Handle last byte, if any. + let i = line.byteLength - 1; + if (i >= 0) { + this.lastByte = line[i]; + // this.lastRuneSize = -1 + } + + return [line, state]; + } } diff --git a/bufio_test.ts b/bufio_test.ts index 85be74fdc..9a3361d6f 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -5,9 +5,10 @@ import * as deno from "deno"; import { test, assertEqual } from "http://deno.land/x/testing/testing.ts"; -import { BufReader } from "./bufio.ts"; +import { BufReader, BufState } from "./bufio.ts"; import { Buffer } from "./buffer.ts"; import * as iotest from "./iotest.ts"; +import { charCode } from "./util.ts"; async function readBytes(buf: BufReader): Promise { const b = new Uint8Array(1000); @@ -42,7 +43,7 @@ type ReadMaker = { name: string; fn: (r: deno.Reader) => deno.Reader }; const readMakers: ReadMaker[] = [ { name: "full", fn: r => r }, { name: "byte", fn: r => new iotest.OneByteReader(r) }, - { name: "half", fn: r => new iotest.HalfReader(r) }, + { name: "half", fn: r => new iotest.HalfReader(r) } // TODO { name: "data+err", r => new iotest.DataErrReader(r) }, // { name: "timeout", fn: r => new iotest.TimeoutReader(r) }, ]; @@ -50,7 +51,7 @@ const readMakers: ReadMaker[] = [ function readLines(b: BufReader): string { let s = ""; while (true) { - let s1 = b.readString('\n'); + let s1 = b.readString("\n"); if (s1 == null) { break; // EOF } @@ -83,7 +84,7 @@ const bufreaders: NamedBufReader[] = [ { name: "4", fn: (b: BufReader) => reads(b, 4) }, { name: "5", fn: (b: BufReader) => reads(b, 5) }, { name: "7", fn: (b: BufReader) => reads(b, 7) }, - { name: "bytes", fn: readBytes }, + { name: "bytes", fn: readBytes } // { name: "lines", fn: readLines }, ]; @@ -128,3 +129,20 @@ test(async function bufioBufReader() { } } }); + +test(async function bufioBufferFull() { + const longString = + "And now, hello, world! It is the time for all good men to come to the aid of their party"; + const buf = new BufReader(stringsReader(longString), MIN_READ_BUFFER_SIZE); + let [line, state] = await buf.readSlice(charCode("!")); + + const decoder = new TextDecoder(); + let actual = decoder.decode(line); + assertEqual(state, BufState.BufferFull); + assertEqual(actual, "And now, hello, "); + + [line, state] = await buf.readSlice(charCode("!")); + actual = decoder.decode(line); + assertEqual(actual, "world!"); + assertEqual(state, BufState.Ok); +}); diff --git a/util.ts b/util.ts index 84ef8b5a8..d05bea8c0 100644 --- a/util.ts +++ b/util.ts @@ -15,3 +15,7 @@ export function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number { dst.set(src, off); return src.byteLength; } + +export function charCode(s: string): number { + return s.charCodeAt(0); +} -- cgit v1.2.3 From 5f74f7eebe8fb657624374d8a8510fe1caa9ffa0 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 23:22:33 -0500 Subject: Use https instead of http. Original: https://github.com/denoland/deno_std/commit/2d8d8247da4f71fe7e796fc1d3da1f797a2c4195 --- buffer_test.ts | 2 +- bufio_test.ts | 2 +- http_test.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/buffer_test.ts b/buffer_test.ts index 8365b29bd..9a71e80a3 100644 --- a/buffer_test.ts +++ b/buffer_test.ts @@ -5,7 +5,7 @@ import { test, assert, assertEqual -} from "http://deno.land/x/testing/testing.ts"; +} from "https://deno.land/x/testing/testing.ts"; import { Buffer } from "./buffer.ts"; // N controls how many iterations of certain checks are performed. diff --git a/bufio_test.ts b/bufio_test.ts index 9a3361d6f..31a8363a2 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -4,7 +4,7 @@ // license that can be found in the LICENSE file. import * as deno from "deno"; -import { test, assertEqual } from "http://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { BufReader, BufState } from "./bufio.ts"; import { Buffer } from "./buffer.ts"; import * as iotest from "./iotest.ts"; diff --git a/http_test.ts b/http_test.ts index 6fbac9a4a..4a8867aba 100644 --- a/http_test.ts +++ b/http_test.ts @@ -1,5 +1,5 @@ //import { listen } from "./server.ts"; -import { test } from "http://deno.land/x/testing/testing.ts"; +import { test } from "https://deno.land/x/testing/testing.ts"; test(function basic() { console.log("ok"); -- cgit v1.2.3 From d35e13e6beb6825a85a2518adebcc8afd91360af Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 8 Nov 2018 02:05:06 -0500 Subject: Add test bufioReadLine Original: https://github.com/denoland/deno_std/commit/01f576af87de38628bf65eccc855a3503e76d03e --- bufio.ts | 62 ++++++++++++++++------------------------ bufio_test.ts | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 106 insertions(+), 47 deletions(-) diff --git a/bufio.ts b/bufio.ts index e57193734..3480047e9 100644 --- a/bufio.ts +++ b/bufio.ts @@ -12,11 +12,7 @@ const MAX_CONSECUTIVE_EMPTY_READS = 100; const CR = charCode("\r"); const LF = charCode("\n"); -export enum BufState { - Ok, - EOF, - BufferFull -} +export type BufState = null | "EOF" | "BufferFull" | "NoProgress" | Error; /** BufReader implements buffering for a Reader object. */ export class BufReader implements Reader { @@ -26,7 +22,7 @@ export class BufReader implements Reader { private w = 0; // buf write position. private lastByte: number; private lastCharSize: number; - private err: null | Error; + private err: BufState; constructor(rd: Reader, size = DEFAULT_BUF_SIZE) { if (size < MIN_BUF_SIZE) { @@ -44,7 +40,7 @@ export class BufReader implements Reader { return this.w - this.r; } - private _readErr(): Error { + private _readErr(): BufState { const err = this.err; this.err = null; return err; @@ -52,7 +48,7 @@ export class BufReader implements Reader { // Reads a new chunk into the buffer. // Returns true if EOF, false on successful read. - private async _fill(): Promise { + private async _fill(): Promise { // Slide existing data to beginning. if (this.r > 0) { this.buf.copyWithin(0, this.r, this.w); @@ -71,18 +67,19 @@ export class BufReader implements Reader { rr = await this.rd.read(this.buf.subarray(this.w)); } catch (e) { this.err = e; - return BufState.Ok; + return; } assert(rr.nread >= 0, "negative read"); this.w += rr.nread; if (rr.eof) { - return BufState.EOF; + this.err = "EOF"; + return; } if (rr.nread > 0) { - return BufState.Ok; + return; } } - throw Error("No Progress"); + this.err = "NoProgress"; } /** Discards any buffered data, resets all state, and switches @@ -96,7 +93,7 @@ export class BufReader implements Reader { this.buf = buf; this.rd = rd; this.lastByte = -1; - this.lastCharSize = -1; + // this.lastRuneSize = -1; } /** reads data into p. @@ -163,13 +160,13 @@ export class BufReader implements Reader { /** Returns the next byte [0, 255] or -1 if EOF. */ async readByte(): Promise { while (this.r === this.w) { - const eof = await this._fill(); // buffer is empty. + await this._fill(); // buffer is empty. + if (this.err == "EOF") { + return -1; + } if (this.err != null) { throw this._readErr(); } - if (eof) { - return -1; - } } const c = this.buf[this.r]; this.r++; @@ -206,20 +203,10 @@ export class BufReader implements Reader { * (possibly a character belonging to the line end) even if that byte is not * part of the line returned by ReadLine. */ - async readLine(): Promise<{ - line?: Uint8Array; - isPrefix: boolean; - state: BufState; - }> { - let line: Uint8Array; - let state: BufState; - try { - [line, state] = await this.readSlice(LF); - } catch (err) { - this.err = err; - } + async readLine(): Promise<[Uint8Array, boolean, BufState]> { + let [line, err] = await this.readSlice(LF); - if (state === BufState.BufferFull) { + if (err === "BufferFull") { // Handle the case where "\r\n" straddles the buffer. if (line.byteLength > 0 && line[line.byteLength - 1] === CR) { // Put the '\r' back on buf and drop it from line. @@ -228,12 +215,13 @@ export class BufReader implements Reader { this.r--; line = line.subarray(0, line.byteLength - 1); } - return { line, isPrefix: true, state }; + return [line, true, null]; } if (line.byteLength === 0) { - return { line, isPrefix: false, state }; + return [line, false, err]; } + err = null; if (line[line.byteLength - 1] == LF) { let drop = 1; @@ -242,7 +230,7 @@ export class BufReader implements Reader { } line = line.subarray(0, line.byteLength - drop); } - return { line, isPrefix: false, state }; + return [line, false, err]; } /** readSlice() reads until the first occurrence of delim in the input, @@ -258,7 +246,7 @@ export class BufReader implements Reader { async readSlice(delim: number): Promise<[Uint8Array, BufState]> { let s = 0; // search start index let line: Uint8Array; - let state = BufState.Ok; + let err: BufState; while (true) { // Search buffer. let i = this.buf.subarray(this.r + s, this.w).indexOf(delim); @@ -273,7 +261,7 @@ export class BufReader implements Reader { if (this.err) { line = this.buf.subarray(this.r, this.w); this.r = this.w; - throw this._readErr(); + err = this._readErr(); break; } @@ -281,7 +269,7 @@ export class BufReader implements Reader { if (this.buffered() >= this.buf.byteLength) { this.r = this.w; line = this.buf; - state = BufState.BufferFull; + err = "BufferFull"; break; } @@ -297,6 +285,6 @@ export class BufReader implements Reader { // this.lastRuneSize = -1 } - return [line, state]; + return [line, err]; } } diff --git a/bufio_test.ts b/bufio_test.ts index 31a8363a2..4319a337d 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -3,12 +3,18 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -import * as deno from "deno"; -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { Reader, ReadResult } from "deno"; +import { + test, + assert, + assertEqual +} from "https://deno.land/x/testing/testing.ts"; import { BufReader, BufState } from "./bufio.ts"; import { Buffer } from "./buffer.ts"; import * as iotest from "./iotest.ts"; -import { charCode } from "./util.ts"; +import { charCode, copyBytes } from "./util.ts"; + +const encoder = new TextEncoder(); async function readBytes(buf: BufReader): Promise { const b = new Uint8Array(1000); @@ -25,8 +31,7 @@ async function readBytes(buf: BufReader): Promise { return decoder.decode(b.subarray(0, nb)); } -function stringsReader(s: string): deno.Reader { - const encoder = new TextEncoder(); +function stringsReader(s: string): Reader { const ui8 = encoder.encode(s); return new Buffer(ui8.buffer as ArrayBuffer); } @@ -38,7 +43,7 @@ test(async function bufioReaderSimple() { assertEqual(s, data); }); -type ReadMaker = { name: string; fn: (r: deno.Reader) => deno.Reader }; +type ReadMaker = { name: string; fn: (r: Reader) => Reader }; const readMakers: ReadMaker[] = [ { name: "full", fn: r => r }, @@ -134,15 +139,81 @@ test(async function bufioBufferFull() { const longString = "And now, hello, world! It is the time for all good men to come to the aid of their party"; const buf = new BufReader(stringsReader(longString), MIN_READ_BUFFER_SIZE); - let [line, state] = await buf.readSlice(charCode("!")); + let [line, err] = await buf.readSlice(charCode("!")); const decoder = new TextDecoder(); let actual = decoder.decode(line); - assertEqual(state, BufState.BufferFull); + assertEqual(err, "BufferFull"); assertEqual(actual, "And now, hello, "); - [line, state] = await buf.readSlice(charCode("!")); + [line, err] = await buf.readSlice(charCode("!")); actual = decoder.decode(line); assertEqual(actual, "world!"); - assertEqual(state, BufState.Ok); + assert(err == null); +}); + +const testInput = encoder.encode( + "012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy" +); +const testInputrn = encoder.encode( + "012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n" +); +const testOutput = encoder.encode("0123456789abcdefghijklmnopqrstuvwxy"); + +// TestReader wraps a Uint8Array and returns reads of a specific length. +class TestReader implements Reader { + constructor(private data: Uint8Array, private stride: number) {} + + async read(buf: ArrayBufferView): Promise { + let nread = this.stride; + if (nread > this.data.byteLength) { + nread = this.data.byteLength; + } + if (nread > buf.byteLength) { + nread = buf.byteLength; + } + copyBytes(buf as Uint8Array, this.data); + this.data = this.data.subarray(nread); + let eof = false; + if (this.data.byteLength == 0) { + eof = true; + } + return { nread, eof }; + } +} + +async function testReadLine(input: Uint8Array): Promise { + for (let stride = 1; stride < 2; stride++) { + let done = 0; + let reader = new TestReader(input, stride); + let l = new BufReader(reader, input.byteLength + 1); + while (true) { + let [line, isPrefix, err] = await l.readLine(); + if (line.byteLength > 0 && err != null) { + throw Error("readLine returned both data and error"); + } + assertEqual(isPrefix, false); + if (err == "EOF") { + break; + } + let want = testOutput.subarray(done, done + line.byteLength); + assertEqual( + line, + want, + `Bad line at stride ${stride}: want: ${want} got: ${line}` + ); + done += line.byteLength; + } + assertEqual( + done, + testOutput.byteLength, + `readLine didn't return everything: got: ${done}, ` + + `want: ${testOutput} (stride: ${stride})` + ); + } +} + +test(async function bufioReadLine() { + await testReadLine(testInput); + await testReadLine(testInputrn); }); -- cgit v1.2.3 From e97fdcac47a7ff53143b15e6686a773bd6202e10 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 8 Nov 2018 04:01:20 -0500 Subject: Add BufReader.peek() Original: https://github.com/denoland/deno_std/commit/90cbca40beb7f5523f7ac99b5f317b727d4df3a4 --- Makefile | 2 +- README.md | 9 ++++--- bufio.ts | 37 +++++++++++++++++++++++++++- bufio_test.ts | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 120 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index 4b8488093..ca2135445 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,6 @@ test: deno test.ts fmt: - prettier *.ts --write + prettier *.md *.ts --write .PHONY: test fmt diff --git a/README.md b/README.md index f27d51a8b..614e53087 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,12 @@ [![Build Status](https://travis-ci.com/denoland/net.svg?branch=master)](https://travis-ci.com/denoland/net) - Usage: + ```typescript -import { Reader } from "https://deno.land/x/net/bufio.ts"; -// TODO Example. +import { serve } from "https://deno.land/x/net/http.ts"; +const s = serve("0.0.0.0:8000"); +for await (const req of s) { + req.respond({ body: "Hello World\n" }); +} ``` diff --git a/bufio.ts b/bufio.ts index 3480047e9..d736e1fc4 100644 --- a/bufio.ts +++ b/bufio.ts @@ -47,7 +47,6 @@ export class BufReader implements Reader { } // Reads a new chunk into the buffer. - // Returns true if EOF, false on successful read. private async _fill(): Promise { // Slide existing data to beginning. if (this.r > 0) { @@ -287,4 +286,40 @@ export class BufReader implements Reader { return [line, err]; } + + /** Peek returns the next n bytes without advancing the reader. The bytes stop + * being valid at the next read call. If Peek returns fewer than n bytes, it + * also returns an error explaining why the read is short. The error is + * ErrBufferFull if n is larger than b's buffer size. + */ + async peek(n: number): Promise<[Uint8Array, BufState]> { + if (n < 0) { + throw Error("negative count"); + } + + while ( + this.w - this.r < n && + this.w - this.r < this.buf.byteLength && + this.err == null + ) { + await this._fill(); // this.w - this.r < len(this.buf) => buffer is not full + } + + if (n > this.buf.byteLength) { + return [this.buf.subarray(this.r, this.w), "BufferFull"]; + } + + // 0 <= n <= len(this.buf) + let err: BufState; + let avail = this.w - this.r; + if (avail < n) { + // not enough data in buffer + n = avail; + err = this._readErr(); + if (!err) { + err = "BufferFull"; + } + } + return [this.buf.subarray(this.r, this.r + n), err]; + } } diff --git a/bufio_test.ts b/bufio_test.ts index 4319a337d..80068f2d3 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -217,3 +217,80 @@ test(async function bufioReadLine() { await testReadLine(testInput); await testReadLine(testInputrn); }); + +test(async function bufioPeek() { + const decoder = new TextDecoder(); + let p = new Uint8Array(10); + // string is 16 (minReadBufferSize) long. + let buf = new BufReader( + stringsReader("abcdefghijklmnop"), + MIN_READ_BUFFER_SIZE + ); + + let [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "a"); + assert(err == null); + + [actual, err] = await buf.peek(4); + assertEqual(decoder.decode(actual), "abcd"); + assert(err == null); + + [actual, err] = await buf.peek(32); + assertEqual(decoder.decode(actual), "abcdefghijklmnop"); + assertEqual(err, "BufferFull"); + + await buf.read(p.subarray(0, 3)); + assertEqual(decoder.decode(p.subarray(0, 3)), "abc"); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "d"); + assert(err == null); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "d"); + assert(err == null); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "d"); + assert(err == null); + + [actual, err] = await buf.peek(2); + assertEqual(decoder.decode(actual), "de"); + assert(err == null); + + let { eof } = await buf.read(p.subarray(0, 3)); + assertEqual(decoder.decode(p.subarray(0, 3)), "def"); + assert(!eof); + assert(err == null); + + [actual, err] = await buf.peek(4); + assertEqual(decoder.decode(actual), "ghij"); + assert(err == null); + + await buf.read(p); + assertEqual(decoder.decode(p), "ghijklmnop"); + + [actual, err] = await buf.peek(0); + assertEqual(decoder.decode(actual), ""); + assert(err == null); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), ""); + assert(err == "EOF"); + /* TODO + // Test for issue 3022, not exposing a reader's error on a successful Peek. + buf = NewReaderSize(dataAndEOFReader("abcd"), 32) + if s, err := buf.Peek(2); string(s) != "ab" || err != nil { + t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err) + } + if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { + t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err) + } + if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil { + t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err) + } + if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF { + t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err) + } + */ +}); -- cgit v1.2.3 From a628a499fa7794ef421e814ae487635890af1cb3 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 8 Nov 2018 11:57:00 -0500 Subject: Simplify travis. Original: https://github.com/denoland/deno_std/commit/22151e4f7bddfa14aed096d7ad7d021b026b562b --- .travis.yml | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1a75f9cbd..7da118d4d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,8 @@ language: python -os: - - linux - -python: - - "2.7" - install: -- |- - curl -sSf https://raw.githubusercontent.com/denoland/deno_install/master/install.py | python - export PATH="$HOME/.deno/bin:$PATH" +- curl -sSf https://raw.githubusercontent.com/denoland/deno_install/master/install.py | python +- export PATH="$HOME/.deno/bin:$PATH" script: - - deno test.ts +- deno test.ts -- cgit v1.2.3 From 0c324a442ef4a296bd925972dfbe3fc94c60b256 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 8 Nov 2018 12:26:20 -0500 Subject: First pass at TextProtoReader. Original: https://github.com/denoland/deno_std/commit/31ab43b9193a9107d965c991f17992fcee791b33 --- buffer.ts | 6 +++ bufio.ts | 2 +- bufio_test.ts | 9 +--- test.ts | 1 + textproto.ts | 144 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ util.ts | 2 + 6 files changed, 156 insertions(+), 8 deletions(-) create mode 100644 textproto.ts diff --git a/buffer.ts b/buffer.ts index a795bc842..ba2715cef 100644 --- a/buffer.ts +++ b/buffer.ts @@ -13,6 +13,12 @@ import { assert, copyBytes } from "./util.ts"; const MIN_READ = 512; const MAX_SIZE = 2 ** 32 - 2; +const encoder = new TextEncoder(); +export function stringsReader(s: string): Reader { + const ui8 = encoder.encode(s); + return new Buffer(ui8.buffer as ArrayBuffer); +} + /** A Buffer is a variable-sized buffer of bytes with read() and write() * methods. Based on https://golang.org/pkg/bytes/#Buffer */ diff --git a/bufio.ts b/bufio.ts index d736e1fc4..8ff02b7e9 100644 --- a/bufio.ts +++ b/bufio.ts @@ -1,4 +1,4 @@ -// Ported to Deno from: +// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio.go // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/bufio_test.ts b/bufio_test.ts index 80068f2d3..9c89f0216 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -1,4 +1,4 @@ -// Ported to Deno from: +// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio_test.go // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -10,7 +10,7 @@ import { assertEqual } from "https://deno.land/x/testing/testing.ts"; import { BufReader, BufState } from "./bufio.ts"; -import { Buffer } from "./buffer.ts"; +import { Buffer, stringsReader } from "./buffer.ts"; import * as iotest from "./iotest.ts"; import { charCode, copyBytes } from "./util.ts"; @@ -31,11 +31,6 @@ async function readBytes(buf: BufReader): Promise { return decoder.decode(b.subarray(0, nb)); } -function stringsReader(s: string): Reader { - const ui8 = encoder.encode(s); - return new Buffer(ui8.buffer as ArrayBuffer); -} - test(async function bufioReaderSimple() { const data = "hello world"; const b = new BufReader(stringsReader(data)); diff --git a/test.ts b/test.ts index 4e65e4c39..2ee9a820b 100644 --- a/test.ts +++ b/test.ts @@ -1,3 +1,4 @@ import "./buffer_test.ts"; import "./bufio_test.ts"; +import "./textproto_test.ts"; // TODO import "./http_test.ts"; diff --git a/textproto.ts b/textproto.ts new file mode 100644 index 000000000..b4336c90d --- /dev/null +++ b/textproto.ts @@ -0,0 +1,144 @@ +// Based on https://github.com/golang/go/blob/891682/src/net/textproto/ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { BufReader, BufState } from "./bufio.ts"; +import { charCode } from "./util.ts"; + +const asciiDecoder = new TextDecoder("ascii"); +function str(buf: Uint8Array): string { + if (buf == null) { + return ""; + } else { + return asciiDecoder.decode(buf); + } +} + +export class ProtocolError extends Error { + constructor(msg: string) { + super(msg); + this.name = "ProtocolError"; + } +} + +export class TextProtoReader { + constructor(readonly r: BufReader) {} + + /** readLine() reads a single line from the TextProtoReader, + * eliding the final \n or \r\n from the returned string. + */ + async readLine(): Promise<[string, BufState]> { + let [line, err] = await this.readLineSlice(); + return [str(line), err]; + } + + /** ReadMIMEHeader reads a MIME-style header from r. + * The header is a sequence of possibly continued Key: Value lines + * ending in a blank line. + * The returned map m maps CanonicalMIMEHeaderKey(key) to a + * sequence of values in the same order encountered in the input. + * + * For example, consider this input: + * + * My-Key: Value 1 + * Long-Key: Even + * Longer Value + * My-Key: Value 2 + * + * Given that input, ReadMIMEHeader returns the map: + * + * map[string][]string{ + * "My-Key": {"Value 1", "Value 2"}, + * "Long-Key": {"Even Longer Value"}, + * } + */ + /* + async readMIMEHeader(): Promise { + let m = new Headers(); + let line: Uint8Array; + + // The first line cannot start with a leading space. + let [buf, err] = await this.r.peek(1); + if (buf[0] == charCode(' ') || buf[0] == charCode('\t')) { + [line, err] = await this.readLineSlice(); + } + + [buf, err] = await this.r.peek(1); + if (err == null && (buf[0] == charCode(' ') || buf[0] == charCode('\t'))) { + throw new ProtocolError(`malformed MIME header initial line: ${str(line)}`) + } + + while (true) { + let [kv, err] = await this.readLineSlice(); // readContinuedLineSlice + if (kv.byteLength == 0) { + return m; + } + + // Key ends at first colon; should not have trailing spaces + // but they appear in the wild, violating specs, so we remove + // them if present. + let i = kv.indexOf(charCode(':')); + if (i < 0) { + throw new ProtocolError(`malformed MIME header line: ${str(kv)}`); + } + let endKey = i; + while (endKey > 0 && kv[endKey - 1] == charCode(' ')) { + endKey--; + } + + //let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey)); + let key = str(kv.subarray(0, endKey)); + + // As per RFC 7230 field-name is a token, tokens consist of one or more chars. + // We could return a ProtocolError here, but better to be liberal in what we + // accept, so if we get an empty key, skip it. + if (key == "") { + continue; + } + + // Skip initial spaces in value. + i++; // skip colon + while (i < kv.byteLength && + (kv[i] == charCode(' ') || kv[i] == charCode('\t'))) { + i++; + } + let value = str(kv.subarray(i)); + + m.append(key, value); + + if (err != null) { + throw err; + } + } + } + */ + + async readLineSlice(): Promise<[Uint8Array, BufState]> { + // this.closeDot(); + let line: null | Uint8Array; + while (true) { + let [l, more, err] = await this.r.readLine(); + if (err != null) { + return [null, err]; + } + // Avoid the copy if the first call produced a full line. + if (line == null && !more) { + return [l, null]; + } + line = append(line, l); + if (!more) { + break; + } + } + return [line, null]; + } +} + +function append(a: Uint8Array, b: Uint8Array): Uint8Array { + if (a == null) { + return b; + } else { + throw Error("Not implemented"); + } +} diff --git a/util.ts b/util.ts index d05bea8c0..6a230ef3b 100644 --- a/util.ts +++ b/util.ts @@ -1,3 +1,5 @@ +import { Reader } from "deno"; + export function assert(cond: boolean, msg = "assert") { if (!cond) { throw Error(msg); -- cgit v1.2.3 From fb0b99408b1ce0c8061d654e9dae3fd8221efa6f Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 8 Nov 2018 12:58:43 -0500 Subject: Add tests for TextProtoReader.readMIMEHeader() Original: https://github.com/denoland/deno_std/commit/36edda18ab75ea8287088478d46e89e5e8d6be0f --- headers.ts | 34 ++++++++++++++++++++++ textproto.ts | 25 +++++++++-------- textproto_test.ts | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 132 insertions(+), 11 deletions(-) create mode 100644 headers.ts create mode 100644 textproto_test.ts diff --git a/headers.ts b/headers.ts new file mode 100644 index 000000000..9fe218195 --- /dev/null +++ b/headers.ts @@ -0,0 +1,34 @@ +// Fake headers to work around +// https://github.com/denoland/deno/issues/1173 + +function normalize(name: string, value?: string): [string, string] { + name = String(name).toLowerCase(); + value = String(value).trim(); + return [name, value]; +} + +export class Headers { + private map = new Map(); + + get(name: string): string | null { + let [name_] = normalize(name); + return this.map.get(name_); + } + + append(name: string, value: string): void { + [name, value] = normalize(name, value); + this.map.set(name, value); + } + + toString(): string { + let out = ""; + this.map.forEach((v, k) => { + out += `${k}: ${v}\n`; + }); + return out; + } + + [Symbol.iterator](): IterableIterator<[string, string]> { + return this.map[Symbol.iterator](); + } +} diff --git a/textproto.ts b/textproto.ts index b4336c90d..61ca45a8a 100644 --- a/textproto.ts +++ b/textproto.ts @@ -5,6 +5,7 @@ import { BufReader, BufState } from "./bufio.ts"; import { charCode } from "./util.ts"; +import { Headers } from "./headers.ts"; const asciiDecoder = new TextDecoder("ascii"); function str(buf: Uint8Array): string { @@ -53,37 +54,38 @@ export class TextProtoReader { * "Long-Key": {"Even Longer Value"}, * } */ - /* - async readMIMEHeader(): Promise { + async readMIMEHeader(): Promise<[Headers, BufState]> { let m = new Headers(); let line: Uint8Array; // The first line cannot start with a leading space. let [buf, err] = await this.r.peek(1); - if (buf[0] == charCode(' ') || buf[0] == charCode('\t')) { + if (buf[0] == charCode(" ") || buf[0] == charCode("\t")) { [line, err] = await this.readLineSlice(); } [buf, err] = await this.r.peek(1); - if (err == null && (buf[0] == charCode(' ') || buf[0] == charCode('\t'))) { - throw new ProtocolError(`malformed MIME header initial line: ${str(line)}`) + if (err == null && (buf[0] == charCode(" ") || buf[0] == charCode("\t"))) { + throw new ProtocolError( + `malformed MIME header initial line: ${str(line)}` + ); } while (true) { let [kv, err] = await this.readLineSlice(); // readContinuedLineSlice if (kv.byteLength == 0) { - return m; + return [m, err]; } // Key ends at first colon; should not have trailing spaces // but they appear in the wild, violating specs, so we remove // them if present. - let i = kv.indexOf(charCode(':')); + let i = kv.indexOf(charCode(":")); if (i < 0) { throw new ProtocolError(`malformed MIME header line: ${str(kv)}`); } let endKey = i; - while (endKey > 0 && kv[endKey - 1] == charCode(' ')) { + while (endKey > 0 && kv[endKey - 1] == charCode(" ")) { endKey--; } @@ -99,8 +101,10 @@ export class TextProtoReader { // Skip initial spaces in value. i++; // skip colon - while (i < kv.byteLength && - (kv[i] == charCode(' ') || kv[i] == charCode('\t'))) { + while ( + i < kv.byteLength && + (kv[i] == charCode(" ") || kv[i] == charCode("\t")) + ) { i++; } let value = str(kv.subarray(i)); @@ -112,7 +116,6 @@ export class TextProtoReader { } } } - */ async readLineSlice(): Promise<[Uint8Array, BufState]> { // this.closeDot(); diff --git a/textproto_test.ts b/textproto_test.ts new file mode 100644 index 000000000..32311a468 --- /dev/null +++ b/textproto_test.ts @@ -0,0 +1,84 @@ +// Based on https://github.com/golang/go/blob/891682/src/net/textproto/ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { BufReader } from "./bufio.ts"; +import { TextProtoReader } from "./textproto.ts"; +import { stringsReader } from "./buffer.ts"; +import { + test, + assert, + assertEqual +} from "https://deno.land/x/testing/testing.ts"; + +function reader(s: string): TextProtoReader { + return new TextProtoReader(new BufReader(stringsReader(s))); +} + +test(async function textprotoReader() { + let r = reader("line1\nline2\n"); + let [s, err] = await r.readLine(); + assertEqual(s, "line1"); + assert(err == null); + + [s, err] = await r.readLine(); + assertEqual(s, "line2"); + assert(err == null); + + [s, err] = await r.readLine(); + assertEqual(s, ""); + assert(err == "EOF"); +}); + +/* +test(async function textprotoReadMIMEHeader() { + let r = reader("my-key: Value 1 \r\nLong-key: Even \n Longer Value\r\nmy-Key: Value 2\r\n\n"); + let [m, err] = await r.readMIMEHeader(); + + console.log("Got headers", m.toString()); + want := MIMEHeader{ + "My-Key": {"Value 1", "Value 2"}, + "Long-Key": {"Even Longer Value"}, + } + if !reflect.DeepEqual(m, want) || err != nil { + t.Fatalf("ReadMIMEHeader: %v, %v; want %v", m, err, want) + } +}); +*/ + +test(async function textprotoReadMIMEHeaderSingle() { + let r = reader("Foo: bar\n\n"); + let [m, err] = await r.readMIMEHeader(); + assertEqual(m.get("Foo"), "bar"); + assert(!err); +}); + +// Test that we read slightly-bogus MIME headers seen in the wild, +// with spaces before colons, and spaces in keys. +test(async function textprotoReadMIMEHeaderNonCompliant() { + // Invalid HTTP response header as sent by an Axis security + // camera: (this is handled by IE, Firefox, Chrome, curl, etc.) + let r = reader( + "Foo: bar\r\n" + + "Content-Language: en\r\n" + + "SID : 0\r\n" + + "Audio Mode : None\r\n" + + "Privilege : 127\r\n\r\n" + ); + let [m, err] = await r.readMIMEHeader(); + console.log(m.toString()); + assert(!err); + /* + let want = MIMEHeader{ + "Foo": {"bar"}, + "Content-Language": {"en"}, + "Sid": {"0"}, + "Audio Mode": {"None"}, + "Privilege": {"127"}, + } + if !reflect.DeepEqual(m, want) || err != nil { + t.Fatalf("ReadMIMEHeader =\n%v, %v; want:\n%v", m, err, want) + } + */ +}); -- cgit v1.2.3 From 80b2067030abdf9f51b1d0eb9ceaaf76c2d09bfb Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 8 Nov 2018 15:03:45 -0500 Subject: Use async iterators for http server. Original: https://github.com/denoland/deno_std/commit/9377d154c5079a732d76a36a6ec5892d8da43087 --- http.ts | 98 +++++++++++++++++++++++++++++------------------------------- http_test.ts | 19 ++++++++++-- 2 files changed, 64 insertions(+), 53 deletions(-) diff --git a/http.ts b/http.ts index 4c209153a..c7ac88879 100644 --- a/http.ts +++ b/http.ts @@ -1,71 +1,67 @@ -import * as deno from "deno"; -import * as bufio from "./bufio.ts"; +import { listen, Conn } from "deno"; +import { BufReader, BufState } from "./bufio.ts"; import { TextProtoReader } from "./textproto.ts"; +import { Headers } from "./headers.ts"; -type Handler = (req: ServerRequest) => Promise; - -class Server { - _closing = false; - - constructor(readonly listener: deno.Listener) {} - - async serve(handler: Handler) { - while (!this._closing) { - const c = await this.listener.accept(); - const sc = new ServerConn(c); - sc.serve(handler); - } +export async function* serve(addr: string) { + const listener = listen("tcp", addr); + while (true) { + const c = await listener.accept(); + yield* serveConn(c); } + listener.close(); +} - close() { - this._closing = true; - this.listener.close(); +export async function* serveConn(c: Conn) { + let bufr = new BufReader(c); + try { + while (true) { + const req = await readRequest(bufr); + yield req; + } + } finally { + c.close(); } } -class ServerConn { - constructor(readonly c: deno.Conn) { - // TODO Use memory pool to obtain bufr and bufw. - this.bufr = new bufio.Reader(c); - this.bufw = new bufio.Writer(c); - } +interface Response { + status?: number; + body: string; +} - async serve(handler: Handler): Promise { - const buffer = new Uint8Array(1024); - try { - while (true) { - const req = readRequest(this.bufr); +class ServerRequest { + url: string; + method: string; + proto: string; - /* - const response = new TextEncoder().encode( - "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" - ); - await this.c.write(response); - */ - } - } finally { - this.c.close(); - } + respond(r: Response = { status: 200 }): Promise { + throw Error("not implemented"); } } -function readRequest(b: bufio.Reader): ServerRequest { +async function readRequest(b: BufReader): Promise { const tp = new TextProtoReader(b); const req = new ServerRequest(); // First line: GET /index.html HTTP/1.0 - const s = await tp.readLine(); - const [method, url, proto] = parseRequestLine(s); - console.log("readRequest", method, url); -} + let s: string; + let err: BufState; + [s, err] = await tp.readLine(); + const { method, url, proto } = parseRequestLine(s); + req.method = method; + req.url = url; + req.proto = proto; -// Returns [method, url, proto] -function parseRequestLine(line: string): [string, string, string] { - return line.split(" ", 3); + let headers: Headers; + [headers, err] = await tp.readMIMEHeader(); + + return req; } -export function listen(addr: string): Server { - const listener = deno.listen("tcp", addr); - const s = new Server(listener); - return s; +// Returns [method, url, proto] +function parseRequestLine( + line: string +): { method: string; url: string; proto: string } { + let [method, url, proto] = line.split(" ", 3); + return { method, url, proto }; } diff --git a/http_test.ts b/http_test.ts index 4a8867aba..1b16b0f0a 100644 --- a/http_test.ts +++ b/http_test.ts @@ -1,6 +1,21 @@ -//import { listen } from "./server.ts"; -import { test } from "https://deno.land/x/testing/testing.ts"; +import { serve } from "./http.ts"; +//import { test } from "https://deno.land/x/testing/testing.ts"; +const addr = "0.0.0.0:8000"; +const s = serve(addr); +console.log(`listening on http://${addr}/`); + +async function main() { + for await (const req of s) { + console.log("Req", req); + req.respond({ body: "Hello World\n" }); + } +} + +main(); + +/* test(function basic() { console.log("ok"); }); + */ -- cgit v1.2.3 From 9b78509ceb975df3dc9d795c7310dcc4c73436a3 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 8 Nov 2018 18:15:26 -0500 Subject: wip Original: https://github.com/denoland/deno_std/commit/ad578ab6fe75dd41585be741e378b92645258b28 --- bufio.ts | 10 ++++++++++ http.ts | 21 ++++++--------------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/bufio.ts b/bufio.ts index 8ff02b7e9..dccd3afc0 100644 --- a/bufio.ts +++ b/bufio.ts @@ -323,3 +323,13 @@ export class BufReader implements Reader { return [this.buf.subarray(this.r, this.r + n), err]; } } + +/** BufWriter implements buffering for an deno.Writer object. + * If an error occurs writing to a Writer, no more data will be + * accepted and all subsequent writes, and flush(), will return the error. + * After all data has been written, the client should call the + * flush() method to guarantee all data has been forwarded to + * the underlying deno.Writer. + */ +export class BufWriter implements Writer { +} diff --git a/http.ts b/http.ts index c7ac88879..c33bc97a2 100644 --- a/http.ts +++ b/http.ts @@ -33,8 +33,9 @@ class ServerRequest { url: string; method: string; proto: string; + headers: Headers; - respond(r: Response = { status: 200 }): Promise { + respond(r: Response): Promise { throw Error("not implemented"); } } @@ -43,25 +44,15 @@ async function readRequest(b: BufReader): Promise { const tp = new TextProtoReader(b); const req = new ServerRequest(); - // First line: GET /index.html HTTP/1.0 let s: string; let err: BufState; + + // First line: GET /index.html HTTP/1.0 [s, err] = await tp.readLine(); - const { method, url, proto } = parseRequestLine(s); - req.method = method; - req.url = url; - req.proto = proto; + [req.method, req.url, req.proto] = s.split(" ", 3); - let headers: Headers; - [headers, err] = await tp.readMIMEHeader(); + [req.headers, err] = await tp.readMIMEHeader(); return req; } -// Returns [method, url, proto] -function parseRequestLine( - line: string -): { method: string; url: string; proto: string } { - let [method, url, proto] = line.split(" ", 3); - return { method, url, proto }; -} -- cgit v1.2.3 From 5880827f33ab90d4d5f5ac2f9166fddc76614cfa Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Fri, 9 Nov 2018 13:25:30 -0500 Subject: First pass at BufWriter Original: https://github.com/denoland/deno_std/commit/9329cd76bd67b96fbeab6ef0b02703bd77a9b482 --- bufio.ts | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- bufio_test.ts | 35 +++++++++++++++++++- http.ts | 1 - 3 files changed, 136 insertions(+), 4 deletions(-) diff --git a/bufio.ts b/bufio.ts index dccd3afc0..2ad9bdd09 100644 --- a/bufio.ts +++ b/bufio.ts @@ -3,7 +3,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -import { Reader, ReadResult } from "deno"; +import { Reader, ReadResult, Writer } from "deno"; import { assert, charCode, copyBytes } from "./util.ts"; const DEFAULT_BUF_SIZE = 4096; @@ -32,7 +32,7 @@ export class BufReader implements Reader { } /** Returns the size of the underlying buffer in bytes. */ - get byteLength(): number { + size(): number { return this.buf.byteLength; } @@ -332,4 +332,104 @@ export class BufReader implements Reader { * the underlying deno.Writer. */ export class BufWriter implements Writer { + buf: Uint8Array; + n: number = 0; + err: null | Error = null; + + constructor(private wr: Writer, size = DEFAULT_BUF_SIZE) { + if (size <= 0) { + size = DEFAULT_BUF_SIZE; + } + this.buf = new Uint8Array(size); + } + + /** Size returns the size of the underlying buffer in bytes. */ + size(): number { + return this.buf.byteLength; + } + + /** Discards any unflushed buffered data, clears any error, and + * resets b to write its output to w. + */ + reset(w: Writer): void { + this.err = null; + this.n = 0; + this.wr = w; + } + + /** Flush writes any buffered data to the underlying io.Writer. */ + async flush(): Promise { + if (this.err != null) { + throw this.err; + } + if (this.n == 0) { + return; + } + + let n: number; + let err: Error = null; + try { + n = await this.wr.write(this.buf.subarray(0, this.n)); + } catch (e) { + err = e; + } + + if (n < this.n && err == null) { + err = new Error("ShortWrite"); + } + + if (err != null) { + if (n > 0 && n < this.n) { + this.buf.copyWithin(0, n, this.n); + } + this.n -= n; + this.err = err; + return; + } + this.n = 0; + } + + /** Returns how many bytes are unused in the buffer. */ + available(): number { + return this.buf.byteLength - this.n; + } + + /** buffered returns the number of bytes that have been written into the + * current buffer. + */ + buffered(): number { + return this.n; + } + + /** Writes the contents of p into the buffer. + * Returns the number of bytes written. + */ + async write(p: Uint8Array): Promise { + let nn = 0; + let n: number; + while (p.byteLength > this.available() && !this.err) { + if (this.buffered() == 0) { + // Large write, empty buffer. + // Write directly from p to avoid copy. + try { + n = await this.wr.write(p); + } catch (e) { + this.err = e; + } + } else { + n = copyBytes(this.buf, p, this.n); + this.n += n; + this.flush(); + } + nn += n; + p = p.subarray(n); + } + if (this.err) { + throw this.err; + } + n = copyBytes(this.buf, p, this.n); + this.n += n; + nn += n; + return nn; + } } diff --git a/bufio_test.ts b/bufio_test.ts index 9c89f0216..f3430a755 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -9,7 +9,7 @@ import { assert, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import { BufReader, BufState } from "./bufio.ts"; +import { BufReader, BufState, BufWriter } from "./bufio.ts"; import { Buffer, stringsReader } from "./buffer.ts"; import * as iotest from "./iotest.ts"; import { charCode, copyBytes } from "./util.ts"; @@ -289,3 +289,36 @@ test(async function bufioPeek() { } */ }); + +test(async function bufioWriter() { + const data = new Uint8Array(8192); + + for (let i = 0; i < data.byteLength; i++) { + data[i] = charCode(" ") + i % (charCode("~") - charCode(" ")); + } + + const w = new Buffer(); + for (let nwrite of bufsizes) { + for (let bs of bufsizes) { + // Write nwrite bytes using buffer size bs. + // Check that the right amount makes it out + // and that the data is correct. + + w.reset(); + const buf = new BufWriter(w, bs); + + const context = `nwrite=${nwrite} bufsize=${bs}`; + const n = await buf.write(data.subarray(0, nwrite)); + assertEqual(n, nwrite, context); + + await buf.flush(); + + const written = w.bytes(); + assertEqual(written.byteLength, nwrite); + + for (let l = 0; l < written.byteLength; l++) { + assertEqual(written[l], data[l]); + } + } + } +}); diff --git a/http.ts b/http.ts index c33bc97a2..0266501ae 100644 --- a/http.ts +++ b/http.ts @@ -55,4 +55,3 @@ async function readRequest(b: BufReader): Promise { return req; } - -- cgit v1.2.3 From 92455a0b67982bd28f23a09acb9e27dcb6f75e1d Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Fri, 9 Nov 2018 17:23:01 -0500 Subject: Basic http demo working. Original: https://github.com/denoland/deno_std/commit/805efdb7508f4b916645df49038b4c143c0de0a1 --- bufio.ts | 24 +++++++---- headers.ts | 34 --------------- http.ts | 72 +++++++++++++++++++++++++++---- http_status.ts | 134 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ http_test.ts | 5 ++- textproto.ts | 1 - 6 files changed, 216 insertions(+), 54 deletions(-) delete mode 100644 headers.ts create mode 100644 http_status.ts diff --git a/bufio.ts b/bufio.ts index 2ad9bdd09..819c610f9 100644 --- a/bufio.ts +++ b/bufio.ts @@ -12,7 +12,13 @@ const MAX_CONSECUTIVE_EMPTY_READS = 100; const CR = charCode("\r"); const LF = charCode("\n"); -export type BufState = null | "EOF" | "BufferFull" | "NoProgress" | Error; +export type BufState = + | null + | "EOF" + | "BufferFull" + | "ShortWrite" + | "NoProgress" + | Error; /** BufReader implements buffering for a Reader object. */ export class BufReader implements Reader { @@ -102,7 +108,7 @@ export class BufReader implements Reader { * At EOF, the count will be zero and err will be io.EOF. * To read exactly len(p) bytes, use io.ReadFull(b, p). */ - async read(p: ArrayBufferView): Promise { + async read(p: Uint8Array): Promise { let rr: ReadResult = { nread: p.byteLength, eof: false }; if (rr.nread === 0) { if (this.err) { @@ -334,7 +340,7 @@ export class BufReader implements Reader { export class BufWriter implements Writer { buf: Uint8Array; n: number = 0; - err: null | Error = null; + err: null | BufState = null; constructor(private wr: Writer, size = DEFAULT_BUF_SIZE) { if (size <= 0) { @@ -358,16 +364,16 @@ export class BufWriter implements Writer { } /** Flush writes any buffered data to the underlying io.Writer. */ - async flush(): Promise { + async flush(): Promise { if (this.err != null) { - throw this.err; + return this.err; } if (this.n == 0) { - return; + return null; } let n: number; - let err: Error = null; + let err: BufState = null; try { n = await this.wr.write(this.buf.subarray(0, this.n)); } catch (e) { @@ -375,7 +381,7 @@ export class BufWriter implements Writer { } if (n < this.n && err == null) { - err = new Error("ShortWrite"); + err = "ShortWrite"; } if (err != null) { @@ -384,7 +390,7 @@ export class BufWriter implements Writer { } this.n -= n; this.err = err; - return; + return err; } this.n = 0; } diff --git a/headers.ts b/headers.ts deleted file mode 100644 index 9fe218195..000000000 --- a/headers.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Fake headers to work around -// https://github.com/denoland/deno/issues/1173 - -function normalize(name: string, value?: string): [string, string] { - name = String(name).toLowerCase(); - value = String(value).trim(); - return [name, value]; -} - -export class Headers { - private map = new Map(); - - get(name: string): string | null { - let [name_] = normalize(name); - return this.map.get(name_); - } - - append(name: string, value: string): void { - [name, value] = normalize(name, value); - this.map.set(name, value); - } - - toString(): string { - let out = ""; - this.map.forEach((v, k) => { - out += `${k}: ${v}\n`; - }); - return out; - } - - [Symbol.iterator](): IterableIterator<[string, string]> { - return this.map[Symbol.iterator](); - } -} diff --git a/http.ts b/http.ts index 0266501ae..4a4f0ccd9 100644 --- a/http.ts +++ b/http.ts @@ -1,7 +1,8 @@ import { listen, Conn } from "deno"; -import { BufReader, BufState } from "./bufio.ts"; +import { BufReader, BufState, BufWriter } from "./bufio.ts"; import { TextProtoReader } from "./textproto.ts"; -import { Headers } from "./headers.ts"; +import { STATUS_TEXT } from "./http_status"; +import { assert } from "./util"; export async function* serve(addr: string) { const listener = listen("tcp", addr); @@ -14,9 +15,21 @@ export async function* serve(addr: string) { export async function* serveConn(c: Conn) { let bufr = new BufReader(c); + let bufw = new BufWriter(c); try { while (true) { - const req = await readRequest(bufr); + const [req, err] = await readRequest(bufr); + if (err == "EOF") { + break; + } + if (err == "ShortWrite") { + console.log("ShortWrite error"); + break; + } + if (err) { + throw err; + } + req.w = bufw; yield req; } } finally { @@ -26,7 +39,19 @@ export async function* serveConn(c: Conn) { interface Response { status?: number; - body: string; + headers?: Headers; + body?: Uint8Array; +} + +function setContentLength(r: Response): void { + if (r.body) { + if (!r.headers) { + r.headers = new Headers(); + } + if (!r.headers.has("content-length")) { + r.headers.append("Content-Length", r.body.byteLength.toString()); + } + } } class ServerRequest { @@ -34,13 +59,41 @@ class ServerRequest { method: string; proto: string; headers: Headers; + w: BufWriter; + + async respond(r: Response): Promise { + const protoMajor = 1; + const protoMinor = 1; + const statusCode = r.status || 200; + const statusText = STATUS_TEXT.get(statusCode); + if (!statusText) { + throw Error("bad status code"); + } - respond(r: Response): Promise { - throw Error("not implemented"); + let out = `HTTP/${protoMajor}.${protoMinor} ${r.status} ${statusText}\r\n`; + + setContentLength(r); + + if (r.headers) { + for (let [key, value] of r.headers) { + out += `${key}: ${value}\r\n`; + } + } + out += "\r\n"; + + const header = new TextEncoder().encode(out); + let n = await this.w.write(header); + assert(header.byteLength == n); + if (r.body) { + n = await this.w.write(r.body); + assert(r.body.byteLength == n); + } + + await this.w.flush(); } } -async function readRequest(b: BufReader): Promise { +async function readRequest(b: BufReader): Promise<[ServerRequest, BufState]> { const tp = new TextProtoReader(b); const req = new ServerRequest(); @@ -49,9 +102,12 @@ async function readRequest(b: BufReader): Promise { // First line: GET /index.html HTTP/1.0 [s, err] = await tp.readLine(); + if (err) { + return [null, err]; + } [req.method, req.url, req.proto] = s.split(" ", 3); [req.headers, err] = await tp.readMIMEHeader(); - return req; + return [req, err]; } diff --git a/http_status.ts b/http_status.ts new file mode 100644 index 000000000..a3006d319 --- /dev/null +++ b/http_status.ts @@ -0,0 +1,134 @@ +export enum Status { + Continue = 100, // RFC 7231, 6.2.1 + SwitchingProtocols = 101, // RFC 7231, 6.2.2 + Processing = 102, // RFC 2518, 10.1 + + OK = 200, // RFC 7231, 6.3.1 + Created = 201, // RFC 7231, 6.3.2 + Accepted = 202, // RFC 7231, 6.3.3 + NonAuthoritativeInfo = 203, // RFC 7231, 6.3.4 + NoContent = 204, // RFC 7231, 6.3.5 + ResetContent = 205, // RFC 7231, 6.3.6 + PartialContent = 206, // RFC 7233, 4.1 + MultiStatus = 207, // RFC 4918, 11.1 + AlreadyReported = 208, // RFC 5842, 7.1 + IMUsed = 226, // RFC 3229, 10.4.1 + + MultipleChoices = 300, // RFC 7231, 6.4.1 + MovedPermanently = 301, // RFC 7231, 6.4.2 + Found = 302, // RFC 7231, 6.4.3 + SeeOther = 303, // RFC 7231, 6.4.4 + NotModified = 304, // RFC 7232, 4.1 + UseProxy = 305, // RFC 7231, 6.4.5 + // _ = 306, // RFC 7231, 6.4.6 (Unused) + TemporaryRedirect = 307, // RFC 7231, 6.4.7 + PermanentRedirect = 308, // RFC 7538, 3 + + BadRequest = 400, // RFC 7231, 6.5.1 + Unauthorized = 401, // RFC 7235, 3.1 + PaymentRequired = 402, // RFC 7231, 6.5.2 + Forbidden = 403, // RFC 7231, 6.5.3 + NotFound = 404, // RFC 7231, 6.5.4 + MethodNotAllowed = 405, // RFC 7231, 6.5.5 + NotAcceptable = 406, // RFC 7231, 6.5.6 + ProxyAuthRequired = 407, // RFC 7235, 3.2 + RequestTimeout = 408, // RFC 7231, 6.5.7 + Conflict = 409, // RFC 7231, 6.5.8 + Gone = 410, // RFC 7231, 6.5.9 + LengthRequired = 411, // RFC 7231, 6.5.10 + PreconditionFailed = 412, // RFC 7232, 4.2 + RequestEntityTooLarge = 413, // RFC 7231, 6.5.11 + RequestURITooLong = 414, // RFC 7231, 6.5.12 + UnsupportedMediaType = 415, // RFC 7231, 6.5.13 + RequestedRangeNotSatisfiable = 416, // RFC 7233, 4.4 + ExpectationFailed = 417, // RFC 7231, 6.5.14 + Teapot = 418, // RFC 7168, 2.3.3 + MisdirectedRequest = 421, // RFC 7540, 9.1.2 + UnprocessableEntity = 422, // RFC 4918, 11.2 + Locked = 423, // RFC 4918, 11.3 + FailedDependency = 424, // RFC 4918, 11.4 + UpgradeRequired = 426, // RFC 7231, 6.5.15 + PreconditionRequired = 428, // RFC 6585, 3 + TooManyRequests = 429, // RFC 6585, 4 + RequestHeaderFieldsTooLarge = 431, // RFC 6585, 5 + UnavailableForLegalReasons = 451, // RFC 7725, 3 + + InternalServerError = 500, // RFC 7231, 6.6.1 + NotImplemented = 501, // RFC 7231, 6.6.2 + BadGateway = 502, // RFC 7231, 6.6.3 + ServiceUnavailable = 503, // RFC 7231, 6.6.4 + GatewayTimeout = 504, // RFC 7231, 6.6.5 + HTTPVersionNotSupported = 505, // RFC 7231, 6.6.6 + VariantAlsoNegotiates = 506, // RFC 2295, 8.1 + InsufficientStorage = 507, // RFC 4918, 11.5 + LoopDetected = 508, // RFC 5842, 7.2 + NotExtended = 510, // RFC 2774, 7 + NetworkAuthenticationRequired = 511 // RFC 6585, 6 +} + +export const STATUS_TEXT = new Map([ + [Status.Continue, "Continue"], + [Status.SwitchingProtocols, "Switching Protocols"], + [Status.Processing, "Processing"], + + [Status.OK, "OK"], + [Status.Created, "Created"], + [Status.Accepted, "Accepted"], + [Status.NonAuthoritativeInfo, "Non-Authoritative Information"], + [Status.NoContent, "No Content"], + [Status.ResetContent, "Reset Content"], + [Status.PartialContent, "Partial Content"], + [Status.MultiStatus, "Multi-Status"], + [Status.AlreadyReported, "Already Reported"], + [Status.IMUsed, "IM Used"], + + [Status.MultipleChoices, "Multiple Choices"], + [Status.MovedPermanently, "Moved Permanently"], + [Status.Found, "Found"], + [Status.SeeOther, "See Other"], + [Status.NotModified, "Not Modified"], + [Status.UseProxy, "Use Proxy"], + [Status.TemporaryRedirect, "Temporary Redirect"], + [Status.PermanentRedirect, "Permanent Redirect"], + + [Status.BadRequest, "Bad Request"], + [Status.Unauthorized, "Unauthorized"], + [Status.PaymentRequired, "Payment Required"], + [Status.Forbidden, "Forbidden"], + [Status.NotFound, "Not Found"], + [Status.MethodNotAllowed, "Method Not Allowed"], + [Status.NotAcceptable, "Not Acceptable"], + [Status.ProxyAuthRequired, "Proxy Authentication Required"], + [Status.RequestTimeout, "Request Timeout"], + [Status.Conflict, "Conflict"], + [Status.Gone, "Gone"], + [Status.LengthRequired, "Length Required"], + [Status.PreconditionFailed, "Precondition Failed"], + [Status.RequestEntityTooLarge, "Request Entity Too Large"], + [Status.RequestURITooLong, "Request URI Too Long"], + [Status.UnsupportedMediaType, "Unsupported Media Type"], + [Status.RequestedRangeNotSatisfiable, "Requested Range Not Satisfiable"], + [Status.ExpectationFailed, "Expectation Failed"], + [Status.Teapot, "I'm a teapot"], + [Status.MisdirectedRequest, "Misdirected Request"], + [Status.UnprocessableEntity, "Unprocessable Entity"], + [Status.Locked, "Locked"], + [Status.FailedDependency, "Failed Dependency"], + [Status.UpgradeRequired, "Upgrade Required"], + [Status.PreconditionRequired, "Precondition Required"], + [Status.TooManyRequests, "Too Many Requests"], + [Status.RequestHeaderFieldsTooLarge, "Request Header Fields Too Large"], + [Status.UnavailableForLegalReasons, "Unavailable For Legal Reasons"], + + [Status.InternalServerError, "Internal Server Error"], + [Status.NotImplemented, "Not Implemented"], + [Status.BadGateway, "Bad Gateway"], + [Status.ServiceUnavailable, "Service Unavailable"], + [Status.GatewayTimeout, "Gateway Timeout"], + [Status.HTTPVersionNotSupported, "HTTP Version Not Supported"], + [Status.VariantAlsoNegotiates, "Variant Also Negotiates"], + [Status.InsufficientStorage, "Insufficient Storage"], + [Status.LoopDetected, "Loop Detected"], + [Status.NotExtended, "Not Extended"], + [Status.NetworkAuthenticationRequired, "Network Authentication Required"] +]); diff --git a/http_test.ts b/http_test.ts index 1b16b0f0a..b0007a892 100644 --- a/http_test.ts +++ b/http_test.ts @@ -5,10 +5,11 @@ const addr = "0.0.0.0:8000"; const s = serve(addr); console.log(`listening on http://${addr}/`); +const body = new TextEncoder().encode("Hello World\n"); + async function main() { for await (const req of s) { - console.log("Req", req); - req.respond({ body: "Hello World\n" }); + await req.respond({ status: 200, body }); } } diff --git a/textproto.ts b/textproto.ts index 61ca45a8a..50c0fea9c 100644 --- a/textproto.ts +++ b/textproto.ts @@ -5,7 +5,6 @@ import { BufReader, BufState } from "./bufio.ts"; import { charCode } from "./util.ts"; -import { Headers } from "./headers.ts"; const asciiDecoder = new TextDecoder("ascii"); function str(buf: Uint8Array): string { -- cgit v1.2.3 From e931c53a234a55f29169415cac016e4d792f7f97 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Mon, 12 Nov 2018 14:09:50 -0500 Subject: Use Uint8Array instead of ArrayBufferView Original: https://github.com/denoland/deno_std/commit/0c8ad6eb1af05b259cc7c622e87e27b402886c96 --- buffer.ts | 10 ++-------- bufio_test.ts | 2 +- http_test.ts | 3 ++- iotest.ts | 6 +++--- 4 files changed, 8 insertions(+), 13 deletions(-) diff --git a/buffer.ts b/buffer.ts index ba2715cef..d177bc18d 100644 --- a/buffer.ts +++ b/buffer.ts @@ -120,10 +120,7 @@ export class Buffer implements Reader, Writer { * is drained. The return value n is the number of bytes read. If the * buffer has no data to return, eof in the response will be true. */ - async read(p: ArrayBufferView): Promise { - if (!(p instanceof Uint8Array)) { - throw Error("Only Uint8Array supported"); - } + async read(p: Uint8Array): Promise { if (this.empty()) { // Buffer is empty, reset to recover space. this.reset(); @@ -139,11 +136,8 @@ export class Buffer implements Reader, Writer { return { nread, eof: false }; } - async write(p: ArrayBufferView): Promise { + async write(p: Uint8Array): Promise { const m = this._grow(p.byteLength); - if (!(p instanceof Uint8Array)) { - throw Error("Only Uint8Array supported"); - } return copyBytes(this.buf, p, m); } diff --git a/bufio_test.ts b/bufio_test.ts index f3430a755..5f32500a7 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -159,7 +159,7 @@ const testOutput = encoder.encode("0123456789abcdefghijklmnopqrstuvwxy"); class TestReader implements Reader { constructor(private data: Uint8Array, private stride: number) {} - async read(buf: ArrayBufferView): Promise { + async read(buf: Uint8Array): Promise { let nread = this.stride; if (nread > this.data.byteLength) { nread = this.data.byteLength; diff --git a/http_test.ts b/http_test.ts index b0007a892..e6cb87f01 100644 --- a/http_test.ts +++ b/http_test.ts @@ -5,7 +5,8 @@ const addr = "0.0.0.0:8000"; const s = serve(addr); console.log(`listening on http://${addr}/`); -const body = new TextEncoder().encode("Hello World\n"); +const body = (new TextEncoder()).encode("Hello World\n"); + async function main() { for await (const req of s) { diff --git a/iotest.ts b/iotest.ts index e2498e155..e3a42f58a 100644 --- a/iotest.ts +++ b/iotest.ts @@ -11,7 +11,7 @@ import { Reader, ReadResult } from "deno"; export class OneByteReader implements Reader { constructor(readonly r: Reader) {} - async read(p: ArrayBufferView): Promise { + async read(p: Uint8Array): Promise { if (p.byteLength === 0) { return { nread: 0, eof: false }; } @@ -28,7 +28,7 @@ export class OneByteReader implements Reader { export class HalfReader implements Reader { constructor(readonly r: Reader) {} - async read(p: ArrayBufferView): Promise { + async read(p: Uint8Array): Promise { if (!(p instanceof Uint8Array)) { throw Error("expected Uint8Array"); } @@ -51,7 +51,7 @@ export class TimeoutReader implements Reader { count = 0; constructor(readonly r: Reader) {} - async read(p: ArrayBufferView): Promise { + async read(p: Uint8Array): Promise { this.count++; if (this.count === 2) { throw new ErrTimeout(); -- cgit v1.2.3 From 6a7c01c2f039c9e3be8a5c4694322dc0a39e78df Mon Sep 17 00:00:00 2001 From: hashrock Date: Sat, 1 Dec 2018 16:40:04 +0900 Subject: Update usage (denoland/deno_std#2) Original: https://github.com/denoland/deno_std/commit/f574e3c6dbb1728c149a3478b11873e03b5ca439 --- README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 614e53087..ee6009304 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,12 @@ Usage: ```typescript import { serve } from "https://deno.land/x/net/http.ts"; const s = serve("0.0.0.0:8000"); -for await (const req of s) { - req.respond({ body: "Hello World\n" }); + +async function main() { + for await (const req of s) { + req.respond({ body: new TextEncoder().encode("Hello World\n") }); + } } + +main(); ``` -- cgit v1.2.3 From 79a1de9b140318837255476df36161d24147f4c6 Mon Sep 17 00:00:00 2001 From: zhmushan Date: Wed, 5 Dec 2018 09:34:35 +0800 Subject: fix statusCode Original: https://github.com/denoland/deno_std/commit/5fbbc2c46c67147415d70499b12630c4934c3b34 --- http.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http.ts b/http.ts index 4a4f0ccd9..c7d2851c0 100644 --- a/http.ts +++ b/http.ts @@ -70,7 +70,7 @@ class ServerRequest { throw Error("bad status code"); } - let out = `HTTP/${protoMajor}.${protoMinor} ${r.status} ${statusText}\r\n`; + let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`; setContentLength(r); -- cgit v1.2.3 From a34bc9040dc86efe5dfa9e89a6d4daadb425891d Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 6 Dec 2018 14:35:41 -0500 Subject: Use Utf8 instead of ASCII in TextDecoder See https://github.com/denoland/deno/issues/1288 Original: https://github.com/denoland/deno_std/commit/718d1da8535d9ee8c99a33b7f62b6235eb3a6824 --- textproto.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/textproto.ts b/textproto.ts index 50c0fea9c..4c4b92627 100644 --- a/textproto.ts +++ b/textproto.ts @@ -6,7 +6,7 @@ import { BufReader, BufState } from "./bufio.ts"; import { charCode } from "./util.ts"; -const asciiDecoder = new TextDecoder("ascii"); +const asciiDecoder = new TextDecoder(); function str(buf: Uint8Array): string { if (buf == null) { return ""; -- cgit v1.2.3 From 17c255581dbeff6bad6fe385b6cdee174e3f93ae Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Thu, 6 Dec 2018 16:08:21 -0500 Subject: Unblock server on multiple HTTP requests (denoland/deno_std#3) Original: https://github.com/denoland/deno_std/commit/1bf555ab2f9c6074b07697d72cb93f276ecf5bb1 --- http.ts | 108 +++++++++++++++++++++++++++++++++++++++++++---------------- http_test.ts | 3 +- 2 files changed, 80 insertions(+), 31 deletions(-) diff --git a/http.ts b/http.ts index c7d2851c0..2dab9e1e5 100644 --- a/http.ts +++ b/http.ts @@ -4,37 +4,82 @@ import { TextProtoReader } from "./textproto.ts"; import { STATUS_TEXT } from "./http_status"; import { assert } from "./util"; -export async function* serve(addr: string) { - const listener = listen("tcp", addr); - while (true) { - const c = await listener.accept(); - yield* serveConn(c); +interface Deferred { + promise: Promise<{}>; + resolve: () => void; + reject: () => void; +} + +function deferred(): Deferred { + let resolve, reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { + promise, + resolve, + reject + }; +} + +interface ServeEnv { + reqQueue: ServerRequest[]; + serveDeferred: Deferred; +} + +// Continuously read more requests from conn until EOF +// Mutually calling with maybeHandleReq +// TODO: make them async function after this change is done +// https://github.com/tc39/ecma262/pull/1250 +// See https://v8.dev/blog/fast-async +export function serveConn(env: ServeEnv, conn: Conn) { + readRequest(conn).then(maybeHandleReq.bind(null, env, conn)); +} +function maybeHandleReq(env: ServeEnv, conn: Conn, maybeReq: any) { + const [req, _err] = maybeReq; + if (_err) { + conn.close(); // assume EOF for now... + return; } - listener.close(); + env.reqQueue.push(req); // push req to queue + env.serveDeferred.resolve(); // signal while loop to process it + // TODO: protection against client req flooding + serveConn(env, conn); // try read more (reusing connection) } -export async function* serveConn(c: Conn) { - let bufr = new BufReader(c); - let bufw = new BufWriter(c); - try { - while (true) { - const [req, err] = await readRequest(bufr); - if (err == "EOF") { - break; - } - if (err == "ShortWrite") { - console.log("ShortWrite error"); - break; - } - if (err) { - throw err; - } - req.w = bufw; - yield req; +export async function* serve(addr: string) { + const listener = listen("tcp", addr); + const env: ServeEnv = { + reqQueue: [], // in case multiple promises are ready + serveDeferred: deferred() + }; + + // Routine that keeps calling accept + const acceptRoutine = () => { + const handleConn = (conn: Conn) => { + serveConn(env, conn); // don't block + scheduleAccept(); // schedule next accept + }; + const scheduleAccept = () => { + listener.accept().then(handleConn); + }; + scheduleAccept(); + }; + + acceptRoutine(); + + // Loop hack to allow yield (yield won't work in callbacks) + while (true) { + await env.serveDeferred.promise; + env.serveDeferred = deferred(); // use a new deferred + let queueToProcess = env.reqQueue; + env.reqQueue = []; + for (const result of queueToProcess) { + yield result; } - } finally { - c.close(); } + listener.close(); } interface Response { @@ -75,7 +120,7 @@ class ServerRequest { setContentLength(r); if (r.headers) { - for (let [key, value] of r.headers) { + for (const [key, value] of r.headers) { out += `${key}: ${value}\r\n`; } } @@ -93,9 +138,12 @@ class ServerRequest { } } -async function readRequest(b: BufReader): Promise<[ServerRequest, BufState]> { - const tp = new TextProtoReader(b); +async function readRequest(c: Conn): Promise<[ServerRequest, BufState]> { + const bufr = new BufReader(c); + const bufw = new BufWriter(c); const req = new ServerRequest(); + req.w = bufw; + const tp = new TextProtoReader(bufr); let s: string; let err: BufState; @@ -109,5 +157,7 @@ async function readRequest(b: BufReader): Promise<[ServerRequest, BufState]> { [req.headers, err] = await tp.readMIMEHeader(); + // TODO: handle body + return [req, err]; } diff --git a/http_test.ts b/http_test.ts index e6cb87f01..b0007a892 100644 --- a/http_test.ts +++ b/http_test.ts @@ -5,8 +5,7 @@ const addr = "0.0.0.0:8000"; const s = serve(addr); console.log(`listening on http://${addr}/`); -const body = (new TextEncoder()).encode("Hello World\n"); - +const body = new TextEncoder().encode("Hello World\n"); async function main() { for await (const req of s) { -- cgit v1.2.3 From c5871cb996d42eec2453b86003f305ec62ee3e46 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 6 Dec 2018 17:18:10 -0500 Subject: Format Original: https://github.com/denoland/deno_std/commit/f3bce9c7b8e75846c33d4b8672510092b92b3139 --- buffer_test.ts | 2 +- bufio_test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/buffer_test.ts b/buffer_test.ts index 9a71e80a3..1958f8e97 100644 --- a/buffer_test.ts +++ b/buffer_test.ts @@ -17,7 +17,7 @@ function init() { if (testBytes == null) { testBytes = new Uint8Array(N); for (let i = 0; i < N; i++) { - testBytes[i] = "a".charCodeAt(0) + i % 26; + testBytes[i] = "a".charCodeAt(0) + (i % 26); } const decoder = new TextDecoder(); testString = decoder.decode(testBytes); diff --git a/bufio_test.ts b/bufio_test.ts index 5f32500a7..fb5dc23e8 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -109,7 +109,7 @@ test(async function bufioBufReader() { for (let i = 0; i < texts.length - 1; i++) { texts[i] = str + "\n"; all += texts[i]; - str += String.fromCharCode(i % 26 + 97); + str += String.fromCharCode((i % 26) + 97); } texts[texts.length - 1] = all; @@ -294,7 +294,7 @@ test(async function bufioWriter() { const data = new Uint8Array(8192); for (let i = 0; i < data.byteLength; i++) { - data[i] = charCode(" ") + i % (charCode("~") - charCode(" ")); + data[i] = charCode(" ") + (i % (charCode("~") - charCode(" "))); } const w = new Buffer(); -- cgit v1.2.3 From 16aedf68ea056c312edd8f857a57c143c4f21f50 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 6 Dec 2018 17:19:12 -0500 Subject: Add http_bench.ts Original: https://github.com/denoland/deno_std/commit/82ceb596f3d1f75b1711117767e26cfac8b64945 --- http_bench.ts | 15 +++++++++++++++ http_test.ts | 22 ---------------------- 2 files changed, 15 insertions(+), 22 deletions(-) create mode 100644 http_bench.ts delete mode 100644 http_test.ts diff --git a/http_bench.ts b/http_bench.ts new file mode 100644 index 000000000..9b4cff464 --- /dev/null +++ b/http_bench.ts @@ -0,0 +1,15 @@ +import * as deno from "deno"; +import { serve } from "https://deno.land/x/net/http.ts"; + +const addr = deno.args[1] || "127.0.0.1:4500"; +const server = serve(addr); + +const body = new TextEncoder().encode("Hello World"); + +async function main(): Promise { + for await (const request of server) { + await request.respond({ status: 200, body }); + } +} + +main(); diff --git a/http_test.ts b/http_test.ts deleted file mode 100644 index b0007a892..000000000 --- a/http_test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { serve } from "./http.ts"; -//import { test } from "https://deno.land/x/testing/testing.ts"; - -const addr = "0.0.0.0:8000"; -const s = serve(addr); -console.log(`listening on http://${addr}/`); - -const body = new TextEncoder().encode("Hello World\n"); - -async function main() { - for await (const req of s) { - await req.respond({ status: 200, body }); - } -} - -main(); - -/* -test(function basic() { - console.log("ok"); -}); - */ -- cgit v1.2.3 From 2516281306a5d49fc987a18461a4982625c890f8 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 6 Dec 2018 17:21:55 -0500 Subject: Relative import for http_bench.ts Original: https://github.com/denoland/deno_std/commit/958dadc8752f1aface8cff39c56011b016fb1460 --- http_bench.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http_bench.ts b/http_bench.ts index 9b4cff464..8e1e24ad6 100644 --- a/http_bench.ts +++ b/http_bench.ts @@ -1,5 +1,5 @@ import * as deno from "deno"; -import { serve } from "https://deno.land/x/net/http.ts"; +import { serve } from "./http.ts"; const addr = deno.args[1] || "127.0.0.1:4500"; const server = serve(addr); -- cgit v1.2.3 From 2b360c60a5b7bfd9b1ac3c1afc8f38ffb9209d32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Sun, 9 Dec 2018 18:44:13 +0100 Subject: set content-length for bodyless response Original: https://github.com/denoland/deno_std/commit/0e82a4249ead38be9ff0e35b2df97eb6dc8ca139 --- http.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/http.ts b/http.ts index 2dab9e1e5..e709dd4a3 100644 --- a/http.ts +++ b/http.ts @@ -89,13 +89,12 @@ interface Response { } function setContentLength(r: Response): void { - if (r.body) { - if (!r.headers) { - r.headers = new Headers(); - } - if (!r.headers.has("content-length")) { - r.headers.append("Content-Length", r.body.byteLength.toString()); - } + if (!r.headers) { + r.headers = new Headers(); + } + if (!r.headers.has("content-length")) { + const bodyLength = r.body ? r.body.byteLength : 0 + r.headers.append("Content-Length", bodyLength.toString()); } } -- cgit v1.2.3 From 2b1733e936b5fff34583628367bbe99244041d55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Sun, 9 Dec 2018 21:35:26 +0100 Subject: Simple file server (denoland/deno_std#11) Original: https://github.com/denoland/deno_std/commit/c8e5d98900884f583d91c7c2526fca8bbc50be1b --- file_server.ts | 42 ++++++++++++++++++++++++++++++++++-------- http.ts | 8 ++++++++ 2 files changed, 42 insertions(+), 8 deletions(-) mode change 100644 => 100755 file_server.ts diff --git a/file_server.ts b/file_server.ts old mode 100644 new mode 100755 index d5deccf3c..498f9b9d2 --- a/file_server.ts +++ b/file_server.ts @@ -1,18 +1,44 @@ +#!/usr/bin/env deno --allow-net + +// This program serves files in the current directory over HTTP. +// TODO Supply the directory to serve as a CLI argument. +// TODO Stream responses instead of reading them into memory. +// TODO Add tests like these: +// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js + import { listenAndServe } from "./http.ts"; -import { open, cwd } from "deno"; +import { cwd, readFile, DenoError, ErrorKind } from "deno"; const addr = "0.0.0.0:4500"; -const d = cwd(); +const currentDir = cwd(); + +const encoder = new TextEncoder(); + +listenAndServe(addr, async req => { + const fileName = req.url.replace(/\/$/, '/index.html'); + const filePath = currentDir + fileName; + let file; -listenAndServe(addr, async req => { - const filename = d + "/" + req.url; - let res; try { - res = { status: 200, body: open(filename) }; + file = await readFile(filePath); } catch (e) { - res = { status: 500, body: "bad" }; + if (e instanceof DenoError && e.kind === ErrorKind.NotFound) { + await req.respond({ status: 404, body: encoder.encode("Not found") }); + } else { + await req.response({ status: 500, body: encoder.encode("Internal server error") }); + } + return; + } + + const headers = new Headers(); + headers.set('content-type', 'octet-stream'); + + const res = { + status: 200, + body: file, + headers, } - req.respond(res); + await req.respond(res); }); console.log(`HTTP server listening on http://${addr}/`); diff --git a/http.ts b/http.ts index e709dd4a3..508d1ecaa 100644 --- a/http.ts +++ b/http.ts @@ -82,6 +82,14 @@ export async function* serve(addr: string) { listener.close(); } +export async function listenAndServe(addr: string, handler: (ServerRequest) => void) { + const server = serve(addr); + + for await (const request of server) { + await handler(request); + } +} + interface Response { status?: number; headers?: Headers; -- cgit v1.2.3 From 335343f51fbea2303f904007a5a12b779919918b Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Sun, 9 Dec 2018 15:45:05 -0500 Subject: Update travis to use v0.2.2 explicitly Original: https://github.com/denoland/deno_std/commit/721306e7269301bde5dd192f941e0c92a4bd162e --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 7da118d4d..b3b2391af 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: python install: -- curl -sSf https://raw.githubusercontent.com/denoland/deno_install/master/install.py | python +- curl -L https://deno.land/x/install/install.py | python - v0.2.2 - export PATH="$HOME/.deno/bin:$PATH" script: -- cgit v1.2.3 From 626cef41b60b3f1802655fd5ea4f638db4934466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E6=9D=89?= Date: Mon, 10 Dec 2018 09:17:55 +0800 Subject: supply the directory to serve as CLI argument (denoland/deno_std#13) Original: https://github.com/denoland/deno_std/commit/7cd4d9f4eaa4b1d167306b9000af30421319600a --- file_server.ts | 16 +++++++++------- http.ts | 2 +- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/file_server.ts b/file_server.ts index 498f9b9d2..9dcac8704 100755 --- a/file_server.ts +++ b/file_server.ts @@ -1,20 +1,22 @@ #!/usr/bin/env deno --allow-net // This program serves files in the current directory over HTTP. -// TODO Supply the directory to serve as a CLI argument. // TODO Stream responses instead of reading them into memory. // TODO Add tests like these: // https://github.com/indexzero/http-server/blob/master/test/http-server-test.js -import { listenAndServe } from "./http.ts"; -import { cwd, readFile, DenoError, ErrorKind } from "deno"; +import { listenAndServe } from "./http"; +import { cwd, readFile, DenoError, ErrorKind, args } from "deno"; const addr = "0.0.0.0:4500"; -const currentDir = cwd(); - +let currentDir = cwd(); +const target = args[1]; +if (target) { + currentDir = `${currentDir}/${target}`; +} const encoder = new TextEncoder(); -listenAndServe(addr, async req => { +listenAndServe(addr, async req => { const fileName = req.url.replace(/\/$/, '/index.html'); const filePath = currentDir + fileName; let file; @@ -25,7 +27,7 @@ listenAndServe(addr, async req => { if (e instanceof DenoError && e.kind === ErrorKind.NotFound) { await req.respond({ status: 404, body: encoder.encode("Not found") }); } else { - await req.response({ status: 500, body: encoder.encode("Internal server error") }); + await req.respond({ status: 500, body: encoder.encode("Internal server error") }); } return; } diff --git a/http.ts b/http.ts index 508d1ecaa..b11e2b369 100644 --- a/http.ts +++ b/http.ts @@ -82,7 +82,7 @@ export async function* serve(addr: string) { listener.close(); } -export async function listenAndServe(addr: string, handler: (ServerRequest) => void) { +export async function listenAndServe(addr: string, handler: (req: ServerRequest) => void) { const server = serve(addr); for await (const request of server) { -- cgit v1.2.3 From a691d9257b89cc210de6371138508c76aa288aba Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Tue, 11 Dec 2018 13:33:52 -0500 Subject: Add file server to README Original: https://github.com/denoland/deno_std/commit/f1f1f39cd3618824534d16b2588e97ecbc6c2681 --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index ee6009304..3963e19a6 100644 --- a/README.md +++ b/README.md @@ -16,3 +16,13 @@ async function main() { main(); ``` + +## File Server + +A small program for serving local files over HTTP. + +Add the following to your `.bash_profile` +``` +alias file_server="deno https://deno.land/x/net/file_server.ts --allow-net" +``` + -- cgit v1.2.3 From b94530332910c0b85553dc91fa1912bce308df3c Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Tue, 11 Dec 2018 17:56:32 -0500 Subject: Serve directory for file server & Fix bufio flush bug (denoland/deno_std#15) Original: https://github.com/denoland/deno_std/commit/b78f4e9fbd477b026f1a309c64f4f8f75cd4d5d6 --- .travis.yml | 2 +- bufio.ts | 2 +- file_server.ts | 187 ++++++++++++++++++++++++++++++++++++++++++++++------ file_server_test.ts | 46 +++++++++++++ http.ts | 13 ++-- test.ts | 15 +++++ 6 files changed, 239 insertions(+), 26 deletions(-) create mode 100644 file_server_test.ts diff --git a/.travis.yml b/.travis.yml index b3b2391af..8c4abc16f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,4 +5,4 @@ install: - export PATH="$HOME/.deno/bin:$PATH" script: -- deno test.ts +- deno test.ts --allow-run --allow-net diff --git a/bufio.ts b/bufio.ts index 819c610f9..a1f673653 100644 --- a/bufio.ts +++ b/bufio.ts @@ -425,7 +425,7 @@ export class BufWriter implements Writer { } else { n = copyBytes(this.buf, p, this.n); this.n += n; - this.flush(); + await this.flush(); } nn += n; p = p.subarray(n); diff --git a/file_server.ts b/file_server.ts index 9dcac8704..d2b9fe0b0 100755 --- a/file_server.ts +++ b/file_server.ts @@ -5,42 +5,191 @@ // TODO Add tests like these: // https://github.com/indexzero/http-server/blob/master/test/http-server-test.js -import { listenAndServe } from "./http"; -import { cwd, readFile, DenoError, ErrorKind, args } from "deno"; +import { listenAndServe, ServerRequest, setContentLength } from "./http"; +import { cwd, readFile, DenoError, ErrorKind, args, stat, readDir } from "deno"; + +const dirViewerTemplate = ` + + + + + + + Deno File Server + + + +

Index of <%DIRNAME%>

+ + + <%CONTENTS%> +
ModeSizeName
+ + +`; -const addr = "0.0.0.0:4500"; let currentDir = cwd(); const target = args[1]; if (target) { currentDir = `${currentDir}/${target}`; } +const addr = `0.0.0.0:${args[2] || 4500}`; const encoder = new TextEncoder(); -listenAndServe(addr, async req => { - const fileName = req.url.replace(/\/$/, '/index.html'); - const filePath = currentDir + fileName; - let file; +function modeToString(isDir: boolean, maybeMode: number | null) { + const modeMap = ["---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"]; - try { - file = await readFile(filePath); - } catch (e) { - if (e instanceof DenoError && e.kind === ErrorKind.NotFound) { - await req.respond({ status: 404, body: encoder.encode("Not found") }); - } else { - await req.respond({ status: 500, body: encoder.encode("Internal server error") }); + if (maybeMode === null) { + return "(unknown mode)"; + } + const mode = maybeMode!.toString(8); + if (mode.length < 3) { + return "(unknown mode)"; + } + let output = ""; + mode + .split("") + .reverse() + .slice(0, 3) + .forEach(v => { + output = modeMap[+v] + output; + }); + output = `(${isDir ? "d" : "-"}${output})`; + return output; +} + +function fileLenToString(len: number) { + const multipler = 1024; + let base = 1; + const suffix = ["B", "K", "M", "G", "T"]; + let suffixIndex = 0; + + while (base * multipler < len) { + if (suffixIndex >= suffix.length - 1) { + break; } - return; + base *= multipler; + suffixIndex++; } - + + return `${(len / base).toFixed(2)}${suffix[suffixIndex]}`; +} + +function createDirEntryDisplay( + name: string, + path: string, + size: number | null, + mode: number | null, + isDir: boolean +) { + const sizeStr = size === null ? "" : "" + fileLenToString(size!); + return ` + ${modeToString( + isDir, + mode + )}${sizeStr}${name}${ + isDir ? "/" : "" + } + + `; +} + +// TODO: simplify this after deno.stat and deno.readDir are fixed +async function serveDir(req: ServerRequest, dirPath: string, dirName: string) { + // dirname has no prefix + const listEntry: string[] = []; + const fileInfos = await readDir(dirPath); + for (const info of fileInfos) { + if (info.name === "index.html" && info.isFile()) { + // in case index.html as dir... + await serveFile(req, info.path); + return; + } + // Yuck! + let mode = null; + try { + mode = (await stat(info.path)).mode; + } catch (e) {} + listEntry.push( + createDirEntryDisplay( + info.name, + dirName + "/" + info.name, + info.isFile() ? info.len : null, + mode, + info.isDirectory() + ) + ); + } + + const page = new TextEncoder().encode( + dirViewerTemplate + .replace("<%DIRNAME%>", dirName + "/") + .replace("<%CONTENTS%>", listEntry.join("")) + ); + const headers = new Headers(); - headers.set('content-type', 'octet-stream'); + headers.set("content-type", "text/html"); + + const res = { + status: 200, + body: page, + headers + }; + setContentLength(res); + await req.respond(res); +} + +async function serveFile(req: ServerRequest, filename: string) { + let file = await readFile(filename); + const headers = new Headers(); + headers.set("content-type", "octet-stream"); const res = { status: 200, body: file, - headers, - } + headers + }; await req.respond(res); +} + +async function serveFallback(req: ServerRequest, e: Error) { + if ( + e instanceof DenoError && + (e as DenoError).kind === ErrorKind.NotFound + ) { + await req.respond({ status: 404, body: encoder.encode("Not found") }); + } else { + await req.respond({ + status: 500, + body: encoder.encode("Internal server error") + }); + } +} + +listenAndServe(addr, async req => { + const fileName = req.url.replace(/\/$/, ""); + const filePath = currentDir + fileName; + + try { + const fileInfo = await stat(filePath); + if (fileInfo.isDirectory()) { + // Bug with deno.stat: name and path not populated + // Yuck! + await serveDir(req, filePath, fileName); + } else { + await serveFile(req, filePath); + } + } catch (e) { + await serveFallback(req, e); + return; + } }); console.log(`HTTP server listening on http://${addr}/`); diff --git a/file_server_test.ts b/file_server_test.ts new file mode 100644 index 000000000..a04ced7e5 --- /dev/null +++ b/file_server_test.ts @@ -0,0 +1,46 @@ +import { readFile } from "deno"; + +import { + test, + assert, + assertEqual +} from "https://deno.land/x/testing/testing.ts"; + +// Promise to completeResolve when all tests completes +let completeResolve; +export const completePromise = new Promise(res => (completeResolve = res)); +let completedTestCount = 0; + +function maybeCompleteTests() { + completedTestCount++; + // Change this when adding more tests + if (completedTestCount === 3) { + completeResolve(); + } +} + +export function runTests(serverReadyPromise: Promise) { + test(async function serveFile() { + await serverReadyPromise; + const res = await fetch("http://localhost:4500/.travis.yml"); + const downloadedFile = await res.text(); + const localFile = new TextDecoder().decode(await readFile("./.travis.yml")); + assertEqual(downloadedFile, localFile); + maybeCompleteTests(); + }); + + test(async function serveDirectory() { + await serverReadyPromise; + const res = await fetch("http://localhost:4500/"); + const page = await res.text(); + assert(page.includes(".travis.yml")); + maybeCompleteTests(); + }); + + test(async function serveFallback() { + await serverReadyPromise; + const res = await fetch("http://localhost:4500/badfile.txt"); + assertEqual(res.status, 404); + maybeCompleteTests(); + }); +} diff --git a/http.ts b/http.ts index b11e2b369..6954a48ba 100644 --- a/http.ts +++ b/http.ts @@ -82,7 +82,10 @@ export async function* serve(addr: string) { listener.close(); } -export async function listenAndServe(addr: string, handler: (req: ServerRequest) => void) { +export async function listenAndServe( + addr: string, + handler: (req: ServerRequest) => void +) { const server = serve(addr); for await (const request of server) { @@ -90,23 +93,23 @@ export async function listenAndServe(addr: string, handler: (req: ServerRequest) } } -interface Response { +export interface Response { status?: number; headers?: Headers; body?: Uint8Array; } -function setContentLength(r: Response): void { +export function setContentLength(r: Response): void { if (!r.headers) { r.headers = new Headers(); } if (!r.headers.has("content-length")) { - const bodyLength = r.body ? r.body.byteLength : 0 + const bodyLength = r.body ? r.body.byteLength : 0; r.headers.append("Content-Length", bodyLength.toString()); } } -class ServerRequest { +export class ServerRequest { url: string; method: string; proto: string; diff --git a/test.ts b/test.ts index 2ee9a820b..44a692015 100644 --- a/test.ts +++ b/test.ts @@ -1,4 +1,19 @@ +import { run } from "deno"; + import "./buffer_test.ts"; import "./bufio_test.ts"; import "./textproto_test.ts"; +import { runTests, completePromise } from "./file_server_test.ts"; + +// file server test +const fileServer = run({ + args: ["deno", "--allow-net", "file_server.ts", "."] +}); +// I am also too lazy to do this properly LOL +runTests(new Promise(res => setTimeout(res, 1000))); +(async () => { + await completePromise; + fileServer.close(); +})(); + // TODO import "./http_test.ts"; -- cgit v1.2.3 From 0212401974434271653e50cc9d8f7188d72a8880 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 12 Dec 2018 10:38:46 +0100 Subject: File server logging (denoland/deno_std#17) Original: https://github.com/denoland/deno_std/commit/108127178b7cfd881ea18fabc92d0ee9bf72fd20 --- file_server.ts | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/file_server.ts b/file_server.ts index d2b9fe0b0..8159132b3 100755 --- a/file_server.ts +++ b/file_server.ts @@ -5,7 +5,7 @@ // TODO Add tests like these: // https://github.com/indexzero/http-server/blob/master/test/http-server-test.js -import { listenAndServe, ServerRequest, setContentLength } from "./http"; +import { listenAndServe, ServerRequest, setContentLength, Response } from "./http"; import { cwd, readFile, DenoError, ErrorKind, args, stat, readDir } from "deno"; const dirViewerTemplate = ` @@ -143,7 +143,7 @@ async function serveDir(req: ServerRequest, dirPath: string, dirName: string) { headers }; setContentLength(res); - await req.respond(res); + return res; } async function serveFile(req: ServerRequest, filename: string) { @@ -156,7 +156,7 @@ async function serveFile(req: ServerRequest, filename: string) { body: file, headers }; - await req.respond(res); + return res; } async function serveFallback(req: ServerRequest, e: Error) { @@ -164,31 +164,45 @@ async function serveFallback(req: ServerRequest, e: Error) { e instanceof DenoError && (e as DenoError).kind === ErrorKind.NotFound ) { - await req.respond({ status: 404, body: encoder.encode("Not found") }); + return { + status: 404, + body: encoder.encode("Not found") + }; } else { - await req.respond({ + return { status: 500, body: encoder.encode("Internal server error") - }); + }; } } +function serverLog(req: ServerRequest, res: Response) { + const d = new Date().toISOString(); + const dateFmt = `[${d.slice(0, 10)} ${d.slice(11, 19)}]`; + const s = `${dateFmt} "${req.method} ${req.url} ${req.proto}" ${res.status}`; + console.log(s); +} + listenAndServe(addr, async req => { const fileName = req.url.replace(/\/$/, ""); const filePath = currentDir + fileName; + let response: Response; + try { const fileInfo = await stat(filePath); if (fileInfo.isDirectory()) { // Bug with deno.stat: name and path not populated // Yuck! - await serveDir(req, filePath, fileName); + response = await serveDir(req, filePath, fileName); } else { - await serveFile(req, filePath); + response = await serveFile(req, filePath); } } catch (e) { - await serveFallback(req, e); - return; + response = await serveFallback(req, e); + } finally { + serverLog(req, response); + req.respond(response); } }); -- cgit v1.2.3 From c4e20b746ffcfc3b2845584c8ea89ec7bc8f67eb Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 12 Dec 2018 12:45:57 -0500 Subject: Fix travis badge Original: https://github.com/denoland/deno_std/commit/dbff42070bf8a94bb6a2af3d63ebffc7e77ab56b --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3963e19a6..9252dbd3d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Deno Networking Libraries -[![Build Status](https://travis-ci.com/denoland/net.svg?branch=master)](https://travis-ci.com/denoland/net) +[![Build Status](https://travis-ci.com/denoland/deno_net.svg?branch=master)](https://travis-ci.com/denoland/deno_net) Usage: -- cgit v1.2.3 From 10daa2982afc556df3f7ad78f9965b035c3126e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 12 Dec 2018 18:47:58 +0100 Subject: Fix file server crash (denoland/deno_std#20) Fix denoland/deno_std#19 Original: https://github.com/denoland/deno_std/commit/d9ab8eb0033ae73551e4979598293c5bd41b417d --- file_server.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/file_server.ts b/file_server.ts index 8159132b3..5cd87e2ec 100755 --- a/file_server.ts +++ b/file_server.ts @@ -109,8 +109,7 @@ async function serveDir(req: ServerRequest, dirPath: string, dirName: string) { for (const info of fileInfos) { if (info.name === "index.html" && info.isFile()) { // in case index.html as dir... - await serveFile(req, info.path); - return; + return await serveFile(req, info.path); } // Yuck! let mode = null; -- cgit v1.2.3 From 579b92de599b056c308a3b2d26f0b09188c4441b Mon Sep 17 00:00:00 2001 From: zhmushan Date: Sat, 15 Dec 2018 08:06:06 +0800 Subject: ci: update deno version to v0.2.3 Original: https://github.com/denoland/deno_std/commit/20714fe47a3a2b2bbb8a3b8553d0e6f4ad1cb76f --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 8c4abc16f..44aafefd3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: python install: -- curl -L https://deno.land/x/install/install.py | python - v0.2.2 +- curl -L https://deno.land/x/install/install.py | python - v0.2.3 - export PATH="$HOME/.deno/bin:$PATH" script: -- cgit v1.2.3 From f6dae45cd2bb0615c136188b4dba8a3272ac5d70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Mon, 17 Dec 2018 17:49:10 +0100 Subject: First pass at streaming http response (denoland/deno_std#16) Original: https://github.com/denoland/deno_std/commit/269665873a9219423085418d605b8af8ac2565dc --- buffer_test.ts | 2 +- bufio_test.ts | 4 ++-- file_server.ts | 20 +++++++++++++------- http.ts | 53 ++++++++++++++++++++++++++++++++++++++++++++++------- http_test.ts | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ test.ts | 1 + 6 files changed, 121 insertions(+), 17 deletions(-) create mode 100644 http_test.ts diff --git a/buffer_test.ts b/buffer_test.ts index 1958f8e97..9a71e80a3 100644 --- a/buffer_test.ts +++ b/buffer_test.ts @@ -17,7 +17,7 @@ function init() { if (testBytes == null) { testBytes = new Uint8Array(N); for (let i = 0; i < N; i++) { - testBytes[i] = "a".charCodeAt(0) + (i % 26); + testBytes[i] = "a".charCodeAt(0) + i % 26; } const decoder = new TextDecoder(); testString = decoder.decode(testBytes); diff --git a/bufio_test.ts b/bufio_test.ts index fb5dc23e8..5f32500a7 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -109,7 +109,7 @@ test(async function bufioBufReader() { for (let i = 0; i < texts.length - 1; i++) { texts[i] = str + "\n"; all += texts[i]; - str += String.fromCharCode((i % 26) + 97); + str += String.fromCharCode(i % 26 + 97); } texts[texts.length - 1] = all; @@ -294,7 +294,7 @@ test(async function bufioWriter() { const data = new Uint8Array(8192); for (let i = 0; i < data.byteLength; i++) { - data[i] = charCode(" ") + (i % (charCode("~") - charCode(" "))); + data[i] = charCode(" ") + i % (charCode("~") - charCode(" ")); } const w = new Buffer(); diff --git a/file_server.ts b/file_server.ts index 5cd87e2ec..bd1c52b88 100755 --- a/file_server.ts +++ b/file_server.ts @@ -5,8 +5,13 @@ // TODO Add tests like these: // https://github.com/indexzero/http-server/blob/master/test/http-server-test.js -import { listenAndServe, ServerRequest, setContentLength, Response } from "./http"; -import { cwd, readFile, DenoError, ErrorKind, args, stat, readDir } from "deno"; +import { + listenAndServe, + ServerRequest, + setContentLength, + Response +} from "./http"; +import { cwd, DenoError, ErrorKind, args, stat, readDir, open } from "deno"; const dirViewerTemplate = ` @@ -146,9 +151,10 @@ async function serveDir(req: ServerRequest, dirPath: string, dirName: string) { } async function serveFile(req: ServerRequest, filename: string) { - let file = await readFile(filename); + const file = await open(filename); + const fileInfo = await stat(filename); const headers = new Headers(); - headers.set("content-type", "octet-stream"); + headers.set("content-length", fileInfo.len.toString()); const res = { status: 200, @@ -163,9 +169,9 @@ async function serveFallback(req: ServerRequest, e: Error) { e instanceof DenoError && (e as DenoError).kind === ErrorKind.NotFound ) { - return { - status: 404, - body: encoder.encode("Not found") + return { + status: 404, + body: encoder.encode("Not found") }; } else { return { diff --git a/http.ts b/http.ts index 6954a48ba..bd45aea0d 100644 --- a/http.ts +++ b/http.ts @@ -1,4 +1,4 @@ -import { listen, Conn } from "deno"; +import { listen, Conn, toAsyncIterator, Reader, copy } from "deno"; import { BufReader, BufState, BufWriter } from "./bufio.ts"; import { TextProtoReader } from "./textproto.ts"; import { STATUS_TEXT } from "./http_status"; @@ -96,16 +96,23 @@ export async function listenAndServe( export interface Response { status?: number; headers?: Headers; - body?: Uint8Array; + body?: Uint8Array | Reader; } export function setContentLength(r: Response): void { if (!r.headers) { r.headers = new Headers(); } - if (!r.headers.has("content-length")) { - const bodyLength = r.body ? r.body.byteLength : 0; - r.headers.append("Content-Length", bodyLength.toString()); + + if (r.body) { + if (!r.headers.has("content-length")) { + if (r.body instanceof Uint8Array) { + const bodyLength = r.body.byteLength; + r.headers.append("Content-Length", bodyLength.toString()); + } else { + r.headers.append("Transfer-Encoding", "chunked"); + } + } } } @@ -116,6 +123,26 @@ export class ServerRequest { headers: Headers; w: BufWriter; + private async _streamBody(body: Reader, bodyLength: number) { + const n = await copy(this.w, body); + assert(n == bodyLength); + } + + private async _streamChunkedBody(body: Reader) { + const encoder = new TextEncoder(); + + for await (const chunk of toAsyncIterator(body)) { + const start = encoder.encode(`${chunk.byteLength.toString(16)}\r\n`); + const end = encoder.encode("\r\n"); + await this.w.write(start); + await this.w.write(chunk); + await this.w.write(end); + } + + const endChunk = encoder.encode("0\r\n\r\n"); + await this.w.write(endChunk); + } + async respond(r: Response): Promise { const protoMajor = 1; const protoMinor = 1; @@ -139,9 +166,21 @@ export class ServerRequest { const header = new TextEncoder().encode(out); let n = await this.w.write(header); assert(header.byteLength == n); + if (r.body) { - n = await this.w.write(r.body); - assert(r.body.byteLength == n); + if (r.body instanceof Uint8Array) { + n = await this.w.write(r.body); + assert(r.body.byteLength == n); + } else { + if (r.headers.has("content-length")) { + await this._streamBody( + r.body, + parseInt(r.headers.get("content-length")) + ); + } else { + await this._streamChunkedBody(r.body); + } + } } await this.w.flush(); diff --git a/http_test.ts b/http_test.ts new file mode 100644 index 000000000..879afbf53 --- /dev/null +++ b/http_test.ts @@ -0,0 +1,58 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Ported from +// https://github.com/golang/go/blob/master/src/net/http/responsewrite_test.go + +import { + test, + assert, + assertEqual +} from "https://deno.land/x/testing/testing.ts"; + +import { + listenAndServe, + ServerRequest, + setContentLength, + Response +} from "./http"; +import { Buffer } from "./buffer"; +import { BufWriter } from "./bufio"; + +interface ResponseTest { + response: Response; + raw: string; +} + +const responseTests: ResponseTest[] = [ + // Default response + { + response: {}, + raw: "HTTP/1.1 200 OK\r\n" + "\r\n" + }, + // HTTP/1.1, chunked coding; empty trailer; close + { + response: { + status: 200, + body: new Buffer(new TextEncoder().encode("abcdef")) + }, + + raw: + "HTTP/1.1 200 OK\r\n" + + "transfer-encoding: chunked\r\n\r\n" + + "6\r\nabcdef\r\n0\r\n\r\n" + } +]; + +test(async function responseWrite() { + for (const testCase of responseTests) { + const buf = new Buffer(); + const bufw = new BufWriter(buf); + const request = new ServerRequest(); + request.w = bufw; + + await request.respond(testCase.response); + assertEqual(buf.toString(), testCase.raw); + } +}); diff --git a/test.ts b/test.ts index 44a692015..8cb0a2ca2 100644 --- a/test.ts +++ b/test.ts @@ -2,6 +2,7 @@ import { run } from "deno"; import "./buffer_test.ts"; import "./bufio_test.ts"; +import "./http_test.ts"; import "./textproto_test.ts"; import { runTests, completePromise } from "./file_server_test.ts"; -- cgit v1.2.3 From 6afc9dca3d6c550b859a7f6bede0ec9527b0ba34 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Mon, 17 Dec 2018 22:40:42 -0500 Subject: Remove buffer.ts and use the one built in to deno. Original: https://github.com/denoland/deno_std/commit/5abec6efc5028bb281c29f5df40c0d87a4b8ebeb --- buffer.ts | 217 ------------------------------------------------------ buffer_test.ts | 189 ----------------------------------------------- bufio_test.ts | 5 +- http_test.ts | 2 +- test.ts | 1 - textproto_test.ts | 2 +- util.ts | 8 +- 7 files changed, 11 insertions(+), 413 deletions(-) delete mode 100644 buffer.ts delete mode 100644 buffer_test.ts diff --git a/buffer.ts b/buffer.ts deleted file mode 100644 index d177bc18d..000000000 --- a/buffer.ts +++ /dev/null @@ -1,217 +0,0 @@ -// This code has been ported almost directly from Go's src/bytes/buffer.go -// Copyright 2009 The Go Authors. All rights reserved. BSD license. -// https://github.com/golang/go/blob/master/LICENSE - -//import * as io from "./io"; -import { Reader, Writer, ReadResult } from "deno"; -import { assert, copyBytes } from "./util.ts"; - -// MIN_READ is the minimum ArrayBuffer size passed to a read call by -// buffer.ReadFrom. As long as the Buffer has at least MIN_READ bytes beyond -// what is required to hold the contents of r, readFrom() will not grow the -// underlying buffer. -const MIN_READ = 512; -const MAX_SIZE = 2 ** 32 - 2; - -const encoder = new TextEncoder(); -export function stringsReader(s: string): Reader { - const ui8 = encoder.encode(s); - return new Buffer(ui8.buffer as ArrayBuffer); -} - -/** A Buffer is a variable-sized buffer of bytes with read() and write() - * methods. Based on https://golang.org/pkg/bytes/#Buffer - */ -export class Buffer implements Reader, Writer { - private buf: Uint8Array; // contents are the bytes buf[off : len(buf)] - private off = 0; // read at buf[off], write at buf[buf.byteLength] - - constructor(ab?: ArrayBuffer) { - if (ab == null) { - this.buf = new Uint8Array(0); - } else { - this.buf = new Uint8Array(ab); - } - } - - /** bytes() returns a slice holding the unread portion of the buffer. - * The slice is valid for use only until the next buffer modification (that - * is, only until the next call to a method like read(), write(), reset(), or - * truncate()). The slice aliases the buffer content at least until the next - * buffer modification, so immediate changes to the slice will affect the - * result of future reads. - */ - bytes(): Uint8Array { - return this.buf.subarray(this.off); - } - - /** toString() returns the contents of the unread portion of the buffer - * as a string. Warning - if multibyte characters are present when data is - * flowing through the buffer, this method may result in incorrect strings - * due to a character being split. - */ - toString(): string { - const decoder = new TextDecoder(); - return decoder.decode(this.buf.subarray(this.off)); - } - - /** empty() returns whether the unread portion of the buffer is empty. */ - empty() { - return this.buf.byteLength <= this.off; - } - - /** length is a getter that returns the number of bytes of the unread - * portion of the buffer - */ - get length() { - return this.buf.byteLength - this.off; - } - - /** Returns the capacity of the buffer's underlying byte slice, that is, - * the total space allocated for the buffer's data. - */ - get capacity(): number { - return this.buf.buffer.byteLength; - } - - /** truncate() discards all but the first n unread bytes from the buffer but - * continues to use the same allocated storage. It throws if n is negative or - * greater than the length of the buffer. - */ - truncate(n: number): void { - if (n === 0) { - this.reset(); - return; - } - if (n < 0 || n > this.length) { - throw Error("bytes.Buffer: truncation out of range"); - } - this._reslice(this.off + n); - } - - /** reset() resets the buffer to be empty, but it retains the underlying - * storage for use by future writes. reset() is the same as truncate(0) - */ - reset(): void { - this._reslice(0); - this.off = 0; - } - - /** _tryGrowByReslice() is a version of grow for the fast-case - * where the internal buffer only needs to be resliced. It returns the index - * where bytes should be written and whether it succeeded. - * It returns -1 if a reslice was not needed. - */ - private _tryGrowByReslice(n: number): number { - const l = this.buf.byteLength; - if (n <= this.capacity - l) { - this._reslice(l + n); - return l; - } - return -1; - } - - private _reslice(len: number): void { - assert(len <= this.buf.buffer.byteLength); - this.buf = new Uint8Array(this.buf.buffer, 0, len); - } - - /** read() reads the next len(p) bytes from the buffer or until the buffer - * is drained. The return value n is the number of bytes read. If the - * buffer has no data to return, eof in the response will be true. - */ - async read(p: Uint8Array): Promise { - if (this.empty()) { - // Buffer is empty, reset to recover space. - this.reset(); - if (p.byteLength === 0) { - // TODO This edge case should be tested by porting TestReadEmptyAtEOF - // from the Go tests. - return { nread: 0, eof: false }; - } - return { nread: 0, eof: true }; - } - const nread = copyBytes(p, this.buf.subarray(this.off)); - this.off += nread; - return { nread, eof: false }; - } - - async write(p: Uint8Array): Promise { - const m = this._grow(p.byteLength); - return copyBytes(this.buf, p, m); - } - - /** _grow() grows the buffer to guarantee space for n more bytes. - * It returns the index where bytes should be written. - * If the buffer can't grow it will throw with ErrTooLarge. - */ - private _grow(n: number): number { - const m = this.length; - // If buffer is empty, reset to recover space. - if (m === 0 && this.off !== 0) { - this.reset(); - } - // Fast: Try to grow by means of a reslice. - const i = this._tryGrowByReslice(n); - if (i >= 0) { - return i; - } - const c = this.capacity; - if (n <= Math.floor(c / 2) - m) { - // We can slide things down instead of allocating a new - // ArrayBuffer. We only need m+n <= c to slide, but - // we instead let capacity get twice as large so we - // don't spend all our time copying. - copyBytes(this.buf, this.buf.subarray(this.off)); - } else if (c > MAX_SIZE - c - n) { - throw Error("ErrTooLarge"); // TODO DenoError(TooLarge) - } else { - // Not enough space anywhere, we need to allocate. - const buf = new Uint8Array(2 * c + n); - copyBytes(buf, this.buf.subarray(this.off)); - this.buf = buf; - } - // Restore this.off and len(this.buf). - this.off = 0; - this._reslice(m + n); - return m; - } - - /** grow() grows the buffer's capacity, if necessary, to guarantee space for - * another n bytes. After grow(n), at least n bytes can be written to the - * buffer without another allocation. If n is negative, grow() will panic. If - * the buffer can't grow it will throw ErrTooLarge. - * Based on https://golang.org/pkg/bytes/#Buffer.Grow - */ - grow(n: number): void { - if (n < 0) { - throw Error("Buffer.grow: negative count"); - } - const m = this._grow(n); - this._reslice(m); - } - - /** readFrom() reads data from r until EOF and appends it to the buffer, - * growing the buffer as needed. It returns the number of bytes read. If the - * buffer becomes too large, readFrom will panic with ErrTooLarge. - * Based on https://golang.org/pkg/bytes/#Buffer.ReadFrom - */ - async readFrom(r: Reader): Promise { - let n = 0; - while (true) { - try { - const i = this._grow(MIN_READ); - this._reslice(i); - const fub = new Uint8Array(this.buf.buffer, i); - const { nread, eof } = await r.read(fub); - this._reslice(i + nread); - n += nread; - if (eof) { - return n; - } - } catch (e) { - return n; - } - } - } -} diff --git a/buffer_test.ts b/buffer_test.ts deleted file mode 100644 index 9a71e80a3..000000000 --- a/buffer_test.ts +++ /dev/null @@ -1,189 +0,0 @@ -// This code has been ported almost directly from Go's src/bytes/buffer_test.go -// Copyright 2009 The Go Authors. All rights reserved. BSD license. -// https://github.com/golang/go/blob/master/LICENSE -import { - test, - assert, - assertEqual -} from "https://deno.land/x/testing/testing.ts"; -import { Buffer } from "./buffer.ts"; - -// N controls how many iterations of certain checks are performed. -const N = 100; -let testBytes: Uint8Array | null; -let testString: string | null; - -function init() { - if (testBytes == null) { - testBytes = new Uint8Array(N); - for (let i = 0; i < N; i++) { - testBytes[i] = "a".charCodeAt(0) + i % 26; - } - const decoder = new TextDecoder(); - testString = decoder.decode(testBytes); - } -} - -function check(buf: Buffer, s: string) { - const bytes = buf.bytes(); - assertEqual(buf.length, bytes.byteLength); - const decoder = new TextDecoder(); - const bytesStr = decoder.decode(bytes); - assertEqual(bytesStr, s); - assertEqual(buf.length, buf.toString().length); - assertEqual(buf.length, s.length); -} - -// Fill buf through n writes of byte slice fub. -// The initial contents of buf corresponds to the string s; -// the result is the final contents of buf returned as a string. -async function fillBytes( - buf: Buffer, - s: string, - n: number, - fub: Uint8Array -): Promise { - check(buf, s); - for (; n > 0; n--) { - let m = await buf.write(fub); - assertEqual(m, fub.byteLength); - const decoder = new TextDecoder(); - s += decoder.decode(fub); - check(buf, s); - } - return s; -} - -// Empty buf through repeated reads into fub. -// The initial contents of buf corresponds to the string s. -async function empty(buf: Buffer, s: string, fub: Uint8Array): Promise { - check(buf, s); - while (true) { - const r = await buf.read(fub); - if (r.nread == 0) { - break; - } - s = s.slice(r.nread); - check(buf, s); - } - check(buf, ""); -} - -test(function bufferNewBuffer() { - init(); - const buf = new Buffer(testBytes.buffer as ArrayBuffer); - check(buf, testString); -}); - -test(async function bufferBasicOperations() { - init(); - let buf = new Buffer(); - for (let i = 0; i < 5; i++) { - check(buf, ""); - - buf.reset(); - check(buf, ""); - - buf.truncate(0); - check(buf, ""); - - let n = await buf.write(testBytes.subarray(0, 1)); - assertEqual(n, 1); - check(buf, "a"); - - n = await buf.write(testBytes.subarray(1, 2)); - assertEqual(n, 1); - check(buf, "ab"); - - n = await buf.write(testBytes.subarray(2, 26)); - assertEqual(n, 24); - check(buf, testString.slice(0, 26)); - - buf.truncate(26); - check(buf, testString.slice(0, 26)); - - buf.truncate(20); - check(buf, testString.slice(0, 20)); - - await empty(buf, testString.slice(0, 20), new Uint8Array(5)); - await empty(buf, "", new Uint8Array(100)); - - // TODO buf.writeByte() - // TODO buf.readByte() - } -}); - -test(async function bufferLargeByteWrites() { - init(); - const buf = new Buffer(); - const limit = 9; - for (let i = 3; i < limit; i += 3) { - const s = await fillBytes(buf, "", 5, testBytes); - await empty(buf, s, new Uint8Array(Math.floor(testString.length / i))); - } - check(buf, ""); -}); - -test(async function bufferLargeByteReads() { - init(); - const buf = new Buffer(); - for (let i = 3; i < 30; i += 3) { - const n = Math.floor(testBytes.byteLength / i); - const s = await fillBytes(buf, "", 5, testBytes.subarray(0, n)); - await empty(buf, s, new Uint8Array(testString.length)); - } - check(buf, ""); -}); - -test(function bufferCapWithPreallocatedSlice() { - const buf = new Buffer(new ArrayBuffer(10)); - assertEqual(buf.capacity, 10); -}); - -test(async function bufferReadFrom() { - init(); - const buf = new Buffer(); - for (let i = 3; i < 30; i += 3) { - const s = await fillBytes( - buf, - "", - 5, - testBytes.subarray(0, Math.floor(testBytes.byteLength / i)) - ); - const b = new Buffer(); - await b.readFrom(buf); - const fub = new Uint8Array(testString.length); - await empty(b, s, fub); - } -}); - -function repeat(c: string, bytes: number): Uint8Array { - assertEqual(c.length, 1); - const ui8 = new Uint8Array(bytes); - ui8.fill(c.charCodeAt(0)); - return ui8; -} - -test(async function bufferTestGrow() { - const tmp = new Uint8Array(72); - for (let startLen of [0, 100, 1000, 10000, 100000]) { - const xBytes = repeat("x", startLen); - for (let growLen of [0, 100, 1000, 10000, 100000]) { - const buf = new Buffer(xBytes.buffer as ArrayBuffer); - // If we read, this affects buf.off, which is good to test. - const { nread, eof } = await buf.read(tmp); - buf.grow(growLen); - const yBytes = repeat("y", growLen); - await buf.write(yBytes); - // Check that buffer has correct data. - assertEqual( - buf.bytes().subarray(0, startLen - nread), - xBytes.subarray(nread) - ); - assertEqual( - buf.bytes().subarray(startLen - nread, startLen - nread + growLen), - yBytes - ); - } - } -}); diff --git a/bufio_test.ts b/bufio_test.ts index 5f32500a7..839e61388 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -3,16 +3,15 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -import { Reader, ReadResult } from "deno"; +import { Buffer, Reader, ReadResult } from "deno"; import { test, assert, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { BufReader, BufState, BufWriter } from "./bufio.ts"; -import { Buffer, stringsReader } from "./buffer.ts"; import * as iotest from "./iotest.ts"; -import { charCode, copyBytes } from "./util.ts"; +import { charCode, copyBytes, stringsReader } from "./util.ts"; const encoder = new TextEncoder(); diff --git a/http_test.ts b/http_test.ts index 879afbf53..cdb7f8303 100644 --- a/http_test.ts +++ b/http_test.ts @@ -17,7 +17,7 @@ import { setContentLength, Response } from "./http"; -import { Buffer } from "./buffer"; +import { Buffer } from "deno"; import { BufWriter } from "./bufio"; interface ResponseTest { diff --git a/test.ts b/test.ts index 8cb0a2ca2..c298b7aab 100644 --- a/test.ts +++ b/test.ts @@ -1,6 +1,5 @@ import { run } from "deno"; -import "./buffer_test.ts"; import "./bufio_test.ts"; import "./http_test.ts"; import "./textproto_test.ts"; diff --git a/textproto_test.ts b/textproto_test.ts index 32311a468..57ee99459 100644 --- a/textproto_test.ts +++ b/textproto_test.ts @@ -5,7 +5,7 @@ import { BufReader } from "./bufio.ts"; import { TextProtoReader } from "./textproto.ts"; -import { stringsReader } from "./buffer.ts"; +import { stringsReader } from "./util.ts"; import { test, assert, diff --git a/util.ts b/util.ts index 6a230ef3b..811940b4d 100644 --- a/util.ts +++ b/util.ts @@ -1,4 +1,4 @@ -import { Reader } from "deno"; +import { Buffer, Reader } from "deno"; export function assert(cond: boolean, msg = "assert") { if (!cond) { @@ -21,3 +21,9 @@ export function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number { export function charCode(s: string): number { return s.charCodeAt(0); } + +const encoder = new TextEncoder(); +export function stringsReader(s: string): Reader { + const ui8 = encoder.encode(s); + return new Buffer(ui8.buffer as ArrayBuffer); +} -- cgit v1.2.3 From 81933b0f04b865cab3b42a257b333f37ccc441b7 Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Mon, 17 Dec 2018 22:57:45 -0500 Subject: Add BufReader.readFull (denoland/deno_std#24) Original: https://github.com/denoland/deno_std/commit/abeb19890e5d6a0cd3461c4aefc920006ef284bd --- bufio.ts | 24 ++++++++++++++++++++++++ bufio_test.ts | 22 ++++++++++++++++++++++ test.ts | 2 +- 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/bufio.ts b/bufio.ts index a1f673653..b412cbce8 100644 --- a/bufio.ts +++ b/bufio.ts @@ -162,6 +162,30 @@ export class BufReader implements Reader { return rr; } + /** reads exactly len(p) bytes into p. + * Ported from https://golang.org/pkg/io/#ReadFull + * It returns the number of bytes copied and an error if fewer bytes were read. + * The error is EOF only if no bytes were read. + * If an EOF happens after reading some but not all the bytes, + * readFull returns ErrUnexpectedEOF. ("EOF" for current impl) + * On return, n == len(p) if and only if err == nil. + * If r returns an error having read at least len(buf) bytes, + * the error is dropped. + */ + async readFull(p: Uint8Array): Promise<[number, BufState]> { + let rr = await this.read(p); + let nread = rr.nread; + if (rr.eof) { + return [nread, nread < p.length ? "EOF" : null]; + } + while (!rr.eof && nread < p.length) { + rr = await this.read(p.subarray(nread)); + nread += rr.nread; + } + return [nread, nread < p.length ? "EOF" : null]; + } + + /** Returns the next byte [0, 255] or -1 if EOF. */ async readByte(): Promise { while (this.r === this.w) { diff --git a/bufio_test.ts b/bufio_test.ts index 839e61388..19954bdf6 100644 --- a/bufio_test.ts +++ b/bufio_test.ts @@ -321,3 +321,25 @@ test(async function bufioWriter() { } } }); + +test(async function bufReaderReadFull() { + const enc = new TextEncoder(); + const dec = new TextDecoder(); + const text = "Hello World"; + const data = new Buffer(enc.encode(text)); + const bufr = new BufReader(data, 3); + { + const buf = new Uint8Array(6); + const [nread, err] = await bufr.readFull(buf); + assertEqual(nread, 6); + assert(!err); + assertEqual(dec.decode(buf), "Hello "); + } + { + const buf = new Uint8Array(6); + const [nread, err] = await bufr.readFull(buf); + assertEqual(nread, 5); + assertEqual(err, "EOF"); + assertEqual(dec.decode(buf.subarray(0, 5)), "World"); + } +}); diff --git a/test.ts b/test.ts index c298b7aab..7c395663e 100644 --- a/test.ts +++ b/test.ts @@ -10,7 +10,7 @@ const fileServer = run({ args: ["deno", "--allow-net", "file_server.ts", "."] }); // I am also too lazy to do this properly LOL -runTests(new Promise(res => setTimeout(res, 1000))); +runTests(new Promise(res => setTimeout(res, 5000))); (async () => { await completePromise; fileServer.close(); -- cgit v1.2.3 From 6e077e71fa27dbb993a49cda211c5385a76ca6aa Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Mon, 17 Dec 2018 23:14:22 -0500 Subject: Implement append() to join 2 Uint8Array (denoland/deno_std#25) Original: https://github.com/denoland/deno_std/commit/6f2811c27594b10dc7c6064eaa82cd0534b7a018 --- textproto.ts | 7 +++++-- textproto_test.ts | 11 ++++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/textproto.ts b/textproto.ts index 4c4b92627..342d74b33 100644 --- a/textproto.ts +++ b/textproto.ts @@ -137,10 +137,13 @@ export class TextProtoReader { } } -function append(a: Uint8Array, b: Uint8Array): Uint8Array { +export function append(a: Uint8Array, b: Uint8Array): Uint8Array { if (a == null) { return b; } else { - throw Error("Not implemented"); + const output = new Uint8Array(a.length + b.length); + output.set(a, 0); + output.set(b, a.length); + return output; } } diff --git a/textproto_test.ts b/textproto_test.ts index 57ee99459..25c12b0e8 100644 --- a/textproto_test.ts +++ b/textproto_test.ts @@ -4,7 +4,7 @@ // license that can be found in the LICENSE file. import { BufReader } from "./bufio.ts"; -import { TextProtoReader } from "./textproto.ts"; +import { TextProtoReader, append } from "./textproto.ts"; import { stringsReader } from "./util.ts"; import { test, @@ -82,3 +82,12 @@ test(async function textprotoReadMIMEHeaderNonCompliant() { } */ }); + +test(async function textprotoAppend() { + const enc = new TextEncoder(); + const dec = new TextDecoder(); + const u1 = enc.encode("Hello "); + const u2 = enc.encode("World"); + const joined = append(u1, u2); + assertEqual(dec.decode(joined), "Hello World"); +}); -- cgit v1.2.3 From 968d50842512a007dc9c2e4ae31b1970fdc6e6a2 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Tue, 18 Dec 2018 18:25:49 -0500 Subject: Rename project to deno_std Move typescript files to net/ Original: https://github.com/denoland/deno_std/commit/99e276eb89fbe0003bfa8d9e7b907ff3ef19ee47 --- README.md | 4 +- bufio.ts | 465 ------------------------------------------------ bufio_test.ts | 345 ----------------------------------- file_server.ts | 214 ---------------------- file_server_test.ts | 46 ----- http.ts | 212 ---------------------- http_bench.ts | 15 -- http_status.ts | 134 -------------- http_test.ts | 58 ------ iotest.ts | 61 ------- net/bufio.ts | 465 ++++++++++++++++++++++++++++++++++++++++++++++++ net/bufio_test.ts | 345 +++++++++++++++++++++++++++++++++++ net/file_server.ts | 214 ++++++++++++++++++++++ net/file_server_test.ts | 46 +++++ net/http.ts | 212 ++++++++++++++++++++++ net/http_bench.ts | 15 ++ net/http_status.ts | 134 ++++++++++++++ net/http_test.ts | 58 ++++++ net/iotest.ts | 61 +++++++ net/textproto.ts | 149 ++++++++++++++++ net/textproto_test.ts | 93 ++++++++++ net/util.ts | 29 +++ test.ts | 13 +- textproto.ts | 149 ---------------- textproto_test.ts | 93 ---------- util.ts | 29 --- 26 files changed, 1829 insertions(+), 1830 deletions(-) delete mode 100644 bufio.ts delete mode 100644 bufio_test.ts delete mode 100755 file_server.ts delete mode 100644 file_server_test.ts delete mode 100644 http.ts delete mode 100644 http_bench.ts delete mode 100644 http_status.ts delete mode 100644 http_test.ts delete mode 100644 iotest.ts create mode 100644 net/bufio.ts create mode 100644 net/bufio_test.ts create mode 100755 net/file_server.ts create mode 100644 net/file_server_test.ts create mode 100644 net/http.ts create mode 100644 net/http_bench.ts create mode 100644 net/http_status.ts create mode 100644 net/http_test.ts create mode 100644 net/iotest.ts create mode 100644 net/textproto.ts create mode 100644 net/textproto_test.ts create mode 100644 net/util.ts mode change 100644 => 100755 test.ts delete mode 100644 textproto.ts delete mode 100644 textproto_test.ts delete mode 100644 util.ts diff --git a/README.md b/README.md index 9252dbd3d..ab668e913 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# Deno Networking Libraries +# Deno Standard Modules -[![Build Status](https://travis-ci.com/denoland/deno_net.svg?branch=master)](https://travis-ci.com/denoland/deno_net) +[![Build Status](https://travis-ci.com/denoland/deno_std.svg?branch=master)](https://travis-ci.com/denoland/deno_std) Usage: diff --git a/bufio.ts b/bufio.ts deleted file mode 100644 index b412cbce8..000000000 --- a/bufio.ts +++ /dev/null @@ -1,465 +0,0 @@ -// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio.go -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import { Reader, ReadResult, Writer } from "deno"; -import { assert, charCode, copyBytes } from "./util.ts"; - -const DEFAULT_BUF_SIZE = 4096; -const MIN_BUF_SIZE = 16; -const MAX_CONSECUTIVE_EMPTY_READS = 100; -const CR = charCode("\r"); -const LF = charCode("\n"); - -export type BufState = - | null - | "EOF" - | "BufferFull" - | "ShortWrite" - | "NoProgress" - | Error; - -/** BufReader implements buffering for a Reader object. */ -export class BufReader implements Reader { - private buf: Uint8Array; - private rd: Reader; // Reader provided by caller. - private r = 0; // buf read position. - private w = 0; // buf write position. - private lastByte: number; - private lastCharSize: number; - private err: BufState; - - constructor(rd: Reader, size = DEFAULT_BUF_SIZE) { - if (size < MIN_BUF_SIZE) { - size = MIN_BUF_SIZE; - } - this._reset(new Uint8Array(size), rd); - } - - /** Returns the size of the underlying buffer in bytes. */ - size(): number { - return this.buf.byteLength; - } - - buffered(): number { - return this.w - this.r; - } - - private _readErr(): BufState { - const err = this.err; - this.err = null; - return err; - } - - // Reads a new chunk into the buffer. - private async _fill(): Promise { - // Slide existing data to beginning. - if (this.r > 0) { - this.buf.copyWithin(0, this.r, this.w); - this.w -= this.r; - this.r = 0; - } - - if (this.w >= this.buf.byteLength) { - throw Error("bufio: tried to fill full buffer"); - } - - // Read new data: try a limited number of times. - for (let i = MAX_CONSECUTIVE_EMPTY_READS; i > 0; i--) { - let rr: ReadResult; - try { - rr = await this.rd.read(this.buf.subarray(this.w)); - } catch (e) { - this.err = e; - return; - } - assert(rr.nread >= 0, "negative read"); - this.w += rr.nread; - if (rr.eof) { - this.err = "EOF"; - return; - } - if (rr.nread > 0) { - return; - } - } - this.err = "NoProgress"; - } - - /** Discards any buffered data, resets all state, and switches - * the buffered reader to read from r. - */ - reset(r: Reader): void { - this._reset(this.buf, r); - } - - private _reset(buf: Uint8Array, rd: Reader): void { - this.buf = buf; - this.rd = rd; - this.lastByte = -1; - // this.lastRuneSize = -1; - } - - /** reads data into p. - * It returns the number of bytes read into p. - * The bytes are taken from at most one Read on the underlying Reader, - * hence n may be less than len(p). - * At EOF, the count will be zero and err will be io.EOF. - * To read exactly len(p) bytes, use io.ReadFull(b, p). - */ - async read(p: Uint8Array): Promise { - let rr: ReadResult = { nread: p.byteLength, eof: false }; - if (rr.nread === 0) { - if (this.err) { - throw this._readErr(); - } - return rr; - } - - if (this.r === this.w) { - if (this.err) { - throw this._readErr(); - } - if (p.byteLength >= this.buf.byteLength) { - // Large read, empty buffer. - // Read directly into p to avoid copy. - rr = await this.rd.read(p); - assert(rr.nread >= 0, "negative read"); - if (rr.nread > 0) { - this.lastByte = p[rr.nread - 1]; - // this.lastRuneSize = -1; - } - if (this.err) { - throw this._readErr(); - } - return rr; - } - // One read. - // Do not use this.fill, which will loop. - this.r = 0; - this.w = 0; - try { - rr = await this.rd.read(this.buf); - } catch (e) { - this.err = e; - } - assert(rr.nread >= 0, "negative read"); - if (rr.nread === 0) { - if (this.err) { - throw this._readErr(); - } - return rr; - } - this.w += rr.nread; - } - - // copy as much as we can - rr.nread = copyBytes(p as Uint8Array, this.buf.subarray(this.r, this.w), 0); - this.r += rr.nread; - this.lastByte = this.buf[this.r - 1]; - // this.lastRuneSize = -1; - return rr; - } - - /** reads exactly len(p) bytes into p. - * Ported from https://golang.org/pkg/io/#ReadFull - * It returns the number of bytes copied and an error if fewer bytes were read. - * The error is EOF only if no bytes were read. - * If an EOF happens after reading some but not all the bytes, - * readFull returns ErrUnexpectedEOF. ("EOF" for current impl) - * On return, n == len(p) if and only if err == nil. - * If r returns an error having read at least len(buf) bytes, - * the error is dropped. - */ - async readFull(p: Uint8Array): Promise<[number, BufState]> { - let rr = await this.read(p); - let nread = rr.nread; - if (rr.eof) { - return [nread, nread < p.length ? "EOF" : null]; - } - while (!rr.eof && nread < p.length) { - rr = await this.read(p.subarray(nread)); - nread += rr.nread; - } - return [nread, nread < p.length ? "EOF" : null]; - } - - - /** Returns the next byte [0, 255] or -1 if EOF. */ - async readByte(): Promise { - while (this.r === this.w) { - await this._fill(); // buffer is empty. - if (this.err == "EOF") { - return -1; - } - if (this.err != null) { - throw this._readErr(); - } - } - const c = this.buf[this.r]; - this.r++; - this.lastByte = c; - return c; - } - - /** readString() reads until the first occurrence of delim in the input, - * returning a string containing the data up to and including the delimiter. - * If ReadString encounters an error before finding a delimiter, - * it returns the data read before the error and the error itself (often io.EOF). - * ReadString returns err != nil if and only if the returned data does not end in - * delim. - * For simple uses, a Scanner may be more convenient. - */ - async readString(delim: string): Promise { - throw new Error("Not implemented"); - } - - /** readLine() is a low-level line-reading primitive. Most callers should use - * readBytes('\n') or readString('\n') instead or use a Scanner. - * - * readLine tries to return a single line, not including the end-of-line bytes. - * If the line was too long for the buffer then isPrefix is set and the - * beginning of the line is returned. The rest of the line will be returned - * from future calls. isPrefix will be false when returning the last fragment - * of the line. The returned buffer is only valid until the next call to - * ReadLine. ReadLine either returns a non-nil line or it returns an error, - * never both. - * - * The text returned from ReadLine does not include the line end ("\r\n" or "\n"). - * No indication or error is given if the input ends without a final line end. - * Calling UnreadByte after ReadLine will always unread the last byte read - * (possibly a character belonging to the line end) even if that byte is not - * part of the line returned by ReadLine. - */ - async readLine(): Promise<[Uint8Array, boolean, BufState]> { - let [line, err] = await this.readSlice(LF); - - if (err === "BufferFull") { - // Handle the case where "\r\n" straddles the buffer. - if (line.byteLength > 0 && line[line.byteLength - 1] === CR) { - // Put the '\r' back on buf and drop it from line. - // Let the next call to ReadLine check for "\r\n". - assert(this.r > 0, "bufio: tried to rewind past start of buffer"); - this.r--; - line = line.subarray(0, line.byteLength - 1); - } - return [line, true, null]; - } - - if (line.byteLength === 0) { - return [line, false, err]; - } - err = null; - - if (line[line.byteLength - 1] == LF) { - let drop = 1; - if (line.byteLength > 1 && line[line.byteLength - 2] === CR) { - drop = 2; - } - line = line.subarray(0, line.byteLength - drop); - } - return [line, false, err]; - } - - /** readSlice() reads until the first occurrence of delim in the input, - * returning a slice pointing at the bytes in the buffer. The bytes stop - * being valid at the next read. If readSlice() encounters an error before - * finding a delimiter, it returns all the data in the buffer and the error - * itself (often io.EOF). readSlice() fails with error ErrBufferFull if the - * buffer fills without a delim. Because the data returned from readSlice() - * will be overwritten by the next I/O operation, most clients should use - * readBytes() or readString() instead. readSlice() returns err != nil if and - * only if line does not end in delim. - */ - async readSlice(delim: number): Promise<[Uint8Array, BufState]> { - let s = 0; // search start index - let line: Uint8Array; - let err: BufState; - while (true) { - // Search buffer. - let i = this.buf.subarray(this.r + s, this.w).indexOf(delim); - if (i >= 0) { - i += s; - line = this.buf.subarray(this.r, this.r + i + 1); - this.r += i + 1; - break; - } - - // Pending error? - if (this.err) { - line = this.buf.subarray(this.r, this.w); - this.r = this.w; - err = this._readErr(); - break; - } - - // Buffer full? - if (this.buffered() >= this.buf.byteLength) { - this.r = this.w; - line = this.buf; - err = "BufferFull"; - break; - } - - s = this.w - this.r; // do not rescan area we scanned before - - await this._fill(); // buffer is not full - } - - // Handle last byte, if any. - let i = line.byteLength - 1; - if (i >= 0) { - this.lastByte = line[i]; - // this.lastRuneSize = -1 - } - - return [line, err]; - } - - /** Peek returns the next n bytes without advancing the reader. The bytes stop - * being valid at the next read call. If Peek returns fewer than n bytes, it - * also returns an error explaining why the read is short. The error is - * ErrBufferFull if n is larger than b's buffer size. - */ - async peek(n: number): Promise<[Uint8Array, BufState]> { - if (n < 0) { - throw Error("negative count"); - } - - while ( - this.w - this.r < n && - this.w - this.r < this.buf.byteLength && - this.err == null - ) { - await this._fill(); // this.w - this.r < len(this.buf) => buffer is not full - } - - if (n > this.buf.byteLength) { - return [this.buf.subarray(this.r, this.w), "BufferFull"]; - } - - // 0 <= n <= len(this.buf) - let err: BufState; - let avail = this.w - this.r; - if (avail < n) { - // not enough data in buffer - n = avail; - err = this._readErr(); - if (!err) { - err = "BufferFull"; - } - } - return [this.buf.subarray(this.r, this.r + n), err]; - } -} - -/** BufWriter implements buffering for an deno.Writer object. - * If an error occurs writing to a Writer, no more data will be - * accepted and all subsequent writes, and flush(), will return the error. - * After all data has been written, the client should call the - * flush() method to guarantee all data has been forwarded to - * the underlying deno.Writer. - */ -export class BufWriter implements Writer { - buf: Uint8Array; - n: number = 0; - err: null | BufState = null; - - constructor(private wr: Writer, size = DEFAULT_BUF_SIZE) { - if (size <= 0) { - size = DEFAULT_BUF_SIZE; - } - this.buf = new Uint8Array(size); - } - - /** Size returns the size of the underlying buffer in bytes. */ - size(): number { - return this.buf.byteLength; - } - - /** Discards any unflushed buffered data, clears any error, and - * resets b to write its output to w. - */ - reset(w: Writer): void { - this.err = null; - this.n = 0; - this.wr = w; - } - - /** Flush writes any buffered data to the underlying io.Writer. */ - async flush(): Promise { - if (this.err != null) { - return this.err; - } - if (this.n == 0) { - return null; - } - - let n: number; - let err: BufState = null; - try { - n = await this.wr.write(this.buf.subarray(0, this.n)); - } catch (e) { - err = e; - } - - if (n < this.n && err == null) { - err = "ShortWrite"; - } - - if (err != null) { - if (n > 0 && n < this.n) { - this.buf.copyWithin(0, n, this.n); - } - this.n -= n; - this.err = err; - return err; - } - this.n = 0; - } - - /** Returns how many bytes are unused in the buffer. */ - available(): number { - return this.buf.byteLength - this.n; - } - - /** buffered returns the number of bytes that have been written into the - * current buffer. - */ - buffered(): number { - return this.n; - } - - /** Writes the contents of p into the buffer. - * Returns the number of bytes written. - */ - async write(p: Uint8Array): Promise { - let nn = 0; - let n: number; - while (p.byteLength > this.available() && !this.err) { - if (this.buffered() == 0) { - // Large write, empty buffer. - // Write directly from p to avoid copy. - try { - n = await this.wr.write(p); - } catch (e) { - this.err = e; - } - } else { - n = copyBytes(this.buf, p, this.n); - this.n += n; - await this.flush(); - } - nn += n; - p = p.subarray(n); - } - if (this.err) { - throw this.err; - } - n = copyBytes(this.buf, p, this.n); - this.n += n; - nn += n; - return nn; - } -} diff --git a/bufio_test.ts b/bufio_test.ts deleted file mode 100644 index 19954bdf6..000000000 --- a/bufio_test.ts +++ /dev/null @@ -1,345 +0,0 @@ -// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio_test.go -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import { Buffer, Reader, ReadResult } from "deno"; -import { - test, - assert, - assertEqual -} from "https://deno.land/x/testing/testing.ts"; -import { BufReader, BufState, BufWriter } from "./bufio.ts"; -import * as iotest from "./iotest.ts"; -import { charCode, copyBytes, stringsReader } from "./util.ts"; - -const encoder = new TextEncoder(); - -async function readBytes(buf: BufReader): Promise { - const b = new Uint8Array(1000); - let nb = 0; - while (true) { - let c = await buf.readByte(); - if (c < 0) { - break; // EOF - } - b[nb] = c; - nb++; - } - const decoder = new TextDecoder(); - return decoder.decode(b.subarray(0, nb)); -} - -test(async function bufioReaderSimple() { - const data = "hello world"; - const b = new BufReader(stringsReader(data)); - const s = await readBytes(b); - assertEqual(s, data); -}); - -type ReadMaker = { name: string; fn: (r: Reader) => Reader }; - -const readMakers: ReadMaker[] = [ - { name: "full", fn: r => r }, - { name: "byte", fn: r => new iotest.OneByteReader(r) }, - { name: "half", fn: r => new iotest.HalfReader(r) } - // TODO { name: "data+err", r => new iotest.DataErrReader(r) }, - // { name: "timeout", fn: r => new iotest.TimeoutReader(r) }, -]; - -function readLines(b: BufReader): string { - let s = ""; - while (true) { - let s1 = b.readString("\n"); - if (s1 == null) { - break; // EOF - } - s += s1; - } - return s; -} - -// Call read to accumulate the text of a file -async function reads(buf: BufReader, m: number): Promise { - const b = new Uint8Array(1000); - let nb = 0; - while (true) { - const { nread, eof } = await buf.read(b.subarray(nb, nb + m)); - nb += nread; - if (eof) { - break; - } - } - const decoder = new TextDecoder(); - return decoder.decode(b.subarray(0, nb)); -} - -type NamedBufReader = { name: string; fn: (r: BufReader) => Promise }; - -const bufreaders: NamedBufReader[] = [ - { name: "1", fn: (b: BufReader) => reads(b, 1) }, - { name: "2", fn: (b: BufReader) => reads(b, 2) }, - { name: "3", fn: (b: BufReader) => reads(b, 3) }, - { name: "4", fn: (b: BufReader) => reads(b, 4) }, - { name: "5", fn: (b: BufReader) => reads(b, 5) }, - { name: "7", fn: (b: BufReader) => reads(b, 7) }, - { name: "bytes", fn: readBytes } - // { name: "lines", fn: readLines }, -]; - -const MIN_READ_BUFFER_SIZE = 16; -const bufsizes: number[] = [ - 0, - MIN_READ_BUFFER_SIZE, - 23, - 32, - 46, - 64, - 93, - 128, - 1024, - 4096 -]; - -test(async function bufioBufReader() { - const texts = new Array(31); - let str = ""; - let all = ""; - for (let i = 0; i < texts.length - 1; i++) { - texts[i] = str + "\n"; - all += texts[i]; - str += String.fromCharCode(i % 26 + 97); - } - texts[texts.length - 1] = all; - - for (let text of texts) { - for (let readmaker of readMakers) { - for (let bufreader of bufreaders) { - for (let bufsize of bufsizes) { - const read = readmaker.fn(stringsReader(text)); - const buf = new BufReader(read, bufsize); - const s = await bufreader.fn(buf); - const debugStr = - `reader=${readmaker.name} ` + - `fn=${bufreader.name} bufsize=${bufsize} want=${text} got=${s}`; - assertEqual(s, text, debugStr); - } - } - } - } -}); - -test(async function bufioBufferFull() { - const longString = - "And now, hello, world! It is the time for all good men to come to the aid of their party"; - const buf = new BufReader(stringsReader(longString), MIN_READ_BUFFER_SIZE); - let [line, err] = await buf.readSlice(charCode("!")); - - const decoder = new TextDecoder(); - let actual = decoder.decode(line); - assertEqual(err, "BufferFull"); - assertEqual(actual, "And now, hello, "); - - [line, err] = await buf.readSlice(charCode("!")); - actual = decoder.decode(line); - assertEqual(actual, "world!"); - assert(err == null); -}); - -const testInput = encoder.encode( - "012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy" -); -const testInputrn = encoder.encode( - "012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n" -); -const testOutput = encoder.encode("0123456789abcdefghijklmnopqrstuvwxy"); - -// TestReader wraps a Uint8Array and returns reads of a specific length. -class TestReader implements Reader { - constructor(private data: Uint8Array, private stride: number) {} - - async read(buf: Uint8Array): Promise { - let nread = this.stride; - if (nread > this.data.byteLength) { - nread = this.data.byteLength; - } - if (nread > buf.byteLength) { - nread = buf.byteLength; - } - copyBytes(buf as Uint8Array, this.data); - this.data = this.data.subarray(nread); - let eof = false; - if (this.data.byteLength == 0) { - eof = true; - } - return { nread, eof }; - } -} - -async function testReadLine(input: Uint8Array): Promise { - for (let stride = 1; stride < 2; stride++) { - let done = 0; - let reader = new TestReader(input, stride); - let l = new BufReader(reader, input.byteLength + 1); - while (true) { - let [line, isPrefix, err] = await l.readLine(); - if (line.byteLength > 0 && err != null) { - throw Error("readLine returned both data and error"); - } - assertEqual(isPrefix, false); - if (err == "EOF") { - break; - } - let want = testOutput.subarray(done, done + line.byteLength); - assertEqual( - line, - want, - `Bad line at stride ${stride}: want: ${want} got: ${line}` - ); - done += line.byteLength; - } - assertEqual( - done, - testOutput.byteLength, - `readLine didn't return everything: got: ${done}, ` + - `want: ${testOutput} (stride: ${stride})` - ); - } -} - -test(async function bufioReadLine() { - await testReadLine(testInput); - await testReadLine(testInputrn); -}); - -test(async function bufioPeek() { - const decoder = new TextDecoder(); - let p = new Uint8Array(10); - // string is 16 (minReadBufferSize) long. - let buf = new BufReader( - stringsReader("abcdefghijklmnop"), - MIN_READ_BUFFER_SIZE - ); - - let [actual, err] = await buf.peek(1); - assertEqual(decoder.decode(actual), "a"); - assert(err == null); - - [actual, err] = await buf.peek(4); - assertEqual(decoder.decode(actual), "abcd"); - assert(err == null); - - [actual, err] = await buf.peek(32); - assertEqual(decoder.decode(actual), "abcdefghijklmnop"); - assertEqual(err, "BufferFull"); - - await buf.read(p.subarray(0, 3)); - assertEqual(decoder.decode(p.subarray(0, 3)), "abc"); - - [actual, err] = await buf.peek(1); - assertEqual(decoder.decode(actual), "d"); - assert(err == null); - - [actual, err] = await buf.peek(1); - assertEqual(decoder.decode(actual), "d"); - assert(err == null); - - [actual, err] = await buf.peek(1); - assertEqual(decoder.decode(actual), "d"); - assert(err == null); - - [actual, err] = await buf.peek(2); - assertEqual(decoder.decode(actual), "de"); - assert(err == null); - - let { eof } = await buf.read(p.subarray(0, 3)); - assertEqual(decoder.decode(p.subarray(0, 3)), "def"); - assert(!eof); - assert(err == null); - - [actual, err] = await buf.peek(4); - assertEqual(decoder.decode(actual), "ghij"); - assert(err == null); - - await buf.read(p); - assertEqual(decoder.decode(p), "ghijklmnop"); - - [actual, err] = await buf.peek(0); - assertEqual(decoder.decode(actual), ""); - assert(err == null); - - [actual, err] = await buf.peek(1); - assertEqual(decoder.decode(actual), ""); - assert(err == "EOF"); - /* TODO - // Test for issue 3022, not exposing a reader's error on a successful Peek. - buf = NewReaderSize(dataAndEOFReader("abcd"), 32) - if s, err := buf.Peek(2); string(s) != "ab" || err != nil { - t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err) - } - if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { - t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err) - } - if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil { - t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err) - } - if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF { - t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err) - } - */ -}); - -test(async function bufioWriter() { - const data = new Uint8Array(8192); - - for (let i = 0; i < data.byteLength; i++) { - data[i] = charCode(" ") + i % (charCode("~") - charCode(" ")); - } - - const w = new Buffer(); - for (let nwrite of bufsizes) { - for (let bs of bufsizes) { - // Write nwrite bytes using buffer size bs. - // Check that the right amount makes it out - // and that the data is correct. - - w.reset(); - const buf = new BufWriter(w, bs); - - const context = `nwrite=${nwrite} bufsize=${bs}`; - const n = await buf.write(data.subarray(0, nwrite)); - assertEqual(n, nwrite, context); - - await buf.flush(); - - const written = w.bytes(); - assertEqual(written.byteLength, nwrite); - - for (let l = 0; l < written.byteLength; l++) { - assertEqual(written[l], data[l]); - } - } - } -}); - -test(async function bufReaderReadFull() { - const enc = new TextEncoder(); - const dec = new TextDecoder(); - const text = "Hello World"; - const data = new Buffer(enc.encode(text)); - const bufr = new BufReader(data, 3); - { - const buf = new Uint8Array(6); - const [nread, err] = await bufr.readFull(buf); - assertEqual(nread, 6); - assert(!err); - assertEqual(dec.decode(buf), "Hello "); - } - { - const buf = new Uint8Array(6); - const [nread, err] = await bufr.readFull(buf); - assertEqual(nread, 5); - assertEqual(err, "EOF"); - assertEqual(dec.decode(buf.subarray(0, 5)), "World"); - } -}); diff --git a/file_server.ts b/file_server.ts deleted file mode 100755 index bd1c52b88..000000000 --- a/file_server.ts +++ /dev/null @@ -1,214 +0,0 @@ -#!/usr/bin/env deno --allow-net - -// This program serves files in the current directory over HTTP. -// TODO Stream responses instead of reading them into memory. -// TODO Add tests like these: -// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js - -import { - listenAndServe, - ServerRequest, - setContentLength, - Response -} from "./http"; -import { cwd, DenoError, ErrorKind, args, stat, readDir, open } from "deno"; - -const dirViewerTemplate = ` - - - - - - - Deno File Server - - - -

Index of <%DIRNAME%>

- - - <%CONTENTS%> -
ModeSizeName
- - -`; - -let currentDir = cwd(); -const target = args[1]; -if (target) { - currentDir = `${currentDir}/${target}`; -} -const addr = `0.0.0.0:${args[2] || 4500}`; -const encoder = new TextEncoder(); - -function modeToString(isDir: boolean, maybeMode: number | null) { - const modeMap = ["---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"]; - - if (maybeMode === null) { - return "(unknown mode)"; - } - const mode = maybeMode!.toString(8); - if (mode.length < 3) { - return "(unknown mode)"; - } - let output = ""; - mode - .split("") - .reverse() - .slice(0, 3) - .forEach(v => { - output = modeMap[+v] + output; - }); - output = `(${isDir ? "d" : "-"}${output})`; - return output; -} - -function fileLenToString(len: number) { - const multipler = 1024; - let base = 1; - const suffix = ["B", "K", "M", "G", "T"]; - let suffixIndex = 0; - - while (base * multipler < len) { - if (suffixIndex >= suffix.length - 1) { - break; - } - base *= multipler; - suffixIndex++; - } - - return `${(len / base).toFixed(2)}${suffix[suffixIndex]}`; -} - -function createDirEntryDisplay( - name: string, - path: string, - size: number | null, - mode: number | null, - isDir: boolean -) { - const sizeStr = size === null ? "" : "" + fileLenToString(size!); - return ` - ${modeToString( - isDir, - mode - )}${sizeStr}${name}${ - isDir ? "/" : "" - } - - `; -} - -// TODO: simplify this after deno.stat and deno.readDir are fixed -async function serveDir(req: ServerRequest, dirPath: string, dirName: string) { - // dirname has no prefix - const listEntry: string[] = []; - const fileInfos = await readDir(dirPath); - for (const info of fileInfos) { - if (info.name === "index.html" && info.isFile()) { - // in case index.html as dir... - return await serveFile(req, info.path); - } - // Yuck! - let mode = null; - try { - mode = (await stat(info.path)).mode; - } catch (e) {} - listEntry.push( - createDirEntryDisplay( - info.name, - dirName + "/" + info.name, - info.isFile() ? info.len : null, - mode, - info.isDirectory() - ) - ); - } - - const page = new TextEncoder().encode( - dirViewerTemplate - .replace("<%DIRNAME%>", dirName + "/") - .replace("<%CONTENTS%>", listEntry.join("")) - ); - - const headers = new Headers(); - headers.set("content-type", "text/html"); - - const res = { - status: 200, - body: page, - headers - }; - setContentLength(res); - return res; -} - -async function serveFile(req: ServerRequest, filename: string) { - const file = await open(filename); - const fileInfo = await stat(filename); - const headers = new Headers(); - headers.set("content-length", fileInfo.len.toString()); - - const res = { - status: 200, - body: file, - headers - }; - return res; -} - -async function serveFallback(req: ServerRequest, e: Error) { - if ( - e instanceof DenoError && - (e as DenoError).kind === ErrorKind.NotFound - ) { - return { - status: 404, - body: encoder.encode("Not found") - }; - } else { - return { - status: 500, - body: encoder.encode("Internal server error") - }; - } -} - -function serverLog(req: ServerRequest, res: Response) { - const d = new Date().toISOString(); - const dateFmt = `[${d.slice(0, 10)} ${d.slice(11, 19)}]`; - const s = `${dateFmt} "${req.method} ${req.url} ${req.proto}" ${res.status}`; - console.log(s); -} - -listenAndServe(addr, async req => { - const fileName = req.url.replace(/\/$/, ""); - const filePath = currentDir + fileName; - - let response: Response; - - try { - const fileInfo = await stat(filePath); - if (fileInfo.isDirectory()) { - // Bug with deno.stat: name and path not populated - // Yuck! - response = await serveDir(req, filePath, fileName); - } else { - response = await serveFile(req, filePath); - } - } catch (e) { - response = await serveFallback(req, e); - } finally { - serverLog(req, response); - req.respond(response); - } -}); - -console.log(`HTTP server listening on http://${addr}/`); diff --git a/file_server_test.ts b/file_server_test.ts deleted file mode 100644 index a04ced7e5..000000000 --- a/file_server_test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { readFile } from "deno"; - -import { - test, - assert, - assertEqual -} from "https://deno.land/x/testing/testing.ts"; - -// Promise to completeResolve when all tests completes -let completeResolve; -export const completePromise = new Promise(res => (completeResolve = res)); -let completedTestCount = 0; - -function maybeCompleteTests() { - completedTestCount++; - // Change this when adding more tests - if (completedTestCount === 3) { - completeResolve(); - } -} - -export function runTests(serverReadyPromise: Promise) { - test(async function serveFile() { - await serverReadyPromise; - const res = await fetch("http://localhost:4500/.travis.yml"); - const downloadedFile = await res.text(); - const localFile = new TextDecoder().decode(await readFile("./.travis.yml")); - assertEqual(downloadedFile, localFile); - maybeCompleteTests(); - }); - - test(async function serveDirectory() { - await serverReadyPromise; - const res = await fetch("http://localhost:4500/"); - const page = await res.text(); - assert(page.includes(".travis.yml")); - maybeCompleteTests(); - }); - - test(async function serveFallback() { - await serverReadyPromise; - const res = await fetch("http://localhost:4500/badfile.txt"); - assertEqual(res.status, 404); - maybeCompleteTests(); - }); -} diff --git a/http.ts b/http.ts deleted file mode 100644 index bd45aea0d..000000000 --- a/http.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { listen, Conn, toAsyncIterator, Reader, copy } from "deno"; -import { BufReader, BufState, BufWriter } from "./bufio.ts"; -import { TextProtoReader } from "./textproto.ts"; -import { STATUS_TEXT } from "./http_status"; -import { assert } from "./util"; - -interface Deferred { - promise: Promise<{}>; - resolve: () => void; - reject: () => void; -} - -function deferred(): Deferred { - let resolve, reject; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { - promise, - resolve, - reject - }; -} - -interface ServeEnv { - reqQueue: ServerRequest[]; - serveDeferred: Deferred; -} - -// Continuously read more requests from conn until EOF -// Mutually calling with maybeHandleReq -// TODO: make them async function after this change is done -// https://github.com/tc39/ecma262/pull/1250 -// See https://v8.dev/blog/fast-async -export function serveConn(env: ServeEnv, conn: Conn) { - readRequest(conn).then(maybeHandleReq.bind(null, env, conn)); -} -function maybeHandleReq(env: ServeEnv, conn: Conn, maybeReq: any) { - const [req, _err] = maybeReq; - if (_err) { - conn.close(); // assume EOF for now... - return; - } - env.reqQueue.push(req); // push req to queue - env.serveDeferred.resolve(); // signal while loop to process it - // TODO: protection against client req flooding - serveConn(env, conn); // try read more (reusing connection) -} - -export async function* serve(addr: string) { - const listener = listen("tcp", addr); - const env: ServeEnv = { - reqQueue: [], // in case multiple promises are ready - serveDeferred: deferred() - }; - - // Routine that keeps calling accept - const acceptRoutine = () => { - const handleConn = (conn: Conn) => { - serveConn(env, conn); // don't block - scheduleAccept(); // schedule next accept - }; - const scheduleAccept = () => { - listener.accept().then(handleConn); - }; - scheduleAccept(); - }; - - acceptRoutine(); - - // Loop hack to allow yield (yield won't work in callbacks) - while (true) { - await env.serveDeferred.promise; - env.serveDeferred = deferred(); // use a new deferred - let queueToProcess = env.reqQueue; - env.reqQueue = []; - for (const result of queueToProcess) { - yield result; - } - } - listener.close(); -} - -export async function listenAndServe( - addr: string, - handler: (req: ServerRequest) => void -) { - const server = serve(addr); - - for await (const request of server) { - await handler(request); - } -} - -export interface Response { - status?: number; - headers?: Headers; - body?: Uint8Array | Reader; -} - -export function setContentLength(r: Response): void { - if (!r.headers) { - r.headers = new Headers(); - } - - if (r.body) { - if (!r.headers.has("content-length")) { - if (r.body instanceof Uint8Array) { - const bodyLength = r.body.byteLength; - r.headers.append("Content-Length", bodyLength.toString()); - } else { - r.headers.append("Transfer-Encoding", "chunked"); - } - } - } -} - -export class ServerRequest { - url: string; - method: string; - proto: string; - headers: Headers; - w: BufWriter; - - private async _streamBody(body: Reader, bodyLength: number) { - const n = await copy(this.w, body); - assert(n == bodyLength); - } - - private async _streamChunkedBody(body: Reader) { - const encoder = new TextEncoder(); - - for await (const chunk of toAsyncIterator(body)) { - const start = encoder.encode(`${chunk.byteLength.toString(16)}\r\n`); - const end = encoder.encode("\r\n"); - await this.w.write(start); - await this.w.write(chunk); - await this.w.write(end); - } - - const endChunk = encoder.encode("0\r\n\r\n"); - await this.w.write(endChunk); - } - - async respond(r: Response): Promise { - const protoMajor = 1; - const protoMinor = 1; - const statusCode = r.status || 200; - const statusText = STATUS_TEXT.get(statusCode); - if (!statusText) { - throw Error("bad status code"); - } - - let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`; - - setContentLength(r); - - if (r.headers) { - for (const [key, value] of r.headers) { - out += `${key}: ${value}\r\n`; - } - } - out += "\r\n"; - - const header = new TextEncoder().encode(out); - let n = await this.w.write(header); - assert(header.byteLength == n); - - if (r.body) { - if (r.body instanceof Uint8Array) { - n = await this.w.write(r.body); - assert(r.body.byteLength == n); - } else { - if (r.headers.has("content-length")) { - await this._streamBody( - r.body, - parseInt(r.headers.get("content-length")) - ); - } else { - await this._streamChunkedBody(r.body); - } - } - } - - await this.w.flush(); - } -} - -async function readRequest(c: Conn): Promise<[ServerRequest, BufState]> { - const bufr = new BufReader(c); - const bufw = new BufWriter(c); - const req = new ServerRequest(); - req.w = bufw; - const tp = new TextProtoReader(bufr); - - let s: string; - let err: BufState; - - // First line: GET /index.html HTTP/1.0 - [s, err] = await tp.readLine(); - if (err) { - return [null, err]; - } - [req.method, req.url, req.proto] = s.split(" ", 3); - - [req.headers, err] = await tp.readMIMEHeader(); - - // TODO: handle body - - return [req, err]; -} diff --git a/http_bench.ts b/http_bench.ts deleted file mode 100644 index 8e1e24ad6..000000000 --- a/http_bench.ts +++ /dev/null @@ -1,15 +0,0 @@ -import * as deno from "deno"; -import { serve } from "./http.ts"; - -const addr = deno.args[1] || "127.0.0.1:4500"; -const server = serve(addr); - -const body = new TextEncoder().encode("Hello World"); - -async function main(): Promise { - for await (const request of server) { - await request.respond({ status: 200, body }); - } -} - -main(); diff --git a/http_status.ts b/http_status.ts deleted file mode 100644 index a3006d319..000000000 --- a/http_status.ts +++ /dev/null @@ -1,134 +0,0 @@ -export enum Status { - Continue = 100, // RFC 7231, 6.2.1 - SwitchingProtocols = 101, // RFC 7231, 6.2.2 - Processing = 102, // RFC 2518, 10.1 - - OK = 200, // RFC 7231, 6.3.1 - Created = 201, // RFC 7231, 6.3.2 - Accepted = 202, // RFC 7231, 6.3.3 - NonAuthoritativeInfo = 203, // RFC 7231, 6.3.4 - NoContent = 204, // RFC 7231, 6.3.5 - ResetContent = 205, // RFC 7231, 6.3.6 - PartialContent = 206, // RFC 7233, 4.1 - MultiStatus = 207, // RFC 4918, 11.1 - AlreadyReported = 208, // RFC 5842, 7.1 - IMUsed = 226, // RFC 3229, 10.4.1 - - MultipleChoices = 300, // RFC 7231, 6.4.1 - MovedPermanently = 301, // RFC 7231, 6.4.2 - Found = 302, // RFC 7231, 6.4.3 - SeeOther = 303, // RFC 7231, 6.4.4 - NotModified = 304, // RFC 7232, 4.1 - UseProxy = 305, // RFC 7231, 6.4.5 - // _ = 306, // RFC 7231, 6.4.6 (Unused) - TemporaryRedirect = 307, // RFC 7231, 6.4.7 - PermanentRedirect = 308, // RFC 7538, 3 - - BadRequest = 400, // RFC 7231, 6.5.1 - Unauthorized = 401, // RFC 7235, 3.1 - PaymentRequired = 402, // RFC 7231, 6.5.2 - Forbidden = 403, // RFC 7231, 6.5.3 - NotFound = 404, // RFC 7231, 6.5.4 - MethodNotAllowed = 405, // RFC 7231, 6.5.5 - NotAcceptable = 406, // RFC 7231, 6.5.6 - ProxyAuthRequired = 407, // RFC 7235, 3.2 - RequestTimeout = 408, // RFC 7231, 6.5.7 - Conflict = 409, // RFC 7231, 6.5.8 - Gone = 410, // RFC 7231, 6.5.9 - LengthRequired = 411, // RFC 7231, 6.5.10 - PreconditionFailed = 412, // RFC 7232, 4.2 - RequestEntityTooLarge = 413, // RFC 7231, 6.5.11 - RequestURITooLong = 414, // RFC 7231, 6.5.12 - UnsupportedMediaType = 415, // RFC 7231, 6.5.13 - RequestedRangeNotSatisfiable = 416, // RFC 7233, 4.4 - ExpectationFailed = 417, // RFC 7231, 6.5.14 - Teapot = 418, // RFC 7168, 2.3.3 - MisdirectedRequest = 421, // RFC 7540, 9.1.2 - UnprocessableEntity = 422, // RFC 4918, 11.2 - Locked = 423, // RFC 4918, 11.3 - FailedDependency = 424, // RFC 4918, 11.4 - UpgradeRequired = 426, // RFC 7231, 6.5.15 - PreconditionRequired = 428, // RFC 6585, 3 - TooManyRequests = 429, // RFC 6585, 4 - RequestHeaderFieldsTooLarge = 431, // RFC 6585, 5 - UnavailableForLegalReasons = 451, // RFC 7725, 3 - - InternalServerError = 500, // RFC 7231, 6.6.1 - NotImplemented = 501, // RFC 7231, 6.6.2 - BadGateway = 502, // RFC 7231, 6.6.3 - ServiceUnavailable = 503, // RFC 7231, 6.6.4 - GatewayTimeout = 504, // RFC 7231, 6.6.5 - HTTPVersionNotSupported = 505, // RFC 7231, 6.6.6 - VariantAlsoNegotiates = 506, // RFC 2295, 8.1 - InsufficientStorage = 507, // RFC 4918, 11.5 - LoopDetected = 508, // RFC 5842, 7.2 - NotExtended = 510, // RFC 2774, 7 - NetworkAuthenticationRequired = 511 // RFC 6585, 6 -} - -export const STATUS_TEXT = new Map([ - [Status.Continue, "Continue"], - [Status.SwitchingProtocols, "Switching Protocols"], - [Status.Processing, "Processing"], - - [Status.OK, "OK"], - [Status.Created, "Created"], - [Status.Accepted, "Accepted"], - [Status.NonAuthoritativeInfo, "Non-Authoritative Information"], - [Status.NoContent, "No Content"], - [Status.ResetContent, "Reset Content"], - [Status.PartialContent, "Partial Content"], - [Status.MultiStatus, "Multi-Status"], - [Status.AlreadyReported, "Already Reported"], - [Status.IMUsed, "IM Used"], - - [Status.MultipleChoices, "Multiple Choices"], - [Status.MovedPermanently, "Moved Permanently"], - [Status.Found, "Found"], - [Status.SeeOther, "See Other"], - [Status.NotModified, "Not Modified"], - [Status.UseProxy, "Use Proxy"], - [Status.TemporaryRedirect, "Temporary Redirect"], - [Status.PermanentRedirect, "Permanent Redirect"], - - [Status.BadRequest, "Bad Request"], - [Status.Unauthorized, "Unauthorized"], - [Status.PaymentRequired, "Payment Required"], - [Status.Forbidden, "Forbidden"], - [Status.NotFound, "Not Found"], - [Status.MethodNotAllowed, "Method Not Allowed"], - [Status.NotAcceptable, "Not Acceptable"], - [Status.ProxyAuthRequired, "Proxy Authentication Required"], - [Status.RequestTimeout, "Request Timeout"], - [Status.Conflict, "Conflict"], - [Status.Gone, "Gone"], - [Status.LengthRequired, "Length Required"], - [Status.PreconditionFailed, "Precondition Failed"], - [Status.RequestEntityTooLarge, "Request Entity Too Large"], - [Status.RequestURITooLong, "Request URI Too Long"], - [Status.UnsupportedMediaType, "Unsupported Media Type"], - [Status.RequestedRangeNotSatisfiable, "Requested Range Not Satisfiable"], - [Status.ExpectationFailed, "Expectation Failed"], - [Status.Teapot, "I'm a teapot"], - [Status.MisdirectedRequest, "Misdirected Request"], - [Status.UnprocessableEntity, "Unprocessable Entity"], - [Status.Locked, "Locked"], - [Status.FailedDependency, "Failed Dependency"], - [Status.UpgradeRequired, "Upgrade Required"], - [Status.PreconditionRequired, "Precondition Required"], - [Status.TooManyRequests, "Too Many Requests"], - [Status.RequestHeaderFieldsTooLarge, "Request Header Fields Too Large"], - [Status.UnavailableForLegalReasons, "Unavailable For Legal Reasons"], - - [Status.InternalServerError, "Internal Server Error"], - [Status.NotImplemented, "Not Implemented"], - [Status.BadGateway, "Bad Gateway"], - [Status.ServiceUnavailable, "Service Unavailable"], - [Status.GatewayTimeout, "Gateway Timeout"], - [Status.HTTPVersionNotSupported, "HTTP Version Not Supported"], - [Status.VariantAlsoNegotiates, "Variant Also Negotiates"], - [Status.InsufficientStorage, "Insufficient Storage"], - [Status.LoopDetected, "Loop Detected"], - [Status.NotExtended, "Not Extended"], - [Status.NetworkAuthenticationRequired, "Network Authentication Required"] -]); diff --git a/http_test.ts b/http_test.ts deleted file mode 100644 index cdb7f8303..000000000 --- a/http_test.ts +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Ported from -// https://github.com/golang/go/blob/master/src/net/http/responsewrite_test.go - -import { - test, - assert, - assertEqual -} from "https://deno.land/x/testing/testing.ts"; - -import { - listenAndServe, - ServerRequest, - setContentLength, - Response -} from "./http"; -import { Buffer } from "deno"; -import { BufWriter } from "./bufio"; - -interface ResponseTest { - response: Response; - raw: string; -} - -const responseTests: ResponseTest[] = [ - // Default response - { - response: {}, - raw: "HTTP/1.1 200 OK\r\n" + "\r\n" - }, - // HTTP/1.1, chunked coding; empty trailer; close - { - response: { - status: 200, - body: new Buffer(new TextEncoder().encode("abcdef")) - }, - - raw: - "HTTP/1.1 200 OK\r\n" + - "transfer-encoding: chunked\r\n\r\n" + - "6\r\nabcdef\r\n0\r\n\r\n" - } -]; - -test(async function responseWrite() { - for (const testCase of responseTests) { - const buf = new Buffer(); - const bufw = new BufWriter(buf); - const request = new ServerRequest(); - request.w = bufw; - - await request.respond(testCase.response); - assertEqual(buf.toString(), testCase.raw); - } -}); diff --git a/iotest.ts b/iotest.ts deleted file mode 100644 index e3a42f58a..000000000 --- a/iotest.ts +++ /dev/null @@ -1,61 +0,0 @@ -// Ported to Deno from -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import { Reader, ReadResult } from "deno"; - -/** OneByteReader returns a Reader that implements - * each non-empty Read by reading one byte from r. - */ -export class OneByteReader implements Reader { - constructor(readonly r: Reader) {} - - async read(p: Uint8Array): Promise { - if (p.byteLength === 0) { - return { nread: 0, eof: false }; - } - if (!(p instanceof Uint8Array)) { - throw Error("expected Uint8Array"); - } - return this.r.read(p.subarray(0, 1)); - } -} - -/** HalfReader returns a Reader that implements Read - * by reading half as many requested bytes from r. - */ -export class HalfReader implements Reader { - constructor(readonly r: Reader) {} - - async read(p: Uint8Array): Promise { - if (!(p instanceof Uint8Array)) { - throw Error("expected Uint8Array"); - } - const half = Math.floor((p.byteLength + 1) / 2); - return this.r.read(p.subarray(0, half)); - } -} - -export class ErrTimeout extends Error { - constructor() { - super("timeout"); - this.name = "ErrTimeout"; - } -} - -/** TimeoutReader returns ErrTimeout on the second read - * with no data. Subsequent calls to read succeed. - */ -export class TimeoutReader implements Reader { - count = 0; - constructor(readonly r: Reader) {} - - async read(p: Uint8Array): Promise { - this.count++; - if (this.count === 2) { - throw new ErrTimeout(); - } - return this.r.read(p); - } -} diff --git a/net/bufio.ts b/net/bufio.ts new file mode 100644 index 000000000..b412cbce8 --- /dev/null +++ b/net/bufio.ts @@ -0,0 +1,465 @@ +// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio.go +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { Reader, ReadResult, Writer } from "deno"; +import { assert, charCode, copyBytes } from "./util.ts"; + +const DEFAULT_BUF_SIZE = 4096; +const MIN_BUF_SIZE = 16; +const MAX_CONSECUTIVE_EMPTY_READS = 100; +const CR = charCode("\r"); +const LF = charCode("\n"); + +export type BufState = + | null + | "EOF" + | "BufferFull" + | "ShortWrite" + | "NoProgress" + | Error; + +/** BufReader implements buffering for a Reader object. */ +export class BufReader implements Reader { + private buf: Uint8Array; + private rd: Reader; // Reader provided by caller. + private r = 0; // buf read position. + private w = 0; // buf write position. + private lastByte: number; + private lastCharSize: number; + private err: BufState; + + constructor(rd: Reader, size = DEFAULT_BUF_SIZE) { + if (size < MIN_BUF_SIZE) { + size = MIN_BUF_SIZE; + } + this._reset(new Uint8Array(size), rd); + } + + /** Returns the size of the underlying buffer in bytes. */ + size(): number { + return this.buf.byteLength; + } + + buffered(): number { + return this.w - this.r; + } + + private _readErr(): BufState { + const err = this.err; + this.err = null; + return err; + } + + // Reads a new chunk into the buffer. + private async _fill(): Promise { + // Slide existing data to beginning. + if (this.r > 0) { + this.buf.copyWithin(0, this.r, this.w); + this.w -= this.r; + this.r = 0; + } + + if (this.w >= this.buf.byteLength) { + throw Error("bufio: tried to fill full buffer"); + } + + // Read new data: try a limited number of times. + for (let i = MAX_CONSECUTIVE_EMPTY_READS; i > 0; i--) { + let rr: ReadResult; + try { + rr = await this.rd.read(this.buf.subarray(this.w)); + } catch (e) { + this.err = e; + return; + } + assert(rr.nread >= 0, "negative read"); + this.w += rr.nread; + if (rr.eof) { + this.err = "EOF"; + return; + } + if (rr.nread > 0) { + return; + } + } + this.err = "NoProgress"; + } + + /** Discards any buffered data, resets all state, and switches + * the buffered reader to read from r. + */ + reset(r: Reader): void { + this._reset(this.buf, r); + } + + private _reset(buf: Uint8Array, rd: Reader): void { + this.buf = buf; + this.rd = rd; + this.lastByte = -1; + // this.lastRuneSize = -1; + } + + /** reads data into p. + * It returns the number of bytes read into p. + * The bytes are taken from at most one Read on the underlying Reader, + * hence n may be less than len(p). + * At EOF, the count will be zero and err will be io.EOF. + * To read exactly len(p) bytes, use io.ReadFull(b, p). + */ + async read(p: Uint8Array): Promise { + let rr: ReadResult = { nread: p.byteLength, eof: false }; + if (rr.nread === 0) { + if (this.err) { + throw this._readErr(); + } + return rr; + } + + if (this.r === this.w) { + if (this.err) { + throw this._readErr(); + } + if (p.byteLength >= this.buf.byteLength) { + // Large read, empty buffer. + // Read directly into p to avoid copy. + rr = await this.rd.read(p); + assert(rr.nread >= 0, "negative read"); + if (rr.nread > 0) { + this.lastByte = p[rr.nread - 1]; + // this.lastRuneSize = -1; + } + if (this.err) { + throw this._readErr(); + } + return rr; + } + // One read. + // Do not use this.fill, which will loop. + this.r = 0; + this.w = 0; + try { + rr = await this.rd.read(this.buf); + } catch (e) { + this.err = e; + } + assert(rr.nread >= 0, "negative read"); + if (rr.nread === 0) { + if (this.err) { + throw this._readErr(); + } + return rr; + } + this.w += rr.nread; + } + + // copy as much as we can + rr.nread = copyBytes(p as Uint8Array, this.buf.subarray(this.r, this.w), 0); + this.r += rr.nread; + this.lastByte = this.buf[this.r - 1]; + // this.lastRuneSize = -1; + return rr; + } + + /** reads exactly len(p) bytes into p. + * Ported from https://golang.org/pkg/io/#ReadFull + * It returns the number of bytes copied and an error if fewer bytes were read. + * The error is EOF only if no bytes were read. + * If an EOF happens after reading some but not all the bytes, + * readFull returns ErrUnexpectedEOF. ("EOF" for current impl) + * On return, n == len(p) if and only if err == nil. + * If r returns an error having read at least len(buf) bytes, + * the error is dropped. + */ + async readFull(p: Uint8Array): Promise<[number, BufState]> { + let rr = await this.read(p); + let nread = rr.nread; + if (rr.eof) { + return [nread, nread < p.length ? "EOF" : null]; + } + while (!rr.eof && nread < p.length) { + rr = await this.read(p.subarray(nread)); + nread += rr.nread; + } + return [nread, nread < p.length ? "EOF" : null]; + } + + + /** Returns the next byte [0, 255] or -1 if EOF. */ + async readByte(): Promise { + while (this.r === this.w) { + await this._fill(); // buffer is empty. + if (this.err == "EOF") { + return -1; + } + if (this.err != null) { + throw this._readErr(); + } + } + const c = this.buf[this.r]; + this.r++; + this.lastByte = c; + return c; + } + + /** readString() reads until the first occurrence of delim in the input, + * returning a string containing the data up to and including the delimiter. + * If ReadString encounters an error before finding a delimiter, + * it returns the data read before the error and the error itself (often io.EOF). + * ReadString returns err != nil if and only if the returned data does not end in + * delim. + * For simple uses, a Scanner may be more convenient. + */ + async readString(delim: string): Promise { + throw new Error("Not implemented"); + } + + /** readLine() is a low-level line-reading primitive. Most callers should use + * readBytes('\n') or readString('\n') instead or use a Scanner. + * + * readLine tries to return a single line, not including the end-of-line bytes. + * If the line was too long for the buffer then isPrefix is set and the + * beginning of the line is returned. The rest of the line will be returned + * from future calls. isPrefix will be false when returning the last fragment + * of the line. The returned buffer is only valid until the next call to + * ReadLine. ReadLine either returns a non-nil line or it returns an error, + * never both. + * + * The text returned from ReadLine does not include the line end ("\r\n" or "\n"). + * No indication or error is given if the input ends without a final line end. + * Calling UnreadByte after ReadLine will always unread the last byte read + * (possibly a character belonging to the line end) even if that byte is not + * part of the line returned by ReadLine. + */ + async readLine(): Promise<[Uint8Array, boolean, BufState]> { + let [line, err] = await this.readSlice(LF); + + if (err === "BufferFull") { + // Handle the case where "\r\n" straddles the buffer. + if (line.byteLength > 0 && line[line.byteLength - 1] === CR) { + // Put the '\r' back on buf and drop it from line. + // Let the next call to ReadLine check for "\r\n". + assert(this.r > 0, "bufio: tried to rewind past start of buffer"); + this.r--; + line = line.subarray(0, line.byteLength - 1); + } + return [line, true, null]; + } + + if (line.byteLength === 0) { + return [line, false, err]; + } + err = null; + + if (line[line.byteLength - 1] == LF) { + let drop = 1; + if (line.byteLength > 1 && line[line.byteLength - 2] === CR) { + drop = 2; + } + line = line.subarray(0, line.byteLength - drop); + } + return [line, false, err]; + } + + /** readSlice() reads until the first occurrence of delim in the input, + * returning a slice pointing at the bytes in the buffer. The bytes stop + * being valid at the next read. If readSlice() encounters an error before + * finding a delimiter, it returns all the data in the buffer and the error + * itself (often io.EOF). readSlice() fails with error ErrBufferFull if the + * buffer fills without a delim. Because the data returned from readSlice() + * will be overwritten by the next I/O operation, most clients should use + * readBytes() or readString() instead. readSlice() returns err != nil if and + * only if line does not end in delim. + */ + async readSlice(delim: number): Promise<[Uint8Array, BufState]> { + let s = 0; // search start index + let line: Uint8Array; + let err: BufState; + while (true) { + // Search buffer. + let i = this.buf.subarray(this.r + s, this.w).indexOf(delim); + if (i >= 0) { + i += s; + line = this.buf.subarray(this.r, this.r + i + 1); + this.r += i + 1; + break; + } + + // Pending error? + if (this.err) { + line = this.buf.subarray(this.r, this.w); + this.r = this.w; + err = this._readErr(); + break; + } + + // Buffer full? + if (this.buffered() >= this.buf.byteLength) { + this.r = this.w; + line = this.buf; + err = "BufferFull"; + break; + } + + s = this.w - this.r; // do not rescan area we scanned before + + await this._fill(); // buffer is not full + } + + // Handle last byte, if any. + let i = line.byteLength - 1; + if (i >= 0) { + this.lastByte = line[i]; + // this.lastRuneSize = -1 + } + + return [line, err]; + } + + /** Peek returns the next n bytes without advancing the reader. The bytes stop + * being valid at the next read call. If Peek returns fewer than n bytes, it + * also returns an error explaining why the read is short. The error is + * ErrBufferFull if n is larger than b's buffer size. + */ + async peek(n: number): Promise<[Uint8Array, BufState]> { + if (n < 0) { + throw Error("negative count"); + } + + while ( + this.w - this.r < n && + this.w - this.r < this.buf.byteLength && + this.err == null + ) { + await this._fill(); // this.w - this.r < len(this.buf) => buffer is not full + } + + if (n > this.buf.byteLength) { + return [this.buf.subarray(this.r, this.w), "BufferFull"]; + } + + // 0 <= n <= len(this.buf) + let err: BufState; + let avail = this.w - this.r; + if (avail < n) { + // not enough data in buffer + n = avail; + err = this._readErr(); + if (!err) { + err = "BufferFull"; + } + } + return [this.buf.subarray(this.r, this.r + n), err]; + } +} + +/** BufWriter implements buffering for an deno.Writer object. + * If an error occurs writing to a Writer, no more data will be + * accepted and all subsequent writes, and flush(), will return the error. + * After all data has been written, the client should call the + * flush() method to guarantee all data has been forwarded to + * the underlying deno.Writer. + */ +export class BufWriter implements Writer { + buf: Uint8Array; + n: number = 0; + err: null | BufState = null; + + constructor(private wr: Writer, size = DEFAULT_BUF_SIZE) { + if (size <= 0) { + size = DEFAULT_BUF_SIZE; + } + this.buf = new Uint8Array(size); + } + + /** Size returns the size of the underlying buffer in bytes. */ + size(): number { + return this.buf.byteLength; + } + + /** Discards any unflushed buffered data, clears any error, and + * resets b to write its output to w. + */ + reset(w: Writer): void { + this.err = null; + this.n = 0; + this.wr = w; + } + + /** Flush writes any buffered data to the underlying io.Writer. */ + async flush(): Promise { + if (this.err != null) { + return this.err; + } + if (this.n == 0) { + return null; + } + + let n: number; + let err: BufState = null; + try { + n = await this.wr.write(this.buf.subarray(0, this.n)); + } catch (e) { + err = e; + } + + if (n < this.n && err == null) { + err = "ShortWrite"; + } + + if (err != null) { + if (n > 0 && n < this.n) { + this.buf.copyWithin(0, n, this.n); + } + this.n -= n; + this.err = err; + return err; + } + this.n = 0; + } + + /** Returns how many bytes are unused in the buffer. */ + available(): number { + return this.buf.byteLength - this.n; + } + + /** buffered returns the number of bytes that have been written into the + * current buffer. + */ + buffered(): number { + return this.n; + } + + /** Writes the contents of p into the buffer. + * Returns the number of bytes written. + */ + async write(p: Uint8Array): Promise { + let nn = 0; + let n: number; + while (p.byteLength > this.available() && !this.err) { + if (this.buffered() == 0) { + // Large write, empty buffer. + // Write directly from p to avoid copy. + try { + n = await this.wr.write(p); + } catch (e) { + this.err = e; + } + } else { + n = copyBytes(this.buf, p, this.n); + this.n += n; + await this.flush(); + } + nn += n; + p = p.subarray(n); + } + if (this.err) { + throw this.err; + } + n = copyBytes(this.buf, p, this.n); + this.n += n; + nn += n; + return nn; + } +} diff --git a/net/bufio_test.ts b/net/bufio_test.ts new file mode 100644 index 000000000..19954bdf6 --- /dev/null +++ b/net/bufio_test.ts @@ -0,0 +1,345 @@ +// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio_test.go +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { Buffer, Reader, ReadResult } from "deno"; +import { + test, + assert, + assertEqual +} from "https://deno.land/x/testing/testing.ts"; +import { BufReader, BufState, BufWriter } from "./bufio.ts"; +import * as iotest from "./iotest.ts"; +import { charCode, copyBytes, stringsReader } from "./util.ts"; + +const encoder = new TextEncoder(); + +async function readBytes(buf: BufReader): Promise { + const b = new Uint8Array(1000); + let nb = 0; + while (true) { + let c = await buf.readByte(); + if (c < 0) { + break; // EOF + } + b[nb] = c; + nb++; + } + const decoder = new TextDecoder(); + return decoder.decode(b.subarray(0, nb)); +} + +test(async function bufioReaderSimple() { + const data = "hello world"; + const b = new BufReader(stringsReader(data)); + const s = await readBytes(b); + assertEqual(s, data); +}); + +type ReadMaker = { name: string; fn: (r: Reader) => Reader }; + +const readMakers: ReadMaker[] = [ + { name: "full", fn: r => r }, + { name: "byte", fn: r => new iotest.OneByteReader(r) }, + { name: "half", fn: r => new iotest.HalfReader(r) } + // TODO { name: "data+err", r => new iotest.DataErrReader(r) }, + // { name: "timeout", fn: r => new iotest.TimeoutReader(r) }, +]; + +function readLines(b: BufReader): string { + let s = ""; + while (true) { + let s1 = b.readString("\n"); + if (s1 == null) { + break; // EOF + } + s += s1; + } + return s; +} + +// Call read to accumulate the text of a file +async function reads(buf: BufReader, m: number): Promise { + const b = new Uint8Array(1000); + let nb = 0; + while (true) { + const { nread, eof } = await buf.read(b.subarray(nb, nb + m)); + nb += nread; + if (eof) { + break; + } + } + const decoder = new TextDecoder(); + return decoder.decode(b.subarray(0, nb)); +} + +type NamedBufReader = { name: string; fn: (r: BufReader) => Promise }; + +const bufreaders: NamedBufReader[] = [ + { name: "1", fn: (b: BufReader) => reads(b, 1) }, + { name: "2", fn: (b: BufReader) => reads(b, 2) }, + { name: "3", fn: (b: BufReader) => reads(b, 3) }, + { name: "4", fn: (b: BufReader) => reads(b, 4) }, + { name: "5", fn: (b: BufReader) => reads(b, 5) }, + { name: "7", fn: (b: BufReader) => reads(b, 7) }, + { name: "bytes", fn: readBytes } + // { name: "lines", fn: readLines }, +]; + +const MIN_READ_BUFFER_SIZE = 16; +const bufsizes: number[] = [ + 0, + MIN_READ_BUFFER_SIZE, + 23, + 32, + 46, + 64, + 93, + 128, + 1024, + 4096 +]; + +test(async function bufioBufReader() { + const texts = new Array(31); + let str = ""; + let all = ""; + for (let i = 0; i < texts.length - 1; i++) { + texts[i] = str + "\n"; + all += texts[i]; + str += String.fromCharCode(i % 26 + 97); + } + texts[texts.length - 1] = all; + + for (let text of texts) { + for (let readmaker of readMakers) { + for (let bufreader of bufreaders) { + for (let bufsize of bufsizes) { + const read = readmaker.fn(stringsReader(text)); + const buf = new BufReader(read, bufsize); + const s = await bufreader.fn(buf); + const debugStr = + `reader=${readmaker.name} ` + + `fn=${bufreader.name} bufsize=${bufsize} want=${text} got=${s}`; + assertEqual(s, text, debugStr); + } + } + } + } +}); + +test(async function bufioBufferFull() { + const longString = + "And now, hello, world! It is the time for all good men to come to the aid of their party"; + const buf = new BufReader(stringsReader(longString), MIN_READ_BUFFER_SIZE); + let [line, err] = await buf.readSlice(charCode("!")); + + const decoder = new TextDecoder(); + let actual = decoder.decode(line); + assertEqual(err, "BufferFull"); + assertEqual(actual, "And now, hello, "); + + [line, err] = await buf.readSlice(charCode("!")); + actual = decoder.decode(line); + assertEqual(actual, "world!"); + assert(err == null); +}); + +const testInput = encoder.encode( + "012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy" +); +const testInputrn = encoder.encode( + "012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n" +); +const testOutput = encoder.encode("0123456789abcdefghijklmnopqrstuvwxy"); + +// TestReader wraps a Uint8Array and returns reads of a specific length. +class TestReader implements Reader { + constructor(private data: Uint8Array, private stride: number) {} + + async read(buf: Uint8Array): Promise { + let nread = this.stride; + if (nread > this.data.byteLength) { + nread = this.data.byteLength; + } + if (nread > buf.byteLength) { + nread = buf.byteLength; + } + copyBytes(buf as Uint8Array, this.data); + this.data = this.data.subarray(nread); + let eof = false; + if (this.data.byteLength == 0) { + eof = true; + } + return { nread, eof }; + } +} + +async function testReadLine(input: Uint8Array): Promise { + for (let stride = 1; stride < 2; stride++) { + let done = 0; + let reader = new TestReader(input, stride); + let l = new BufReader(reader, input.byteLength + 1); + while (true) { + let [line, isPrefix, err] = await l.readLine(); + if (line.byteLength > 0 && err != null) { + throw Error("readLine returned both data and error"); + } + assertEqual(isPrefix, false); + if (err == "EOF") { + break; + } + let want = testOutput.subarray(done, done + line.byteLength); + assertEqual( + line, + want, + `Bad line at stride ${stride}: want: ${want} got: ${line}` + ); + done += line.byteLength; + } + assertEqual( + done, + testOutput.byteLength, + `readLine didn't return everything: got: ${done}, ` + + `want: ${testOutput} (stride: ${stride})` + ); + } +} + +test(async function bufioReadLine() { + await testReadLine(testInput); + await testReadLine(testInputrn); +}); + +test(async function bufioPeek() { + const decoder = new TextDecoder(); + let p = new Uint8Array(10); + // string is 16 (minReadBufferSize) long. + let buf = new BufReader( + stringsReader("abcdefghijklmnop"), + MIN_READ_BUFFER_SIZE + ); + + let [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "a"); + assert(err == null); + + [actual, err] = await buf.peek(4); + assertEqual(decoder.decode(actual), "abcd"); + assert(err == null); + + [actual, err] = await buf.peek(32); + assertEqual(decoder.decode(actual), "abcdefghijklmnop"); + assertEqual(err, "BufferFull"); + + await buf.read(p.subarray(0, 3)); + assertEqual(decoder.decode(p.subarray(0, 3)), "abc"); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "d"); + assert(err == null); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "d"); + assert(err == null); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "d"); + assert(err == null); + + [actual, err] = await buf.peek(2); + assertEqual(decoder.decode(actual), "de"); + assert(err == null); + + let { eof } = await buf.read(p.subarray(0, 3)); + assertEqual(decoder.decode(p.subarray(0, 3)), "def"); + assert(!eof); + assert(err == null); + + [actual, err] = await buf.peek(4); + assertEqual(decoder.decode(actual), "ghij"); + assert(err == null); + + await buf.read(p); + assertEqual(decoder.decode(p), "ghijklmnop"); + + [actual, err] = await buf.peek(0); + assertEqual(decoder.decode(actual), ""); + assert(err == null); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), ""); + assert(err == "EOF"); + /* TODO + // Test for issue 3022, not exposing a reader's error on a successful Peek. + buf = NewReaderSize(dataAndEOFReader("abcd"), 32) + if s, err := buf.Peek(2); string(s) != "ab" || err != nil { + t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err) + } + if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { + t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err) + } + if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil { + t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err) + } + if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF { + t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err) + } + */ +}); + +test(async function bufioWriter() { + const data = new Uint8Array(8192); + + for (let i = 0; i < data.byteLength; i++) { + data[i] = charCode(" ") + i % (charCode("~") - charCode(" ")); + } + + const w = new Buffer(); + for (let nwrite of bufsizes) { + for (let bs of bufsizes) { + // Write nwrite bytes using buffer size bs. + // Check that the right amount makes it out + // and that the data is correct. + + w.reset(); + const buf = new BufWriter(w, bs); + + const context = `nwrite=${nwrite} bufsize=${bs}`; + const n = await buf.write(data.subarray(0, nwrite)); + assertEqual(n, nwrite, context); + + await buf.flush(); + + const written = w.bytes(); + assertEqual(written.byteLength, nwrite); + + for (let l = 0; l < written.byteLength; l++) { + assertEqual(written[l], data[l]); + } + } + } +}); + +test(async function bufReaderReadFull() { + const enc = new TextEncoder(); + const dec = new TextDecoder(); + const text = "Hello World"; + const data = new Buffer(enc.encode(text)); + const bufr = new BufReader(data, 3); + { + const buf = new Uint8Array(6); + const [nread, err] = await bufr.readFull(buf); + assertEqual(nread, 6); + assert(!err); + assertEqual(dec.decode(buf), "Hello "); + } + { + const buf = new Uint8Array(6); + const [nread, err] = await bufr.readFull(buf); + assertEqual(nread, 5); + assertEqual(err, "EOF"); + assertEqual(dec.decode(buf.subarray(0, 5)), "World"); + } +}); diff --git a/net/file_server.ts b/net/file_server.ts new file mode 100755 index 000000000..bd1c52b88 --- /dev/null +++ b/net/file_server.ts @@ -0,0 +1,214 @@ +#!/usr/bin/env deno --allow-net + +// This program serves files in the current directory over HTTP. +// TODO Stream responses instead of reading them into memory. +// TODO Add tests like these: +// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js + +import { + listenAndServe, + ServerRequest, + setContentLength, + Response +} from "./http"; +import { cwd, DenoError, ErrorKind, args, stat, readDir, open } from "deno"; + +const dirViewerTemplate = ` + + + + + + + Deno File Server + + + +

Index of <%DIRNAME%>

+ + + <%CONTENTS%> +
ModeSizeName
+ + +`; + +let currentDir = cwd(); +const target = args[1]; +if (target) { + currentDir = `${currentDir}/${target}`; +} +const addr = `0.0.0.0:${args[2] || 4500}`; +const encoder = new TextEncoder(); + +function modeToString(isDir: boolean, maybeMode: number | null) { + const modeMap = ["---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"]; + + if (maybeMode === null) { + return "(unknown mode)"; + } + const mode = maybeMode!.toString(8); + if (mode.length < 3) { + return "(unknown mode)"; + } + let output = ""; + mode + .split("") + .reverse() + .slice(0, 3) + .forEach(v => { + output = modeMap[+v] + output; + }); + output = `(${isDir ? "d" : "-"}${output})`; + return output; +} + +function fileLenToString(len: number) { + const multipler = 1024; + let base = 1; + const suffix = ["B", "K", "M", "G", "T"]; + let suffixIndex = 0; + + while (base * multipler < len) { + if (suffixIndex >= suffix.length - 1) { + break; + } + base *= multipler; + suffixIndex++; + } + + return `${(len / base).toFixed(2)}${suffix[suffixIndex]}`; +} + +function createDirEntryDisplay( + name: string, + path: string, + size: number | null, + mode: number | null, + isDir: boolean +) { + const sizeStr = size === null ? "" : "" + fileLenToString(size!); + return ` + ${modeToString( + isDir, + mode + )}${sizeStr}${name}${ + isDir ? "/" : "" + } + + `; +} + +// TODO: simplify this after deno.stat and deno.readDir are fixed +async function serveDir(req: ServerRequest, dirPath: string, dirName: string) { + // dirname has no prefix + const listEntry: string[] = []; + const fileInfos = await readDir(dirPath); + for (const info of fileInfos) { + if (info.name === "index.html" && info.isFile()) { + // in case index.html as dir... + return await serveFile(req, info.path); + } + // Yuck! + let mode = null; + try { + mode = (await stat(info.path)).mode; + } catch (e) {} + listEntry.push( + createDirEntryDisplay( + info.name, + dirName + "/" + info.name, + info.isFile() ? info.len : null, + mode, + info.isDirectory() + ) + ); + } + + const page = new TextEncoder().encode( + dirViewerTemplate + .replace("<%DIRNAME%>", dirName + "/") + .replace("<%CONTENTS%>", listEntry.join("")) + ); + + const headers = new Headers(); + headers.set("content-type", "text/html"); + + const res = { + status: 200, + body: page, + headers + }; + setContentLength(res); + return res; +} + +async function serveFile(req: ServerRequest, filename: string) { + const file = await open(filename); + const fileInfo = await stat(filename); + const headers = new Headers(); + headers.set("content-length", fileInfo.len.toString()); + + const res = { + status: 200, + body: file, + headers + }; + return res; +} + +async function serveFallback(req: ServerRequest, e: Error) { + if ( + e instanceof DenoError && + (e as DenoError).kind === ErrorKind.NotFound + ) { + return { + status: 404, + body: encoder.encode("Not found") + }; + } else { + return { + status: 500, + body: encoder.encode("Internal server error") + }; + } +} + +function serverLog(req: ServerRequest, res: Response) { + const d = new Date().toISOString(); + const dateFmt = `[${d.slice(0, 10)} ${d.slice(11, 19)}]`; + const s = `${dateFmt} "${req.method} ${req.url} ${req.proto}" ${res.status}`; + console.log(s); +} + +listenAndServe(addr, async req => { + const fileName = req.url.replace(/\/$/, ""); + const filePath = currentDir + fileName; + + let response: Response; + + try { + const fileInfo = await stat(filePath); + if (fileInfo.isDirectory()) { + // Bug with deno.stat: name and path not populated + // Yuck! + response = await serveDir(req, filePath, fileName); + } else { + response = await serveFile(req, filePath); + } + } catch (e) { + response = await serveFallback(req, e); + } finally { + serverLog(req, response); + req.respond(response); + } +}); + +console.log(`HTTP server listening on http://${addr}/`); diff --git a/net/file_server_test.ts b/net/file_server_test.ts new file mode 100644 index 000000000..a04ced7e5 --- /dev/null +++ b/net/file_server_test.ts @@ -0,0 +1,46 @@ +import { readFile } from "deno"; + +import { + test, + assert, + assertEqual +} from "https://deno.land/x/testing/testing.ts"; + +// Promise to completeResolve when all tests completes +let completeResolve; +export const completePromise = new Promise(res => (completeResolve = res)); +let completedTestCount = 0; + +function maybeCompleteTests() { + completedTestCount++; + // Change this when adding more tests + if (completedTestCount === 3) { + completeResolve(); + } +} + +export function runTests(serverReadyPromise: Promise) { + test(async function serveFile() { + await serverReadyPromise; + const res = await fetch("http://localhost:4500/.travis.yml"); + const downloadedFile = await res.text(); + const localFile = new TextDecoder().decode(await readFile("./.travis.yml")); + assertEqual(downloadedFile, localFile); + maybeCompleteTests(); + }); + + test(async function serveDirectory() { + await serverReadyPromise; + const res = await fetch("http://localhost:4500/"); + const page = await res.text(); + assert(page.includes(".travis.yml")); + maybeCompleteTests(); + }); + + test(async function serveFallback() { + await serverReadyPromise; + const res = await fetch("http://localhost:4500/badfile.txt"); + assertEqual(res.status, 404); + maybeCompleteTests(); + }); +} diff --git a/net/http.ts b/net/http.ts new file mode 100644 index 000000000..bd45aea0d --- /dev/null +++ b/net/http.ts @@ -0,0 +1,212 @@ +import { listen, Conn, toAsyncIterator, Reader, copy } from "deno"; +import { BufReader, BufState, BufWriter } from "./bufio.ts"; +import { TextProtoReader } from "./textproto.ts"; +import { STATUS_TEXT } from "./http_status"; +import { assert } from "./util"; + +interface Deferred { + promise: Promise<{}>; + resolve: () => void; + reject: () => void; +} + +function deferred(): Deferred { + let resolve, reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { + promise, + resolve, + reject + }; +} + +interface ServeEnv { + reqQueue: ServerRequest[]; + serveDeferred: Deferred; +} + +// Continuously read more requests from conn until EOF +// Mutually calling with maybeHandleReq +// TODO: make them async function after this change is done +// https://github.com/tc39/ecma262/pull/1250 +// See https://v8.dev/blog/fast-async +export function serveConn(env: ServeEnv, conn: Conn) { + readRequest(conn).then(maybeHandleReq.bind(null, env, conn)); +} +function maybeHandleReq(env: ServeEnv, conn: Conn, maybeReq: any) { + const [req, _err] = maybeReq; + if (_err) { + conn.close(); // assume EOF for now... + return; + } + env.reqQueue.push(req); // push req to queue + env.serveDeferred.resolve(); // signal while loop to process it + // TODO: protection against client req flooding + serveConn(env, conn); // try read more (reusing connection) +} + +export async function* serve(addr: string) { + const listener = listen("tcp", addr); + const env: ServeEnv = { + reqQueue: [], // in case multiple promises are ready + serveDeferred: deferred() + }; + + // Routine that keeps calling accept + const acceptRoutine = () => { + const handleConn = (conn: Conn) => { + serveConn(env, conn); // don't block + scheduleAccept(); // schedule next accept + }; + const scheduleAccept = () => { + listener.accept().then(handleConn); + }; + scheduleAccept(); + }; + + acceptRoutine(); + + // Loop hack to allow yield (yield won't work in callbacks) + while (true) { + await env.serveDeferred.promise; + env.serveDeferred = deferred(); // use a new deferred + let queueToProcess = env.reqQueue; + env.reqQueue = []; + for (const result of queueToProcess) { + yield result; + } + } + listener.close(); +} + +export async function listenAndServe( + addr: string, + handler: (req: ServerRequest) => void +) { + const server = serve(addr); + + for await (const request of server) { + await handler(request); + } +} + +export interface Response { + status?: number; + headers?: Headers; + body?: Uint8Array | Reader; +} + +export function setContentLength(r: Response): void { + if (!r.headers) { + r.headers = new Headers(); + } + + if (r.body) { + if (!r.headers.has("content-length")) { + if (r.body instanceof Uint8Array) { + const bodyLength = r.body.byteLength; + r.headers.append("Content-Length", bodyLength.toString()); + } else { + r.headers.append("Transfer-Encoding", "chunked"); + } + } + } +} + +export class ServerRequest { + url: string; + method: string; + proto: string; + headers: Headers; + w: BufWriter; + + private async _streamBody(body: Reader, bodyLength: number) { + const n = await copy(this.w, body); + assert(n == bodyLength); + } + + private async _streamChunkedBody(body: Reader) { + const encoder = new TextEncoder(); + + for await (const chunk of toAsyncIterator(body)) { + const start = encoder.encode(`${chunk.byteLength.toString(16)}\r\n`); + const end = encoder.encode("\r\n"); + await this.w.write(start); + await this.w.write(chunk); + await this.w.write(end); + } + + const endChunk = encoder.encode("0\r\n\r\n"); + await this.w.write(endChunk); + } + + async respond(r: Response): Promise { + const protoMajor = 1; + const protoMinor = 1; + const statusCode = r.status || 200; + const statusText = STATUS_TEXT.get(statusCode); + if (!statusText) { + throw Error("bad status code"); + } + + let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`; + + setContentLength(r); + + if (r.headers) { + for (const [key, value] of r.headers) { + out += `${key}: ${value}\r\n`; + } + } + out += "\r\n"; + + const header = new TextEncoder().encode(out); + let n = await this.w.write(header); + assert(header.byteLength == n); + + if (r.body) { + if (r.body instanceof Uint8Array) { + n = await this.w.write(r.body); + assert(r.body.byteLength == n); + } else { + if (r.headers.has("content-length")) { + await this._streamBody( + r.body, + parseInt(r.headers.get("content-length")) + ); + } else { + await this._streamChunkedBody(r.body); + } + } + } + + await this.w.flush(); + } +} + +async function readRequest(c: Conn): Promise<[ServerRequest, BufState]> { + const bufr = new BufReader(c); + const bufw = new BufWriter(c); + const req = new ServerRequest(); + req.w = bufw; + const tp = new TextProtoReader(bufr); + + let s: string; + let err: BufState; + + // First line: GET /index.html HTTP/1.0 + [s, err] = await tp.readLine(); + if (err) { + return [null, err]; + } + [req.method, req.url, req.proto] = s.split(" ", 3); + + [req.headers, err] = await tp.readMIMEHeader(); + + // TODO: handle body + + return [req, err]; +} diff --git a/net/http_bench.ts b/net/http_bench.ts new file mode 100644 index 000000000..8e1e24ad6 --- /dev/null +++ b/net/http_bench.ts @@ -0,0 +1,15 @@ +import * as deno from "deno"; +import { serve } from "./http.ts"; + +const addr = deno.args[1] || "127.0.0.1:4500"; +const server = serve(addr); + +const body = new TextEncoder().encode("Hello World"); + +async function main(): Promise { + for await (const request of server) { + await request.respond({ status: 200, body }); + } +} + +main(); diff --git a/net/http_status.ts b/net/http_status.ts new file mode 100644 index 000000000..a3006d319 --- /dev/null +++ b/net/http_status.ts @@ -0,0 +1,134 @@ +export enum Status { + Continue = 100, // RFC 7231, 6.2.1 + SwitchingProtocols = 101, // RFC 7231, 6.2.2 + Processing = 102, // RFC 2518, 10.1 + + OK = 200, // RFC 7231, 6.3.1 + Created = 201, // RFC 7231, 6.3.2 + Accepted = 202, // RFC 7231, 6.3.3 + NonAuthoritativeInfo = 203, // RFC 7231, 6.3.4 + NoContent = 204, // RFC 7231, 6.3.5 + ResetContent = 205, // RFC 7231, 6.3.6 + PartialContent = 206, // RFC 7233, 4.1 + MultiStatus = 207, // RFC 4918, 11.1 + AlreadyReported = 208, // RFC 5842, 7.1 + IMUsed = 226, // RFC 3229, 10.4.1 + + MultipleChoices = 300, // RFC 7231, 6.4.1 + MovedPermanently = 301, // RFC 7231, 6.4.2 + Found = 302, // RFC 7231, 6.4.3 + SeeOther = 303, // RFC 7231, 6.4.4 + NotModified = 304, // RFC 7232, 4.1 + UseProxy = 305, // RFC 7231, 6.4.5 + // _ = 306, // RFC 7231, 6.4.6 (Unused) + TemporaryRedirect = 307, // RFC 7231, 6.4.7 + PermanentRedirect = 308, // RFC 7538, 3 + + BadRequest = 400, // RFC 7231, 6.5.1 + Unauthorized = 401, // RFC 7235, 3.1 + PaymentRequired = 402, // RFC 7231, 6.5.2 + Forbidden = 403, // RFC 7231, 6.5.3 + NotFound = 404, // RFC 7231, 6.5.4 + MethodNotAllowed = 405, // RFC 7231, 6.5.5 + NotAcceptable = 406, // RFC 7231, 6.5.6 + ProxyAuthRequired = 407, // RFC 7235, 3.2 + RequestTimeout = 408, // RFC 7231, 6.5.7 + Conflict = 409, // RFC 7231, 6.5.8 + Gone = 410, // RFC 7231, 6.5.9 + LengthRequired = 411, // RFC 7231, 6.5.10 + PreconditionFailed = 412, // RFC 7232, 4.2 + RequestEntityTooLarge = 413, // RFC 7231, 6.5.11 + RequestURITooLong = 414, // RFC 7231, 6.5.12 + UnsupportedMediaType = 415, // RFC 7231, 6.5.13 + RequestedRangeNotSatisfiable = 416, // RFC 7233, 4.4 + ExpectationFailed = 417, // RFC 7231, 6.5.14 + Teapot = 418, // RFC 7168, 2.3.3 + MisdirectedRequest = 421, // RFC 7540, 9.1.2 + UnprocessableEntity = 422, // RFC 4918, 11.2 + Locked = 423, // RFC 4918, 11.3 + FailedDependency = 424, // RFC 4918, 11.4 + UpgradeRequired = 426, // RFC 7231, 6.5.15 + PreconditionRequired = 428, // RFC 6585, 3 + TooManyRequests = 429, // RFC 6585, 4 + RequestHeaderFieldsTooLarge = 431, // RFC 6585, 5 + UnavailableForLegalReasons = 451, // RFC 7725, 3 + + InternalServerError = 500, // RFC 7231, 6.6.1 + NotImplemented = 501, // RFC 7231, 6.6.2 + BadGateway = 502, // RFC 7231, 6.6.3 + ServiceUnavailable = 503, // RFC 7231, 6.6.4 + GatewayTimeout = 504, // RFC 7231, 6.6.5 + HTTPVersionNotSupported = 505, // RFC 7231, 6.6.6 + VariantAlsoNegotiates = 506, // RFC 2295, 8.1 + InsufficientStorage = 507, // RFC 4918, 11.5 + LoopDetected = 508, // RFC 5842, 7.2 + NotExtended = 510, // RFC 2774, 7 + NetworkAuthenticationRequired = 511 // RFC 6585, 6 +} + +export const STATUS_TEXT = new Map([ + [Status.Continue, "Continue"], + [Status.SwitchingProtocols, "Switching Protocols"], + [Status.Processing, "Processing"], + + [Status.OK, "OK"], + [Status.Created, "Created"], + [Status.Accepted, "Accepted"], + [Status.NonAuthoritativeInfo, "Non-Authoritative Information"], + [Status.NoContent, "No Content"], + [Status.ResetContent, "Reset Content"], + [Status.PartialContent, "Partial Content"], + [Status.MultiStatus, "Multi-Status"], + [Status.AlreadyReported, "Already Reported"], + [Status.IMUsed, "IM Used"], + + [Status.MultipleChoices, "Multiple Choices"], + [Status.MovedPermanently, "Moved Permanently"], + [Status.Found, "Found"], + [Status.SeeOther, "See Other"], + [Status.NotModified, "Not Modified"], + [Status.UseProxy, "Use Proxy"], + [Status.TemporaryRedirect, "Temporary Redirect"], + [Status.PermanentRedirect, "Permanent Redirect"], + + [Status.BadRequest, "Bad Request"], + [Status.Unauthorized, "Unauthorized"], + [Status.PaymentRequired, "Payment Required"], + [Status.Forbidden, "Forbidden"], + [Status.NotFound, "Not Found"], + [Status.MethodNotAllowed, "Method Not Allowed"], + [Status.NotAcceptable, "Not Acceptable"], + [Status.ProxyAuthRequired, "Proxy Authentication Required"], + [Status.RequestTimeout, "Request Timeout"], + [Status.Conflict, "Conflict"], + [Status.Gone, "Gone"], + [Status.LengthRequired, "Length Required"], + [Status.PreconditionFailed, "Precondition Failed"], + [Status.RequestEntityTooLarge, "Request Entity Too Large"], + [Status.RequestURITooLong, "Request URI Too Long"], + [Status.UnsupportedMediaType, "Unsupported Media Type"], + [Status.RequestedRangeNotSatisfiable, "Requested Range Not Satisfiable"], + [Status.ExpectationFailed, "Expectation Failed"], + [Status.Teapot, "I'm a teapot"], + [Status.MisdirectedRequest, "Misdirected Request"], + [Status.UnprocessableEntity, "Unprocessable Entity"], + [Status.Locked, "Locked"], + [Status.FailedDependency, "Failed Dependency"], + [Status.UpgradeRequired, "Upgrade Required"], + [Status.PreconditionRequired, "Precondition Required"], + [Status.TooManyRequests, "Too Many Requests"], + [Status.RequestHeaderFieldsTooLarge, "Request Header Fields Too Large"], + [Status.UnavailableForLegalReasons, "Unavailable For Legal Reasons"], + + [Status.InternalServerError, "Internal Server Error"], + [Status.NotImplemented, "Not Implemented"], + [Status.BadGateway, "Bad Gateway"], + [Status.ServiceUnavailable, "Service Unavailable"], + [Status.GatewayTimeout, "Gateway Timeout"], + [Status.HTTPVersionNotSupported, "HTTP Version Not Supported"], + [Status.VariantAlsoNegotiates, "Variant Also Negotiates"], + [Status.InsufficientStorage, "Insufficient Storage"], + [Status.LoopDetected, "Loop Detected"], + [Status.NotExtended, "Not Extended"], + [Status.NetworkAuthenticationRequired, "Network Authentication Required"] +]); diff --git a/net/http_test.ts b/net/http_test.ts new file mode 100644 index 000000000..cdb7f8303 --- /dev/null +++ b/net/http_test.ts @@ -0,0 +1,58 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Ported from +// https://github.com/golang/go/blob/master/src/net/http/responsewrite_test.go + +import { + test, + assert, + assertEqual +} from "https://deno.land/x/testing/testing.ts"; + +import { + listenAndServe, + ServerRequest, + setContentLength, + Response +} from "./http"; +import { Buffer } from "deno"; +import { BufWriter } from "./bufio"; + +interface ResponseTest { + response: Response; + raw: string; +} + +const responseTests: ResponseTest[] = [ + // Default response + { + response: {}, + raw: "HTTP/1.1 200 OK\r\n" + "\r\n" + }, + // HTTP/1.1, chunked coding; empty trailer; close + { + response: { + status: 200, + body: new Buffer(new TextEncoder().encode("abcdef")) + }, + + raw: + "HTTP/1.1 200 OK\r\n" + + "transfer-encoding: chunked\r\n\r\n" + + "6\r\nabcdef\r\n0\r\n\r\n" + } +]; + +test(async function responseWrite() { + for (const testCase of responseTests) { + const buf = new Buffer(); + const bufw = new BufWriter(buf); + const request = new ServerRequest(); + request.w = bufw; + + await request.respond(testCase.response); + assertEqual(buf.toString(), testCase.raw); + } +}); diff --git a/net/iotest.ts b/net/iotest.ts new file mode 100644 index 000000000..e3a42f58a --- /dev/null +++ b/net/iotest.ts @@ -0,0 +1,61 @@ +// Ported to Deno from +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { Reader, ReadResult } from "deno"; + +/** OneByteReader returns a Reader that implements + * each non-empty Read by reading one byte from r. + */ +export class OneByteReader implements Reader { + constructor(readonly r: Reader) {} + + async read(p: Uint8Array): Promise { + if (p.byteLength === 0) { + return { nread: 0, eof: false }; + } + if (!(p instanceof Uint8Array)) { + throw Error("expected Uint8Array"); + } + return this.r.read(p.subarray(0, 1)); + } +} + +/** HalfReader returns a Reader that implements Read + * by reading half as many requested bytes from r. + */ +export class HalfReader implements Reader { + constructor(readonly r: Reader) {} + + async read(p: Uint8Array): Promise { + if (!(p instanceof Uint8Array)) { + throw Error("expected Uint8Array"); + } + const half = Math.floor((p.byteLength + 1) / 2); + return this.r.read(p.subarray(0, half)); + } +} + +export class ErrTimeout extends Error { + constructor() { + super("timeout"); + this.name = "ErrTimeout"; + } +} + +/** TimeoutReader returns ErrTimeout on the second read + * with no data. Subsequent calls to read succeed. + */ +export class TimeoutReader implements Reader { + count = 0; + constructor(readonly r: Reader) {} + + async read(p: Uint8Array): Promise { + this.count++; + if (this.count === 2) { + throw new ErrTimeout(); + } + return this.r.read(p); + } +} diff --git a/net/textproto.ts b/net/textproto.ts new file mode 100644 index 000000000..342d74b33 --- /dev/null +++ b/net/textproto.ts @@ -0,0 +1,149 @@ +// Based on https://github.com/golang/go/blob/891682/src/net/textproto/ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { BufReader, BufState } from "./bufio.ts"; +import { charCode } from "./util.ts"; + +const asciiDecoder = new TextDecoder(); +function str(buf: Uint8Array): string { + if (buf == null) { + return ""; + } else { + return asciiDecoder.decode(buf); + } +} + +export class ProtocolError extends Error { + constructor(msg: string) { + super(msg); + this.name = "ProtocolError"; + } +} + +export class TextProtoReader { + constructor(readonly r: BufReader) {} + + /** readLine() reads a single line from the TextProtoReader, + * eliding the final \n or \r\n from the returned string. + */ + async readLine(): Promise<[string, BufState]> { + let [line, err] = await this.readLineSlice(); + return [str(line), err]; + } + + /** ReadMIMEHeader reads a MIME-style header from r. + * The header is a sequence of possibly continued Key: Value lines + * ending in a blank line. + * The returned map m maps CanonicalMIMEHeaderKey(key) to a + * sequence of values in the same order encountered in the input. + * + * For example, consider this input: + * + * My-Key: Value 1 + * Long-Key: Even + * Longer Value + * My-Key: Value 2 + * + * Given that input, ReadMIMEHeader returns the map: + * + * map[string][]string{ + * "My-Key": {"Value 1", "Value 2"}, + * "Long-Key": {"Even Longer Value"}, + * } + */ + async readMIMEHeader(): Promise<[Headers, BufState]> { + let m = new Headers(); + let line: Uint8Array; + + // The first line cannot start with a leading space. + let [buf, err] = await this.r.peek(1); + if (buf[0] == charCode(" ") || buf[0] == charCode("\t")) { + [line, err] = await this.readLineSlice(); + } + + [buf, err] = await this.r.peek(1); + if (err == null && (buf[0] == charCode(" ") || buf[0] == charCode("\t"))) { + throw new ProtocolError( + `malformed MIME header initial line: ${str(line)}` + ); + } + + while (true) { + let [kv, err] = await this.readLineSlice(); // readContinuedLineSlice + if (kv.byteLength == 0) { + return [m, err]; + } + + // Key ends at first colon; should not have trailing spaces + // but they appear in the wild, violating specs, so we remove + // them if present. + let i = kv.indexOf(charCode(":")); + if (i < 0) { + throw new ProtocolError(`malformed MIME header line: ${str(kv)}`); + } + let endKey = i; + while (endKey > 0 && kv[endKey - 1] == charCode(" ")) { + endKey--; + } + + //let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey)); + let key = str(kv.subarray(0, endKey)); + + // As per RFC 7230 field-name is a token, tokens consist of one or more chars. + // We could return a ProtocolError here, but better to be liberal in what we + // accept, so if we get an empty key, skip it. + if (key == "") { + continue; + } + + // Skip initial spaces in value. + i++; // skip colon + while ( + i < kv.byteLength && + (kv[i] == charCode(" ") || kv[i] == charCode("\t")) + ) { + i++; + } + let value = str(kv.subarray(i)); + + m.append(key, value); + + if (err != null) { + throw err; + } + } + } + + async readLineSlice(): Promise<[Uint8Array, BufState]> { + // this.closeDot(); + let line: null | Uint8Array; + while (true) { + let [l, more, err] = await this.r.readLine(); + if (err != null) { + return [null, err]; + } + // Avoid the copy if the first call produced a full line. + if (line == null && !more) { + return [l, null]; + } + line = append(line, l); + if (!more) { + break; + } + } + return [line, null]; + } +} + +export function append(a: Uint8Array, b: Uint8Array): Uint8Array { + if (a == null) { + return b; + } else { + const output = new Uint8Array(a.length + b.length); + output.set(a, 0); + output.set(b, a.length); + return output; + } +} diff --git a/net/textproto_test.ts b/net/textproto_test.ts new file mode 100644 index 000000000..25c12b0e8 --- /dev/null +++ b/net/textproto_test.ts @@ -0,0 +1,93 @@ +// Based on https://github.com/golang/go/blob/891682/src/net/textproto/ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { BufReader } from "./bufio.ts"; +import { TextProtoReader, append } from "./textproto.ts"; +import { stringsReader } from "./util.ts"; +import { + test, + assert, + assertEqual +} from "https://deno.land/x/testing/testing.ts"; + +function reader(s: string): TextProtoReader { + return new TextProtoReader(new BufReader(stringsReader(s))); +} + +test(async function textprotoReader() { + let r = reader("line1\nline2\n"); + let [s, err] = await r.readLine(); + assertEqual(s, "line1"); + assert(err == null); + + [s, err] = await r.readLine(); + assertEqual(s, "line2"); + assert(err == null); + + [s, err] = await r.readLine(); + assertEqual(s, ""); + assert(err == "EOF"); +}); + +/* +test(async function textprotoReadMIMEHeader() { + let r = reader("my-key: Value 1 \r\nLong-key: Even \n Longer Value\r\nmy-Key: Value 2\r\n\n"); + let [m, err] = await r.readMIMEHeader(); + + console.log("Got headers", m.toString()); + want := MIMEHeader{ + "My-Key": {"Value 1", "Value 2"}, + "Long-Key": {"Even Longer Value"}, + } + if !reflect.DeepEqual(m, want) || err != nil { + t.Fatalf("ReadMIMEHeader: %v, %v; want %v", m, err, want) + } +}); +*/ + +test(async function textprotoReadMIMEHeaderSingle() { + let r = reader("Foo: bar\n\n"); + let [m, err] = await r.readMIMEHeader(); + assertEqual(m.get("Foo"), "bar"); + assert(!err); +}); + +// Test that we read slightly-bogus MIME headers seen in the wild, +// with spaces before colons, and spaces in keys. +test(async function textprotoReadMIMEHeaderNonCompliant() { + // Invalid HTTP response header as sent by an Axis security + // camera: (this is handled by IE, Firefox, Chrome, curl, etc.) + let r = reader( + "Foo: bar\r\n" + + "Content-Language: en\r\n" + + "SID : 0\r\n" + + "Audio Mode : None\r\n" + + "Privilege : 127\r\n\r\n" + ); + let [m, err] = await r.readMIMEHeader(); + console.log(m.toString()); + assert(!err); + /* + let want = MIMEHeader{ + "Foo": {"bar"}, + "Content-Language": {"en"}, + "Sid": {"0"}, + "Audio Mode": {"None"}, + "Privilege": {"127"}, + } + if !reflect.DeepEqual(m, want) || err != nil { + t.Fatalf("ReadMIMEHeader =\n%v, %v; want:\n%v", m, err, want) + } + */ +}); + +test(async function textprotoAppend() { + const enc = new TextEncoder(); + const dec = new TextDecoder(); + const u1 = enc.encode("Hello "); + const u2 = enc.encode("World"); + const joined = append(u1, u2); + assertEqual(dec.decode(joined), "Hello World"); +}); diff --git a/net/util.ts b/net/util.ts new file mode 100644 index 000000000..811940b4d --- /dev/null +++ b/net/util.ts @@ -0,0 +1,29 @@ +import { Buffer, Reader } from "deno"; + +export function assert(cond: boolean, msg = "assert") { + if (!cond) { + throw Error(msg); + } +} + +// `off` is the offset into `dst` where it will at which to begin writing values +// from `src`. +// Returns the number of bytes copied. +export function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number { + const r = dst.byteLength - off; + if (src.byteLength > r) { + src = src.subarray(0, r); + } + dst.set(src, off); + return src.byteLength; +} + +export function charCode(s: string): number { + return s.charCodeAt(0); +} + +const encoder = new TextEncoder(); +export function stringsReader(s: string): Reader { + const ui8 = encoder.encode(s); + return new Buffer(ui8.buffer as ArrayBuffer); +} diff --git a/test.ts b/test.ts old mode 100644 new mode 100755 index 7c395663e..95003e0ad --- a/test.ts +++ b/test.ts @@ -1,13 +1,14 @@ +#!/usr/bin/env deno --allow-run --allow-net import { run } from "deno"; -import "./bufio_test.ts"; -import "./http_test.ts"; -import "./textproto_test.ts"; -import { runTests, completePromise } from "./file_server_test.ts"; +import "net/bufio_test.ts"; +import "net/http_test.ts"; +import "net/textproto_test.ts"; +import { runTests, completePromise } from "net/file_server_test.ts"; // file server test const fileServer = run({ - args: ["deno", "--allow-net", "file_server.ts", "."] + args: ["deno", "--allow-net", "net/file_server.ts", "."] }); // I am also too lazy to do this properly LOL runTests(new Promise(res => setTimeout(res, 5000))); @@ -15,5 +16,3 @@ runTests(new Promise(res => setTimeout(res, 5000))); await completePromise; fileServer.close(); })(); - -// TODO import "./http_test.ts"; diff --git a/textproto.ts b/textproto.ts deleted file mode 100644 index 342d74b33..000000000 --- a/textproto.ts +++ /dev/null @@ -1,149 +0,0 @@ -// Based on https://github.com/golang/go/blob/891682/src/net/textproto/ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import { BufReader, BufState } from "./bufio.ts"; -import { charCode } from "./util.ts"; - -const asciiDecoder = new TextDecoder(); -function str(buf: Uint8Array): string { - if (buf == null) { - return ""; - } else { - return asciiDecoder.decode(buf); - } -} - -export class ProtocolError extends Error { - constructor(msg: string) { - super(msg); - this.name = "ProtocolError"; - } -} - -export class TextProtoReader { - constructor(readonly r: BufReader) {} - - /** readLine() reads a single line from the TextProtoReader, - * eliding the final \n or \r\n from the returned string. - */ - async readLine(): Promise<[string, BufState]> { - let [line, err] = await this.readLineSlice(); - return [str(line), err]; - } - - /** ReadMIMEHeader reads a MIME-style header from r. - * The header is a sequence of possibly continued Key: Value lines - * ending in a blank line. - * The returned map m maps CanonicalMIMEHeaderKey(key) to a - * sequence of values in the same order encountered in the input. - * - * For example, consider this input: - * - * My-Key: Value 1 - * Long-Key: Even - * Longer Value - * My-Key: Value 2 - * - * Given that input, ReadMIMEHeader returns the map: - * - * map[string][]string{ - * "My-Key": {"Value 1", "Value 2"}, - * "Long-Key": {"Even Longer Value"}, - * } - */ - async readMIMEHeader(): Promise<[Headers, BufState]> { - let m = new Headers(); - let line: Uint8Array; - - // The first line cannot start with a leading space. - let [buf, err] = await this.r.peek(1); - if (buf[0] == charCode(" ") || buf[0] == charCode("\t")) { - [line, err] = await this.readLineSlice(); - } - - [buf, err] = await this.r.peek(1); - if (err == null && (buf[0] == charCode(" ") || buf[0] == charCode("\t"))) { - throw new ProtocolError( - `malformed MIME header initial line: ${str(line)}` - ); - } - - while (true) { - let [kv, err] = await this.readLineSlice(); // readContinuedLineSlice - if (kv.byteLength == 0) { - return [m, err]; - } - - // Key ends at first colon; should not have trailing spaces - // but they appear in the wild, violating specs, so we remove - // them if present. - let i = kv.indexOf(charCode(":")); - if (i < 0) { - throw new ProtocolError(`malformed MIME header line: ${str(kv)}`); - } - let endKey = i; - while (endKey > 0 && kv[endKey - 1] == charCode(" ")) { - endKey--; - } - - //let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey)); - let key = str(kv.subarray(0, endKey)); - - // As per RFC 7230 field-name is a token, tokens consist of one or more chars. - // We could return a ProtocolError here, but better to be liberal in what we - // accept, so if we get an empty key, skip it. - if (key == "") { - continue; - } - - // Skip initial spaces in value. - i++; // skip colon - while ( - i < kv.byteLength && - (kv[i] == charCode(" ") || kv[i] == charCode("\t")) - ) { - i++; - } - let value = str(kv.subarray(i)); - - m.append(key, value); - - if (err != null) { - throw err; - } - } - } - - async readLineSlice(): Promise<[Uint8Array, BufState]> { - // this.closeDot(); - let line: null | Uint8Array; - while (true) { - let [l, more, err] = await this.r.readLine(); - if (err != null) { - return [null, err]; - } - // Avoid the copy if the first call produced a full line. - if (line == null && !more) { - return [l, null]; - } - line = append(line, l); - if (!more) { - break; - } - } - return [line, null]; - } -} - -export function append(a: Uint8Array, b: Uint8Array): Uint8Array { - if (a == null) { - return b; - } else { - const output = new Uint8Array(a.length + b.length); - output.set(a, 0); - output.set(b, a.length); - return output; - } -} diff --git a/textproto_test.ts b/textproto_test.ts deleted file mode 100644 index 25c12b0e8..000000000 --- a/textproto_test.ts +++ /dev/null @@ -1,93 +0,0 @@ -// Based on https://github.com/golang/go/blob/891682/src/net/textproto/ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import { BufReader } from "./bufio.ts"; -import { TextProtoReader, append } from "./textproto.ts"; -import { stringsReader } from "./util.ts"; -import { - test, - assert, - assertEqual -} from "https://deno.land/x/testing/testing.ts"; - -function reader(s: string): TextProtoReader { - return new TextProtoReader(new BufReader(stringsReader(s))); -} - -test(async function textprotoReader() { - let r = reader("line1\nline2\n"); - let [s, err] = await r.readLine(); - assertEqual(s, "line1"); - assert(err == null); - - [s, err] = await r.readLine(); - assertEqual(s, "line2"); - assert(err == null); - - [s, err] = await r.readLine(); - assertEqual(s, ""); - assert(err == "EOF"); -}); - -/* -test(async function textprotoReadMIMEHeader() { - let r = reader("my-key: Value 1 \r\nLong-key: Even \n Longer Value\r\nmy-Key: Value 2\r\n\n"); - let [m, err] = await r.readMIMEHeader(); - - console.log("Got headers", m.toString()); - want := MIMEHeader{ - "My-Key": {"Value 1", "Value 2"}, - "Long-Key": {"Even Longer Value"}, - } - if !reflect.DeepEqual(m, want) || err != nil { - t.Fatalf("ReadMIMEHeader: %v, %v; want %v", m, err, want) - } -}); -*/ - -test(async function textprotoReadMIMEHeaderSingle() { - let r = reader("Foo: bar\n\n"); - let [m, err] = await r.readMIMEHeader(); - assertEqual(m.get("Foo"), "bar"); - assert(!err); -}); - -// Test that we read slightly-bogus MIME headers seen in the wild, -// with spaces before colons, and spaces in keys. -test(async function textprotoReadMIMEHeaderNonCompliant() { - // Invalid HTTP response header as sent by an Axis security - // camera: (this is handled by IE, Firefox, Chrome, curl, etc.) - let r = reader( - "Foo: bar\r\n" + - "Content-Language: en\r\n" + - "SID : 0\r\n" + - "Audio Mode : None\r\n" + - "Privilege : 127\r\n\r\n" - ); - let [m, err] = await r.readMIMEHeader(); - console.log(m.toString()); - assert(!err); - /* - let want = MIMEHeader{ - "Foo": {"bar"}, - "Content-Language": {"en"}, - "Sid": {"0"}, - "Audio Mode": {"None"}, - "Privilege": {"127"}, - } - if !reflect.DeepEqual(m, want) || err != nil { - t.Fatalf("ReadMIMEHeader =\n%v, %v; want:\n%v", m, err, want) - } - */ -}); - -test(async function textprotoAppend() { - const enc = new TextEncoder(); - const dec = new TextDecoder(); - const u1 = enc.encode("Hello "); - const u2 = enc.encode("World"); - const joined = append(u1, u2); - assertEqual(dec.decode(joined), "Hello World"); -}); diff --git a/util.ts b/util.ts deleted file mode 100644 index 811940b4d..000000000 --- a/util.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Buffer, Reader } from "deno"; - -export function assert(cond: boolean, msg = "assert") { - if (!cond) { - throw Error(msg); - } -} - -// `off` is the offset into `dst` where it will at which to begin writing values -// from `src`. -// Returns the number of bytes copied. -export function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number { - const r = dst.byteLength - off; - if (src.byteLength > r) { - src = src.subarray(0, r); - } - dst.set(src, off); - return src.byteLength; -} - -export function charCode(s: string): number { - return s.charCodeAt(0); -} - -const encoder = new TextEncoder(); -export function stringsReader(s: string): Reader { - const ui8 = encoder.encode(s); - return new Buffer(ui8.buffer as ArrayBuffer); -} -- cgit v1.2.3 From e249378fdfebdb0e513cc692b581dad49efd9af1 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Tue, 18 Dec 2018 18:56:12 -0500 Subject: Add format script. Original: https://github.com/denoland/deno_std/commit/85ff88b0cc076d1a79fd15ddf4475270765bcfda --- format.ts | 13 +++++++++++++ net/bufio.ts | 1 - 2 files changed, 13 insertions(+), 1 deletion(-) create mode 100755 format.ts diff --git a/format.ts b/format.ts new file mode 100755 index 000000000..251cba1ed --- /dev/null +++ b/format.ts @@ -0,0 +1,13 @@ +#!/usr/bin/env deno --allow-run + +import { exit, run } from "deno"; + +async function main() { + const prettier = run({ + args: ["bash", "-c", "prettier --write *.ts **/*.ts"] + }); + const s = await prettier.status(); + exit(s.code); +} + +main(); diff --git a/net/bufio.ts b/net/bufio.ts index b412cbce8..0dd2b94b4 100644 --- a/net/bufio.ts +++ b/net/bufio.ts @@ -185,7 +185,6 @@ export class BufReader implements Reader { return [nread, nread < p.length ? "EOF" : null]; } - /** Returns the next byte [0, 255] or -1 if EOF. */ async readByte(): Promise { while (this.r === this.w) { -- cgit v1.2.3 From ee72e869f7073f8f3ccce55f32695df96e3d8113 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Tue, 18 Dec 2018 18:57:58 -0500 Subject: Remove Makefile Original: https://github.com/denoland/deno_std/commit/2ae63d35d0dcb3da77c8323418264346db012fa6 --- Makefile | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 Makefile diff --git a/Makefile b/Makefile deleted file mode 100644 index ca2135445..000000000 --- a/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -test: - deno test.ts - -fmt: - prettier *.md *.ts --write - -.PHONY: test fmt -- cgit v1.2.3 From 3c8f564ab8c3087bac8256723aed9572faba756f Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Tue, 18 Dec 2018 20:48:05 -0500 Subject: http: Request body & Streaming (denoland/deno_std#23) Original: https://github.com/denoland/deno_std/commit/e0e677bb02ad1587743373fe59efcaba1f89d1ed --- net/http.ts | 141 ++++++++++++++++++++++++++++++++++++++++----- net/http_test.ts | 172 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 298 insertions(+), 15 deletions(-) diff --git a/net/http.ts b/net/http.ts index bd45aea0d..2b0e5477a 100644 --- a/net/http.ts +++ b/net/http.ts @@ -28,13 +28,16 @@ interface ServeEnv { serveDeferred: Deferred; } -// Continuously read more requests from conn until EOF -// Mutually calling with maybeHandleReq -// TODO: make them async function after this change is done -// https://github.com/tc39/ecma262/pull/1250 -// See https://v8.dev/blog/fast-async -export function serveConn(env: ServeEnv, conn: Conn) { - readRequest(conn).then(maybeHandleReq.bind(null, env, conn)); +/** Continuously read more requests from conn until EOF + * Calls maybeHandleReq. + * bufr is empty on a fresh TCP connection. + * Would be passed around and reused for later request on same conn + * TODO: make them async function after this change is done + * https://github.com/tc39/ecma262/pull/1250 + * See https://v8.dev/blog/fast-async + */ +function serveConn(env: ServeEnv, conn: Conn, bufr?: BufReader) { + readRequest(conn, bufr).then(maybeHandleReq.bind(null, env, conn)); } function maybeHandleReq(env: ServeEnv, conn: Conn, maybeReq: any) { const [req, _err] = maybeReq; @@ -44,8 +47,6 @@ function maybeHandleReq(env: ServeEnv, conn: Conn, maybeReq: any) { } env.reqQueue.push(req); // push req to queue env.serveDeferred.resolve(); // signal while loop to process it - // TODO: protection against client req flooding - serveConn(env, conn); // try read more (reusing connection) } export async function* serve(addr: string) { @@ -77,6 +78,9 @@ export async function* serve(addr: string) { env.reqQueue = []; for (const result of queueToProcess) { yield result; + // Continue read more from conn when user is done with the current req + // Moving this here makes it easier to manage + serveConn(env, result.conn, result.r); } } listener.close(); @@ -121,8 +125,90 @@ export class ServerRequest { method: string; proto: string; headers: Headers; + conn: Conn; + r: BufReader; w: BufWriter; + public async *bodyStream() { + if (this.headers.has("content-length")) { + const len = +this.headers.get("content-length"); + if (Number.isNaN(len)) { + return new Uint8Array(0); + } + let buf = new Uint8Array(1024); + let rr = await this.r.read(buf); + let nread = rr.nread; + while (!rr.eof && nread < len) { + yield buf.subarray(0, rr.nread); + buf = new Uint8Array(1024); + rr = await this.r.read(buf); + nread += rr.nread; + } + yield buf.subarray(0, rr.nread); + } else { + if (this.headers.has("transfer-encoding")) { + const transferEncodings = this.headers + .get("transfer-encoding") + .split(",") + .map(e => e.trim().toLowerCase()); + if (transferEncodings.includes("chunked")) { + // Based on https://tools.ietf.org/html/rfc2616#section-19.4.6 + const tp = new TextProtoReader(this.r); + let [line, _] = await tp.readLine(); + // TODO: handle chunk extension + let [chunkSizeString, optExt] = line.split(";"); + let chunkSize = parseInt(chunkSizeString, 16); + if (Number.isNaN(chunkSize) || chunkSize < 0) { + throw new Error("Invalid chunk size"); + } + while (chunkSize > 0) { + let data = new Uint8Array(chunkSize); + let [nread, err] = await this.r.readFull(data); + if (nread !== chunkSize) { + throw new Error("Chunk data does not match size"); + } + yield data; + await this.r.readLine(); // Consume \r\n + [line, _] = await tp.readLine(); + chunkSize = parseInt(line, 16); + } + const [entityHeaders, err] = await tp.readMIMEHeader(); + if (!err) { + for (let [k, v] of entityHeaders) { + this.headers.set(k, v); + } + } + /* Pseudo code from https://tools.ietf.org/html/rfc2616#section-19.4.6 + length := 0 + read chunk-size, chunk-extension (if any) and CRLF + while (chunk-size > 0) { + read chunk-data and CRLF + append chunk-data to entity-body + length := length + chunk-size + read chunk-size and CRLF + } + read entity-header + while (entity-header not empty) { + append entity-header to existing header fields + read entity-header + } + Content-Length := length + Remove "chunked" from Transfer-Encoding + */ + return; // Must return here to avoid fall through + } + // TODO: handle other transfer-encoding types + } + // Otherwise... + yield new Uint8Array(0); + } + } + + // Read the body of the request into a single Uint8Array + public async body(): Promise { + return readAllIterator(this.bodyStream()); + } + private async _streamBody(body: Reader, bodyLength: number) { const n = await copy(this.w, body); assert(n == bodyLength); @@ -187,12 +273,19 @@ export class ServerRequest { } } -async function readRequest(c: Conn): Promise<[ServerRequest, BufState]> { - const bufr = new BufReader(c); +async function readRequest( + c: Conn, + bufr?: BufReader +): Promise<[ServerRequest, BufState]> { + if (!bufr) { + bufr = new BufReader(c); + } const bufw = new BufWriter(c); const req = new ServerRequest(); + req.conn = c; + req.r = bufr!; req.w = bufw; - const tp = new TextProtoReader(bufr); + const tp = new TextProtoReader(bufr!); let s: string; let err: BufState; @@ -206,7 +299,27 @@ async function readRequest(c: Conn): Promise<[ServerRequest, BufState]> { [req.headers, err] = await tp.readMIMEHeader(); - // TODO: handle body - return [req, err]; } + +async function readAllIterator( + it: AsyncIterableIterator +): Promise { + const chunks = []; + let len = 0; + for await (const chunk of it) { + chunks.push(chunk); + len += chunk.length; + } + if (chunks.length === 0) { + // No need for copy + return chunks[0]; + } + const collected = new Uint8Array(len); + let offset = 0; + for (let chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} diff --git a/net/http_test.ts b/net/http_test.ts index cdb7f8303..97d07a5b4 100644 --- a/net/http_test.ts +++ b/net/http_test.ts @@ -18,13 +18,16 @@ import { Response } from "./http"; import { Buffer } from "deno"; -import { BufWriter } from "./bufio"; +import { BufWriter, BufReader } from "./bufio"; interface ResponseTest { response: Response; raw: string; } +const enc = new TextEncoder(); +const dec = new TextDecoder(); + const responseTests: ResponseTest[] = [ // Default response { @@ -56,3 +59,170 @@ test(async function responseWrite() { assertEqual(buf.toString(), testCase.raw); } }); + +test(async function requestBodyWithContentLength() { + { + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("content-length", "5"); + const buf = new Buffer(enc.encode("Hello")); + req.r = new BufReader(buf); + const body = dec.decode(await req.body()); + assertEqual(body, "Hello"); + } + + // Larger than internal buf + { + const longText = "1234\n".repeat(1000); + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("Content-Length", "5000"); + const buf = new Buffer(enc.encode(longText)); + req.r = new BufReader(buf); + const body = dec.decode(await req.body()); + assertEqual(body, longText); + } +}); + +test(async function requestBodyWithTransferEncoding() { + { + const shortText = "Hello"; + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("transfer-encoding", "chunked"); + let chunksData = ""; + let chunkOffset = 0; + const maxChunkSize = 70; + while (chunkOffset < shortText.length) { + const chunkSize = Math.min(maxChunkSize, shortText.length - chunkOffset); + chunksData += `${chunkSize.toString(16)}\r\n${shortText.substr( + chunkOffset, + chunkSize + )}\r\n`; + chunkOffset += chunkSize; + } + chunksData += "0\r\n\r\n"; + const buf = new Buffer(enc.encode(chunksData)); + req.r = new BufReader(buf); + const body = dec.decode(await req.body()); + assertEqual(body, shortText); + } + + // Larger than internal buf + { + const longText = "1234\n".repeat(1000); + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("transfer-encoding", "chunked"); + let chunksData = ""; + let chunkOffset = 0; + const maxChunkSize = 70; + while (chunkOffset < longText.length) { + const chunkSize = Math.min(maxChunkSize, longText.length - chunkOffset); + chunksData += `${chunkSize.toString(16)}\r\n${longText.substr( + chunkOffset, + chunkSize + )}\r\n`; + chunkOffset += chunkSize; + } + chunksData += "0\r\n\r\n"; + const buf = new Buffer(enc.encode(chunksData)); + req.r = new BufReader(buf); + const body = dec.decode(await req.body()); + assertEqual(body, longText); + } +}); + +test(async function requestBodyStreamWithContentLength() { + { + const shortText = "Hello"; + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("content-length", "" + shortText.length); + const buf = new Buffer(enc.encode(shortText)); + req.r = new BufReader(buf); + const it = await req.bodyStream(); + let offset = 0; + for await (const chunk of it) { + const s = dec.decode(chunk); + assertEqual(shortText.substr(offset, s.length), s); + offset += s.length; + } + } + + // Larger than internal buf + { + const longText = "1234\n".repeat(1000); + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("Content-Length", "5000"); + const buf = new Buffer(enc.encode(longText)); + req.r = new BufReader(buf); + const it = await req.bodyStream(); + let offset = 0; + for await (const chunk of it) { + const s = dec.decode(chunk); + assertEqual(longText.substr(offset, s.length), s); + offset += s.length; + } + } +}); + +test(async function requestBodyStreamWithTransferEncoding() { + { + const shortText = "Hello"; + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("transfer-encoding", "chunked"); + let chunksData = ""; + let chunkOffset = 0; + const maxChunkSize = 70; + while (chunkOffset < shortText.length) { + const chunkSize = Math.min(maxChunkSize, shortText.length - chunkOffset); + chunksData += `${chunkSize.toString(16)}\r\n${shortText.substr( + chunkOffset, + chunkSize + )}\r\n`; + chunkOffset += chunkSize; + } + chunksData += "0\r\n\r\n"; + const buf = new Buffer(enc.encode(chunksData)); + req.r = new BufReader(buf); + const it = await req.bodyStream(); + let offset = 0; + for await (const chunk of it) { + const s = dec.decode(chunk); + assertEqual(shortText.substr(offset, s.length), s); + offset += s.length; + } + } + + // Larger than internal buf + { + const longText = "1234\n".repeat(1000); + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("transfer-encoding", "chunked"); + let chunksData = ""; + let chunkOffset = 0; + const maxChunkSize = 70; + while (chunkOffset < longText.length) { + const chunkSize = Math.min(maxChunkSize, longText.length - chunkOffset); + chunksData += `${chunkSize.toString(16)}\r\n${longText.substr( + chunkOffset, + chunkSize + )}\r\n`; + chunkOffset += chunkSize; + } + chunksData += "0\r\n\r\n"; + const buf = new Buffer(enc.encode(chunksData)); + req.r = new BufReader(buf); + const it = await req.bodyStream(); + let offset = 0; + for await (const chunk of it) { + const s = dec.decode(chunk); + assertEqual(longText.substr(offset, s.length), s); + offset += s.length; + } + } +}); -- cgit v1.2.3 From 2d58da520fffaeaee1bceeb33b6e3dc339ea68a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E6=9D=89?= Date: Wed, 19 Dec 2018 10:29:39 +0800 Subject: migrate deno_path to deno_std (denoland/deno_std#26) Previously https://github.com/zhmushan/deno_path Original: https://github.com/denoland/deno_std/commit/1a35f9daf5aa1c10c61d62cccbe7f9ae3c615a0e --- LICENSE | 21 + net/bufio_test.ts | 4 +- path/README.md | 7 + path/basename_test.ts | 75 ++ path/constants.ts | 53 ++ path/dirname_test.ts | 61 ++ path/extname_test.ts | 89 +++ path/index.ts | 1425 ++++++++++++++++++++++++++++++++++++++ path/interface.ts | 47 ++ path/isabsolute_test.ts | 33 + path/join_test.ts | 124 ++++ path/parse_format_test.ts | 176 +++++ path/relative_test.ts | 72 ++ path/resolve_test.ts | 49 ++ path/zero_length_strings_test.ts | 46 ++ test.ts | 13 +- 16 files changed, 2292 insertions(+), 3 deletions(-) create mode 100644 LICENSE create mode 100644 path/README.md create mode 100644 path/basename_test.ts create mode 100644 path/constants.ts create mode 100644 path/dirname_test.ts create mode 100644 path/extname_test.ts create mode 100644 path/index.ts create mode 100644 path/interface.ts create mode 100644 path/isabsolute_test.ts create mode 100644 path/join_test.ts create mode 100644 path/parse_format_test.ts create mode 100644 path/relative_test.ts create mode 100644 path/resolve_test.ts create mode 100644 path/zero_length_strings_test.ts diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..0270530e3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright 2018 the Deno authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/net/bufio_test.ts b/net/bufio_test.ts index 19954bdf6..96490a6c9 100644 --- a/net/bufio_test.ts +++ b/net/bufio_test.ts @@ -108,7 +108,7 @@ test(async function bufioBufReader() { for (let i = 0; i < texts.length - 1; i++) { texts[i] = str + "\n"; all += texts[i]; - str += String.fromCharCode(i % 26 + 97); + str += String.fromCharCode((i % 26) + 97); } texts[texts.length - 1] = all; @@ -293,7 +293,7 @@ test(async function bufioWriter() { const data = new Uint8Array(8192); for (let i = 0; i < data.byteLength; i++) { - data[i] = charCode(" ") + i % (charCode("~") - charCode(" ")); + data[i] = charCode(" ") + (i % (charCode("~") - charCode(" "))); } const w = new Buffer(); diff --git a/path/README.md b/path/README.md new file mode 100644 index 000000000..d4f693577 --- /dev/null +++ b/path/README.md @@ -0,0 +1,7 @@ +# Deno Path Manipulation Libraries + +Usage: + +```ts +import * as path from 'https://deno.land/x/path/index.ts' +``` diff --git a/path/basename_test.ts b/path/basename_test.ts new file mode 100644 index 000000000..9e051fbcd --- /dev/null +++ b/path/basename_test.ts @@ -0,0 +1,75 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import * as path from "./index"; + +test(function basename() { + assertEqual(path.basename(".js", ".js"), ""); + assertEqual(path.basename(""), ""); + assertEqual(path.basename("/dir/basename.ext"), "basename.ext"); + assertEqual(path.basename("/basename.ext"), "basename.ext"); + assertEqual(path.basename("basename.ext"), "basename.ext"); + assertEqual(path.basename("basename.ext/"), "basename.ext"); + assertEqual(path.basename("basename.ext//"), "basename.ext"); + assertEqual(path.basename("aaa/bbb", "/bbb"), "bbb"); + assertEqual(path.basename("aaa/bbb", "a/bbb"), "bbb"); + assertEqual(path.basename("aaa/bbb", "bbb"), "bbb"); + assertEqual(path.basename("aaa/bbb//", "bbb"), "bbb"); + assertEqual(path.basename("aaa/bbb", "bb"), "b"); + assertEqual(path.basename("aaa/bbb", "b"), "bb"); + assertEqual(path.basename("/aaa/bbb", "/bbb"), "bbb"); + assertEqual(path.basename("/aaa/bbb", "a/bbb"), "bbb"); + assertEqual(path.basename("/aaa/bbb", "bbb"), "bbb"); + assertEqual(path.basename("/aaa/bbb//", "bbb"), "bbb"); + assertEqual(path.basename("/aaa/bbb", "bb"), "b"); + assertEqual(path.basename("/aaa/bbb", "b"), "bb"); + assertEqual(path.basename("/aaa/bbb"), "bbb"); + assertEqual(path.basename("/aaa/"), "aaa"); + assertEqual(path.basename("/aaa/b"), "b"); + assertEqual(path.basename("/a/b"), "b"); + assertEqual(path.basename("//a"), "a"); + + // On unix a backslash is just treated as any other character. + assertEqual( + path.posix.basename("\\dir\\basename.ext"), + "\\dir\\basename.ext" + ); + assertEqual(path.posix.basename("\\basename.ext"), "\\basename.ext"); + assertEqual(path.posix.basename("basename.ext"), "basename.ext"); + assertEqual(path.posix.basename("basename.ext\\"), "basename.ext\\"); + assertEqual(path.posix.basename("basename.ext\\\\"), "basename.ext\\\\"); + assertEqual(path.posix.basename("foo"), "foo"); + + // POSIX filenames may include control characters + const controlCharFilename = "Icon" + String.fromCharCode(13); + assertEqual( + path.posix.basename("/a/b/" + controlCharFilename), + controlCharFilename + ); +}); + +test(function basenameWin32() { + assertEqual(path.win32.basename("\\dir\\basename.ext"), "basename.ext"); + assertEqual(path.win32.basename("\\basename.ext"), "basename.ext"); + assertEqual(path.win32.basename("basename.ext"), "basename.ext"); + assertEqual(path.win32.basename("basename.ext\\"), "basename.ext"); + assertEqual(path.win32.basename("basename.ext\\\\"), "basename.ext"); + assertEqual(path.win32.basename("foo"), "foo"); + assertEqual(path.win32.basename("aaa\\bbb", "\\bbb"), "bbb"); + assertEqual(path.win32.basename("aaa\\bbb", "a\\bbb"), "bbb"); + assertEqual(path.win32.basename("aaa\\bbb", "bbb"), "bbb"); + assertEqual(path.win32.basename("aaa\\bbb\\\\\\\\", "bbb"), "bbb"); + assertEqual(path.win32.basename("aaa\\bbb", "bb"), "b"); + assertEqual(path.win32.basename("aaa\\bbb", "b"), "bb"); + assertEqual(path.win32.basename("C:"), ""); + assertEqual(path.win32.basename("C:."), "."); + assertEqual(path.win32.basename("C:\\"), ""); + assertEqual(path.win32.basename("C:\\dir\\base.ext"), "base.ext"); + assertEqual(path.win32.basename("C:\\basename.ext"), "basename.ext"); + assertEqual(path.win32.basename("C:basename.ext"), "basename.ext"); + assertEqual(path.win32.basename("C:basename.ext\\"), "basename.ext"); + assertEqual(path.win32.basename("C:basename.ext\\\\"), "basename.ext"); + assertEqual(path.win32.basename("C:foo"), "foo"); + assertEqual(path.win32.basename("file:stream"), "file:stream"); +}); diff --git a/path/constants.ts b/path/constants.ts new file mode 100644 index 000000000..b440be9cc --- /dev/null +++ b/path/constants.ts @@ -0,0 +1,53 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { platform } from "deno"; + +const isWindows = platform.os === "win"; + +// Alphabet chars. +export const CHAR_UPPERCASE_A = 65; /* A */ +export const CHAR_LOWERCASE_A = 97; /* a */ +export const CHAR_UPPERCASE_Z = 90; /* Z */ +export const CHAR_LOWERCASE_Z = 122; /* z */ + +// Non-alphabetic chars. +export const CHAR_DOT = 46; /* . */ +export const CHAR_FORWARD_SLASH = 47; /* / */ +export const CHAR_BACKWARD_SLASH = 92; /* \ */ +export const CHAR_VERTICAL_LINE = 124; /* | */ +export const CHAR_COLON = 58; /* : */ +export const CHAR_QUESTION_MARK = 63; /* ? */ +export const CHAR_UNDERSCORE = 95; /* _ */ +export const CHAR_LINE_FEED = 10; /* \n */ +export const CHAR_CARRIAGE_RETURN = 13; /* \r */ +export const CHAR_TAB = 9; /* \t */ +export const CHAR_FORM_FEED = 12; /* \f */ +export const CHAR_EXCLAMATION_MARK = 33; /* ! */ +export const CHAR_HASH = 35; /* # */ +export const CHAR_SPACE = 32; /* */ +export const CHAR_NO_BREAK_SPACE = 160; /* \u00A0 */ +export const CHAR_ZERO_WIDTH_NOBREAK_SPACE = 65279; /* \uFEFF */ +export const CHAR_LEFT_SQUARE_BRACKET = 91; /* [ */ +export const CHAR_RIGHT_SQUARE_BRACKET = 93; /* ] */ +export const CHAR_LEFT_ANGLE_BRACKET = 60; /* < */ +export const CHAR_RIGHT_ANGLE_BRACKET = 62; /* > */ +export const CHAR_LEFT_CURLY_BRACKET = 123; /* { */ +export const CHAR_RIGHT_CURLY_BRACKET = 125; /* } */ +export const CHAR_HYPHEN_MINUS = 45; /* - */ +export const CHAR_PLUS = 43; /* + */ +export const CHAR_DOUBLE_QUOTE = 34; /* " */ +export const CHAR_SINGLE_QUOTE = 39; /* ' */ +export const CHAR_PERCENT = 37; /* % */ +export const CHAR_SEMICOLON = 59; /* ; */ +export const CHAR_CIRCUMFLEX_ACCENT = 94; /* ^ */ +export const CHAR_GRAVE_ACCENT = 96; /* ` */ +export const CHAR_AT = 64; /* @ */ +export const CHAR_AMPERSAND = 38; /* & */ +export const CHAR_EQUAL = 61; /* = */ + +// Digits +export const CHAR_0 = 48; /* 0 */ +export const CHAR_9 = 57; /* 9 */ + +export const EOL = isWindows ? "\r\n" : "\n"; diff --git a/path/dirname_test.ts b/path/dirname_test.ts new file mode 100644 index 000000000..12fa58743 --- /dev/null +++ b/path/dirname_test.ts @@ -0,0 +1,61 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import * as path from "./index"; + +test(function dirname() { + assertEqual(path.posix.dirname("/a/b/"), "/a"); + assertEqual(path.posix.dirname("/a/b"), "/a"); + assertEqual(path.posix.dirname("/a"), "/"); + assertEqual(path.posix.dirname(""), "."); + assertEqual(path.posix.dirname("/"), "/"); + assertEqual(path.posix.dirname("////"), "/"); + assertEqual(path.posix.dirname("//a"), "//"); + assertEqual(path.posix.dirname("foo"), "."); +}); + +test(function dirnameWin32() { + assertEqual(path.win32.dirname("c:\\"), "c:\\"); + assertEqual(path.win32.dirname("c:\\foo"), "c:\\"); + assertEqual(path.win32.dirname("c:\\foo\\"), "c:\\"); + assertEqual(path.win32.dirname("c:\\foo\\bar"), "c:\\foo"); + assertEqual(path.win32.dirname("c:\\foo\\bar\\"), "c:\\foo"); + assertEqual(path.win32.dirname("c:\\foo\\bar\\baz"), "c:\\foo\\bar"); + assertEqual(path.win32.dirname("\\"), "\\"); + assertEqual(path.win32.dirname("\\foo"), "\\"); + assertEqual(path.win32.dirname("\\foo\\"), "\\"); + assertEqual(path.win32.dirname("\\foo\\bar"), "\\foo"); + assertEqual(path.win32.dirname("\\foo\\bar\\"), "\\foo"); + assertEqual(path.win32.dirname("\\foo\\bar\\baz"), "\\foo\\bar"); + assertEqual(path.win32.dirname("c:"), "c:"); + assertEqual(path.win32.dirname("c:foo"), "c:"); + assertEqual(path.win32.dirname("c:foo\\"), "c:"); + assertEqual(path.win32.dirname("c:foo\\bar"), "c:foo"); + assertEqual(path.win32.dirname("c:foo\\bar\\"), "c:foo"); + assertEqual(path.win32.dirname("c:foo\\bar\\baz"), "c:foo\\bar"); + assertEqual(path.win32.dirname("file:stream"), "."); + assertEqual(path.win32.dirname("dir\\file:stream"), "dir"); + assertEqual(path.win32.dirname("\\\\unc\\share"), "\\\\unc\\share"); + assertEqual(path.win32.dirname("\\\\unc\\share\\foo"), "\\\\unc\\share\\"); + assertEqual(path.win32.dirname("\\\\unc\\share\\foo\\"), "\\\\unc\\share\\"); + assertEqual( + path.win32.dirname("\\\\unc\\share\\foo\\bar"), + "\\\\unc\\share\\foo" + ); + assertEqual( + path.win32.dirname("\\\\unc\\share\\foo\\bar\\"), + "\\\\unc\\share\\foo" + ); + assertEqual( + path.win32.dirname("\\\\unc\\share\\foo\\bar\\baz"), + "\\\\unc\\share\\foo\\bar" + ); + assertEqual(path.win32.dirname("/a/b/"), "/a"); + assertEqual(path.win32.dirname("/a/b"), "/a"); + assertEqual(path.win32.dirname("/a"), "/"); + assertEqual(path.win32.dirname(""), "."); + assertEqual(path.win32.dirname("/"), "/"); + assertEqual(path.win32.dirname("////"), "/"); + assertEqual(path.win32.dirname("foo"), "."); +}); diff --git a/path/extname_test.ts b/path/extname_test.ts new file mode 100644 index 000000000..f9a44a812 --- /dev/null +++ b/path/extname_test.ts @@ -0,0 +1,89 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import * as path from "./index"; + +const slashRE = /\//g; + +const pairs = [ + ["", ""], + ["/path/to/file", ""], + ["/path/to/file.ext", ".ext"], + ["/path.to/file.ext", ".ext"], + ["/path.to/file", ""], + ["/path.to/.file", ""], + ["/path.to/.file.ext", ".ext"], + ["/path/to/f.ext", ".ext"], + ["/path/to/..ext", ".ext"], + ["/path/to/..", ""], + ["file", ""], + ["file.ext", ".ext"], + [".file", ""], + [".file.ext", ".ext"], + ["/file", ""], + ["/file.ext", ".ext"], + ["/.file", ""], + ["/.file.ext", ".ext"], + [".path/file.ext", ".ext"], + ["file.ext.ext", ".ext"], + ["file.", "."], + [".", ""], + ["./", ""], + [".file.ext", ".ext"], + [".file", ""], + [".file.", "."], + [".file..", "."], + ["..", ""], + ["../", ""], + ["..file.ext", ".ext"], + ["..file", ".file"], + ["..file.", "."], + ["..file..", "."], + ["...", "."], + ["...ext", ".ext"], + ["....", "."], + ["file.ext/", ".ext"], + ["file.ext//", ".ext"], + ["file/", ""], + ["file//", ""], + ["file./", "."], + ["file.//", "."] +]; + +test(function extname() { + pairs.forEach(function(p) { + const input = p[0]; + const expected = p[1]; + assertEqual(expected, path.posix.extname(input)); + }); + + // On *nix, backslash is a valid name component like any other character. + assertEqual(path.posix.extname(".\\"), ""); + assertEqual(path.posix.extname("..\\"), ".\\"); + assertEqual(path.posix.extname("file.ext\\"), ".ext\\"); + assertEqual(path.posix.extname("file.ext\\\\"), ".ext\\\\"); + assertEqual(path.posix.extname("file\\"), ""); + assertEqual(path.posix.extname("file\\\\"), ""); + assertEqual(path.posix.extname("file.\\"), ".\\"); + assertEqual(path.posix.extname("file.\\\\"), ".\\\\"); +}); + +test(function extnameWin32() { + pairs.forEach(function(p) { + const input = p[0].replace(slashRE, "\\"); + const expected = p[1]; + assertEqual(expected, path.win32.extname(input)); + assertEqual(expected, path.win32.extname("C:" + input)); + }); + + // On Windows, backslash is a path separator. + assertEqual(path.win32.extname(".\\"), ""); + assertEqual(path.win32.extname("..\\"), ""); + assertEqual(path.win32.extname("file.ext\\"), ".ext"); + assertEqual(path.win32.extname("file.ext\\\\"), ".ext"); + assertEqual(path.win32.extname("file\\"), ""); + assertEqual(path.win32.extname("file\\\\"), ""); + assertEqual(path.win32.extname("file.\\"), "."); + assertEqual(path.win32.extname("file.\\\\"), "."); +}); diff --git a/path/index.ts b/path/index.ts new file mode 100644 index 000000000..3b59bffa7 --- /dev/null +++ b/path/index.ts @@ -0,0 +1,1425 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { + CHAR_UPPERCASE_A, + CHAR_LOWERCASE_A, + CHAR_UPPERCASE_Z, + CHAR_LOWERCASE_Z, + CHAR_DOT, + CHAR_FORWARD_SLASH, + CHAR_BACKWARD_SLASH, + CHAR_COLON, + CHAR_QUESTION_MARK +} from "./constants"; +import { cwd, env, platform } from "deno"; +import { FormatInputPathObject, ParsedPath } from "./interface"; + +function assertPath(path: string) { + if (typeof path !== "string") { + throw new TypeError( + `Path must be a string. Received ${JSON.stringify(path)}` + ); + } +} + +function isPathSeparator(code: number) { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +} + +function isPosixPathSeparator(code: number) { + return code === CHAR_FORWARD_SLASH; +} + +function isWindowsDeviceRoot(code: number) { + return ( + (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || + (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z) + ); +} + +// Resolves . and .. elements in a path with directory names +function normalizeString( + path: string, + allowAboveRoot: boolean, + separator: string, + isPathSeparator: (code: number) => boolean +) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code: number; + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) code = path.charCodeAt(i); + else if (isPathSeparator(code)) break; + else code = CHAR_FORWARD_SLASH; + + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) { + // NOOP + } else if (lastSlash !== i - 1 && dots === 2) { + if ( + res.length < 2 || + lastSegmentLength !== 2 || + res.charCodeAt(res.length - 1) !== CHAR_DOT || + res.charCodeAt(res.length - 2) !== CHAR_DOT + ) { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf(separator); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } else if (res.length === 2 || res.length === 1) { + res = ""; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) res += `${separator}..`; + else res = ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) res += separator + path.slice(lastSlash + 1, i); + else res = path.slice(lastSlash + 1, i); + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} + +function _format(sep: string, pathObject: FormatInputPathObject) { + const dir = pathObject.dir || pathObject.root; + const base = + pathObject.base || (pathObject.name || "") + (pathObject.ext || ""); + if (!dir) { + return base; + } + if (dir === pathObject.root) { + return dir + base; + } + return dir + sep + base; +} + +const win32 = { + // path.resolve([from ...], to) + resolve: function resolve(...pathSegments: string[]) { + let resolvedDevice = ""; + let resolvedTail = ""; + let resolvedAbsolute = false; + + for (let i = arguments.length - 1; i >= -1; i--) { + let path: string; + if (i >= 0) { + path = arguments[i]; + } else if (!resolvedDevice) { + path = cwd(); + } else { + // Windows has the concept of drive-specific current working + // directories. If we've resolved a drive letter but not yet an + // absolute path, get cwd for that drive, or the process cwd if + // the drive cwd is not available. We're sure the device is not + // a UNC path at this points, because UNC paths are always absolute. + path = env()[`=${resolvedDevice}`] || cwd(); + + // Verify that a cwd was found and that it actually points + // to our drive. If not, default to the drive's root. + if ( + path === undefined || + path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\` + ) { + path = `${resolvedDevice}\\`; + } + } + + assertPath(path); + + // Skip empty entries + if (path.length === 0) { + continue; + } + + let len = path.length; + let rootEnd = 0; + let device = ""; + let isAbsolute = false; + const code = path.charCodeAt(0); + + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + + // If we started with a separator, we know we at least have an + // absolute path of some kind (UNC or otherwise) + isAbsolute = true; + + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + device = `\\\\${firstPart}\\${path.slice(last)}`; + rootEnd = j; + } else if (j !== last) { + // We matched a UNC root with leftovers + + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } else { + rootEnd = 1; + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + + if (path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + // Treat separator following drive name as an absolute path + // indicator + isAbsolute = true; + rootEnd = 3; + } + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator + rootEnd = 1; + isAbsolute = true; + } + + if ( + device.length > 0 && + resolvedDevice.length > 0 && + device.toLowerCase() !== resolvedDevice.toLowerCase() + ) { + // This path points to another device so it is not applicable + continue; + } + + if (resolvedDevice.length === 0 && device.length > 0) { + resolvedDevice = device; + } + if (!resolvedAbsolute) { + resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; + resolvedAbsolute = isAbsolute; + } + + if (resolvedDevice.length > 0 && resolvedAbsolute) { + break; + } + } + + // At this point the path should be resolved to a full absolute path, + // but handle relative paths to be safe (might happen when process.cwd() + // fails) + + // Normalize the tail path + resolvedTail = normalizeString( + resolvedTail, + !resolvedAbsolute, + "\\", + isPathSeparator + ); + + return ( + resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || "." + ); + }, + + normalize: function normalize(path: string) { + assertPath(path); + const len = path.length; + if (len === 0) return "."; + let rootEnd = 0; + let device: string; + let isAbsolute = false; + const code = path.charCodeAt(0); + + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + + // If we started with a separator, we know we at least have an absolute + // path of some kind (UNC or otherwise) + isAbsolute = true; + + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + // Return the normalized version of the UNC root since there + // is nothing left to process + + return `\\\\${firstPart}\\${path.slice(last)}\\`; + } else if (j !== last) { + // We matched a UNC root with leftovers + + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } else { + rootEnd = 1; + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + + if (path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + // Treat separator following drive name as an absolute path + // indicator + isAbsolute = true; + rootEnd = 3; + } + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid unnecessary + // work + return "\\"; + } + + let tail: string; + if (rootEnd < len) { + tail = normalizeString( + path.slice(rootEnd), + !isAbsolute, + "\\", + isPathSeparator + ); + } else { + tail = ""; + } + if (tail.length === 0 && !isAbsolute) tail = "."; + if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) + tail += "\\"; + if (device === undefined) { + if (isAbsolute) { + if (tail.length > 0) return `\\${tail}`; + else return "\\"; + } else if (tail.length > 0) { + return tail; + } else { + return ""; + } + } else if (isAbsolute) { + if (tail.length > 0) return `${device}\\${tail}`; + else return `${device}\\`; + } else if (tail.length > 0) { + return device + tail; + } else { + return device; + } + }, + + isAbsolute: function isAbsolute(path: string) { + assertPath(path); + const len = path.length; + if (len === 0) return false; + + const code = path.charCodeAt(0); + if (isPathSeparator(code)) { + return true; + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + + if (len > 2 && path.charCodeAt(1) === CHAR_COLON) { + if (isPathSeparator(path.charCodeAt(2))) return true; + } + } + return false; + }, + + join: function join(...paths: string[]) { + if (arguments.length === 0) return "."; + + let joined: string; + let firstPart: string; + for (let i = 0; i < arguments.length; ++i) { + let arg = arguments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === undefined) joined = firstPart = arg; + else joined += `\\${arg}`; + } + } + + if (joined === undefined) return "."; + + // Make sure that the joined path doesn't start with two slashes, because + // normalize() will mistake it for an UNC path then. + // + // This step is skipped when it is very clear that the user actually + // intended to point at an UNC path. This is assumed when the first + // non-empty string arguments starts with exactly two slashes followed by + // at least one more non-slash character. + // + // Note that for normalize() to treat a path as an UNC path it needs to + // have at least 2 components, so we don't filter for that here. + // This means that the user can use join to construct UNC paths from + // a server name and a share name; for example: + // path.join('//server', 'share') -> '\\\\server\\share\\') + let needsReplace = true; + let slashCount = 0; + if (isPathSeparator(firstPart.charCodeAt(0))) { + ++slashCount; + const firstLen = firstPart.length; + if (firstLen > 1) { + if (isPathSeparator(firstPart.charCodeAt(1))) { + ++slashCount; + if (firstLen > 2) { + if (isPathSeparator(firstPart.charCodeAt(2))) ++slashCount; + else { + // We matched a UNC path in the first part + needsReplace = false; + } + } + } + } + } + if (needsReplace) { + // Find any more consecutive slashes we need to replace + for (; slashCount < joined.length; ++slashCount) { + if (!isPathSeparator(joined.charCodeAt(slashCount))) break; + } + + // Replace the slashes if needed + if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`; + } + + return win32.normalize(joined); + }, + + // It will solve the relative path from `from` to `to`, for instance: + // from = 'C:\\orandea\\test\\aaa' + // to = 'C:\\orandea\\impl\\bbb' + // The output of the function should be: '..\\..\\impl\\bbb' + relative: function relative(from: string, to: string) { + assertPath(from); + assertPath(to); + + if (from === to) return ""; + + let fromOrig = win32.resolve(from); + let toOrig = win32.resolve(to); + + if (fromOrig === toOrig) return ""; + + from = fromOrig.toLowerCase(); + to = toOrig.toLowerCase(); + + if (from === to) return ""; + + // Trim any leading backslashes + let fromStart = 0; + for (; fromStart < from.length; ++fromStart) { + if (from.charCodeAt(fromStart) !== CHAR_BACKWARD_SLASH) break; + } + // Trim trailing backslashes (applicable to UNC paths only) + let fromEnd = from.length; + for (; fromEnd - 1 > fromStart; --fromEnd) { + if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break; + } + let fromLen = fromEnd - fromStart; + + // Trim any leading backslashes + let toStart = 0; + for (; toStart < to.length; ++toStart) { + if (to.charCodeAt(toStart) !== CHAR_BACKWARD_SLASH) break; + } + // Trim trailing backslashes (applicable to UNC paths only) + let toEnd = to.length; + for (; toEnd - 1 > toStart; --toEnd) { + if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break; + } + let toLen = toEnd - toStart; + + // Compare paths to find the longest common path from root + let length = fromLen < toLen ? fromLen : toLen; + let lastCommonSep = -1; + let i = 0; + for (; i <= length; ++i) { + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { + // We get here if `from` is the exact base path for `to`. + // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' + return toOrig.slice(toStart + i + 1); + } else if (i === 2) { + // We get here if `from` is the device root. + // For example: from='C:\\'; to='C:\\foo' + return toOrig.slice(toStart + i); + } + } + if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='C:\\foo\\bar'; to='C:\\foo' + lastCommonSep = i; + } else if (i === 2) { + // We get here if `to` is the device root. + // For example: from='C:\\foo\\bar'; to='C:\\' + lastCommonSep = 3; + } + } + break; + } + let fromCode = from.charCodeAt(fromStart + i); + let toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) break; + else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i; + } + + // We found a mismatch before the first common path separator was seen, so + // return the original `to`. + if (i !== length && lastCommonSep === -1) { + return toOrig; + } + + let out = ""; + if (lastCommonSep === -1) lastCommonSep = 0; + // Generate the relative path based on the path difference between `to` and + // `from` + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { + if (out.length === 0) out += ".."; + else out += "\\.."; + } + } + + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) + return out + toOrig.slice(toStart + lastCommonSep, toEnd); + else { + toStart += lastCommonSep; + if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) ++toStart; + return toOrig.slice(toStart, toEnd); + } + }, + + toNamespacedPath: function toNamespacedPath(path: string) { + // Note: this will *probably* throw somewhere. + if (typeof path !== "string") return path; + + if (path.length === 0) { + return ""; + } + + const resolvedPath = win32.resolve(path); + + if (resolvedPath.length >= 3) { + if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { + // Possible UNC root + + if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { + const code = resolvedPath.charCodeAt(2); + if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { + // Matched non-long UNC root, convert the path to a long UNC path + return `\\\\?\\UNC\\${resolvedPath.slice(2)}`; + } + } + } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0))) { + // Possible device root + + if ( + resolvedPath.charCodeAt(1) === CHAR_COLON && + resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH + ) { + // Matched device root, convert the path to a long UNC path + return `\\\\?\\${resolvedPath}`; + } + } + } + + return path; + }, + + dirname: function dirname(path: string) { + assertPath(path); + const len = path.length; + if (len === 0) return "."; + let rootEnd = -1; + let end = -1; + let matchedSlash = true; + let offset = 0; + const code = path.charCodeAt(0); + + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + + rootEnd = offset = 1; + + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + return path; + } + if (j !== last) { + // We matched a UNC root with leftovers + + // Offset by 1 to include the separator after the UNC root to + // treat it as a "normal root" on top of a (UNC) root + rootEnd = offset = j + 1; + } + } + } + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + + if (path.charCodeAt(1) === CHAR_COLON) { + rootEnd = offset = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) rootEnd = offset = 3; + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid + // unnecessary work + return path; + } + + for (let i = len - 1; i >= offset; --i) { + if (isPathSeparator(path.charCodeAt(i))) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) { + if (rootEnd === -1) return "."; + else end = rootEnd; + } + return path.slice(0, end); + }, + + basename: function basename(path: string, ext = "") { + if (ext !== undefined && typeof ext !== "string") + throw new TypeError('"ext" argument must be a string'); + assertPath(path); + let start = 0; + let end = -1; + let matchedSlash = true; + let i: number; + + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + if (path.length >= 2) { + const drive = path.charCodeAt(0); + if (isWindowsDeviceRoot(drive)) { + if (path.charCodeAt(1) === CHAR_COLON) start = 2; + } + } + + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) return ""; + let extIdx = ext.length - 1; + let firstNonSlashEnd = -1; + for (i = path.length - 1; i >= start; --i) { + const code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + + if (start === end) end = firstNonSlashEnd; + else if (end === -1) end = path.length; + return path.slice(start, end); + } else { + for (i = path.length - 1; i >= start; --i) { + if (isPathSeparator(path.charCodeAt(i))) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ""; + return path.slice(start, end); + } + }, + + extname: function extname(path: string) { + assertPath(path); + let start = 0; + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + + if ( + path.length >= 2 && + path.charCodeAt(1) === CHAR_COLON && + isWindowsDeviceRoot(path.charCodeAt(0)) + ) { + start = startPart = 2; + } + + for (let i = path.length - 1; i >= start; --i) { + const code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if ( + startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) + ) { + return ""; + } + return path.slice(startDot, end); + }, + + format: function format(pathObject: FormatInputPathObject) { + if (pathObject === null || typeof pathObject !== "object") { + throw new TypeError( + `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` + ); + } + return _format("\\", pathObject); + }, + + parse: function parse(path: string) { + assertPath(path); + + let ret = { root: "", dir: "", base: "", ext: "", name: "" } as ParsedPath; + if (path.length === 0) return ret; + + let len = path.length; + let rootEnd = 0; + let code = path.charCodeAt(0); + + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + + rootEnd = 1; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + + rootEnd = j; + } else if (j !== last) { + // We matched a UNC root with leftovers + + rootEnd = j + 1; + } + } + } + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + + if (path.charCodeAt(1) === CHAR_COLON) { + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + if (len === 3) { + // `path` contains just a drive root, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + rootEnd = 3; + } + } else { + // `path` contains just a drive root, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + + if (rootEnd > 0) ret.root = path.slice(0, rootEnd); + + let startDot = -1; + let startPart = rootEnd; + let end = -1; + let matchedSlash = true; + let i = path.length - 1; + + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + + // Get non-dir info + for (; i >= rootEnd; --i) { + code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if ( + startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) + ) { + if (end !== -1) { + ret.base = ret.name = path.slice(startPart, end); + } + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + ret.ext = path.slice(startDot, end); + } + + // If the directory is the root, use the entire root as the `dir` including + // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the + // trailing slash (`C:\abc\def` -> `C:\abc`). + if (startPart > 0 && startPart !== rootEnd) + ret.dir = path.slice(0, startPart - 1); + else ret.dir = ret.root; + + return ret; + }, + + sep: "\\", + delimiter: ";", + win32: null, + posix: null +}; + +const posix = { + // path.resolve([from ...], to) + resolve: function resolve(...pathSegments: string[]) { + let resolvedPath = ""; + let resolvedAbsolute = false; + + for (let i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + let path: string; + if (i >= 0) path = arguments[i]; + else { + path = cwd(); + } + + assertPath(path); + + // Skip empty entries + if (path.length === 0) { + continue; + } + + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeString( + resolvedPath, + !resolvedAbsolute, + "/", + isPosixPathSeparator + ); + + if (resolvedAbsolute) { + if (resolvedPath.length > 0) return `/${resolvedPath}`; + else return "/"; + } else if (resolvedPath.length > 0) { + return resolvedPath; + } else { + return "."; + } + }, + + normalize: function normalize(path: string) { + assertPath(path); + + if (path.length === 0) return "."; + + const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + const trailingSeparator = + path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; + + // Normalize the path + path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator); + + if (path.length === 0 && !isAbsolute) path = "."; + if (path.length > 0 && trailingSeparator) path += "/"; + + if (isAbsolute) return `/${path}`; + return path; + }, + + isAbsolute: function isAbsolute(path: string) { + assertPath(path); + return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; + }, + + join: function join(...paths: string[]) { + if (arguments.length === 0) return "."; + let joined: string; + for (let i = 0; i < arguments.length; ++i) { + let arg = arguments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === undefined) joined = arg; + else joined += `/${arg}`; + } + } + if (joined === undefined) return "."; + return posix.normalize(joined); + }, + + relative: function relative(from: string, to: string) { + assertPath(from); + assertPath(to); + + if (from === to) return ""; + + from = posix.resolve(from); + to = posix.resolve(to); + + if (from === to) return ""; + + // Trim any leading backslashes + let fromStart = 1; + for (; fromStart < from.length; ++fromStart) { + if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) break; + } + let fromEnd = from.length; + let fromLen = fromEnd - fromStart; + + // Trim any leading backslashes + let toStart = 1; + for (; toStart < to.length; ++toStart) { + if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) break; + } + let toEnd = to.length; + let toLen = toEnd - toStart; + + // Compare paths to find the longest common path from root + let length = fromLen < toLen ? fromLen : toLen; + let lastCommonSep = -1; + let i = 0; + for (; i <= length; ++i) { + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1); + } else if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i); + } + } else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo'; to='/' + lastCommonSep = 0; + } + } + break; + } + let fromCode = from.charCodeAt(fromStart + i); + let toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) break; + else if (fromCode === CHAR_FORWARD_SLASH) lastCommonSep = i; + } + + let out = ""; + // Generate the relative path based on the path difference between `to` + // and `from` + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) { + if (out.length === 0) out += ".."; + else out += "/.."; + } + } + + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) return out + to.slice(toStart + lastCommonSep); + else { + toStart += lastCommonSep; + if (to.charCodeAt(toStart) === CHAR_FORWARD_SLASH) ++toStart; + return to.slice(toStart); + } + }, + + toNamespacedPath: function toNamespacedPath(path: string) { + // Non-op on posix systems + return path; + }, + + dirname: function dirname(path: string) { + assertPath(path); + if (path.length === 0) return "."; + const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + let end = -1; + let matchedSlash = true; + for (let i = path.length - 1; i >= 1; --i) { + if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) return hasRoot ? "/" : "."; + if (hasRoot && end === 1) return "//"; + return path.slice(0, end); + }, + + basename: function basename(path: string, ext = "") { + if (ext !== undefined && typeof ext !== "string") + throw new TypeError('"ext" argument must be a string'); + assertPath(path); + + let start = 0; + let end = -1; + let matchedSlash = true; + let i: number; + + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) return ""; + let extIdx = ext.length - 1; + let firstNonSlashEnd = -1; + for (i = path.length - 1; i >= 0; --i) { + const code = path.charCodeAt(i); + if (code === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + + if (start === end) end = firstNonSlashEnd; + else if (end === -1) end = path.length; + return path.slice(start, end); + } else { + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ""; + return path.slice(start, end); + } + }, + + extname: function extname(path: string) { + assertPath(path); + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + for (let i = path.length - 1; i >= 0; --i) { + const code = path.charCodeAt(i); + if (code === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if ( + startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) + ) { + return ""; + } + return path.slice(startDot, end); + }, + + format: function format(pathObject: FormatInputPathObject) { + if (pathObject === null || typeof pathObject !== "object") { + throw new TypeError( + `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` + ); + } + return _format("/", pathObject); + }, + + parse: function parse(path: string) { + assertPath(path); + + let ret = { root: "", dir: "", base: "", ext: "", name: "" } as ParsedPath; + if (path.length === 0) return ret; + let isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + let start: number; + if (isAbsolute) { + ret.root = "/"; + start = 1; + } else { + start = 0; + } + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + let i = path.length - 1; + + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + + // Get non-dir info + for (; i >= start; --i) { + const code = path.charCodeAt(i); + if (code === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if ( + startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) + ) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) + ret.base = ret.name = path.slice(1, end); + else ret.base = ret.name = path.slice(startPart, end); + } + } else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot); + ret.base = path.slice(1, end); + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + } + ret.ext = path.slice(startDot, end); + } + + if (startPart > 0) ret.dir = path.slice(0, startPart - 1); + else if (isAbsolute) ret.dir = "/"; + + return ret; + }, + + sep: "/", + delimiter: ":", + win32: null, + posix: null +}; + +posix.win32 = win32.win32 = win32; +posix.posix = win32.posix = posix; + +const module = platform.os === "win" ? win32 : posix; +export = module; diff --git a/path/interface.ts b/path/interface.ts new file mode 100644 index 000000000..84a3030ff --- /dev/null +++ b/path/interface.ts @@ -0,0 +1,47 @@ +/** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ +export 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; +} +export interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string; + /** + * The file extension (if any) such as '.html' + */ + ext?: string; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string; +} diff --git a/path/isabsolute_test.ts b/path/isabsolute_test.ts new file mode 100644 index 000000000..c338dbc03 --- /dev/null +++ b/path/isabsolute_test.ts @@ -0,0 +1,33 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import * as path from "./index"; + +test(function isAbsolute() { + assertEqual(path.posix.isAbsolute("/home/foo"), true); + assertEqual(path.posix.isAbsolute("/home/foo/.."), true); + assertEqual(path.posix.isAbsolute("bar/"), false); + assertEqual(path.posix.isAbsolute("./baz"), false); +}); + +test(function isAbsoluteWin32() { + assertEqual(path.win32.isAbsolute("/"), true); + assertEqual(path.win32.isAbsolute("//"), true); + assertEqual(path.win32.isAbsolute("//server"), true); + assertEqual(path.win32.isAbsolute("//server/file"), true); + assertEqual(path.win32.isAbsolute("\\\\server\\file"), true); + assertEqual(path.win32.isAbsolute("\\\\server"), true); + assertEqual(path.win32.isAbsolute("\\\\"), true); + assertEqual(path.win32.isAbsolute("c"), false); + assertEqual(path.win32.isAbsolute("c:"), false); + assertEqual(path.win32.isAbsolute("c:\\"), true); + assertEqual(path.win32.isAbsolute("c:/"), true); + assertEqual(path.win32.isAbsolute("c://"), true); + assertEqual(path.win32.isAbsolute("C:/Users/"), true); + assertEqual(path.win32.isAbsolute("C:\\Users\\"), true); + assertEqual(path.win32.isAbsolute("C:cwd/another"), false); + assertEqual(path.win32.isAbsolute("C:cwd\\another"), false); + assertEqual(path.win32.isAbsolute("directory/directory"), false); + assertEqual(path.win32.isAbsolute("directory\\directory"), false); +}); diff --git a/path/join_test.ts b/path/join_test.ts new file mode 100644 index 000000000..70b78c7be --- /dev/null +++ b/path/join_test.ts @@ -0,0 +1,124 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import * as path from "./index"; + +const backslashRE = /\\/g; + +const joinTests = + // arguments result + [ + [[".", "x/b", "..", "/b/c.js"], "x/b/c.js"], + [[], "."], + [["/.", "x/b", "..", "/b/c.js"], "/x/b/c.js"], + [["/foo", "../../../bar"], "/bar"], + [["foo", "../../../bar"], "../../bar"], + [["foo/", "../../../bar"], "../../bar"], + [["foo/x", "../../../bar"], "../bar"], + [["foo/x", "./bar"], "foo/x/bar"], + [["foo/x/", "./bar"], "foo/x/bar"], + [["foo/x/", ".", "bar"], "foo/x/bar"], + [["./"], "./"], + [[".", "./"], "./"], + [[".", ".", "."], "."], + [[".", "./", "."], "."], + [[".", "/./", "."], "."], + [[".", "/////./", "."], "."], + [["."], "."], + [["", "."], "."], + [["", "foo"], "foo"], + [["foo", "/bar"], "foo/bar"], + [["", "/foo"], "/foo"], + [["", "", "/foo"], "/foo"], + [["", "", "foo"], "foo"], + [["foo", ""], "foo"], + [["foo/", ""], "foo/"], + [["foo", "", "/bar"], "foo/bar"], + [["./", "..", "/foo"], "../foo"], + [["./", "..", "..", "/foo"], "../../foo"], + [[".", "..", "..", "/foo"], "../../foo"], + [["", "..", "..", "/foo"], "../../foo"], + [["/"], "/"], + [["/", "."], "/"], + [["/", ".."], "/"], + [["/", "..", ".."], "/"], + [[""], "."], + [["", ""], "."], + [[" /foo"], " /foo"], + [[" ", "foo"], " /foo"], + [[" ", "."], " "], + [[" ", "/"], " /"], + [[" ", ""], " "], + [["/", "foo"], "/foo"], + [["/", "/foo"], "/foo"], + [["/", "//foo"], "/foo"], + [["/", "", "/foo"], "/foo"], + [["", "/", "foo"], "/foo"], + [["", "/", "/foo"], "/foo"] + ]; + +// Windows-specific join tests +const windowsJoinTests = [ + // arguments result + // UNC path expected + [["//foo/bar"], "\\\\foo\\bar\\"], + [["\\/foo/bar"], "\\\\foo\\bar\\"], + [["\\\\foo/bar"], "\\\\foo\\bar\\"], + // UNC path expected - server and share separate + [["//foo", "bar"], "\\\\foo\\bar\\"], + [["//foo/", "bar"], "\\\\foo\\bar\\"], + [["//foo", "/bar"], "\\\\foo\\bar\\"], + // UNC path expected - questionable + [["//foo", "", "bar"], "\\\\foo\\bar\\"], + [["//foo/", "", "bar"], "\\\\foo\\bar\\"], + [["//foo/", "", "/bar"], "\\\\foo\\bar\\"], + // UNC path expected - even more questionable + [["", "//foo", "bar"], "\\\\foo\\bar\\"], + [["", "//foo/", "bar"], "\\\\foo\\bar\\"], + [["", "//foo/", "/bar"], "\\\\foo\\bar\\"], + // No UNC path expected (no double slash in first component) + [["\\", "foo/bar"], "\\foo\\bar"], + [["\\", "/foo/bar"], "\\foo\\bar"], + [["", "/", "/foo/bar"], "\\foo\\bar"], + // No UNC path expected (no non-slashes in first component - + // questionable) + [["//", "foo/bar"], "\\foo\\bar"], + [["//", "/foo/bar"], "\\foo\\bar"], + [["\\\\", "/", "/foo/bar"], "\\foo\\bar"], + [["//"], "\\"], + // No UNC path expected (share name missing - questionable). + [["//foo"], "\\foo"], + [["//foo/"], "\\foo\\"], + [["//foo", "/"], "\\foo\\"], + [["//foo", "", "/"], "\\foo\\"], + // No UNC path expected (too many leading slashes - questionable) + [["///foo/bar"], "\\foo\\bar"], + [["////foo", "bar"], "\\foo\\bar"], + [["\\\\\\/foo/bar"], "\\foo\\bar"], + // Drive-relative vs drive-absolute paths. This merely describes the + // status quo, rather than being obviously right + [["c:"], "c:."], + [["c:."], "c:."], + [["c:", ""], "c:."], + [["", "c:"], "c:."], + [["c:.", "/"], "c:.\\"], + [["c:.", "file"], "c:file"], + [["c:", "/"], "c:\\"], + [["c:", "file"], "c:\\file"] +]; + +test(function join() { + joinTests.forEach(function(p) { + const actual = path.posix.join.apply(null, p[0]); + assertEqual(actual, p[1]); + }); +}); + +test(function joinWin32() { + joinTests.forEach(function(p) { + const actual = path.win32.join.apply(null, p[0]).replace(backslashRE, "/"); + assertEqual(actual, p[1]); + }); + windowsJoinTests.forEach(function(p) { + const actual = path.win32.join.apply(null, p[0]); + assertEqual(actual, p[1]); + }); +}); diff --git a/path/parse_format_test.ts b/path/parse_format_test.ts new file mode 100644 index 000000000..b15026975 --- /dev/null +++ b/path/parse_format_test.ts @@ -0,0 +1,176 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import * as path from "./index"; + +const winPaths = [ + // [path, root] + ["C:\\path\\dir\\index.html", "C:\\"], + ["C:\\another_path\\DIR\\1\\2\\33\\\\index", "C:\\"], + ["another_path\\DIR with spaces\\1\\2\\33\\index", ""], + ["\\", "\\"], + ["\\foo\\C:", "\\"], + ["file", ""], + ["file:stream", ""], + [".\\file", ""], + ["C:", "C:"], + ["C:.", "C:"], + ["C:..", "C:"], + ["C:abc", "C:"], + ["C:\\", "C:\\"], + ["C:\\abc", "C:\\"], + ["", ""], + + // unc + ["\\\\server\\share\\file_path", "\\\\server\\share\\"], + [ + "\\\\server two\\shared folder\\file path.zip", + "\\\\server two\\shared folder\\" + ], + ["\\\\teela\\admin$\\system32", "\\\\teela\\admin$\\"], + ["\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\"] +]; + +const winSpecialCaseParseTests = [["/foo/bar", { root: "/" }]]; + +const winSpecialCaseFormatTests = [ + [{ dir: "some\\dir" }, "some\\dir\\"], + [{ base: "index.html" }, "index.html"], + [{ root: "C:\\" }, "C:\\"], + [{ name: "index", ext: ".html" }, "index.html"], + [{ dir: "some\\dir", name: "index", ext: ".html" }, "some\\dir\\index.html"], + [{ root: "C:\\", name: "index", ext: ".html" }, "C:\\index.html"], + [{}, ""] +]; + +const unixPaths = [ + // [path, root] + ["/home/user/dir/file.txt", "/"], + ["/home/user/a dir/another File.zip", "/"], + ["/home/user/a dir//another&File.", "/"], + ["/home/user/a$$$dir//another File.zip", "/"], + ["user/dir/another File.zip", ""], + ["file", ""], + [".\\file", ""], + ["./file", ""], + ["C:\\foo", ""], + ["/", "/"], + ["", ""], + [".", ""], + ["..", ""], + ["/foo", "/"], + ["/foo.", "/"], + ["/foo.bar", "/"], + ["/.", "/"], + ["/.foo", "/"], + ["/.foo.bar", "/"], + ["/foo/bar.baz", "/"] +]; + +const unixSpecialCaseFormatTests = [ + [{ dir: "some/dir" }, "some/dir/"], + [{ base: "index.html" }, "index.html"], + [{ root: "/" }, "/"], + [{ name: "index", ext: ".html" }, "index.html"], + [{ dir: "some/dir", name: "index", ext: ".html" }, "some/dir/index.html"], + [{ root: "/", name: "index", ext: ".html" }, "/index.html"], + [{}, ""] +]; + +test(function parseWin32() { + checkParseFormat(path.win32, winPaths); + checkSpecialCaseParseFormat(path.win32, winSpecialCaseParseTests); +}); + +test(function parse() { + checkParseFormat(path.posix, unixPaths); +}); + +test(function formatWin32() { + checkFormat(path.win32, winSpecialCaseFormatTests); +}); + +test(function format() { + checkFormat(path.posix, unixSpecialCaseFormatTests); +}); + +// Test removal of trailing path separators +const windowsTrailingTests = [ + [".\\", { root: "", dir: "", base: ".", ext: "", name: "." }], + ["\\\\", { root: "\\", dir: "\\", base: "", ext: "", name: "" }], + ["\\\\", { root: "\\", dir: "\\", base: "", ext: "", name: "" }], + [ + "c:\\foo\\\\\\", + { root: "c:\\", dir: "c:\\", base: "foo", ext: "", name: "foo" } + ], + [ + "D:\\foo\\\\\\bar.baz", + { + root: "D:\\", + dir: "D:\\foo\\\\", + base: "bar.baz", + ext: ".baz", + name: "bar" + } + ] +]; +const posixTrailingTests = [ + ["./", { root: "", dir: "", base: ".", ext: "", name: "." }], + ["//", { root: "/", dir: "/", base: "", ext: "", name: "" }], + ["///", { root: "/", dir: "/", base: "", ext: "", name: "" }], + ["/foo///", { root: "/", dir: "/", base: "foo", ext: "", name: "foo" }], + [ + "/foo///bar.baz", + { root: "/", dir: "/foo//", base: "bar.baz", ext: ".baz", name: "bar" } + ] +]; + +function checkParseFormat(path, paths) { + paths.forEach(function(p) { + const element = p[0]; + const output = path.parse(element); + assertEqual(typeof output.root, "string"); + assertEqual(typeof output.dir, "string"); + assertEqual(typeof output.base, "string"); + assertEqual(typeof output.ext, "string"); + assertEqual(typeof output.name, "string"); + assertEqual(path.format(output), element); + assertEqual(output.rooroot, undefined); + assertEqual(output.dir, output.dir ? path.dirname(element) : ""); + assertEqual(output.base, path.basename(element)); + }); +} + +function checkSpecialCaseParseFormat(path, testCases) { + testCases.forEach(function(testCase) { + const element = testCase[0]; + const expect = testCase[1]; + const output = path.parse(element); + Object.keys(expect).forEach(function(key) { + assertEqual(output[key], expect[key]); + }); + }); +} + +function checkFormat(path, testCases) { + testCases.forEach(function(testCase) { + assertEqual(path.format(testCase[0]), testCase[1]); + }); +} + +test(function parseTrailingWin32() { + windowsTrailingTests.forEach(function(p) { + const actual = path.win32.parse(p[0]); + const expected = p[1]; + assertEqual(actual, expected); + }); +}); + +test(function parseTrailing() { + posixTrailingTests.forEach(function(p) { + const actual = path.posix.parse(p[0]); + const expected = p[1]; + assertEqual(actual, expected); + }); +}); diff --git a/path/relative_test.ts b/path/relative_test.ts new file mode 100644 index 000000000..7e77376c6 --- /dev/null +++ b/path/relative_test.ts @@ -0,0 +1,72 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import * as path from "./index"; + +const relativeTests = { + win32: + // arguments result + [ + ["c:/blah\\blah", "d:/games", "d:\\games"], + ["c:/aaaa/bbbb", "c:/aaaa", ".."], + ["c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc"], + ["c:/aaaa/bbbb", "c:/aaaa/bbbb", ""], + ["c:/aaaa/bbbb", "c:/aaaa/cccc", "..\\cccc"], + ["c:/aaaa/", "c:/aaaa/cccc", "cccc"], + ["c:/", "c:\\aaaa\\bbbb", "aaaa\\bbbb"], + ["c:/aaaa/bbbb", "d:\\", "d:\\"], + ["c:/AaAa/bbbb", "c:/aaaa/bbbb", ""], + ["c:/aaaaa/", "c:/aaaa/cccc", "..\\aaaa\\cccc"], + ["C:\\foo\\bar\\baz\\quux", "C:\\", "..\\..\\..\\.."], + [ + "C:\\foo\\test", + "C:\\foo\\test\\bar\\package.json", + "bar\\package.json" + ], + ["C:\\foo\\bar\\baz-quux", "C:\\foo\\bar\\baz", "..\\baz"], + ["C:\\foo\\bar\\baz", "C:\\foo\\bar\\baz-quux", "..\\baz-quux"], + ["\\\\foo\\bar", "\\\\foo\\bar\\baz", "baz"], + ["\\\\foo\\bar\\baz", "\\\\foo\\bar", ".."], + ["\\\\foo\\bar\\baz-quux", "\\\\foo\\bar\\baz", "..\\baz"], + ["\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz-quux", "..\\baz-quux"], + ["C:\\baz-quux", "C:\\baz", "..\\baz"], + ["C:\\baz", "C:\\baz-quux", "..\\baz-quux"], + ["\\\\foo\\baz-quux", "\\\\foo\\baz", "..\\baz"], + ["\\\\foo\\baz", "\\\\foo\\baz-quux", "..\\baz-quux"], + ["C:\\baz", "\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz"], + ["\\\\foo\\bar\\baz", "C:\\baz", "C:\\baz"] + ], + posix: + // arguments result + [ + ["/var/lib", "/var", ".."], + ["/var/lib", "/bin", "../../bin"], + ["/var/lib", "/var/lib", ""], + ["/var/lib", "/var/apache", "../apache"], + ["/var/", "/var/lib", "lib"], + ["/", "/var/lib", "var/lib"], + ["/foo/test", "/foo/test/bar/package.json", "bar/package.json"], + ["/Users/a/web/b/test/mails", "/Users/a/web/b", "../.."], + ["/foo/bar/baz-quux", "/foo/bar/baz", "../baz"], + ["/foo/bar/baz", "/foo/bar/baz-quux", "../baz-quux"], + ["/baz-quux", "/baz", "../baz"], + ["/baz", "/baz-quux", "../baz-quux"] + ] +}; + +test(function relative() { + relativeTests.posix.forEach(function(p) { + const expected = p[2]; + const actual = path.posix.relative(p[0], p[1]); + assertEqual(actual, expected); + }); +}); + +test(function relativeWin32() { + relativeTests.win32.forEach(function(p) { + const expected = p[2]; + const actual = path.win32.relative(p[0], p[1]); + assertEqual(actual, expected); + }); +}); diff --git a/path/resolve_test.ts b/path/resolve_test.ts new file mode 100644 index 000000000..1b3d580ed --- /dev/null +++ b/path/resolve_test.ts @@ -0,0 +1,49 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import * as path from "./index"; +import { cwd } from "deno"; + +const windowsTests = + // arguments result + [ + [["c:/blah\\blah", "d:/games", "c:../a"], "c:\\blah\\a"], + [["c:/ignore", "d:\\a/b\\c/d", "\\e.exe"], "d:\\e.exe"], + [["c:/ignore", "c:/some/file"], "c:\\some\\file"], + [["d:/ignore", "d:some/dir//"], "d:\\ignore\\some\\dir"], + [["//server/share", "..", "relative\\"], "\\\\server\\share\\relative"], + [["c:/", "//"], "c:\\"], + [["c:/", "//dir"], "c:\\dir"], + [["c:/", "//server/share"], "\\\\server\\share\\"], + [["c:/", "//server//share"], "\\\\server\\share\\"], + [["c:/", "///some//dir"], "c:\\some\\dir"], + [ + ["C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js"], + "C:\\foo\\tmp.3\\cycles\\root.js" + ] + ]; +const posixTests = + // arguments result + [ + [["/var/lib", "../", "file/"], "/var/file"], + [["/var/lib", "/../", "file/"], "/file"], + [["a/b/c/", "../../.."], cwd()], + [["."], cwd()], + [["/some/dir", ".", "/absolute/"], "/absolute"], + [["/foo/tmp.3/", "../tmp.3/cycles/root.js"], "/foo/tmp.3/cycles/root.js"] + ]; + +test(function resolve() { + posixTests.forEach(function(p) { + const actual = path.posix.resolve.apply(null, p[0]); + assertEqual(actual, p[1]); + }); +}); + +test(function resolveWin32() { + windowsTests.forEach(function(p) { + const actual = path.win32.resolve.apply(null, p[0]); + assertEqual(actual, p[1]); + }); +}); diff --git a/path/zero_length_strings_test.ts b/path/zero_length_strings_test.ts new file mode 100644 index 000000000..dec9696d3 --- /dev/null +++ b/path/zero_length_strings_test.ts @@ -0,0 +1,46 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import * as path from "./index"; +import { cwd } from "deno"; + +const pwd = cwd(); + +test(function joinZeroLength() { + // join will internally ignore all the zero-length strings and it will return + // '.' if the joined string is a zero-length string. + assertEqual(path.posix.join(""), "."); + assertEqual(path.posix.join("", ""), "."); + if (path.win32) assertEqual(path.win32.join(""), "."); + if (path.win32) assertEqual(path.win32.join("", ""), "."); + assertEqual(path.join(pwd), pwd); + assertEqual(path.join(pwd, ""), pwd); +}); + +test(function normalizeZeroLength() { + // normalize will return '.' if the input is a zero-length string + assertEqual(path.posix.normalize(""), "."); + if (path.win32) assertEqual(path.win32.normalize(""), "."); + assertEqual(path.normalize(pwd), pwd); +}); + +test(function isAbsoluteZeroLength() { + // Since '' is not a valid path in any of the common environments, return false + assertEqual(path.posix.isAbsolute(""), false); + if (path.win32) assertEqual(path.win32.isAbsolute(""), false); +}); + +test(function resolveZeroLength() { + // resolve, internally ignores all the zero-length strings and returns the + // current working directory + assertEqual(path.resolve(""), pwd); + assertEqual(path.resolve("", ""), pwd); +}); + +test(function relativeZeroLength() { + // relative, internally calls resolve. So, '' is actually the current directory + assertEqual(path.relative("", pwd), ""); + assertEqual(path.relative(pwd, ""), ""); + assertEqual(path.relative(pwd, pwd), ""); +}); diff --git a/test.ts b/test.ts index 95003e0ad..54413ecd9 100755 --- a/test.ts +++ b/test.ts @@ -1,5 +1,5 @@ #!/usr/bin/env deno --allow-run --allow-net -import { run } from "deno"; +import { run, exit } from "deno"; import "net/bufio_test.ts"; import "net/http_test.ts"; @@ -10,6 +10,17 @@ import { runTests, completePromise } from "net/file_server_test.ts"; const fileServer = run({ args: ["deno", "--allow-net", "net/file_server.ts", "."] }); +// path test +import "path/basename_test.ts"; +import "path/dirname_test.ts"; +import "path/extname_test.ts"; +import "path/isabsolute_test.ts"; +import "path/join_test.ts"; +import "path/parse_format_test.ts"; +import "path/relative_test.ts"; +import "path/resolve_test.ts"; +import "path/zero_length_strings_test.ts"; + // I am also too lazy to do this properly LOL runTests(new Promise(res => setTimeout(res, 5000))); (async () => { -- cgit v1.2.3 From a3d164df917536c702775af1937569825fc5ceaf Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Wed, 19 Dec 2018 15:30:44 +1100 Subject: Add colors module (denoland/deno_std#30) Original: https://github.com/denoland/deno_std/commit/54787f172c62df7c98d8e9e534c40e317825e614 --- README.md | 30 ++++++++---------------- colors/README.md | 28 +++++++++++++++++++++++ colors/main.ts | 33 +++++++++++++++++++++++++++ colors/main_test.ts | 10 ++++++++ colors/styles.ts | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++ net/README.md | 26 +++++++++++++++++++++ test.ts | 6 ++++- 7 files changed, 177 insertions(+), 22 deletions(-) create mode 100644 colors/README.md create mode 100644 colors/main.ts create mode 100644 colors/main_test.ts create mode 100644 colors/styles.ts create mode 100644 net/README.md diff --git a/README.md b/README.md index ab668e913..73d48ab3a 100644 --- a/README.md +++ b/README.md @@ -2,27 +2,15 @@ [![Build Status](https://travis-ci.com/denoland/deno_std.svg?branch=master)](https://travis-ci.com/denoland/deno_std) -Usage: +This repository contains collections of modules that create a standard library +for Deno. -```typescript -import { serve } from "https://deno.land/x/net/http.ts"; -const s = serve("0.0.0.0:8000"); +| Collection | Description | +| ---------------------------- | --------------------------------------------------------------- | +| [colors](./colors/README.md) | Modules that generate ANSI color codes for the console. | +| [net](./net/README.md) | A framework for creating HTTP/HTTPS servers inspired by GoLang. | +| [path](./path/README.md) | A path manipulation library. | -async function main() { - for await (const req of s) { - req.respond({ body: new TextEncoder().encode("Hello World\n") }); - } -} - -main(); -``` - -## File Server - -A small program for serving local files over HTTP. - -Add the following to your `.bash_profile` -``` -alias file_server="deno https://deno.land/x/net/file_server.ts --allow-net" -``` +--- +Copyright 2018 the Deno authors. All rights reserved. MIT license. diff --git a/colors/README.md b/colors/README.md new file mode 100644 index 000000000..f20d1939a --- /dev/null +++ b/colors/README.md @@ -0,0 +1,28 @@ +# colors + +Is a basic console color library intended for [Deno](https://deno.land/). It is +inspired by packages like [chalk](https://www.npmjs.com/package/chalk) and +[colors](https://www.npmjs.com/package/colors) on npm. + +## Usage + +The main modules exports a single function name `color` which is a function +that provides chaining to stack colors. Basic usage looks like this: + +```ts +import { color } from "https://deno.land/x/colors/main.ts"; + +console.log(color.bgBlue.red.bold("Hello world!")); +``` + +## TODO + +- Currently, it just assumes it is running in an environment that supports ANSI + escape code terminal coloring. It should actually detect, specifically + windows and adjust properly. + +- Test coverage is very basic at the moment. + +--- + +Copyright 2018 the Deno authors. All rights reserved. MIT license. diff --git a/colors/main.ts b/colors/main.ts new file mode 100644 index 000000000..af4e1aace --- /dev/null +++ b/colors/main.ts @@ -0,0 +1,33 @@ +// Copyright 2018 the Deno authors. All rights reserved. MIT license. +import { styles } from "./styles.ts"; + +type Styles = { readonly [S in keyof typeof styles]: Color }; + +type Color = Styles & { + (str: string): string; +}; + +const styleStack: string[] = []; + +export const color = function color(str: string): string { + styleStack.reverse(); + while (styleStack.length) { + const style = styleStack.pop(); + const code = styles[style]; + str = `${code.open}${str.replace(code.closeRe, code.open)}${ + code.close + }`.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + return str; +} as Color; + +for (const style of Object.keys(styles)) { + Object.defineProperty(color, style, { + get() { + styleStack.push(style); + return color; + }, + enumerable: true, + configurable: false + }); +} diff --git a/colors/main_test.ts b/colors/main_test.ts new file mode 100644 index 000000000..596a592a6 --- /dev/null +++ b/colors/main_test.ts @@ -0,0 +1,10 @@ +import { assertEqual, test } from "https://deno.land/x/testing/testing.ts"; +import { color } from "./main"; + +test(function singleColor() { + assertEqual(color.red("Hello world"), "Hello world"); +}); + +test(function doubleColor() { + assertEqual(color.red.bgBlue("Hello world"), "Hello world"); +}); diff --git a/colors/styles.ts b/colors/styles.ts new file mode 100644 index 000000000..74f609b83 --- /dev/null +++ b/colors/styles.ts @@ -0,0 +1,66 @@ +// Copyright 2018 the Deno authors. All rights reserved. MIT license. +const matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +function escapeStringRegexp(str: string): string { + return str.replace(matchOperatorsRe, "\\$&"); +} + +const codes = { + reset: [0, 0], + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39], + + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] +}; + +type Styles = { + [S in keyof T]: { open: string; close: string; closeRe: RegExp } +}; + +export const styles: Styles = {} as any; + +for (const [style, [open, close]] of Object.entries(codes)) { + styles[style] = { + open: `\u001b[${open}m`, + close: `\u001b[${close}m`, + closeRe: new RegExp(escapeStringRegexp(`\u001b[${close}m`), "g") + }; +} diff --git a/net/README.md b/net/README.md new file mode 100644 index 000000000..65f2b9ad7 --- /dev/null +++ b/net/README.md @@ -0,0 +1,26 @@ +# net + +Usage: + +```typescript +import { serve } from "https://deno.land/x/net/http.ts"; +const s = serve("0.0.0.0:8000"); + +async function main() { + for await (const req of s) { + req.respond({ body: new TextEncoder().encode("Hello World\n") }); + } +} + +main(); +``` + +### File Server + +A small program for serving local files over HTTP. + +Add the following to your `.bash_profile` + +``` +alias file_server="deno https://deno.land/x/net/file_server.ts --allow-net" +``` diff --git a/test.ts b/test.ts index 54413ecd9..1155202d1 100755 --- a/test.ts +++ b/test.ts @@ -1,6 +1,10 @@ #!/usr/bin/env deno --allow-run --allow-net -import { run, exit } from "deno"; +import { run } from "deno"; +// colors tests +import "colors/main_test.ts"; + +// net tests import "net/bufio_test.ts"; import "net/http_test.ts"; import "net/textproto_test.ts"; -- cgit v1.2.3 From 2351df72db2be5906a7441e16c883926051284b1 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 19 Dec 2018 13:01:26 -0500 Subject: Fix prettier version (denoland/deno_std#27) Original: https://github.com/denoland/deno_std/commit/772698f4d2b65d81118f6f70232a4eccb1becc83 --- format.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/format.ts b/format.ts index 251cba1ed..25a56641d 100755 --- a/format.ts +++ b/format.ts @@ -1,8 +1,31 @@ #!/usr/bin/env deno --allow-run +// Copyright 2018 the Deno authors. All rights reserved. MIT license. -import { exit, run } from "deno"; +import { readAll, exit, run } from "deno"; + +async function checkVersion() { + const prettierVersion = run({ + args: ["bash", "-c", "prettier --version"], + stdout: "piped" + }); + const b = await readAll(prettierVersion.stdout); + const s = await prettierVersion.status(); + if (s.code != 0) { + console.log("error calling prettier --version error"); + exit(s.code); + } + const version = new TextDecoder().decode(b).trim(); + const requiredVersion = "1.15"; + if (!version.startsWith(requiredVersion)) { + console.log(`Required prettier version: ${requiredVersion}`); + console.log(`Installed prettier version: ${version}`); + exit(1); + } +} async function main() { + await checkVersion(); + const prettier = run({ args: ["bash", "-c", "prettier --write *.ts **/*.ts"] }); -- cgit v1.2.3 From 700b4ce0d99dca02fe192c8722ab1bb7a33dc709 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 19 Dec 2018 19:06:31 +0100 Subject: Add flags module (denoland/deno_std#32) Original: https://github.com/denoland/deno_std/commit/b15b0d20d722ad16ebba363c0e8e35bbbc869f20 --- README.md | 1 + flags/README.md | 59 ++++++++++ flags/example.ts | 4 + flags/index.ts | 271 ++++++++++++++++++++++++++++++++++++++++++++ flags/test.ts | 13 +++ flags/tests/all_bool.ts | 32 ++++++ flags/tests/bool.ts | 158 ++++++++++++++++++++++++++ flags/tests/dash.ts | 28 +++++ flags/tests/default_bool.ts | 32 ++++++ flags/tests/dotted.ts | 19 ++++ flags/tests/kv_short.ts | 12 ++ flags/tests/long.ts | 25 ++++ flags/tests/num.ts | 34 ++++++ flags/tests/parse.ts | 182 +++++++++++++++++++++++++++++ flags/tests/short.ts | 57 ++++++++++ flags/tests/stop_early.ts | 14 +++ flags/tests/unknown.ts | 96 ++++++++++++++++ flags/tests/whitespace.ts | 6 + test.ts | 3 + 19 files changed, 1046 insertions(+) create mode 100644 flags/README.md create mode 100644 flags/example.ts create mode 100644 flags/index.ts create mode 100644 flags/test.ts create mode 100755 flags/tests/all_bool.ts create mode 100755 flags/tests/bool.ts create mode 100755 flags/tests/dash.ts create mode 100755 flags/tests/default_bool.ts create mode 100755 flags/tests/dotted.ts create mode 100755 flags/tests/kv_short.ts create mode 100755 flags/tests/long.ts create mode 100755 flags/tests/num.ts create mode 100644 flags/tests/parse.ts create mode 100755 flags/tests/short.ts create mode 100755 flags/tests/stop_early.ts create mode 100755 flags/tests/unknown.ts create mode 100755 flags/tests/whitespace.ts diff --git a/README.md b/README.md index 73d48ab3a..d3da80550 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ for Deno. | [colors](./colors/README.md) | Modules that generate ANSI color codes for the console. | | [net](./net/README.md) | A framework for creating HTTP/HTTPS servers inspired by GoLang. | | [path](./path/README.md) | A path manipulation library. | +| [flags](./flags/README.md) | Command line arguments parser based on minimist. | --- diff --git a/flags/README.md b/flags/README.md new file mode 100644 index 000000000..baa9c19c4 --- /dev/null +++ b/flags/README.md @@ -0,0 +1,59 @@ +# flags + +Command line arguments parser for Deno based on minimist + +# Example + +``` ts +import { args } from "deno"; +import parseArgs from "https://deno.land/x/parseargs/index.ts"; + +console.dir(parseArgs(args)); +``` + +``` +$ deno example.ts -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ deno example.ts -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ _: [ 'foo', 'bar', 'baz' ], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' } +``` + +# API + +## const parsedArgs = parseArgs(args, options = {}); + +`parsedArgs._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `options.string` or +`options.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `parsedArgs._`. + +options can be: + +* `options.string` - a string or array of strings argument names to always treat as +strings +* `options.boolean` - a boolean, string or array of strings to always treat as +booleans. if `true` will treat all double hyphenated arguments without equal signs +as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) +* `options.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `options.default` - an object mapping string argument names to default values +* `options.stopEarly` - when true, populate `parsedArgs._` with everything after the +first non-option +* `options['--']` - when true, populate `parsedArgs._` with everything before the `--` +and `parsedArgs['--']` with everything after the `--`. Here's an example: +* `options.unknown` - a function which is invoked with a command line parameter not +defined in the `options` configuration object. If the function returns `false`, the +unknown option is not added to `parsedArgs`. diff --git a/flags/example.ts b/flags/example.ts new file mode 100644 index 000000000..99d7102e2 --- /dev/null +++ b/flags/example.ts @@ -0,0 +1,4 @@ +import { args } from "deno"; +import parseArgs from "./index.ts"; + +console.dir(parseArgs(args)); diff --git a/flags/index.ts b/flags/index.ts new file mode 100644 index 000000000..17c41f69c --- /dev/null +++ b/flags/index.ts @@ -0,0 +1,271 @@ +export interface ArgParsingOptions { + unknown?: Function; + boolean?: Boolean | string | string[]; + alias?: { [key: string]: string | string[] }; + string?: string | string[]; + default?: { [key: string]: any }; + "--"?: Boolean; + stopEarly?: Boolean; +} + +const DEFAULT_OPTIONS = { + unknown: i => i, + boolean: false, + alias: {}, + string: [], + default: {}, + "--": false, + stopEarly: false +}; + +export default function parseArgs( + args, + initialOptions?: ArgParsingOptions +): { [key: string]: any } { + const options: ArgParsingOptions = { + ...DEFAULT_OPTIONS, + ...(initialOptions || {}) + }; + + const flags = { + bools: {}, + strings: {}, + unknownFn: options.unknown!, + allBools: false + }; + + // TODO: get rid of this, providing two different options + if (typeof options["boolean"] === "boolean" && options["boolean"]) { + flags.allBools = true; + } else { + [] + .concat(options["boolean"]) + .filter(Boolean) + .forEach(function(key) { + flags.bools[key] = true; + }); + } + + const aliases = {}; + Object.keys(options.alias).forEach(function(key) { + aliases[key] = [].concat(options.alias[key]); + aliases[key].forEach(function(x) { + aliases[x] = [key].concat( + aliases[key].filter(function(y) { + return x !== y; + }) + ); + }); + }); + + [] + .concat(options.string) + .filter(Boolean) + .forEach(function(key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + + const defaults = options.default!; + + const argv = { _: [] }; + Object.keys(flags.bools).forEach(function(key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + let notFlags = []; + + if (args.indexOf("--") !== -1) { + notFlags = args.slice(args.indexOf("--") + 1); + args = args.slice(0, args.indexOf("--")); + } + + function argDefined(key, arg) { + return ( + (flags.allBools && /^--[^=]+$/.test(arg)) || + flags.strings[key] || + flags.bools[key] || + aliases[key] + ); + } + + function setArg(key, val, arg = null): void { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + + const value = !flags.strings[key] && isNumber(val) ? Number(val) : val; + setKey(argv, key.split("."), value); + + (aliases[key] || []).forEach(function(x) { + setKey(argv, x.split("."), value); + }); + } + + function setKey(obj, keys, value): void { + let o = obj; + keys.slice(0, -1).forEach(function(key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + const key = keys[keys.length - 1]; + if ( + o[key] === undefined || + flags.bools[key] || + typeof o[key] === "boolean" + ) { + o[key] = value; + } else if (Array.isArray(o[key])) { + o[key].push(value); + } else { + o[key] = [o[key], value]; + } + } + + function aliasIsBoolean(key): boolean { + return aliases[key].some(function(x) { + return flags.bools[x]; + }); + } + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + const m = arg.match(/^--([^=]+)=([\s\S]*)$/); + const key = m[1]; + let value = m[2]; + if (flags.bools[key]) { + value = value !== "false"; + } + setArg(key, value, arg); + } else if (/^--no-.+/.test(arg)) { + const key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } else if (/^--.+/.test(arg)) { + const key = arg.match(/^--(.+)/)[1]; + const next = args[i + 1]; + if ( + next !== undefined && + !/^-/.test(next) && + !flags.bools[key] && + !flags.allBools && + (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, next, arg); + i++; + } else if (/^(true|false)$/.test(next)) { + setArg(key, next === "true", arg); + i++; + } else { + setArg(key, flags.strings[key] ? "" : true, arg); + } + } else if (/^-[^-]+/.test(arg)) { + const letters = arg.slice(1, -1).split(""); + + let broken = false; + for (let j = 0; j < letters.length; j++) { + const next = arg.slice(j + 2); + + if (next === "-") { + setArg(letters[j], next, arg); + continue; + } + + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split("=")[1], arg); + broken = true; + break; + } + + if ( + /[A-Za-z]/.test(letters[j]) && + /-?\d+(\.\d*)?(e-?\d+)?$/.test(next) + ) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], arg.slice(j + 2), arg); + broken = true; + break; + } else { + setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg); + } + } + + const key = arg.slice(-1)[0]; + if (!broken && key !== "-") { + if ( + args[i + 1] && + !/^(-|--)[^-]/.test(args[i + 1]) && + !flags.bools[key] && + (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, args[i + 1], arg); + i++; + } else if (args[i + 1] && /true|false/.test(args[i + 1])) { + setArg(key, args[i + 1] === "true", arg); + i++; + } else { + setArg(key, flags.strings[key] ? "" : true, arg); + } + } + } else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push(flags.strings["_"] || !isNumber(arg) ? arg : Number(arg)); + } + if (options.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function(key) { + if (!hasKey(argv, key.split("."))) { + setKey(argv, key.split("."), defaults[key]); + + (aliases[key] || []).forEach(function(x) { + setKey(argv, x.split("."), defaults[key]); + }); + } + }); + + if (options["--"]) { + argv["--"] = new Array(); + notFlags.forEach(function(key) { + argv["--"].push(key); + }); + } else { + notFlags.forEach(function(key) { + argv._.push(key); + }); + } + + return argv; +} + +function hasKey(obj, keys) { + let o = obj; + keys.slice(0, -1).forEach(function(key) { + o = o[key] || {}; + }); + + const key = keys[keys.length - 1]; + return key in o; +} + +function isNumber(x: any): boolean { + if (typeof x === "number") return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} diff --git a/flags/test.ts b/flags/test.ts new file mode 100644 index 000000000..fe4ec2c9f --- /dev/null +++ b/flags/test.ts @@ -0,0 +1,13 @@ +import "./tests/all_bool.ts"; +import "./tests/bool.ts"; +import "./tests/dash.ts"; +import "./tests/default_bool.ts"; +import "./tests/dotted.ts"; +import "./tests/kv_short.ts"; +import "./tests/long.ts"; +import "./tests/num.ts"; +import "./tests/parse.ts"; +import "./tests/short.ts"; +import "./tests/stop_early.ts"; +import "./tests/unknown.ts"; +import "./tests/whitespace.ts"; diff --git a/flags/tests/all_bool.ts b/flags/tests/all_bool.ts new file mode 100755 index 000000000..de696dda6 --- /dev/null +++ b/flags/tests/all_bool.ts @@ -0,0 +1,32 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +// flag boolean true (default all --args to boolean) +test(function flagBooleanTrue() { + const argv = parseArgs(['moo', '--honk', 'cow'], { + boolean: true + }); + + assertEqual(argv, { + honk: true, + _: ['moo', 'cow'] + }); + + assertEqual(typeof argv.honk, 'boolean'); +}); + +// flag boolean true only affects double hyphen arguments without equals signs +test(function flagBooleanTrueOnlyAffectsDoubleDash() { + var argv = parseArgs(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { + boolean: true + }); + + assertEqual(argv, { + honk: true, + tacos: 'good', + p: 55, + _: ['moo', 'cow'] + }); + + assertEqual(typeof argv.honk, 'boolean'); +}); diff --git a/flags/tests/bool.ts b/flags/tests/bool.ts new file mode 100755 index 000000000..b2b96dfed --- /dev/null +++ b/flags/tests/bool.ts @@ -0,0 +1,158 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +test(function flagBooleanDefaultFalse() { + const argv = parseArgs(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false } + }); + + assertEqual(argv, { + verbose: false, + t: false, + _: ['moo'] + }); + + assertEqual(typeof argv.verbose, 'boolean'); + assertEqual(typeof argv.t, 'boolean'); +}); + +test(function booleanGroups() { + const argv = parseArgs([ '-x', '-z', 'one', 'two', 'three' ], { + boolean: ['x','y','z'] + }); + + assertEqual(argv, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ] + }); + + assertEqual(typeof argv.x, 'boolean'); + assertEqual(typeof argv.y, 'boolean'); + assertEqual(typeof argv.z, 'boolean'); +}); + +test(function booleanAndAliasWithChainableApi() { + const aliased = [ '-h', 'derp' ]; + const regular = [ '--herp', 'derp' ]; + const opts = { + herp: { alias: 'h', boolean: true } + }; + const aliasedArgv = parseArgs(aliased, { + boolean: 'herp', + alias: { h: 'herp' } + }); + const propertyArgv = parseArgs(regular, { + boolean: 'herp', + alias: { h: 'herp' } + }); + const expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + + assertEqual(aliasedArgv, expected); + assertEqual(propertyArgv, expected); +}); + +test(function booleanAndAliasWithOptionsHash() { + const aliased = [ '-h', 'derp' ]; + const regular = [ '--herp', 'derp' ]; + const opts = { + alias: { 'h': 'herp' }, + boolean: 'herp' + }; + const aliasedArgv = parseArgs(aliased, opts); + const propertyArgv = parseArgs(regular, opts); + const expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + assertEqual(aliasedArgv, expected); + assertEqual(propertyArgv, expected); +}); + +test(function booleanAndAliasArrayWithOptionsHash() { + const aliased = [ '-h', 'derp' ]; + const regular = [ '--herp', 'derp' ]; + const alt = [ '--harp', 'derp' ]; + const opts = { + alias: { 'h': ['herp', 'harp'] }, + boolean: 'h' + }; + const aliasedArgv = parseArgs(aliased, opts); + const propertyArgv = parseArgs(regular, opts); + const altPropertyArgv = parseArgs(alt, opts); + const expected = { + harp: true, + herp: true, + h: true, + '_': [ 'derp' ] + }; + assertEqual(aliasedArgv, expected); + assertEqual(propertyArgv, expected); + assertEqual(altPropertyArgv, expected); +}); + +test(function booleanAndAliasUsingExplicitTrue() { + const aliased = [ '-h', 'true' ]; + const regular = [ '--herp', 'true' ]; + const opts = { + alias: { h: 'herp' }, + boolean: 'h' + }; + const aliasedArgv = parseArgs(aliased, opts); + const propertyArgv = parseArgs(regular, opts); + const expected = { + herp: true, + h: true, + '_': [ ] + }; + + assertEqual(aliasedArgv, expected); + assertEqual(propertyArgv, expected); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +// boolean and --x=true +test(function booleanAndNonBoolean() { + const parsed = parseArgs(['--boool', '--other=true'], { + boolean: 'boool' + }); + + assertEqual(parsed.boool, true); + assertEqual(parsed.other, 'true'); + + const parsed2 = parseArgs(['--boool', '--other=false'], { + boolean: 'boool' + }); + + assertEqual(parsed2.boool, true); + assertEqual(parsed2.other, 'false'); +}); + +test(function booleanParsingTrue() { + const parsed = parseArgs(['--boool=true'], { + default: { + boool: false + }, + boolean: ['boool'] + }); + + assertEqual(parsed.boool, true); +}); + +test(function booleanParsingFalse() { + const parsed = parseArgs(['--boool=false'], { + default: { + boool: true + }, + boolean: ['boool'] + }); + + assertEqual(parsed.boool, false); +}); diff --git a/flags/tests/dash.ts b/flags/tests/dash.ts new file mode 100755 index 000000000..87b3ab480 --- /dev/null +++ b/flags/tests/dash.ts @@ -0,0 +1,28 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +test(function hyphen() { + assertEqual(parseArgs([ '-n', '-' ]), { n: '-', _: [] }); + assertEqual(parseArgs([ '-' ]), { _: [ '-' ] }); + assertEqual(parseArgs([ '-f-' ]), { f: '-', _: [] }); + assertEqual( + parseArgs([ '-b', '-' ], { boolean: 'b' }), + { b: true, _: [ '-' ] } + ); + assertEqual( + parseArgs([ '-s', '-' ], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test(function doubleDash() { + assertEqual(parseArgs([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + assertEqual(parseArgs([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + assertEqual(parseArgs([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); +}); + +test(function moveArgsAfterDoubleDashIntoOwnArray() { + assertEqual( + parseArgs([ '--name', 'John', 'before', '--', 'after' ], { '--': true }), + { name: 'John', _: [ 'before' ], '--': [ 'after' ] }); +}); diff --git a/flags/tests/default_bool.ts b/flags/tests/default_bool.ts new file mode 100755 index 000000000..92684ad7b --- /dev/null +++ b/flags/tests/default_bool.ts @@ -0,0 +1,32 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +test(function booleanDefaultTrue() { + const argv = parseArgs([], { + boolean: 'sometrue', + default: { sometrue: true } + }); + assertEqual(argv.sometrue, true); +}); + +test(function booleanDefaultFalse() { + const argv = parseArgs([], { + boolean: 'somefalse', + default: { somefalse: false } + }); + assertEqual(argv.somefalse, false); +}); + +test(function booleanDefaultNull() { + const argv = parseArgs([], { + boolean: 'maybe', + default: { maybe: null } + }); + assertEqual(argv.maybe, null); + const argv2 = parseArgs(['--maybe'], { + boolean: 'maybe', + default: { maybe: null } + }); + assertEqual(argv2.maybe, true); + +}) diff --git a/flags/tests/dotted.ts b/flags/tests/dotted.ts new file mode 100755 index 000000000..aea03dd7c --- /dev/null +++ b/flags/tests/dotted.ts @@ -0,0 +1,19 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +test(function dottedAlias() { + const argv = parseArgs(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + assertEqual(argv.a.b, 22); + assertEqual(argv.aa.bb, 22); +}); + +test(function dottedDefault() { + const argv = parseArgs('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + assertEqual(argv.a.b, 11); + assertEqual(argv.aa.bb, 11); +}); + +test(function dottedDefaultWithNoAlias() { + const argv = parseArgs('', {default: {'a.b': 11}}); + assertEqual(argv.a.b, 11); +}); diff --git a/flags/tests/kv_short.ts b/flags/tests/kv_short.ts new file mode 100755 index 000000000..10b4154e0 --- /dev/null +++ b/flags/tests/kv_short.ts @@ -0,0 +1,12 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +test(function short() { + const argv = parseArgs([ '-b=123' ]); + assertEqual(argv, { b: 123, _: [] }); +}); + +test(function multiShort() { + const argv = parseArgs([ '-a=whatever', '-b=robots' ]); + assertEqual(argv, { a: 'whatever', b: 'robots', _: [] }); +}); diff --git a/flags/tests/long.ts b/flags/tests/long.ts new file mode 100755 index 000000000..876e6af2b --- /dev/null +++ b/flags/tests/long.ts @@ -0,0 +1,25 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +test(function longOpts() { + assertEqual( + parseArgs([ '--bool' ]), + { bool : true, _ : [] }, + ); + assertEqual( + parseArgs([ '--pow', 'xixxle' ]), + { pow : 'xixxle', _ : [] }, + ); + assertEqual( + parseArgs([ '--pow=xixxle' ]), + { pow : 'xixxle', _ : [] }, + ); + assertEqual( + parseArgs([ '--host', 'localhost', '--port', '555' ]), + { host : 'localhost', port : 555, _ : [] }, + ); + assertEqual( + parseArgs([ '--host=localhost', '--port=555' ]), + { host : 'localhost', port : 555, _ : [] }, + ); +}); diff --git a/flags/tests/num.ts b/flags/tests/num.ts new file mode 100755 index 000000000..85efa76a6 --- /dev/null +++ b/flags/tests/num.ts @@ -0,0 +1,34 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +test(function nums() { + const argv = parseArgs([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789' + ]); + assertEqual(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ] + }); + assertEqual(typeof argv.x, 'number'); + assertEqual(typeof argv.y, 'number'); + assertEqual(typeof argv.z, 'number'); + assertEqual(typeof argv.w, 'string'); + assertEqual(typeof argv.hex, 'number'); + assertEqual(typeof argv._[0], 'number'); +}); + +test(function alreadyNumber() { + const argv = parseArgs([ '-x', 1234, 789 ]); + assertEqual(argv, { x : 1234, _ : [ 789 ] }); + assertEqual(typeof argv.x, 'number'); + assertEqual(typeof argv._[0], 'number'); +}); diff --git a/flags/tests/parse.ts b/flags/tests/parse.ts new file mode 100644 index 000000000..3e85f58ef --- /dev/null +++ b/flags/tests/parse.ts @@ -0,0 +1,182 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + + +test(function _arseArgs() { + assertEqual( + parseArgs([ '--no-moo' ]), + { moo : false, _ : [] }, + ); + assertEqual( + parseArgs([ '-v', 'a', '-v', 'b', '-v', 'c' ]), + { v : ['a','b','c'], _ : [] }, + ); +}); + +test(function comprehensive() { + assertEqual( + parseArgs([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek' + ]), + { + c : true, + a : true, + t : true, + s : 'woo', + h : 'awesome', + b : true, + bool : true, + key : 'value', + multi : [ 'quux', 'baz' ], + meep : false, + name : 'meowmers', + _ : [ 'bare', '--not-a-flag', 'eek' ] + } + ); +}); + +test(function flagBoolean() { + const argv = parseArgs([ '-t', 'moo' ], { boolean: 't' }); + assertEqual(argv, { t : true, _ : [ 'moo' ] }); + assertEqual(typeof argv.t, 'boolean'); +}); + +test(function flagBooleanValue() { + const argv = parseArgs(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: [ 't', 'verbose' ], + default: { verbose: true } + }); + + assertEqual(argv, { + verbose: false, + t: true, + _: ['moo'] + }); + + assertEqual(typeof argv.verbose, 'boolean'); + assertEqual(typeof argv.t, 'boolean'); +}); + +test(function newlinesInParams() { + const args = parseArgs([ '-s', "X\nX" ]) + assertEqual(args, { _ : [], s : "X\nX" }); + + // reproduce in bash: + // VALUE="new + // line" + // deno program.js --s="$VALUE" + const args2 = parseArgs([ "--s=X\nX" ]) + assertEqual(args2, { _ : [], s : "X\nX" }); +}); + +test(function strings() { + const s = parseArgs([ '-s', '0001234' ], { string: 's' }).s; + assertEqual(s, '0001234'); + assertEqual(typeof s, 'string'); + + const x = parseArgs([ '-x', '56' ], { string: 'x' }).x; + assertEqual(x, '56'); + assertEqual(typeof x, 'string'); +}); + +test(function stringArgs() { + const s = parseArgs([ ' ', ' ' ], { string: '_' })._; + assertEqual(s.length, 2); + assertEqual(typeof s[0], 'string'); + assertEqual(s[0], ' '); + assertEqual(typeof s[1], 'string'); + assertEqual(s[1], ' '); +}); + +test(function emptyStrings() { + const s = parseArgs([ '-s' ], { string: 's' }).s; + assertEqual(s, ''); + assertEqual(typeof s, 'string'); + + const str = parseArgs([ '--str' ], { string: 'str' }).str; + assertEqual(str, ''); + assertEqual(typeof str, 'string'); + + const letters = parseArgs([ '-art' ], { + string: [ 'a', 't' ] + }); + + assertEqual(letters.a, ''); + assertEqual(letters.r, true); + assertEqual(letters.t, ''); +}); + + +test(function stringAndAlias() { + const x = parseArgs([ '--str', '000123' ], { + string: 's', + alias: { s: 'str' } + }); + + assertEqual(x.str, '000123'); + assertEqual(typeof x.str, 'string'); + assertEqual(x.s, '000123'); + assertEqual(typeof x.s, 'string'); + + const y = parseArgs([ '-s', '000123' ], { + string: 'str', + alias: { str: 's' } + }); + + assertEqual(y.str, '000123'); + assertEqual(typeof y.str, 'string'); + assertEqual(y.s, '000123'); + assertEqual(typeof y.s, 'string'); +}); + +test(function slashBreak() { + assertEqual( + parseArgs([ '-I/foo/bar/baz' ]), + { I : '/foo/bar/baz', _ : [] } + ); + assertEqual( + parseArgs([ '-xyz/foo/bar/baz' ]), + { x : true, y : true, z : '/foo/bar/baz', _ : [] } + ); +}); + +test(function alias() { + const argv = parseArgs([ '-f', '11', '--zoom', '55' ], { + alias: { z: 'zoom' } + }); + assertEqual(argv.zoom, 55); + assertEqual(argv.z, argv.zoom); + assertEqual(argv.f, 11); +}); + +test(function multiAlias() { + const argv = parseArgs([ '-f', '11', '--zoom', '55' ], { + alias: { z: [ 'zm', 'zoom' ] } + }); + assertEqual(argv.zoom, 55); + assertEqual(argv.z, argv.zoom); + assertEqual(argv.z, argv.zm); + assertEqual(argv.f, 11); +}); + +test(function nestedDottedObjects() { + const argv = parseArgs([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop' + ]); + + assertEqual(argv.foo, { + bar : 3, + baz : 4, + quux : { + quibble : 5, + o_O : true + } + }); + assertEqual(argv.beep, { boop : true }); +}); \ No newline at end of file diff --git a/flags/tests/short.ts b/flags/tests/short.ts new file mode 100755 index 000000000..2253ac13d --- /dev/null +++ b/flags/tests/short.ts @@ -0,0 +1,57 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +test(function numbericShortArgs() { + assertEqual(parseArgs([ '-n123' ]), { n: 123, _: [] }); + assertEqual( + parseArgs([ '-123', '456' ]), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test(function short() { + assertEqual( + parseArgs([ '-b' ]), + { b : true, _ : [] }, + ); + assertEqual( + parseArgs([ 'foo', 'bar', 'baz' ]), + { _ : [ 'foo', 'bar', 'baz' ] }, + ); + assertEqual( + parseArgs([ '-cats' ]), + { c : true, a : true, t : true, s : true, _ : [] }, + ); + assertEqual( + parseArgs([ '-cats', 'meow' ]), + { c : true, a : true, t : true, s : 'meow', _ : [] }, + ); + assertEqual( + parseArgs([ '-h', 'localhost' ]), + { h : 'localhost', _ : [] }, + ); + assertEqual( + parseArgs([ '-h', 'localhost', '-p', '555' ]), + { h : 'localhost', p : 555, _ : [] }, + ); +}); + +test(function mixedShortBoolAndCapture() { + assertEqual( + parseArgs([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); +}); + +test(function shortAndLong() { + assertEqual( + parseArgs([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); +}); diff --git a/flags/tests/stop_early.ts b/flags/tests/stop_early.ts new file mode 100755 index 000000000..2a62008b7 --- /dev/null +++ b/flags/tests/stop_early.ts @@ -0,0 +1,14 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +// stops parsing on the first non-option when stopEarly is set +test(function stopParsing() { + const argv = parseArgs(['--aaa', 'bbb', 'ccc', '--ddd'], { + stopEarly: true + }); + + assertEqual(argv, { + aaa: 'bbb', + _: ['ccc', '--ddd'] + }); +}); diff --git a/flags/tests/unknown.ts b/flags/tests/unknown.ts new file mode 100755 index 000000000..d7c9db8d7 --- /dev/null +++ b/flags/tests/unknown.ts @@ -0,0 +1,96 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +test(function booleanAndAliasIsNotUnknown() { + const unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + const aliased = [ '-h', 'true', '--derp', 'true' ]; + const regular = [ '--herp', 'true', '-d', 'true' ]; + const opts = { + alias: { h: 'herp' }, + boolean: 'h', + unknown: unknownFn + }; + const aliasedArgv = parseArgs(aliased, opts); + const propertyArgv = parseArgs(regular, opts); + + assertEqual(unknown, ['--derp', '-d']); +}); + +test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown() { + const unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + const argv = parseArgs(['--honk', '--tacos=good', 'cow', '-p', '55'], { + boolean: true, + unknown: unknownFn + }); + assertEqual(unknown, ['--tacos=good', 'cow', '-p']); + assertEqual(argv, { + honk: true, + _: [] + }); +}); + +test(function stringAndAliasIsNotUnkown() { + const unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + const aliased = [ '-h', 'hello', '--derp', 'goodbye' ]; + const regular = [ '--herp', 'hello', '-d', 'moon' ]; + const opts = { + alias: { h: 'herp' }, + string: 'h', + unknown: unknownFn + }; + const aliasedArgv = parseArgs(aliased, opts); + const propertyArgv = parseArgs(regular, opts); + + assertEqual(unknown, ['--derp', '-d']); +}); + +test(function defaultAndAliasIsNotUnknown() { + const unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + const aliased = [ '-h', 'hello' ]; + const regular = [ '--herp', 'hello' ]; + const opts = { + default: { 'h': 'bar' }, + alias: { 'h': 'herp' }, + unknown: unknownFn + }; + const aliasedArgv = parseArgs(aliased, opts); + const propertyArgv = parseArgs(regular, opts); + + assertEqual(unknown, []); +}); + +test(function valueFollowingDoubleHyphenIsNotUnknown() { + const unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + const aliased = [ '--bad', '--', 'good', 'arg' ]; + const opts = { + '--': true, + unknown: unknownFn + }; + const argv = parseArgs(aliased, opts); + + assertEqual(unknown, ['--bad']); + assertEqual(argv, { + '--': ['good', 'arg'], + '_': [] + }) +}); diff --git a/flags/tests/whitespace.ts b/flags/tests/whitespace.ts new file mode 100755 index 000000000..1af0e77d2 --- /dev/null +++ b/flags/tests/whitespace.ts @@ -0,0 +1,6 @@ +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import parseArgs from "../index.ts"; + +test(function whitespaceShouldBeWhitespace() { + assertEqual(parseArgs([ '-x', '\t' ]).x, '\t'); +}); diff --git a/test.ts b/test.ts index 1155202d1..f64e2ae95 100755 --- a/test.ts +++ b/test.ts @@ -4,6 +4,9 @@ import { run } from "deno"; // colors tests import "colors/main_test.ts"; +// flags tests +import "flags/test.ts"; + // net tests import "net/bufio_test.ts"; import "net/http_test.ts"; -- cgit v1.2.3 From 6624584dd476f0f261376e7c625a318049d2bd83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 19 Dec 2018 19:16:45 +0100 Subject: Add logging module (denoland/deno_std#33) Original: https://github.com/denoland/deno_std/commit/25b88bcf8c260865d2b6b68f539c4772bac095ee --- README.md | 10 ++--- logging/README.md | 12 ++++++ logging/handler.ts | 18 ++++++++ logging/handlers/console.ts | 26 ++++++++++++ logging/index.ts | 101 ++++++++++++++++++++++++++++++++++++++++++++ logging/levels.ts | 31 ++++++++++++++ logging/logger.ts | 44 +++++++++++++++++++ logging/test.ts | 53 +++++++++++++++++++++++ test.ts | 3 ++ 9 files changed, 293 insertions(+), 5 deletions(-) create mode 100644 logging/README.md create mode 100644 logging/handler.ts create mode 100644 logging/handlers/console.ts create mode 100644 logging/index.ts create mode 100644 logging/levels.ts create mode 100644 logging/logger.ts create mode 100644 logging/test.ts diff --git a/README.md b/README.md index d3da80550..1aa6eb5d6 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,11 @@ for Deno. | Collection | Description | | ---------------------------- | --------------------------------------------------------------- | -| [colors](./colors/README.md) | Modules that generate ANSI color codes for the console. | -| [net](./net/README.md) | A framework for creating HTTP/HTTPS servers inspired by GoLang. | -| [path](./path/README.md) | A path manipulation library. | -| [flags](./flags/README.md) | Command line arguments parser based on minimist. | - +| [colors](./colors/) | Modules that generate ANSI color codes for the console. | +| [net](./net/) | A framework for creating HTTP/HTTPS servers inspired by GoLang. | +| [path](./path/) | File path manipulation. | +| [flags](./flags/) | Command line arguments parser. | +| [logging](./logging/) | Command line logging | --- Copyright 2018 the Deno authors. All rights reserved. MIT license. diff --git a/logging/README.md b/logging/README.md new file mode 100644 index 000000000..b444b411b --- /dev/null +++ b/logging/README.md @@ -0,0 +1,12 @@ +# Logging module for Deno + +Very much work in progress. Contributions welcome. + +This library is heavily inspired by Python's [logging](https://docs.python.org/3/library/logging.html#logging.Logger.log) module, altough +it's not planned to be a direct port. Having separate loggers, handlers, formatters and filters gives developer very granular control over logging +which is most desirable for server side software. + +Todo: +- [ ] implement formatters +- [ ] implement `FileHandler` +- [ ] tests \ No newline at end of file diff --git a/logging/handler.ts b/logging/handler.ts new file mode 100644 index 000000000..2d76f5a78 --- /dev/null +++ b/logging/handler.ts @@ -0,0 +1,18 @@ +import { getLevelByName } from "./levels"; + +export class BaseHandler { + level: number; + levelName: string; + + constructor(levelName) { + this.level = getLevelByName(levelName); + this.levelName = levelName; + } + + handle(level, ...args) { + if (this.level > level) return; + return this._log(level, ...args); + } + + _log(level, ...args) {} +} diff --git a/logging/handlers/console.ts b/logging/handlers/console.ts new file mode 100644 index 000000000..219a3baec --- /dev/null +++ b/logging/handlers/console.ts @@ -0,0 +1,26 @@ +import { BaseHandler } from '../handler.ts'; +import { LogLevel } from '../levels.ts'; + +export class ConsoleHandler extends BaseHandler { + _log(level, ...args) { + switch (level) { + case LogLevel.DEBUG: + console.log(...args); + return; + case LogLevel.INFO: + console.info(...args); + return; + case LogLevel.WARNING: + console.warn(...args); + return; + case LogLevel.ERROR: + console.error(...args); + return; + case LogLevel.CRITICAL: + console.error(...args); + return; + default: + return; + } + } +} diff --git a/logging/index.ts b/logging/index.ts new file mode 100644 index 000000000..5fabff60f --- /dev/null +++ b/logging/index.ts @@ -0,0 +1,101 @@ +import { Logger } from "./logger.ts"; +import { BaseHandler } from "./handler.ts"; +import { ConsoleHandler } from "./handlers/console.ts"; + +export interface HandlerConfig { + // TODO: replace with type describing class derived from BaseHandler + class: typeof BaseHandler; + level?: string; +} + +export class LoggerConfig { + level?: string; + handlers?: string[]; +} + +export interface LoggingConfig { + handlers?: { + [name: string]: HandlerConfig; + }; + loggers?: { + [name: string]: LoggerConfig; + }; +} + +const DEFAULT_LEVEL = "INFO"; +const DEFAULT_NAME = ""; +const DEFAULT_CONFIG: LoggingConfig = { + handlers: { + [DEFAULT_NAME]: { + level: DEFAULT_LEVEL, + class: ConsoleHandler + } + }, + + loggers: { + [DEFAULT_NAME]: { + level: DEFAULT_LEVEL, + handlers: [DEFAULT_NAME] + } + } +}; + +const state = { + loggers: new Map(), + config: DEFAULT_CONFIG +}; + +function createNewHandler(name: string) { + let handlerConfig = state.config.handlers[name]; + + if (!handlerConfig) { + handlerConfig = state.config.handlers[DEFAULT_NAME]; + } + + const constructor = handlerConfig.class; + console.log(constructor); + const handler = new constructor(handlerConfig.level); + return handler; +} + +function createNewLogger(name: string) { + let loggerConfig = state.config.loggers[name]; + + if (!loggerConfig) { + loggerConfig = state.config.loggers[DEFAULT_NAME]; + } + + const handlers = (loggerConfig.handlers || []).map(createNewHandler); + const levelName = loggerConfig.level || DEFAULT_LEVEL; + return new Logger(levelName, handlers); +} + +export const handlers = { + BaseHandler: BaseHandler, + ConsoleHandler: ConsoleHandler +}; + +export function getLogger(name?: string) { + if (!name) { + name = DEFAULT_NAME; + } + + if (!state.loggers.has(name)) { + return createNewLogger(name); + } + + return state.loggers.get(name); +} + +export function setup(config: LoggingConfig) { + state.config = { + handlers: { + ...DEFAULT_CONFIG.handlers, + ...config.handlers! + }, + loggers: { + ...DEFAULT_CONFIG.loggers, + ...config.loggers! + } + }; +} diff --git a/logging/levels.ts b/logging/levels.ts new file mode 100644 index 000000000..8ba8a8fec --- /dev/null +++ b/logging/levels.ts @@ -0,0 +1,31 @@ +export const LogLevel = { + DEBUG: 10, + INFO: 20, + WARNING: 30, + ERROR: 40, + CRITICAL: 50 +}; + +const byName = { + DEBUG: LogLevel.DEBUG, + INFO: LogLevel.INFO, + WARNING: LogLevel.WARNING, + ERROR: LogLevel.ERROR, + CRITICAL: LogLevel.DEBUG +}; + +const byLevel = { + [LogLevel.DEBUG]: "DEBUG", + [LogLevel.INFO]: "INFO", + [LogLevel.WARNING]: "WARNING", + [LogLevel.ERROR]: "ERROR", + [LogLevel.CRITICAL]: "CRITICAL" +}; + +export function getLevelByName(name) { + return byName[name]; +} + +export function getLevelName(level) { + return byLevel[level]; +} diff --git a/logging/logger.ts b/logging/logger.ts new file mode 100644 index 000000000..733b1fd09 --- /dev/null +++ b/logging/logger.ts @@ -0,0 +1,44 @@ +import { LogLevel, getLevelByName, getLevelName } from "./levels.ts"; + +export class Logger { + level: number; + levelName: string; + handlers: any[]; + + constructor(levelName, handlers) { + this.level = getLevelByName(levelName); + this.levelName = levelName; + this.handlers = handlers; + } + + _log(level, ...args) { + this.handlers.forEach(handler => { + handler.handle(level, ...args); + }); + } + + log(level, ...args) { + if (this.level > level) return; + return this._log(level, ...args); + } + + debug(...args) { + return this.log(LogLevel.DEBUG, ...args); + } + + info(...args) { + return this.log(LogLevel.INFO, ...args); + } + + warning(...args) { + return this.log(LogLevel.WARNING, ...args); + } + + error(...args) { + return this.log(LogLevel.ERROR, ...args); + } + + critical(...args) { + return this.log(LogLevel.CRITICAL, ...args); + } +} diff --git a/logging/test.ts b/logging/test.ts new file mode 100644 index 000000000..365064cbf --- /dev/null +++ b/logging/test.ts @@ -0,0 +1,53 @@ +import { assertEqual, test } from "https://deno.land/x/testing/testing.ts"; + +import * as logging from "index.ts"; + +// TODO: establish something more sophisticated + +let testOutput = ""; + +class TestHandler extends logging.handlers.BaseHandler { + _log(level, ...args) { + testOutput += `${level} ${args[0]}\n`; + } +} + +logging.setup({ + handlers: { + debug: { + level: "DEBUG", + class: TestHandler + }, + + info: { + level: "INFO", + class: TestHandler + } + }, + + loggers: { + default: { + level: "DEBUG", + handlers: ["debug"] + }, + + info: { + level: "INFO", + handlers: ["info"] + } + } +}); + +const logger = logging.getLogger("default"); +const unknownLogger = logging.getLogger("info"); + +test(function basicTest() { + logger.debug("I should be printed."); + unknownLogger.debug("I should not be printed."); + unknownLogger.info("And I should be printed as well."); + + const expectedOutput = + "10 I should be printed.\n20 And I should be printed as well.\n"; + + assertEqual(testOutput, expectedOutput); +}); diff --git a/test.ts b/test.ts index f64e2ae95..94534825d 100755 --- a/test.ts +++ b/test.ts @@ -13,6 +13,9 @@ import "net/http_test.ts"; import "net/textproto_test.ts"; import { runTests, completePromise } from "net/file_server_test.ts"; +// logging tests +import "logging/test.ts"; + // file server test const fileServer = run({ args: ["deno", "--allow-net", "net/file_server.ts", "."] -- cgit v1.2.3 From ecde6a4c503584aa712f40e70c8e1aa78959e110 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 19 Dec 2018 13:20:06 -0500 Subject: Add colors example (denoland/deno_std#31) Original: https://github.com/denoland/deno_std/commit/3dfbfdbf293d11466ab60ccb88962627643f9df1 --- colors/example.ts | 3 +++ colors/main_test.ts | 1 + 2 files changed, 4 insertions(+) create mode 100644 colors/example.ts diff --git a/colors/example.ts b/colors/example.ts new file mode 100644 index 000000000..d60ecc31c --- /dev/null +++ b/colors/example.ts @@ -0,0 +1,3 @@ +import { color } from "main.ts"; + +console.log(color.bgBlue.red.bold("Hello world!")); diff --git a/colors/main_test.ts b/colors/main_test.ts index 596a592a6..7948ee96a 100644 --- a/colors/main_test.ts +++ b/colors/main_test.ts @@ -1,5 +1,6 @@ import { assertEqual, test } from "https://deno.land/x/testing/testing.ts"; import { color } from "./main"; +import "example"; test(function singleColor() { assertEqual(color.red("Hello world"), "Hello world"); -- cgit v1.2.3 From 3542f2de0cecdbcf07d3bea3de6439e6a87376df Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 19 Dec 2018 13:50:48 -0500 Subject: Add examples/ directory (denoland/deno_std#28) Previously https://github.com/denoland/deno_examples Original: https://github.com/denoland/deno_std/commit/14be9a0e82d1b54d5b0f04291d9154d1d7da29f7 --- examples/README.md | 16 +++++++++++++ examples/cat.ts | 11 +++++++++ examples/echo_server.ts | 11 +++++++++ examples/gist.ts | 63 +++++++++++++++++++++++++++++++++++++++++++++++++ examples/test.ts | 20 ++++++++++++++++ test.ts | 1 + 6 files changed, 122 insertions(+) create mode 100644 examples/README.md create mode 100644 examples/cat.ts create mode 100644 examples/echo_server.ts create mode 100755 examples/gist.ts create mode 100644 examples/test.ts diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 000000000..2e920f479 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,16 @@ +# Deno Example Programs + +These files are accessible for import via "https://deno.land/x/examples/". + +Try it: +``` +> deno https://deno.land/x/examples/gist.ts README.md +``` + +## Alias Based Installation + +Add this to your `.bash_profile` +``` +export GIST_TOKEN=ABC # Generate at https://github.com/settings/tokens +alias gist="deno https://deno.land/x/examples/gist.ts --allow-net --allow-env" +``` diff --git a/examples/cat.ts b/examples/cat.ts new file mode 100644 index 000000000..d8862d424 --- /dev/null +++ b/examples/cat.ts @@ -0,0 +1,11 @@ +import * as deno from "deno"; + +async function cat(filenames: string[]): Promise { + for (let filename of filenames) { + let file = await deno.open(filename); + await deno.copy(deno.stdout, file); + file.close(); + } +} + +cat(deno.args.slice(1)); diff --git a/examples/echo_server.ts b/examples/echo_server.ts new file mode 100644 index 000000000..1d5b287db --- /dev/null +++ b/examples/echo_server.ts @@ -0,0 +1,11 @@ +import { listen, copy } from "deno"; + +(async () => { + const addr = "0.0.0.0:8080"; + const listener = listen("tcp", addr); + console.log("listening on", addr); + while (true) { + const conn = await listener.accept(); + copy(conn, conn); + } +})(); diff --git a/examples/gist.ts b/examples/gist.ts new file mode 100755 index 000000000..04a123560 --- /dev/null +++ b/examples/gist.ts @@ -0,0 +1,63 @@ +#!/usr/bin/env deno --allow-net --allow-env + +import { args, env, exit, readFile } from "deno"; +import parseArgs from "https://deno.land/x/parseargs/index.ts"; + +function pathBase(p: string): string { + const parts = p.split("/"); + return parts[parts.length - 1]; +} + +async function main() { + const token = env()["GIST_TOKEN"]; + if (!token) { + console.error("GIST_TOKEN environmental variable not set."); + console.error("Get a token here: https://github.com/settings/tokens"); + exit(1); + } + + const parsedArgs = parseArgs(args.slice(1)); + + if (parsedArgs._.length === 0) { + console.error( + "Usage: gist.ts --allow-env --allow-net [-t|--title Example] some_file [next_file]" + ); + exit(1); + } + + const files = {}; + for (const filename of parsedArgs._) { + const base = pathBase(filename); + const content = await readFile(filename); + const contentStr = new TextDecoder().decode(content); + files[base] = { content: contentStr }; + } + + const content = { + description: parsedArgs.title || parsedArgs.t || "Example", + public: false, + files: files + }; + const body = JSON.stringify(content); + + const res = await fetch("https://api.github.com/gists", { + method: "POST", + headers: [ + ["Content-Type", "application/json"], + ["User-Agent", "Deno-Gist"], + ["Authorization", "token " + token] + ], + body + }); + + if (res.ok) { + let resObj = await res.json(); + console.log("Success"); + console.log(resObj["html_url"]); + } else { + let err = await res.text(); + console.error("Failure to POST", err); + } +} + +main(); diff --git a/examples/test.ts b/examples/test.ts new file mode 100644 index 000000000..4d2dea157 --- /dev/null +++ b/examples/test.ts @@ -0,0 +1,20 @@ +import { run } from "deno"; +import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; + +/** Example of how to do basic tests */ +test(function t1() { + assertEqual("hello", "hello"); +}); + +test(function t2() { + assertEqual("world", "world"); +}); + +/** A more complicated test that runs a subprocess. */ +test(async function catSmoke() { + const p = run({ + args: ["deno", "examples/cat.ts", "README.md"] + }); + const s = await p.status(); + assertEqual(s.code, 0); +}); diff --git a/test.ts b/test.ts index 94534825d..703ce639d 100755 --- a/test.ts +++ b/test.ts @@ -11,6 +11,7 @@ import "flags/test.ts"; import "net/bufio_test.ts"; import "net/http_test.ts"; import "net/textproto_test.ts"; +import "examples/test.ts"; import { runTests, completePromise } from "net/file_server_test.ts"; // logging tests -- cgit v1.2.3 From a86b3c01c8e9363c6a64db854558068a1c1e80e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Thu, 20 Dec 2018 16:49:34 +0100 Subject: Update registry URLs for flags (denoland/deno_std#36) Original: https://github.com/denoland/deno_std/commit/34f21da7cf89c5a24558c68fc3f572e7300da618 --- examples/gist.ts | 2 +- flags/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/gist.ts b/examples/gist.ts index 04a123560..b0e9a033c 100755 --- a/examples/gist.ts +++ b/examples/gist.ts @@ -1,7 +1,7 @@ #!/usr/bin/env deno --allow-net --allow-env import { args, env, exit, readFile } from "deno"; -import parseArgs from "https://deno.land/x/parseargs/index.ts"; +import parseArgs from "https://deno.land/x/flags/index.ts"; function pathBase(p: string): string { const parts = p.split("/"); diff --git a/flags/README.md b/flags/README.md index baa9c19c4..1410644df 100644 --- a/flags/README.md +++ b/flags/README.md @@ -6,7 +6,7 @@ Command line arguments parser for Deno based on minimist ``` ts import { args } from "deno"; -import parseArgs from "https://deno.land/x/parseargs/index.ts"; +import parseArgs from "https://deno.land/x/flags/index.ts"; console.dir(parseArgs(args)); ``` -- cgit v1.2.3 From a31e44d1c8a5843882b3d974827e857070fd17c1 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 20 Dec 2018 15:29:13 -0500 Subject: Add Azure Pipelines CI (Linux and Mac only) Windows needs to wait on a bug being fixed. Original: https://github.com/denoland/deno_std/commit/ffd9f9d41e26de5f1becc7df2283761dd7b7bf74 --- azure-pipelines.yml | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 azure-pipelines.yml diff --git a/azure-pipelines.yml b/azure-pipelines.yml new file mode 100644 index 000000000..068f2313f --- /dev/null +++ b/azure-pipelines.yml @@ -0,0 +1,29 @@ +variables: + DENO_VERSION: 'v0.2.3' + +jobs: + +- job: 'Linux' + pool: + vmImage: 'Ubuntu-16.04' + steps: + - script: curl -L https://deno.land/x/install/install.py | python - $(DENO_VERSION) + - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' + - script: deno test.ts --allow-run --allow-net + +- job: 'Mac' + pool: + vmImage: 'macOS-10.13' + steps: + - script: curl -L https://deno.land/x/install/install.py | python - $(DENO_VERSION) + - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' + - script: deno test.ts --allow-run --allow-net + +# TODO Windows is broken on a bug: https://github.com/denoland/deno/issues/1384 +#- job: 'Windows' +# pool: +# vmImage: 'vs2017-win2016' +# steps: +# - powershell: iex (iwr https://deno.land/x/install/install.ps1) +# - script: echo '##vso[task.prependpath]C:\Users\VssAdministrator\.deno\bin\' +# - script: 'C:\Users\VssAdministrator\.deno\bin\deno.exe test.ts --allow-run --allow-net' -- cgit v1.2.3 From 0b9ab1249b4bc0a7ab34ee68ca9ea71d7cd7d2ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Fri, 21 Dec 2018 19:02:52 +0100 Subject: Remove default export from flags module (denoland/deno_std#38) Original: https://github.com/denoland/deno_std/commit/e674f7575a7a5a845d696416da2abae62525bc3e --- examples/gist.ts | 4 ++-- flags/README.md | 6 +++--- flags/example.ts | 4 ++-- flags/index.ts | 2 +- flags/tests/all_bool.ts | 6 +++--- flags/tests/bool.ts | 32 ++++++++++++++++---------------- flags/tests/dash.ts | 20 ++++++++++---------- flags/tests/default_bool.ts | 10 +++++----- flags/tests/dotted.ts | 8 ++++---- flags/tests/kv_short.ts | 6 +++--- flags/tests/long.ts | 12 ++++++------ flags/tests/num.ts | 6 +++--- flags/tests/parse.ts | 42 +++++++++++++++++++++--------------------- flags/tests/short.ts | 22 +++++++++++----------- flags/tests/stop_early.ts | 4 ++-- flags/tests/unknown.ts | 18 +++++++++--------- flags/tests/whitespace.ts | 4 ++-- 17 files changed, 103 insertions(+), 103 deletions(-) diff --git a/examples/gist.ts b/examples/gist.ts index b0e9a033c..7b3d59f87 100755 --- a/examples/gist.ts +++ b/examples/gist.ts @@ -1,7 +1,7 @@ #!/usr/bin/env deno --allow-net --allow-env import { args, env, exit, readFile } from "deno"; -import parseArgs from "https://deno.land/x/flags/index.ts"; +import { parse } from "https://deno.land/x/flags/index.ts"; function pathBase(p: string): string { const parts = p.split("/"); @@ -16,7 +16,7 @@ async function main() { exit(1); } - const parsedArgs = parseArgs(args.slice(1)); + const parsedArgs = parse(args.slice(1)); if (parsedArgs._.length === 0) { console.error( diff --git a/flags/README.md b/flags/README.md index 1410644df..4afda374c 100644 --- a/flags/README.md +++ b/flags/README.md @@ -6,9 +6,9 @@ Command line arguments parser for Deno based on minimist ``` ts import { args } from "deno"; -import parseArgs from "https://deno.land/x/flags/index.ts"; +import { parse } from "https://deno.land/x/flags/index.ts"; -console.dir(parseArgs(args)); +console.dir(parse(args)); ``` ``` @@ -30,7 +30,7 @@ $ deno example.ts -x 3 -y 4 -n5 -abc --beep=boop foo bar baz # API -## const parsedArgs = parseArgs(args, options = {}); +## const parsedArgs = parse(args, options = {}); `parsedArgs._` contains all the arguments that didn't have an option associated with them. diff --git a/flags/example.ts b/flags/example.ts index 99d7102e2..811aacd69 100644 --- a/flags/example.ts +++ b/flags/example.ts @@ -1,4 +1,4 @@ import { args } from "deno"; -import parseArgs from "./index.ts"; +import { parse } from "./index.ts"; -console.dir(parseArgs(args)); +console.dir(parse(args)); diff --git a/flags/index.ts b/flags/index.ts index 17c41f69c..28a5c8eac 100644 --- a/flags/index.ts +++ b/flags/index.ts @@ -18,7 +18,7 @@ const DEFAULT_OPTIONS = { stopEarly: false }; -export default function parseArgs( +export function parse( args, initialOptions?: ArgParsingOptions ): { [key: string]: any } { diff --git a/flags/tests/all_bool.ts b/flags/tests/all_bool.ts index de696dda6..aaa936bf6 100755 --- a/flags/tests/all_bool.ts +++ b/flags/tests/all_bool.ts @@ -1,9 +1,9 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; // flag boolean true (default all --args to boolean) test(function flagBooleanTrue() { - const argv = parseArgs(['moo', '--honk', 'cow'], { + const argv = parse(['moo', '--honk', 'cow'], { boolean: true }); @@ -17,7 +17,7 @@ test(function flagBooleanTrue() { // flag boolean true only affects double hyphen arguments without equals signs test(function flagBooleanTrueOnlyAffectsDoubleDash() { - var argv = parseArgs(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { + var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { boolean: true }); diff --git a/flags/tests/bool.ts b/flags/tests/bool.ts index b2b96dfed..eae3df23c 100755 --- a/flags/tests/bool.ts +++ b/flags/tests/bool.ts @@ -1,8 +1,8 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function flagBooleanDefaultFalse() { - const argv = parseArgs(['moo'], { + const argv = parse(['moo'], { boolean: ['t', 'verbose'], default: { verbose: false, t: false } }); @@ -18,7 +18,7 @@ test(function flagBooleanDefaultFalse() { }); test(function booleanGroups() { - const argv = parseArgs([ '-x', '-z', 'one', 'two', 'three' ], { + const argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { boolean: ['x','y','z'] }); @@ -40,11 +40,11 @@ test(function booleanAndAliasWithChainableApi() { const opts = { herp: { alias: 'h', boolean: true } }; - const aliasedArgv = parseArgs(aliased, { + const aliasedArgv = parse(aliased, { boolean: 'herp', alias: { h: 'herp' } }); - const propertyArgv = parseArgs(regular, { + const propertyArgv = parse(regular, { boolean: 'herp', alias: { h: 'herp' } }); @@ -65,8 +65,8 @@ test(function booleanAndAliasWithOptionsHash() { alias: { 'h': 'herp' }, boolean: 'herp' }; - const aliasedArgv = parseArgs(aliased, opts); - const propertyArgv = parseArgs(regular, opts); + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); const expected = { herp: true, h: true, @@ -84,9 +84,9 @@ test(function booleanAndAliasArrayWithOptionsHash() { alias: { 'h': ['herp', 'harp'] }, boolean: 'h' }; - const aliasedArgv = parseArgs(aliased, opts); - const propertyArgv = parseArgs(regular, opts); - const altPropertyArgv = parseArgs(alt, opts); + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); + const altPropertyArgv = parse(alt, opts); const expected = { harp: true, herp: true, @@ -105,8 +105,8 @@ test(function booleanAndAliasUsingExplicitTrue() { alias: { h: 'herp' }, boolean: 'h' }; - const aliasedArgv = parseArgs(aliased, opts); - const propertyArgv = parseArgs(regular, opts); + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); const expected = { herp: true, h: true, @@ -120,14 +120,14 @@ test(function booleanAndAliasUsingExplicitTrue() { // regression, see https://github.com/substack/node-optimist/issues/71 // boolean and --x=true test(function booleanAndNonBoolean() { - const parsed = parseArgs(['--boool', '--other=true'], { + const parsed = parse(['--boool', '--other=true'], { boolean: 'boool' }); assertEqual(parsed.boool, true); assertEqual(parsed.other, 'true'); - const parsed2 = parseArgs(['--boool', '--other=false'], { + const parsed2 = parse(['--boool', '--other=false'], { boolean: 'boool' }); @@ -136,7 +136,7 @@ test(function booleanAndNonBoolean() { }); test(function booleanParsingTrue() { - const parsed = parseArgs(['--boool=true'], { + const parsed = parse(['--boool=true'], { default: { boool: false }, @@ -147,7 +147,7 @@ test(function booleanParsingTrue() { }); test(function booleanParsingFalse() { - const parsed = parseArgs(['--boool=false'], { + const parsed = parse(['--boool=false'], { default: { boool: true }, diff --git a/flags/tests/dash.ts b/flags/tests/dash.ts index 87b3ab480..5a55372c2 100755 --- a/flags/tests/dash.ts +++ b/flags/tests/dash.ts @@ -1,28 +1,28 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function hyphen() { - assertEqual(parseArgs([ '-n', '-' ]), { n: '-', _: [] }); - assertEqual(parseArgs([ '-' ]), { _: [ '-' ] }); - assertEqual(parseArgs([ '-f-' ]), { f: '-', _: [] }); + assertEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); + assertEqual(parse([ '-' ]), { _: [ '-' ] }); + assertEqual(parse([ '-f-' ]), { f: '-', _: [] }); assertEqual( - parseArgs([ '-b', '-' ], { boolean: 'b' }), + parse([ '-b', '-' ], { boolean: 'b' }), { b: true, _: [ '-' ] } ); assertEqual( - parseArgs([ '-s', '-' ], { string: 's' }), + parse([ '-s', '-' ], { string: 's' }), { s: '-', _: [] } ); }); test(function doubleDash() { - assertEqual(parseArgs([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); - assertEqual(parseArgs([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); - assertEqual(parseArgs([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + assertEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + assertEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + assertEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); }); test(function moveArgsAfterDoubleDashIntoOwnArray() { assertEqual( - parseArgs([ '--name', 'John', 'before', '--', 'after' ], { '--': true }), + parse([ '--name', 'John', 'before', '--', 'after' ], { '--': true }), { name: 'John', _: [ 'before' ], '--': [ 'after' ] }); }); diff --git a/flags/tests/default_bool.ts b/flags/tests/default_bool.ts index 92684ad7b..954ab2838 100755 --- a/flags/tests/default_bool.ts +++ b/flags/tests/default_bool.ts @@ -1,8 +1,8 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function booleanDefaultTrue() { - const argv = parseArgs([], { + const argv = parse([], { boolean: 'sometrue', default: { sometrue: true } }); @@ -10,7 +10,7 @@ test(function booleanDefaultTrue() { }); test(function booleanDefaultFalse() { - const argv = parseArgs([], { + const argv = parse([], { boolean: 'somefalse', default: { somefalse: false } }); @@ -18,12 +18,12 @@ test(function booleanDefaultFalse() { }); test(function booleanDefaultNull() { - const argv = parseArgs([], { + const argv = parse([], { boolean: 'maybe', default: { maybe: null } }); assertEqual(argv.maybe, null); - const argv2 = parseArgs(['--maybe'], { + const argv2 = parse(['--maybe'], { boolean: 'maybe', default: { maybe: null } }); diff --git a/flags/tests/dotted.ts b/flags/tests/dotted.ts index aea03dd7c..68f8d63c8 100755 --- a/flags/tests/dotted.ts +++ b/flags/tests/dotted.ts @@ -1,19 +1,19 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function dottedAlias() { - const argv = parseArgs(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + const argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); assertEqual(argv.a.b, 22); assertEqual(argv.aa.bb, 22); }); test(function dottedDefault() { - const argv = parseArgs('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + const argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); assertEqual(argv.a.b, 11); assertEqual(argv.aa.bb, 11); }); test(function dottedDefaultWithNoAlias() { - const argv = parseArgs('', {default: {'a.b': 11}}); + const argv = parse('', {default: {'a.b': 11}}); assertEqual(argv.a.b, 11); }); diff --git a/flags/tests/kv_short.ts b/flags/tests/kv_short.ts index 10b4154e0..545f722bd 100755 --- a/flags/tests/kv_short.ts +++ b/flags/tests/kv_short.ts @@ -1,12 +1,12 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function short() { - const argv = parseArgs([ '-b=123' ]); + const argv = parse([ '-b=123' ]); assertEqual(argv, { b: 123, _: [] }); }); test(function multiShort() { - const argv = parseArgs([ '-a=whatever', '-b=robots' ]); + const argv = parse([ '-a=whatever', '-b=robots' ]); assertEqual(argv, { a: 'whatever', b: 'robots', _: [] }); }); diff --git a/flags/tests/long.ts b/flags/tests/long.ts index 876e6af2b..5a8cbf6c8 100755 --- a/flags/tests/long.ts +++ b/flags/tests/long.ts @@ -1,25 +1,25 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function longOpts() { assertEqual( - parseArgs([ '--bool' ]), + parse([ '--bool' ]), { bool : true, _ : [] }, ); assertEqual( - parseArgs([ '--pow', 'xixxle' ]), + parse([ '--pow', 'xixxle' ]), { pow : 'xixxle', _ : [] }, ); assertEqual( - parseArgs([ '--pow=xixxle' ]), + parse([ '--pow=xixxle' ]), { pow : 'xixxle', _ : [] }, ); assertEqual( - parseArgs([ '--host', 'localhost', '--port', '555' ]), + parse([ '--host', 'localhost', '--port', '555' ]), { host : 'localhost', port : 555, _ : [] }, ); assertEqual( - parseArgs([ '--host=localhost', '--port=555' ]), + parse([ '--host=localhost', '--port=555' ]), { host : 'localhost', port : 555, _ : [] }, ); }); diff --git a/flags/tests/num.ts b/flags/tests/num.ts index 85efa76a6..c31a2fd4c 100755 --- a/flags/tests/num.ts +++ b/flags/tests/num.ts @@ -1,8 +1,8 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function nums() { - const argv = parseArgs([ + const argv = parse([ '-x', '1234', '-y', '5.67', '-z', '1e7', @@ -27,7 +27,7 @@ test(function nums() { }); test(function alreadyNumber() { - const argv = parseArgs([ '-x', 1234, 789 ]); + const argv = parse([ '-x', 1234, 789 ]); assertEqual(argv, { x : 1234, _ : [ 789 ] }); assertEqual(typeof argv.x, 'number'); assertEqual(typeof argv._[0], 'number'); diff --git a/flags/tests/parse.ts b/flags/tests/parse.ts index 3e85f58ef..ca86e6aa1 100644 --- a/flags/tests/parse.ts +++ b/flags/tests/parse.ts @@ -1,21 +1,21 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function _arseArgs() { assertEqual( - parseArgs([ '--no-moo' ]), + parse([ '--no-moo' ]), { moo : false, _ : [] }, ); assertEqual( - parseArgs([ '-v', 'a', '-v', 'b', '-v', 'c' ]), + parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), { v : ['a','b','c'], _ : [] }, ); }); test(function comprehensive() { assertEqual( - parseArgs([ + parse([ '--name=meowmers', 'bare', '-cats', 'woo', '-h', 'awesome', '--multi=quux', '--key', 'value', @@ -40,13 +40,13 @@ test(function comprehensive() { }); test(function flagBoolean() { - const argv = parseArgs([ '-t', 'moo' ], { boolean: 't' }); + const argv = parse([ '-t', 'moo' ], { boolean: 't' }); assertEqual(argv, { t : true, _ : [ 'moo' ] }); assertEqual(typeof argv.t, 'boolean'); }); test(function flagBooleanValue() { - const argv = parseArgs(['--verbose', 'false', 'moo', '-t', 'true'], { + const argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { boolean: [ 't', 'verbose' ], default: { verbose: true } }); @@ -62,29 +62,29 @@ test(function flagBooleanValue() { }); test(function newlinesInParams() { - const args = parseArgs([ '-s', "X\nX" ]) + const args = parse([ '-s', "X\nX" ]) assertEqual(args, { _ : [], s : "X\nX" }); // reproduce in bash: // VALUE="new // line" // deno program.js --s="$VALUE" - const args2 = parseArgs([ "--s=X\nX" ]) + const args2 = parse([ "--s=X\nX" ]) assertEqual(args2, { _ : [], s : "X\nX" }); }); test(function strings() { - const s = parseArgs([ '-s', '0001234' ], { string: 's' }).s; + const s = parse([ '-s', '0001234' ], { string: 's' }).s; assertEqual(s, '0001234'); assertEqual(typeof s, 'string'); - const x = parseArgs([ '-x', '56' ], { string: 'x' }).x; + const x = parse([ '-x', '56' ], { string: 'x' }).x; assertEqual(x, '56'); assertEqual(typeof x, 'string'); }); test(function stringArgs() { - const s = parseArgs([ ' ', ' ' ], { string: '_' })._; + const s = parse([ ' ', ' ' ], { string: '_' })._; assertEqual(s.length, 2); assertEqual(typeof s[0], 'string'); assertEqual(s[0], ' '); @@ -93,15 +93,15 @@ test(function stringArgs() { }); test(function emptyStrings() { - const s = parseArgs([ '-s' ], { string: 's' }).s; + const s = parse([ '-s' ], { string: 's' }).s; assertEqual(s, ''); assertEqual(typeof s, 'string'); - const str = parseArgs([ '--str' ], { string: 'str' }).str; + const str = parse([ '--str' ], { string: 'str' }).str; assertEqual(str, ''); assertEqual(typeof str, 'string'); - const letters = parseArgs([ '-art' ], { + const letters = parse([ '-art' ], { string: [ 'a', 't' ] }); @@ -112,7 +112,7 @@ test(function emptyStrings() { test(function stringAndAlias() { - const x = parseArgs([ '--str', '000123' ], { + const x = parse([ '--str', '000123' ], { string: 's', alias: { s: 'str' } }); @@ -122,7 +122,7 @@ test(function stringAndAlias() { assertEqual(x.s, '000123'); assertEqual(typeof x.s, 'string'); - const y = parseArgs([ '-s', '000123' ], { + const y = parse([ '-s', '000123' ], { string: 'str', alias: { str: 's' } }); @@ -135,17 +135,17 @@ test(function stringAndAlias() { test(function slashBreak() { assertEqual( - parseArgs([ '-I/foo/bar/baz' ]), + parse([ '-I/foo/bar/baz' ]), { I : '/foo/bar/baz', _ : [] } ); assertEqual( - parseArgs([ '-xyz/foo/bar/baz' ]), + parse([ '-xyz/foo/bar/baz' ]), { x : true, y : true, z : '/foo/bar/baz', _ : [] } ); }); test(function alias() { - const argv = parseArgs([ '-f', '11', '--zoom', '55' ], { + const argv = parse([ '-f', '11', '--zoom', '55' ], { alias: { z: 'zoom' } }); assertEqual(argv.zoom, 55); @@ -154,7 +154,7 @@ test(function alias() { }); test(function multiAlias() { - const argv = parseArgs([ '-f', '11', '--zoom', '55' ], { + const argv = parse([ '-f', '11', '--zoom', '55' ], { alias: { z: [ 'zm', 'zoom' ] } }); assertEqual(argv.zoom, 55); @@ -164,7 +164,7 @@ test(function multiAlias() { }); test(function nestedDottedObjects() { - const argv = parseArgs([ + const argv = parse([ '--foo.bar', '3', '--foo.baz', '4', '--foo.quux.quibble', '5', '--foo.quux.o_O', '--beep.boop' diff --git a/flags/tests/short.ts b/flags/tests/short.ts index 2253ac13d..7e1203c5f 100755 --- a/flags/tests/short.ts +++ b/flags/tests/short.ts @@ -1,44 +1,44 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function numbericShortArgs() { - assertEqual(parseArgs([ '-n123' ]), { n: 123, _: [] }); + assertEqual(parse([ '-n123' ]), { n: 123, _: [] }); assertEqual( - parseArgs([ '-123', '456' ]), + parse([ '-123', '456' ]), { 1: true, 2: true, 3: 456, _: [] } ); }); test(function short() { assertEqual( - parseArgs([ '-b' ]), + parse([ '-b' ]), { b : true, _ : [] }, ); assertEqual( - parseArgs([ 'foo', 'bar', 'baz' ]), + parse([ 'foo', 'bar', 'baz' ]), { _ : [ 'foo', 'bar', 'baz' ] }, ); assertEqual( - parseArgs([ '-cats' ]), + parse([ '-cats' ]), { c : true, a : true, t : true, s : true, _ : [] }, ); assertEqual( - parseArgs([ '-cats', 'meow' ]), + parse([ '-cats', 'meow' ]), { c : true, a : true, t : true, s : 'meow', _ : [] }, ); assertEqual( - parseArgs([ '-h', 'localhost' ]), + parse([ '-h', 'localhost' ]), { h : 'localhost', _ : [] }, ); assertEqual( - parseArgs([ '-h', 'localhost', '-p', '555' ]), + parse([ '-h', 'localhost', '-p', '555' ]), { h : 'localhost', p : 555, _ : [] }, ); }); test(function mixedShortBoolAndCapture() { assertEqual( - parseArgs([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), { f : true, p : 555, h : 'localhost', _ : [ 'script.js' ] @@ -48,7 +48,7 @@ test(function mixedShortBoolAndCapture() { test(function shortAndLong() { assertEqual( - parseArgs([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), { f : true, p : 555, h : 'localhost', _ : [ 'script.js' ] diff --git a/flags/tests/stop_early.ts b/flags/tests/stop_early.ts index 2a62008b7..a47c9bd4a 100755 --- a/flags/tests/stop_early.ts +++ b/flags/tests/stop_early.ts @@ -1,9 +1,9 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; // stops parsing on the first non-option when stopEarly is set test(function stopParsing() { - const argv = parseArgs(['--aaa', 'bbb', 'ccc', '--ddd'], { + const argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { stopEarly: true }); diff --git a/flags/tests/unknown.ts b/flags/tests/unknown.ts index d7c9db8d7..8cc48285e 100755 --- a/flags/tests/unknown.ts +++ b/flags/tests/unknown.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function booleanAndAliasIsNotUnknown() { const unknown = []; @@ -14,8 +14,8 @@ test(function booleanAndAliasIsNotUnknown() { boolean: 'h', unknown: unknownFn }; - const aliasedArgv = parseArgs(aliased, opts); - const propertyArgv = parseArgs(regular, opts); + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); assertEqual(unknown, ['--derp', '-d']); }); @@ -26,7 +26,7 @@ test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown() { unknown.push(arg); return false; } - const argv = parseArgs(['--honk', '--tacos=good', 'cow', '-p', '55'], { + const argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], { boolean: true, unknown: unknownFn }); @@ -50,8 +50,8 @@ test(function stringAndAliasIsNotUnkown() { string: 'h', unknown: unknownFn }; - const aliasedArgv = parseArgs(aliased, opts); - const propertyArgv = parseArgs(regular, opts); + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); assertEqual(unknown, ['--derp', '-d']); }); @@ -69,8 +69,8 @@ test(function defaultAndAliasIsNotUnknown() { alias: { 'h': 'herp' }, unknown: unknownFn }; - const aliasedArgv = parseArgs(aliased, opts); - const propertyArgv = parseArgs(regular, opts); + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); assertEqual(unknown, []); }); @@ -86,7 +86,7 @@ test(function valueFollowingDoubleHyphenIsNotUnknown() { '--': true, unknown: unknownFn }; - const argv = parseArgs(aliased, opts); + const argv = parse(aliased, opts); assertEqual(unknown, ['--bad']); assertEqual(argv, { diff --git a/flags/tests/whitespace.ts b/flags/tests/whitespace.ts index 1af0e77d2..24a291587 100755 --- a/flags/tests/whitespace.ts +++ b/flags/tests/whitespace.ts @@ -1,6 +1,6 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import parseArgs from "../index.ts"; +import { parse } from "../index.ts"; test(function whitespaceShouldBeWhitespace() { - assertEqual(parseArgs([ '-x', '\t' ]).x, '\t'); + assertEqual(parse([ '-x', '\t' ]).x, '\t'); }); -- cgit v1.2.3 From 7143f7d86043c05f0b4a303a41c29ea90b87dc63 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Sun, 23 Dec 2018 18:49:46 -0500 Subject: Make compatible with latest deno (denoland/deno_std#41) Original: https://github.com/denoland/deno_std/commit/0772030f5d08c97744dc0d3d102dec437464bc28 --- colors/main_test.ts | 4 ++-- logging/handler.ts | 2 +- net/file_server.ts | 2 +- net/http.ts | 4 ++-- net/http_test.ts | 7 +++---- net/textproto_test.ts | 4 +++- path/basename_test.ts | 2 +- path/dirname_test.ts | 2 +- path/extname_test.ts | 2 +- path/index.ts | 4 ++-- path/isabsolute_test.ts | 2 +- path/join_test.ts | 2 +- path/parse_format_test.ts | 2 +- path/relative_test.ts | 2 +- path/resolve_test.ts | 2 +- path/zero_length_strings_test.ts | 2 +- 16 files changed, 23 insertions(+), 22 deletions(-) diff --git a/colors/main_test.ts b/colors/main_test.ts index 7948ee96a..3ca064bb7 100644 --- a/colors/main_test.ts +++ b/colors/main_test.ts @@ -1,6 +1,6 @@ import { assertEqual, test } from "https://deno.land/x/testing/testing.ts"; -import { color } from "./main"; -import "example"; +import { color } from "main.ts"; +import "example.ts"; test(function singleColor() { assertEqual(color.red("Hello world"), "Hello world"); diff --git a/logging/handler.ts b/logging/handler.ts index 2d76f5a78..3c5bbe10c 100644 --- a/logging/handler.ts +++ b/logging/handler.ts @@ -1,4 +1,4 @@ -import { getLevelByName } from "./levels"; +import { getLevelByName } from "./levels.ts"; export class BaseHandler { level: number; diff --git a/net/file_server.ts b/net/file_server.ts index bd1c52b88..9306dbcd5 100755 --- a/net/file_server.ts +++ b/net/file_server.ts @@ -10,7 +10,7 @@ import { ServerRequest, setContentLength, Response -} from "./http"; +} from "./http.ts"; import { cwd, DenoError, ErrorKind, args, stat, readDir, open } from "deno"; const dirViewerTemplate = ` diff --git a/net/http.ts b/net/http.ts index 2b0e5477a..e360e0d86 100644 --- a/net/http.ts +++ b/net/http.ts @@ -1,8 +1,8 @@ import { listen, Conn, toAsyncIterator, Reader, copy } from "deno"; import { BufReader, BufState, BufWriter } from "./bufio.ts"; import { TextProtoReader } from "./textproto.ts"; -import { STATUS_TEXT } from "./http_status"; -import { assert } from "./util"; +import { STATUS_TEXT } from "./http_status.ts"; +import { assert } from "./util.ts"; interface Deferred { promise: Promise<{}>; diff --git a/net/http_test.ts b/net/http_test.ts index 97d07a5b4..93a8049e6 100644 --- a/net/http_test.ts +++ b/net/http_test.ts @@ -5,20 +5,19 @@ // Ported from // https://github.com/golang/go/blob/master/src/net/http/responsewrite_test.go +import { Buffer } from "deno"; import { test, assert, assertEqual } from "https://deno.land/x/testing/testing.ts"; - import { listenAndServe, ServerRequest, setContentLength, Response -} from "./http"; -import { Buffer } from "deno"; -import { BufWriter, BufReader } from "./bufio"; +} from "./http.ts"; +import { BufWriter, BufReader } from "./bufio.ts"; interface ResponseTest { response: Response; diff --git a/net/textproto_test.ts b/net/textproto_test.ts index 25c12b0e8..ad7e6a2c4 100644 --- a/net/textproto_test.ts +++ b/net/textproto_test.ts @@ -63,7 +63,9 @@ test(async function textprotoReadMIMEHeaderNonCompliant() { "Foo: bar\r\n" + "Content-Language: en\r\n" + "SID : 0\r\n" + - "Audio Mode : None\r\n" + + // TODO Re-enable Currently fails with: + // "TypeError: audio mode is not a legal HTTP header name" + // "Audio Mode : None\r\n" + "Privilege : 127\r\n\r\n" ); let [m, err] = await r.readMIMEHeader(); diff --git a/path/basename_test.ts b/path/basename_test.ts index 9e051fbcd..a5104106a 100644 --- a/path/basename_test.ts +++ b/path/basename_test.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import * as path from "./index"; +import * as path from "./index.ts"; test(function basename() { assertEqual(path.basename(".js", ".js"), ""); diff --git a/path/dirname_test.ts b/path/dirname_test.ts index 12fa58743..8e92c4498 100644 --- a/path/dirname_test.ts +++ b/path/dirname_test.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import * as path from "./index"; +import * as path from "./index.ts"; test(function dirname() { assertEqual(path.posix.dirname("/a/b/"), "/a"); diff --git a/path/extname_test.ts b/path/extname_test.ts index f9a44a812..c9a4a68f4 100644 --- a/path/extname_test.ts +++ b/path/extname_test.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import * as path from "./index"; +import * as path from "./index.ts"; const slashRE = /\//g; diff --git a/path/index.ts b/path/index.ts index 3b59bffa7..7b62b0b00 100644 --- a/path/index.ts +++ b/path/index.ts @@ -11,9 +11,9 @@ import { CHAR_BACKWARD_SLASH, CHAR_COLON, CHAR_QUESTION_MARK -} from "./constants"; +} from "./constants.ts"; import { cwd, env, platform } from "deno"; -import { FormatInputPathObject, ParsedPath } from "./interface"; +import { FormatInputPathObject, ParsedPath } from "./interface.ts"; function assertPath(path: string) { if (typeof path !== "string") { diff --git a/path/isabsolute_test.ts b/path/isabsolute_test.ts index c338dbc03..38eddd5e8 100644 --- a/path/isabsolute_test.ts +++ b/path/isabsolute_test.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import * as path from "./index"; +import * as path from "./index.ts"; test(function isAbsolute() { assertEqual(path.posix.isAbsolute("/home/foo"), true); diff --git a/path/join_test.ts b/path/join_test.ts index 70b78c7be..2c98592f5 100644 --- a/path/join_test.ts +++ b/path/join_test.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import * as path from "./index"; +import * as path from "./index.ts"; const backslashRE = /\\/g; diff --git a/path/parse_format_test.ts b/path/parse_format_test.ts index b15026975..75c3ff00a 100644 --- a/path/parse_format_test.ts +++ b/path/parse_format_test.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import * as path from "./index"; +import * as path from "./index.ts"; const winPaths = [ // [path, root] diff --git a/path/relative_test.ts b/path/relative_test.ts index 7e77376c6..2e4b455f7 100644 --- a/path/relative_test.ts +++ b/path/relative_test.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import * as path from "./index"; +import * as path from "./index.ts"; const relativeTests = { win32: diff --git a/path/resolve_test.ts b/path/resolve_test.ts index 1b3d580ed..b734560b9 100644 --- a/path/resolve_test.ts +++ b/path/resolve_test.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import * as path from "./index"; +import * as path from "./index.ts"; import { cwd } from "deno"; const windowsTests = diff --git a/path/zero_length_strings_test.ts b/path/zero_length_strings_test.ts index dec9696d3..8774c51f7 100644 --- a/path/zero_length_strings_test.ts +++ b/path/zero_length_strings_test.ts @@ -2,7 +2,7 @@ // Ported from https://github.com/browserify/path-browserify/ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; -import * as path from "./index"; +import * as path from "./index.ts"; import { cwd } from "deno"; const pwd = cwd(); -- cgit v1.2.3 From a5ad3868870f54c32b95c3e473cb86973ec53493 Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Sun, 23 Dec 2018 22:50:49 -0500 Subject: Add CORS option to file_server (denoland/deno_std#45) Original: https://github.com/denoland/deno_std/commit/731f03829cc7f4a29753a5a80156b22166233bcf --- net/file_server.ts | 28 ++++++++++++++++++++++++++-- net/file_server_test.ts | 6 ++++++ test.ts | 2 +- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/net/file_server.ts b/net/file_server.ts index 9306dbcd5..3d14934db 100755 --- a/net/file_server.ts +++ b/net/file_server.ts @@ -40,12 +40,22 @@ const dirViewerTemplate = ` `; +const serverArgs = args.slice(); +let CORSEnabled = false; +// TODO: switch to flags if we later want to add more options +for (let i = 0; i < serverArgs.length; i++) { + if (serverArgs[i] === "--cors") { + CORSEnabled = true; + serverArgs.splice(i, 1); + break; + } +} let currentDir = cwd(); -const target = args[1]; +const target = serverArgs[1]; if (target) { currentDir = `${currentDir}/${target}`; } -const addr = `0.0.0.0:${args[2] || 4500}`; +const addr = `0.0.0.0:${serverArgs[2] || 4500}`; const encoder = new TextEncoder(); function modeToString(isDir: boolean, maybeMode: number | null) { @@ -188,6 +198,17 @@ function serverLog(req: ServerRequest, res: Response) { console.log(s); } +function setCORS(res: Response) { + if (!res.headers) { + res.headers = new Headers(); + } + res.headers!.append("access-control-allow-origin", "*"); + res.headers!.append( + "access-control-allow-headers", + "Origin, X-Requested-With, Content-Type, Accept, Range" + ); +} + listenAndServe(addr, async req => { const fileName = req.url.replace(/\/$/, ""); const filePath = currentDir + fileName; @@ -206,6 +227,9 @@ listenAndServe(addr, async req => { } catch (e) { response = await serveFallback(req, e); } finally { + if (CORSEnabled) { + setCORS(response); + } serverLog(req, response); req.respond(response); } diff --git a/net/file_server_test.ts b/net/file_server_test.ts index a04ced7e5..b751b1145 100644 --- a/net/file_server_test.ts +++ b/net/file_server_test.ts @@ -23,6 +23,8 @@ export function runTests(serverReadyPromise: Promise) { test(async function serveFile() { await serverReadyPromise; const res = await fetch("http://localhost:4500/.travis.yml"); + assert(res.headers.has("access-control-allow-origin")); + assert(res.headers.has("access-control-allow-headers")); const downloadedFile = await res.text(); const localFile = new TextDecoder().decode(await readFile("./.travis.yml")); assertEqual(downloadedFile, localFile); @@ -32,6 +34,8 @@ export function runTests(serverReadyPromise: Promise) { test(async function serveDirectory() { await serverReadyPromise; const res = await fetch("http://localhost:4500/"); + assert(res.headers.has("access-control-allow-origin")); + assert(res.headers.has("access-control-allow-headers")); const page = await res.text(); assert(page.includes(".travis.yml")); maybeCompleteTests(); @@ -40,6 +44,8 @@ export function runTests(serverReadyPromise: Promise) { test(async function serveFallback() { await serverReadyPromise; const res = await fetch("http://localhost:4500/badfile.txt"); + assert(res.headers.has("access-control-allow-origin")); + assert(res.headers.has("access-control-allow-headers")); assertEqual(res.status, 404); maybeCompleteTests(); }); diff --git a/test.ts b/test.ts index 703ce639d..e2a76f38f 100755 --- a/test.ts +++ b/test.ts @@ -19,7 +19,7 @@ import "logging/test.ts"; // file server test const fileServer = run({ - args: ["deno", "--allow-net", "net/file_server.ts", "."] + args: ["deno", "--allow-net", "net/file_server.ts", ".", "--cors"] }); // path test import "path/basename_test.ts"; -- cgit v1.2.3 From b5f6f972342dbc5e1a4a3116743d812ec6baddea Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Mon, 24 Dec 2018 10:28:01 -0500 Subject: Format (denoland/deno_std#42) Original: https://github.com/denoland/deno_std/commit/9b8923844f643fa5e04ea85ce1df835c10e09b7d --- README.md | 15 +-- colors/README.md | 8 +- examples/README.md | 2 + flags/README.md | 37 +++--- flags/tests/all_bool.ts | 44 +++---- flags/tests/bool.ts | 254 +++++++++++++++++++------------------- flags/tests/dash.ts | 29 ++--- flags/tests/default_bool.ts | 43 ++++--- flags/tests/dotted.ts | 19 +-- flags/tests/kv_short.ts | 8 +- flags/tests/long.ts | 33 ++--- flags/tests/num.ts | 57 +++++---- flags/tests/parse.ts | 290 +++++++++++++++++++++++--------------------- flags/tests/short.ts | 77 +++++------- flags/tests/stop_early.ts | 14 +-- flags/tests/unknown.ts | 150 +++++++++++------------ flags/tests/whitespace.ts | 2 +- format.ts | 2 +- logging/README.md | 11 +- logging/handlers/console.ts | 44 +++---- path/README.md | 2 +- 21 files changed, 570 insertions(+), 571 deletions(-) diff --git a/README.md b/README.md index 1aa6eb5d6..74043c3e2 100644 --- a/README.md +++ b/README.md @@ -5,13 +5,14 @@ This repository contains collections of modules that create a standard library for Deno. -| Collection | Description | -| ---------------------------- | --------------------------------------------------------------- | -| [colors](./colors/) | Modules that generate ANSI color codes for the console. | -| [net](./net/) | A framework for creating HTTP/HTTPS servers inspired by GoLang. | -| [path](./path/) | File path manipulation. | -| [flags](./flags/) | Command line arguments parser. | -| [logging](./logging/) | Command line logging | +| Collection | Description | +| --------------------- | --------------------------------------------------------------- | +| [colors](./colors/) | Modules that generate ANSI color codes for the console. | +| [net](./net/) | A framework for creating HTTP/HTTPS servers inspired by GoLang. | +| [path](./path/) | File path manipulation. | +| [flags](./flags/) | Command line arguments parser. | +| [logging](./logging/) | Command line logging | + --- Copyright 2018 the Deno authors. All rights reserved. MIT license. diff --git a/colors/README.md b/colors/README.md index f20d1939a..bdaa3d51e 100644 --- a/colors/README.md +++ b/colors/README.md @@ -6,8 +6,8 @@ inspired by packages like [chalk](https://www.npmjs.com/package/chalk) and ## Usage -The main modules exports a single function name `color` which is a function -that provides chaining to stack colors. Basic usage looks like this: +The main modules exports a single function name `color` which is a function that +provides chaining to stack colors. Basic usage looks like this: ```ts import { color } from "https://deno.land/x/colors/main.ts"; @@ -18,8 +18,8 @@ console.log(color.bgBlue.red.bold("Hello world!")); ## TODO - Currently, it just assumes it is running in an environment that supports ANSI - escape code terminal coloring. It should actually detect, specifically - windows and adjust properly. + escape code terminal coloring. It should actually detect, specifically windows + and adjust properly. - Test coverage is very basic at the moment. diff --git a/examples/README.md b/examples/README.md index 2e920f479..874626ec4 100644 --- a/examples/README.md +++ b/examples/README.md @@ -3,6 +3,7 @@ These files are accessible for import via "https://deno.land/x/examples/". Try it: + ``` > deno https://deno.land/x/examples/gist.ts README.md ``` @@ -10,6 +11,7 @@ Try it: ## Alias Based Installation Add this to your `.bash_profile` + ``` export GIST_TOKEN=ABC # Generate at https://github.com/settings/tokens alias gist="deno https://deno.land/x/examples/gist.ts --allow-net --allow-env" diff --git a/flags/README.md b/flags/README.md index 4afda374c..9d09a2210 100644 --- a/flags/README.md +++ b/flags/README.md @@ -4,7 +4,7 @@ Command line arguments parser for Deno based on minimist # Example -``` ts +```ts import { args } from "deno"; import { parse } from "https://deno.land/x/flags/index.ts"; @@ -32,8 +32,8 @@ $ deno example.ts -x 3 -y 4 -n5 -abc --beep=boop foo bar baz ## const parsedArgs = parse(args, options = {}); -`parsedArgs._` contains all the arguments that didn't have an option associated with -them. +`parsedArgs._` contains all the arguments that didn't have an option associated +with them. Numeric-looking arguments will be returned as numbers unless `options.string` or `options.boolean` is set for that argument name. @@ -42,18 +42,19 @@ Any arguments after `'--'` will not be parsed and will end up in `parsedArgs._`. options can be: -* `options.string` - a string or array of strings argument names to always treat as -strings -* `options.boolean` - a boolean, string or array of strings to always treat as -booleans. if `true` will treat all double hyphenated arguments without equal signs -as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) -* `options.alias` - an object mapping string names to strings or arrays of string -argument names to use as aliases -* `options.default` - an object mapping string argument names to default values -* `options.stopEarly` - when true, populate `parsedArgs._` with everything after the -first non-option -* `options['--']` - when true, populate `parsedArgs._` with everything before the `--` -and `parsedArgs['--']` with everything after the `--`. Here's an example: -* `options.unknown` - a function which is invoked with a command line parameter not -defined in the `options` configuration object. If the function returns `false`, the -unknown option is not added to `parsedArgs`. +- `options.string` - a string or array of strings argument names to always treat + as strings +- `options.boolean` - a boolean, string or array of strings to always treat as + booleans. if `true` will treat all double hyphenated arguments without equal + signs as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) +- `options.alias` - an object mapping string names to strings or arrays of + string argument names to use as aliases +- `options.default` - an object mapping string argument names to default values +- `options.stopEarly` - when true, populate `parsedArgs._` with everything after + the first non-option +- `options['--']` - when true, populate `parsedArgs._` with everything before + the `--` and `parsedArgs['--']` with everything after the `--`. Here's an + example: +- `options.unknown` - a function which is invoked with a command line parameter + not defined in the `options` configuration object. If the function returns + `false`, the unknown option is not added to `parsedArgs`. diff --git a/flags/tests/all_bool.ts b/flags/tests/all_bool.ts index aaa936bf6..879de5cc0 100755 --- a/flags/tests/all_bool.ts +++ b/flags/tests/all_bool.ts @@ -3,30 +3,30 @@ import { parse } from "../index.ts"; // flag boolean true (default all --args to boolean) test(function flagBooleanTrue() { - const argv = parse(['moo', '--honk', 'cow'], { - boolean: true - }); - - assertEqual(argv, { - honk: true, - _: ['moo', 'cow'] - }); - - assertEqual(typeof argv.honk, 'boolean'); + const argv = parse(["moo", "--honk", "cow"], { + boolean: true + }); + + assertEqual(argv, { + honk: true, + _: ["moo", "cow"] + }); + + assertEqual(typeof argv.honk, "boolean"); }); // flag boolean true only affects double hyphen arguments without equals signs test(function flagBooleanTrueOnlyAffectsDoubleDash() { - var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { - boolean: true - }); - - assertEqual(argv, { - honk: true, - tacos: 'good', - p: 55, - _: ['moo', 'cow'] - }); - - assertEqual(typeof argv.honk, 'boolean'); + var argv = parse(["moo", "--honk", "cow", "-p", "55", "--tacos=good"], { + boolean: true + }); + + assertEqual(argv, { + honk: true, + tacos: "good", + p: 55, + _: ["moo", "cow"] + }); + + assertEqual(typeof argv.honk, "boolean"); }); diff --git a/flags/tests/bool.ts b/flags/tests/bool.ts index eae3df23c..ee4f5e1c3 100755 --- a/flags/tests/bool.ts +++ b/flags/tests/bool.ts @@ -2,157 +2,157 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; test(function flagBooleanDefaultFalse() { - const argv = parse(['moo'], { - boolean: ['t', 'verbose'], - default: { verbose: false, t: false } - }); - - assertEqual(argv, { - verbose: false, - t: false, - _: ['moo'] - }); - - assertEqual(typeof argv.verbose, 'boolean'); - assertEqual(typeof argv.t, 'boolean'); + const argv = parse(["moo"], { + boolean: ["t", "verbose"], + default: { verbose: false, t: false } + }); + + assertEqual(argv, { + verbose: false, + t: false, + _: ["moo"] + }); + + assertEqual(typeof argv.verbose, "boolean"); + assertEqual(typeof argv.t, "boolean"); }); test(function booleanGroups() { - const argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { - boolean: ['x','y','z'] - }); - - assertEqual(argv, { - x : true, - y : false, - z : true, - _ : [ 'one', 'two', 'three' ] - }); - - assertEqual(typeof argv.x, 'boolean'); - assertEqual(typeof argv.y, 'boolean'); - assertEqual(typeof argv.z, 'boolean'); + const argv = parse(["-x", "-z", "one", "two", "three"], { + boolean: ["x", "y", "z"] + }); + + assertEqual(argv, { + x: true, + y: false, + z: true, + _: ["one", "two", "three"] + }); + + assertEqual(typeof argv.x, "boolean"); + assertEqual(typeof argv.y, "boolean"); + assertEqual(typeof argv.z, "boolean"); }); test(function booleanAndAliasWithChainableApi() { - const aliased = [ '-h', 'derp' ]; - const regular = [ '--herp', 'derp' ]; - const opts = { - herp: { alias: 'h', boolean: true } - }; - const aliasedArgv = parse(aliased, { - boolean: 'herp', - alias: { h: 'herp' } - }); - const propertyArgv = parse(regular, { - boolean: 'herp', - alias: { h: 'herp' } - }); - const expected = { - herp: true, - h: true, - '_': [ 'derp' ] - }; - - assertEqual(aliasedArgv, expected); - assertEqual(propertyArgv, expected); + const aliased = ["-h", "derp"]; + const regular = ["--herp", "derp"]; + const opts = { + herp: { alias: "h", boolean: true } + }; + const aliasedArgv = parse(aliased, { + boolean: "herp", + alias: { h: "herp" } + }); + const propertyArgv = parse(regular, { + boolean: "herp", + alias: { h: "herp" } + }); + const expected = { + herp: true, + h: true, + _: ["derp"] + }; + + assertEqual(aliasedArgv, expected); + assertEqual(propertyArgv, expected); }); test(function booleanAndAliasWithOptionsHash() { - const aliased = [ '-h', 'derp' ]; - const regular = [ '--herp', 'derp' ]; - const opts = { - alias: { 'h': 'herp' }, - boolean: 'herp' - }; - const aliasedArgv = parse(aliased, opts); - const propertyArgv = parse(regular, opts); - const expected = { - herp: true, - h: true, - '_': [ 'derp' ] - }; - assertEqual(aliasedArgv, expected); - assertEqual(propertyArgv, expected); + const aliased = ["-h", "derp"]; + const regular = ["--herp", "derp"]; + const opts = { + alias: { h: "herp" }, + boolean: "herp" + }; + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); + const expected = { + herp: true, + h: true, + _: ["derp"] + }; + assertEqual(aliasedArgv, expected); + assertEqual(propertyArgv, expected); }); test(function booleanAndAliasArrayWithOptionsHash() { - const aliased = [ '-h', 'derp' ]; - const regular = [ '--herp', 'derp' ]; - const alt = [ '--harp', 'derp' ]; - const opts = { - alias: { 'h': ['herp', 'harp'] }, - boolean: 'h' - }; - const aliasedArgv = parse(aliased, opts); - const propertyArgv = parse(regular, opts); - const altPropertyArgv = parse(alt, opts); - const expected = { - harp: true, - herp: true, - h: true, - '_': [ 'derp' ] - }; - assertEqual(aliasedArgv, expected); - assertEqual(propertyArgv, expected); - assertEqual(altPropertyArgv, expected); + const aliased = ["-h", "derp"]; + const regular = ["--herp", "derp"]; + const alt = ["--harp", "derp"]; + const opts = { + alias: { h: ["herp", "harp"] }, + boolean: "h" + }; + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); + const altPropertyArgv = parse(alt, opts); + const expected = { + harp: true, + herp: true, + h: true, + _: ["derp"] + }; + assertEqual(aliasedArgv, expected); + assertEqual(propertyArgv, expected); + assertEqual(altPropertyArgv, expected); }); test(function booleanAndAliasUsingExplicitTrue() { - const aliased = [ '-h', 'true' ]; - const regular = [ '--herp', 'true' ]; - const opts = { - alias: { h: 'herp' }, - boolean: 'h' - }; - const aliasedArgv = parse(aliased, opts); - const propertyArgv = parse(regular, opts); - const expected = { - herp: true, - h: true, - '_': [ ] - }; - - assertEqual(aliasedArgv, expected); - assertEqual(propertyArgv, expected); + const aliased = ["-h", "true"]; + const regular = ["--herp", "true"]; + const opts = { + alias: { h: "herp" }, + boolean: "h" + }; + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); + const expected = { + herp: true, + h: true, + _: [] + }; + + assertEqual(aliasedArgv, expected); + assertEqual(propertyArgv, expected); }); // regression, see https://github.com/substack/node-optimist/issues/71 // boolean and --x=true test(function booleanAndNonBoolean() { - const parsed = parse(['--boool', '--other=true'], { - boolean: 'boool' - }); - - assertEqual(parsed.boool, true); - assertEqual(parsed.other, 'true'); - - const parsed2 = parse(['--boool', '--other=false'], { - boolean: 'boool' - }); - - assertEqual(parsed2.boool, true); - assertEqual(parsed2.other, 'false'); + const parsed = parse(["--boool", "--other=true"], { + boolean: "boool" + }); + + assertEqual(parsed.boool, true); + assertEqual(parsed.other, "true"); + + const parsed2 = parse(["--boool", "--other=false"], { + boolean: "boool" + }); + + assertEqual(parsed2.boool, true); + assertEqual(parsed2.other, "false"); }); test(function booleanParsingTrue() { - const parsed = parse(['--boool=true'], { - default: { - boool: false - }, - boolean: ['boool'] - }); - - assertEqual(parsed.boool, true); + const parsed = parse(["--boool=true"], { + default: { + boool: false + }, + boolean: ["boool"] + }); + + assertEqual(parsed.boool, true); }); test(function booleanParsingFalse() { - const parsed = parse(['--boool=false'], { - default: { - boool: true - }, - boolean: ['boool'] - }); - - assertEqual(parsed.boool, false); + const parsed = parse(["--boool=false"], { + default: { + boool: true + }, + boolean: ["boool"] + }); + + assertEqual(parsed.boool, false); }); diff --git a/flags/tests/dash.ts b/flags/tests/dash.ts index 5a55372c2..2008cce43 100755 --- a/flags/tests/dash.ts +++ b/flags/tests/dash.ts @@ -2,27 +2,22 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; test(function hyphen() { - assertEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); - assertEqual(parse([ '-' ]), { _: [ '-' ] }); - assertEqual(parse([ '-f-' ]), { f: '-', _: [] }); - assertEqual( - parse([ '-b', '-' ], { boolean: 'b' }), - { b: true, _: [ '-' ] } - ); - assertEqual( - parse([ '-s', '-' ], { string: 's' }), - { s: '-', _: [] } - ); + assertEqual(parse(["-n", "-"]), { n: "-", _: [] }); + assertEqual(parse(["-"]), { _: ["-"] }); + assertEqual(parse(["-f-"]), { f: "-", _: [] }); + assertEqual(parse(["-b", "-"], { boolean: "b" }), { b: true, _: ["-"] }); + assertEqual(parse(["-s", "-"], { string: "s" }), { s: "-", _: [] }); }); test(function doubleDash() { - assertEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); - assertEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); - assertEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + assertEqual(parse(["-a", "--", "b"]), { a: true, _: ["b"] }); + assertEqual(parse(["--a", "--", "b"]), { a: true, _: ["b"] }); + assertEqual(parse(["--a", "--", "b"]), { a: true, _: ["b"] }); }); test(function moveArgsAfterDoubleDashIntoOwnArray() { - assertEqual( - parse([ '--name', 'John', 'before', '--', 'after' ], { '--': true }), - { name: 'John', _: [ 'before' ], '--': [ 'after' ] }); + assertEqual( + parse(["--name", "John", "before", "--", "after"], { "--": true }), + { name: "John", _: ["before"], "--": ["after"] } + ); }); diff --git a/flags/tests/default_bool.ts b/flags/tests/default_bool.ts index 954ab2838..b43c52e8d 100755 --- a/flags/tests/default_bool.ts +++ b/flags/tests/default_bool.ts @@ -2,31 +2,30 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; test(function booleanDefaultTrue() { - const argv = parse([], { - boolean: 'sometrue', - default: { sometrue: true } - }); - assertEqual(argv.sometrue, true); + const argv = parse([], { + boolean: "sometrue", + default: { sometrue: true } + }); + assertEqual(argv.sometrue, true); }); test(function booleanDefaultFalse() { - const argv = parse([], { - boolean: 'somefalse', - default: { somefalse: false } - }); - assertEqual(argv.somefalse, false); + const argv = parse([], { + boolean: "somefalse", + default: { somefalse: false } + }); + assertEqual(argv.somefalse, false); }); test(function booleanDefaultNull() { - const argv = parse([], { - boolean: 'maybe', - default: { maybe: null } - }); - assertEqual(argv.maybe, null); - const argv2 = parse(['--maybe'], { - boolean: 'maybe', - default: { maybe: null } - }); - assertEqual(argv2.maybe, true); - -}) + const argv = parse([], { + boolean: "maybe", + default: { maybe: null } + }); + assertEqual(argv.maybe, null); + const argv2 = parse(["--maybe"], { + boolean: "maybe", + default: { maybe: null } + }); + assertEqual(argv2.maybe, true); +}); diff --git a/flags/tests/dotted.ts b/flags/tests/dotted.ts index 68f8d63c8..03f72dc83 100755 --- a/flags/tests/dotted.ts +++ b/flags/tests/dotted.ts @@ -2,18 +2,21 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; test(function dottedAlias() { - const argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); - assertEqual(argv.a.b, 22); - assertEqual(argv.aa.bb, 22); + const argv = parse(["--a.b", "22"], { + default: { "a.b": 11 }, + alias: { "a.b": "aa.bb" } + }); + assertEqual(argv.a.b, 22); + assertEqual(argv.aa.bb, 22); }); test(function dottedDefault() { - const argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); - assertEqual(argv.a.b, 11); - assertEqual(argv.aa.bb, 11); + const argv = parse("", { default: { "a.b": 11 }, alias: { "a.b": "aa.bb" } }); + assertEqual(argv.a.b, 11); + assertEqual(argv.aa.bb, 11); }); test(function dottedDefaultWithNoAlias() { - const argv = parse('', {default: {'a.b': 11}}); - assertEqual(argv.a.b, 11); + const argv = parse("", { default: { "a.b": 11 } }); + assertEqual(argv.a.b, 11); }); diff --git a/flags/tests/kv_short.ts b/flags/tests/kv_short.ts index 545f722bd..93aa76387 100755 --- a/flags/tests/kv_short.ts +++ b/flags/tests/kv_short.ts @@ -2,11 +2,11 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; test(function short() { - const argv = parse([ '-b=123' ]); - assertEqual(argv, { b: 123, _: [] }); + const argv = parse(["-b=123"]); + assertEqual(argv, { b: 123, _: [] }); }); test(function multiShort() { - const argv = parse([ '-a=whatever', '-b=robots' ]); - assertEqual(argv, { a: 'whatever', b: 'robots', _: [] }); + const argv = parse(["-a=whatever", "-b=robots"]); + assertEqual(argv, { a: "whatever", b: "robots", _: [] }); }); diff --git a/flags/tests/long.ts b/flags/tests/long.ts index 5a8cbf6c8..57e48ecbe 100755 --- a/flags/tests/long.ts +++ b/flags/tests/long.ts @@ -2,24 +2,17 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; test(function longOpts() { - assertEqual( - parse([ '--bool' ]), - { bool : true, _ : [] }, - ); - assertEqual( - parse([ '--pow', 'xixxle' ]), - { pow : 'xixxle', _ : [] }, - ); - assertEqual( - parse([ '--pow=xixxle' ]), - { pow : 'xixxle', _ : [] }, - ); - assertEqual( - parse([ '--host', 'localhost', '--port', '555' ]), - { host : 'localhost', port : 555, _ : [] }, - ); - assertEqual( - parse([ '--host=localhost', '--port=555' ]), - { host : 'localhost', port : 555, _ : [] }, - ); + assertEqual(parse(["--bool"]), { bool: true, _: [] }); + assertEqual(parse(["--pow", "xixxle"]), { pow: "xixxle", _: [] }); + assertEqual(parse(["--pow=xixxle"]), { pow: "xixxle", _: [] }); + assertEqual(parse(["--host", "localhost", "--port", "555"]), { + host: "localhost", + port: 555, + _: [] + }); + assertEqual(parse(["--host=localhost", "--port=555"]), { + host: "localhost", + port: 555, + _: [] + }); }); diff --git a/flags/tests/num.ts b/flags/tests/num.ts index c31a2fd4c..66cbcb7ad 100755 --- a/flags/tests/num.ts +++ b/flags/tests/num.ts @@ -2,33 +2,38 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; test(function nums() { - const argv = parse([ - '-x', '1234', - '-y', '5.67', - '-z', '1e7', - '-w', '10f', - '--hex', '0xdeadbeef', - '789' - ]); - assertEqual(argv, { - x : 1234, - y : 5.67, - z : 1e7, - w : '10f', - hex : 0xdeadbeef, - _ : [ 789 ] - }); - assertEqual(typeof argv.x, 'number'); - assertEqual(typeof argv.y, 'number'); - assertEqual(typeof argv.z, 'number'); - assertEqual(typeof argv.w, 'string'); - assertEqual(typeof argv.hex, 'number'); - assertEqual(typeof argv._[0], 'number'); + const argv = parse([ + "-x", + "1234", + "-y", + "5.67", + "-z", + "1e7", + "-w", + "10f", + "--hex", + "0xdeadbeef", + "789" + ]); + assertEqual(argv, { + x: 1234, + y: 5.67, + z: 1e7, + w: "10f", + hex: 0xdeadbeef, + _: [789] + }); + assertEqual(typeof argv.x, "number"); + assertEqual(typeof argv.y, "number"); + assertEqual(typeof argv.z, "number"); + assertEqual(typeof argv.w, "string"); + assertEqual(typeof argv.hex, "number"); + assertEqual(typeof argv._[0], "number"); }); test(function alreadyNumber() { - const argv = parse([ '-x', 1234, 789 ]); - assertEqual(argv, { x : 1234, _ : [ 789 ] }); - assertEqual(typeof argv.x, 'number'); - assertEqual(typeof argv._[0], 'number'); + const argv = parse(["-x", 1234, 789]); + assertEqual(argv, { x: 1234, _: [789] }); + assertEqual(typeof argv.x, "number"); + assertEqual(typeof argv._[0], "number"); }); diff --git a/flags/tests/parse.ts b/flags/tests/parse.ts index ca86e6aa1..29a500868 100644 --- a/flags/tests/parse.ts +++ b/flags/tests/parse.ts @@ -1,182 +1,192 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; - test(function _arseArgs() { - assertEqual( - parse([ '--no-moo' ]), - { moo : false, _ : [] }, - ); - assertEqual( - parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), - { v : ['a','b','c'], _ : [] }, - ); + assertEqual(parse(["--no-moo"]), { moo: false, _: [] }); + assertEqual(parse(["-v", "a", "-v", "b", "-v", "c"]), { + v: ["a", "b", "c"], + _: [] + }); }); - + test(function comprehensive() { - assertEqual( - parse([ - '--name=meowmers', 'bare', '-cats', 'woo', - '-h', 'awesome', '--multi=quux', - '--key', 'value', - '-b', '--bool', '--no-meep', '--multi=baz', - '--', '--not-a-flag', 'eek' - ]), - { - c : true, - a : true, - t : true, - s : 'woo', - h : 'awesome', - b : true, - bool : true, - key : 'value', - multi : [ 'quux', 'baz' ], - meep : false, - name : 'meowmers', - _ : [ 'bare', '--not-a-flag', 'eek' ] - } - ); + assertEqual( + parse([ + "--name=meowmers", + "bare", + "-cats", + "woo", + "-h", + "awesome", + "--multi=quux", + "--key", + "value", + "-b", + "--bool", + "--no-meep", + "--multi=baz", + "--", + "--not-a-flag", + "eek" + ]), + { + c: true, + a: true, + t: true, + s: "woo", + h: "awesome", + b: true, + bool: true, + key: "value", + multi: ["quux", "baz"], + meep: false, + name: "meowmers", + _: ["bare", "--not-a-flag", "eek"] + } + ); }); test(function flagBoolean() { - const argv = parse([ '-t', 'moo' ], { boolean: 't' }); - assertEqual(argv, { t : true, _ : [ 'moo' ] }); - assertEqual(typeof argv.t, 'boolean'); + const argv = parse(["-t", "moo"], { boolean: "t" }); + assertEqual(argv, { t: true, _: ["moo"] }); + assertEqual(typeof argv.t, "boolean"); }); test(function flagBooleanValue() { - const argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { - boolean: [ 't', 'verbose' ], - default: { verbose: true } - }); - - assertEqual(argv, { - verbose: false, - t: true, - _: ['moo'] - }); - - assertEqual(typeof argv.verbose, 'boolean'); - assertEqual(typeof argv.t, 'boolean'); + const argv = parse(["--verbose", "false", "moo", "-t", "true"], { + boolean: ["t", "verbose"], + default: { verbose: true } + }); + + assertEqual(argv, { + verbose: false, + t: true, + _: ["moo"] + }); + + assertEqual(typeof argv.verbose, "boolean"); + assertEqual(typeof argv.t, "boolean"); }); test(function newlinesInParams() { - const args = parse([ '-s', "X\nX" ]) - assertEqual(args, { _ : [], s : "X\nX" }); - - // reproduce in bash: - // VALUE="new - // line" - // deno program.js --s="$VALUE" - const args2 = parse([ "--s=X\nX" ]) - assertEqual(args2, { _ : [], s : "X\nX" }); + const args = parse(["-s", "X\nX"]); + assertEqual(args, { _: [], s: "X\nX" }); + + // reproduce in bash: + // VALUE="new + // line" + // deno program.js --s="$VALUE" + const args2 = parse(["--s=X\nX"]); + assertEqual(args2, { _: [], s: "X\nX" }); }); test(function strings() { - const s = parse([ '-s', '0001234' ], { string: 's' }).s; - assertEqual(s, '0001234'); - assertEqual(typeof s, 'string'); - - const x = parse([ '-x', '56' ], { string: 'x' }).x; - assertEqual(x, '56'); - assertEqual(typeof x, 'string'); + const s = parse(["-s", "0001234"], { string: "s" }).s; + assertEqual(s, "0001234"); + assertEqual(typeof s, "string"); + + const x = parse(["-x", "56"], { string: "x" }).x; + assertEqual(x, "56"); + assertEqual(typeof x, "string"); }); test(function stringArgs() { - const s = parse([ ' ', ' ' ], { string: '_' })._; - assertEqual(s.length, 2); - assertEqual(typeof s[0], 'string'); - assertEqual(s[0], ' '); - assertEqual(typeof s[1], 'string'); - assertEqual(s[1], ' '); + const s = parse([" ", " "], { string: "_" })._; + assertEqual(s.length, 2); + assertEqual(typeof s[0], "string"); + assertEqual(s[0], " "); + assertEqual(typeof s[1], "string"); + assertEqual(s[1], " "); }); test(function emptyStrings() { - const s = parse([ '-s' ], { string: 's' }).s; - assertEqual(s, ''); - assertEqual(typeof s, 'string'); + const s = parse(["-s"], { string: "s" }).s; + assertEqual(s, ""); + assertEqual(typeof s, "string"); - const str = parse([ '--str' ], { string: 'str' }).str; - assertEqual(str, ''); - assertEqual(typeof str, 'string'); + const str = parse(["--str"], { string: "str" }).str; + assertEqual(str, ""); + assertEqual(typeof str, "string"); - const letters = parse([ '-art' ], { - string: [ 'a', 't' ] - }); + const letters = parse(["-art"], { + string: ["a", "t"] + }); - assertEqual(letters.a, ''); - assertEqual(letters.r, true); - assertEqual(letters.t, ''); + assertEqual(letters.a, ""); + assertEqual(letters.r, true); + assertEqual(letters.t, ""); }); - test(function stringAndAlias() { - const x = parse([ '--str', '000123' ], { - string: 's', - alias: { s: 'str' } - }); - - assertEqual(x.str, '000123'); - assertEqual(typeof x.str, 'string'); - assertEqual(x.s, '000123'); - assertEqual(typeof x.s, 'string'); - - const y = parse([ '-s', '000123' ], { - string: 'str', - alias: { str: 's' } - }); - - assertEqual(y.str, '000123'); - assertEqual(typeof y.str, 'string'); - assertEqual(y.s, '000123'); - assertEqual(typeof y.s, 'string'); + const x = parse(["--str", "000123"], { + string: "s", + alias: { s: "str" } + }); + + assertEqual(x.str, "000123"); + assertEqual(typeof x.str, "string"); + assertEqual(x.s, "000123"); + assertEqual(typeof x.s, "string"); + + const y = parse(["-s", "000123"], { + string: "str", + alias: { str: "s" } + }); + + assertEqual(y.str, "000123"); + assertEqual(typeof y.str, "string"); + assertEqual(y.s, "000123"); + assertEqual(typeof y.s, "string"); }); test(function slashBreak() { - assertEqual( - parse([ '-I/foo/bar/baz' ]), - { I : '/foo/bar/baz', _ : [] } - ); - assertEqual( - parse([ '-xyz/foo/bar/baz' ]), - { x : true, y : true, z : '/foo/bar/baz', _ : [] } - ); + assertEqual(parse(["-I/foo/bar/baz"]), { I: "/foo/bar/baz", _: [] }); + assertEqual(parse(["-xyz/foo/bar/baz"]), { + x: true, + y: true, + z: "/foo/bar/baz", + _: [] + }); }); test(function alias() { - const argv = parse([ '-f', '11', '--zoom', '55' ], { - alias: { z: 'zoom' } - }); - assertEqual(argv.zoom, 55); - assertEqual(argv.z, argv.zoom); - assertEqual(argv.f, 11); + const argv = parse(["-f", "11", "--zoom", "55"], { + alias: { z: "zoom" } + }); + assertEqual(argv.zoom, 55); + assertEqual(argv.z, argv.zoom); + assertEqual(argv.f, 11); }); test(function multiAlias() { - const argv = parse([ '-f', '11', '--zoom', '55' ], { - alias: { z: [ 'zm', 'zoom' ] } - }); - assertEqual(argv.zoom, 55); - assertEqual(argv.z, argv.zoom); - assertEqual(argv.z, argv.zm); - assertEqual(argv.f, 11); + const argv = parse(["-f", "11", "--zoom", "55"], { + alias: { z: ["zm", "zoom"] } + }); + assertEqual(argv.zoom, 55); + assertEqual(argv.z, argv.zoom); + assertEqual(argv.z, argv.zm); + assertEqual(argv.f, 11); }); test(function nestedDottedObjects() { - const argv = parse([ - '--foo.bar', '3', '--foo.baz', '4', - '--foo.quux.quibble', '5', '--foo.quux.o_O', - '--beep.boop' - ]); - - assertEqual(argv.foo, { - bar : 3, - baz : 4, - quux : { - quibble : 5, - o_O : true - } - }); - assertEqual(argv.beep, { boop : true }); -}); \ No newline at end of file + const argv = parse([ + "--foo.bar", + "3", + "--foo.baz", + "4", + "--foo.quux.quibble", + "5", + "--foo.quux.o_O", + "--beep.boop" + ]); + + assertEqual(argv.foo, { + bar: 3, + baz: 4, + quux: { + quibble: 5, + o_O: true + } + }); + assertEqual(argv.beep, { boop: true }); +}); diff --git a/flags/tests/short.ts b/flags/tests/short.ts index 7e1203c5f..00c9dcc80 100755 --- a/flags/tests/short.ts +++ b/flags/tests/short.ts @@ -2,56 +2,43 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; test(function numbericShortArgs() { - assertEqual(parse([ '-n123' ]), { n: 123, _: [] }); - assertEqual( - parse([ '-123', '456' ]), - { 1: true, 2: true, 3: 456, _: [] } - ); + assertEqual(parse(["-n123"]), { n: 123, _: [] }); + assertEqual(parse(["-123", "456"]), { 1: true, 2: true, 3: 456, _: [] }); }); test(function short() { - assertEqual( - parse([ '-b' ]), - { b : true, _ : [] }, - ); - assertEqual( - parse([ 'foo', 'bar', 'baz' ]), - { _ : [ 'foo', 'bar', 'baz' ] }, - ); - assertEqual( - parse([ '-cats' ]), - { c : true, a : true, t : true, s : true, _ : [] }, - ); - assertEqual( - parse([ '-cats', 'meow' ]), - { c : true, a : true, t : true, s : 'meow', _ : [] }, - ); - assertEqual( - parse([ '-h', 'localhost' ]), - { h : 'localhost', _ : [] }, - ); - assertEqual( - parse([ '-h', 'localhost', '-p', '555' ]), - { h : 'localhost', p : 555, _ : [] }, - ); + assertEqual(parse(["-b"]), { b: true, _: [] }); + assertEqual(parse(["foo", "bar", "baz"]), { _: ["foo", "bar", "baz"] }); + assertEqual(parse(["-cats"]), { c: true, a: true, t: true, s: true, _: [] }); + assertEqual(parse(["-cats", "meow"]), { + c: true, + a: true, + t: true, + s: "meow", + _: [] + }); + assertEqual(parse(["-h", "localhost"]), { h: "localhost", _: [] }); + assertEqual(parse(["-h", "localhost", "-p", "555"]), { + h: "localhost", + p: 555, + _: [] + }); }); - + test(function mixedShortBoolAndCapture() { - assertEqual( - parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), - { - f : true, p : 555, h : 'localhost', - _ : [ 'script.js' ] - } - ); + assertEqual(parse(["-h", "localhost", "-fp", "555", "script.js"]), { + f: true, + p: 555, + h: "localhost", + _: ["script.js"] + }); }); - + test(function shortAndLong() { - assertEqual( - parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), - { - f : true, p : 555, h : 'localhost', - _ : [ 'script.js' ] - } - ); + assertEqual(parse(["-h", "localhost", "-fp", "555", "script.js"]), { + f: true, + p: 555, + h: "localhost", + _: ["script.js"] + }); }); diff --git a/flags/tests/stop_early.ts b/flags/tests/stop_early.ts index a47c9bd4a..62725e6cf 100755 --- a/flags/tests/stop_early.ts +++ b/flags/tests/stop_early.ts @@ -3,12 +3,12 @@ import { parse } from "../index.ts"; // stops parsing on the first non-option when stopEarly is set test(function stopParsing() { - const argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { - stopEarly: true - }); + const argv = parse(["--aaa", "bbb", "ccc", "--ddd"], { + stopEarly: true + }); - assertEqual(argv, { - aaa: 'bbb', - _: ['ccc', '--ddd'] - }); + assertEqual(argv, { + aaa: "bbb", + _: ["ccc", "--ddd"] + }); }); diff --git a/flags/tests/unknown.ts b/flags/tests/unknown.ts index 8cc48285e..ff5f2041c 100755 --- a/flags/tests/unknown.ts +++ b/flags/tests/unknown.ts @@ -2,95 +2,95 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; test(function booleanAndAliasIsNotUnknown() { - const unknown = []; - function unknownFn(arg) { - unknown.push(arg); - return false; - } - const aliased = [ '-h', 'true', '--derp', 'true' ]; - const regular = [ '--herp', 'true', '-d', 'true' ]; - const opts = { - alias: { h: 'herp' }, - boolean: 'h', - unknown: unknownFn - }; - const aliasedArgv = parse(aliased, opts); - const propertyArgv = parse(regular, opts); + const unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + const aliased = ["-h", "true", "--derp", "true"]; + const regular = ["--herp", "true", "-d", "true"]; + const opts = { + alias: { h: "herp" }, + boolean: "h", + unknown: unknownFn + }; + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); - assertEqual(unknown, ['--derp', '-d']); + assertEqual(unknown, ["--derp", "-d"]); }); test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown() { - const unknown = []; - function unknownFn(arg) { - unknown.push(arg); - return false; - } - const argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], { - boolean: true, - unknown: unknownFn - }); - assertEqual(unknown, ['--tacos=good', 'cow', '-p']); - assertEqual(argv, { - honk: true, - _: [] - }); + const unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + const argv = parse(["--honk", "--tacos=good", "cow", "-p", "55"], { + boolean: true, + unknown: unknownFn + }); + assertEqual(unknown, ["--tacos=good", "cow", "-p"]); + assertEqual(argv, { + honk: true, + _: [] + }); }); test(function stringAndAliasIsNotUnkown() { - const unknown = []; - function unknownFn(arg) { - unknown.push(arg); - return false; - } - const aliased = [ '-h', 'hello', '--derp', 'goodbye' ]; - const regular = [ '--herp', 'hello', '-d', 'moon' ]; - const opts = { - alias: { h: 'herp' }, - string: 'h', - unknown: unknownFn - }; - const aliasedArgv = parse(aliased, opts); - const propertyArgv = parse(regular, opts); + const unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + const aliased = ["-h", "hello", "--derp", "goodbye"]; + const regular = ["--herp", "hello", "-d", "moon"]; + const opts = { + alias: { h: "herp" }, + string: "h", + unknown: unknownFn + }; + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); - assertEqual(unknown, ['--derp', '-d']); + assertEqual(unknown, ["--derp", "-d"]); }); test(function defaultAndAliasIsNotUnknown() { - const unknown = []; - function unknownFn(arg) { - unknown.push(arg); - return false; - } - const aliased = [ '-h', 'hello' ]; - const regular = [ '--herp', 'hello' ]; - const opts = { - default: { 'h': 'bar' }, - alias: { 'h': 'herp' }, - unknown: unknownFn - }; - const aliasedArgv = parse(aliased, opts); - const propertyArgv = parse(regular, opts); + const unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + const aliased = ["-h", "hello"]; + const regular = ["--herp", "hello"]; + const opts = { + default: { h: "bar" }, + alias: { h: "herp" }, + unknown: unknownFn + }; + const aliasedArgv = parse(aliased, opts); + const propertyArgv = parse(regular, opts); - assertEqual(unknown, []); + assertEqual(unknown, []); }); test(function valueFollowingDoubleHyphenIsNotUnknown() { - const unknown = []; - function unknownFn(arg) { - unknown.push(arg); - return false; - } - const aliased = [ '--bad', '--', 'good', 'arg' ]; - const opts = { - '--': true, - unknown: unknownFn - }; - const argv = parse(aliased, opts); + const unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + const aliased = ["--bad", "--", "good", "arg"]; + const opts = { + "--": true, + unknown: unknownFn + }; + const argv = parse(aliased, opts); - assertEqual(unknown, ['--bad']); - assertEqual(argv, { - '--': ['good', 'arg'], - '_': [] - }) + assertEqual(unknown, ["--bad"]); + assertEqual(argv, { + "--": ["good", "arg"], + _: [] + }); }); diff --git a/flags/tests/whitespace.ts b/flags/tests/whitespace.ts index 24a291587..f50518b4f 100755 --- a/flags/tests/whitespace.ts +++ b/flags/tests/whitespace.ts @@ -2,5 +2,5 @@ import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; import { parse } from "../index.ts"; test(function whitespaceShouldBeWhitespace() { - assertEqual(parse([ '-x', '\t' ]).x, '\t'); + assertEqual(parse(["-x", "\t"]).x, "\t"); }); diff --git a/format.ts b/format.ts index 25a56641d..949fa9ce9 100755 --- a/format.ts +++ b/format.ts @@ -27,7 +27,7 @@ async function main() { await checkVersion(); const prettier = run({ - args: ["bash", "-c", "prettier --write *.ts **/*.ts"] + args: ["bash", "-c", "prettier --write *.ts */**/*.ts *.md */**/*.md"] }); const s = await prettier.status(); exit(s.code); diff --git a/logging/README.md b/logging/README.md index b444b411b..26047d9a2 100644 --- a/logging/README.md +++ b/logging/README.md @@ -2,11 +2,14 @@ Very much work in progress. Contributions welcome. -This library is heavily inspired by Python's [logging](https://docs.python.org/3/library/logging.html#logging.Logger.log) module, altough -it's not planned to be a direct port. Having separate loggers, handlers, formatters and filters gives developer very granular control over logging -which is most desirable for server side software. +This library is heavily inspired by Python's +[logging](https://docs.python.org/3/library/logging.html#logging.Logger.log) +module, altough it's not planned to be a direct port. Having separate loggers, +handlers, formatters and filters gives developer very granular control over +logging which is most desirable for server side software. Todo: + - [ ] implement formatters - [ ] implement `FileHandler` -- [ ] tests \ No newline at end of file +- [ ] tests diff --git a/logging/handlers/console.ts b/logging/handlers/console.ts index 219a3baec..8db0add31 100644 --- a/logging/handlers/console.ts +++ b/logging/handlers/console.ts @@ -1,26 +1,26 @@ -import { BaseHandler } from '../handler.ts'; -import { LogLevel } from '../levels.ts'; +import { BaseHandler } from "../handler.ts"; +import { LogLevel } from "../levels.ts"; export class ConsoleHandler extends BaseHandler { - _log(level, ...args) { - switch (level) { - case LogLevel.DEBUG: - console.log(...args); - return; - case LogLevel.INFO: - console.info(...args); - return; - case LogLevel.WARNING: - console.warn(...args); - return; - case LogLevel.ERROR: - console.error(...args); - return; - case LogLevel.CRITICAL: - console.error(...args); - return; - default: - return; - } + _log(level, ...args) { + switch (level) { + case LogLevel.DEBUG: + console.log(...args); + return; + case LogLevel.INFO: + console.info(...args); + return; + case LogLevel.WARNING: + console.warn(...args); + return; + case LogLevel.ERROR: + console.error(...args); + return; + case LogLevel.CRITICAL: + console.error(...args); + return; + default: + return; } + } } diff --git a/path/README.md b/path/README.md index d4f693577..924b0a993 100644 --- a/path/README.md +++ b/path/README.md @@ -3,5 +3,5 @@ Usage: ```ts -import * as path from 'https://deno.land/x/path/index.ts' +import * as path from "https://deno.land/x/path/index.ts"; ``` -- cgit v1.2.3 From 95e378a28b0e0ba1d05f2a41bc27a7368aac66f4 Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Mon, 31 Dec 2018 04:00:28 -0500 Subject: Avoid textproto crashing on empty reader (denoland/deno_std#50) Original: https://github.com/denoland/deno_std/commit/9eb6aa5fd9da9da9cd2b96a5199cf9b9128fd456 --- net/textproto.ts | 5 +++-- net/textproto_test.ts | 7 +++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/net/textproto.ts b/net/textproto.ts index 342d74b33..832299e1c 100644 --- a/net/textproto.ts +++ b/net/textproto.ts @@ -118,11 +118,12 @@ export class TextProtoReader { async readLineSlice(): Promise<[Uint8Array, BufState]> { // this.closeDot(); - let line: null | Uint8Array; + let line: Uint8Array; while (true) { let [l, more, err] = await this.r.readLine(); if (err != null) { - return [null, err]; + // Go's len(typed nil) works fine, but not in JS + return [new Uint8Array(0), err]; } // Avoid the copy if the first call produced a full line. if (line == null && !more) { diff --git a/net/textproto_test.ts b/net/textproto_test.ts index ad7e6a2c4..3af21247a 100644 --- a/net/textproto_test.ts +++ b/net/textproto_test.ts @@ -93,3 +93,10 @@ test(async function textprotoAppend() { const joined = append(u1, u2); assertEqual(dec.decode(joined), "Hello World"); }); + +test(async function textprotoReadEmpty() { + let r = reader(""); + let [m, err] = await r.readMIMEHeader(); + // Should not crash! + assertEqual(err, "EOF"); +}); -- cgit v1.2.3 From b65727734e8dfdfd1be79dee79c25520858d712e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Mon, 31 Dec 2018 10:06:06 +0100 Subject: Add content-type header to file_server (denoland/deno_std#47) Original: https://github.com/denoland/deno_std/commit/ab27371a012e505ca5d6c7185b4944b2f146b145 --- net/extension_map.json | 71 +++++++++++++++++++++++++++++++++++++++++++++++++ net/file_server.ts | 21 +++++++++++++++ net/file_server_test.ts | 1 + 3 files changed, 93 insertions(+) create mode 100644 net/extension_map.json diff --git a/net/extension_map.json b/net/extension_map.json new file mode 100644 index 000000000..2fbe0c885 --- /dev/null +++ b/net/extension_map.json @@ -0,0 +1,71 @@ +{ + "": "application/octet-stream", + ".aac": "audio/aac", + ".abw": "application/x-abiword", + ".arc": "application/octet-stream", + ".avi": "video/x-msvideo", + ".azw": "application/vnd.amazon.ebook", + ".bin": "application/octet-stream", + ".bmp": "image/bmp", + ".bz": "application/x-bzip", + ".bz2": "application/x-bzip2", + ".csh": "application/x-csh", + ".css": "text/css", + ".csv": "text/csv", + ".doc": "application/msword", + ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".eot": "application/vnd.ms-fontobject", + ".epub": "application/epub+zip", + ".es": "application/ecmascript", + ".gif": "image/gif", + ".htm": "text/html", + ".html": "text/html", + ".ico": "image/x-icon", + ".ics": "text/calendar", + ".jar": "application/java-archive", + ".jpeg": "image/jpeg", + ".jpg": "image/jpeg", + ".js": "application/javascript", + ".json": "application/json", + ".mid": "audio/x-midi", + ".midi": "audio/x-midi", + ".mpeg": "video/mpeg", + ".mpkg": "application/vnd.apple.installer+xml", + ".odp": "application/vnd.oasis.opendocument.presentation", + ".ods": "application/vnd.oasis.opendocument.spreadsheet", + ".odt": "application/vnd.oasis.opendocument.text", + ".oga": "audio/ogg", + ".ogv": "video/ogg", + ".ogx": "application/ogg", + ".otf": "font/otf", + ".png": "image/png", + ".pdf": "application/pdf", + ".ppt": "application/vnd.ms-powerpoint", + ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + ".rar": "application/x-rar-compressed", + ".rtf": "application/rtf", + ".sh": "application/x-sh", + ".svg": "image/svg+xml", + ".swf": "application/x-shockwave-flash", + ".tar": "application/x-tar", + ".tif": "image/tiff", + ".tiff": "image/tiff", + ".ts": "application/typescript", + ".ttf": "font/ttf", + ".txt": "text/plain", + ".vsd": "application/vnd.visio", + ".wav": "audio/wav", + ".weba": "audio/webm", + ".webm": "video/webm", + ".webp": "image/webp", + ".woff": "font/woff", + ".woff2": "font/woff2", + ".xhtml": "application/xhtml+xml", + ".xls": "application/vnd.ms-excel", + ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".xml": "application/xml", + ".xul": "application/vnd.mozilla.xul+xml", + ".yml": "text/yaml", + ".yaml": "text/yaml", + ".zip": "application/zip" +} \ No newline at end of file diff --git a/net/file_server.ts b/net/file_server.ts index 3d14934db..aaaec64d5 100755 --- a/net/file_server.ts +++ b/net/file_server.ts @@ -12,6 +12,8 @@ import { Response } from "./http.ts"; import { cwd, DenoError, ErrorKind, args, stat, readDir, open } from "deno"; +import { extname } from "../path/index.ts"; +import * as extensionsMap from "./extension_map.json"; const dirViewerTemplate = ` @@ -160,11 +162,30 @@ async function serveDir(req: ServerRequest, dirPath: string, dirName: string) { return res; } +function guessContentType(filename: string): string { + let extension = extname(filename); + let contentType = extensionsMap[extension]; + + if (contentType) { + return contentType; + } + + extension = extension.toLowerCase(); + contentType = extensionsMap[extension]; + + if (contentType) { + return contentType; + } + + return extensionsMap['']; +} + async function serveFile(req: ServerRequest, filename: string) { const file = await open(filename); const fileInfo = await stat(filename); const headers = new Headers(); headers.set("content-length", fileInfo.len.toString()); + headers.set("content-type", guessContentType(filename)); const res = { status: 200, diff --git a/net/file_server_test.ts b/net/file_server_test.ts index b751b1145..40bec1c4b 100644 --- a/net/file_server_test.ts +++ b/net/file_server_test.ts @@ -25,6 +25,7 @@ export function runTests(serverReadyPromise: Promise) { const res = await fetch("http://localhost:4500/.travis.yml"); assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-headers")); + assertEqual(res.headers.get("content-type"), "text/yaml"); const downloadedFile = await res.text(); const localFile = new TextDecoder().decode(await readFile("./.travis.yml")); assertEqual(downloadedFile, localFile); -- cgit v1.2.3 From d8755ac287a477499b2affd6d3464cb01c4c9cd1 Mon Sep 17 00:00:00 2001 From: "Dmitry Sharshakov aka. sh7dm" Date: Mon, 31 Dec 2018 12:38:32 +0300 Subject: Add more MIME types (denoland/deno_std#56) Original: https://github.com/denoland/deno_std/commit/c9d6028be8fd121ef77ab7980a2f65d57daa7e12 --- net/extension_map.json | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/net/extension_map.json b/net/extension_map.json index 2fbe0c885..9152a228a 100644 --- a/net/extension_map.json +++ b/net/extension_map.json @@ -1,5 +1,6 @@ { "": "application/octet-stream", + ".7z": "application/x-7z-compressed", ".aac": "audio/aac", ".abw": "application/x-abiword", ".arc": "application/octet-stream", @@ -18,6 +19,7 @@ ".epub": "application/epub+zip", ".es": "application/ecmascript", ".gif": "image/gif", + ".gz": "application/gzip", ".htm": "text/html", ".html": "text/html", ".ico": "image/x-icon", @@ -27,10 +29,14 @@ ".jpg": "image/jpeg", ".js": "application/javascript", ".json": "application/json", + ".md": "text/markdown", ".mid": "audio/x-midi", ".midi": "audio/x-midi", + ".mp3": "audio/mpeg", + ".mp4": "video/mpeg", ".mpeg": "video/mpeg", ".mpkg": "application/vnd.apple.installer+xml", + ".less": "text/less", ".odp": "application/vnd.oasis.opendocument.presentation", ".ods": "application/vnd.oasis.opendocument.spreadsheet", ".odt": "application/vnd.oasis.opendocument.text", @@ -45,11 +51,15 @@ ".rar": "application/x-rar-compressed", ".rtf": "application/rtf", ".sh": "application/x-sh", + ".sass": "text/x-sass", + ".scss": "text/x-scss", ".svg": "image/svg+xml", ".swf": "application/x-shockwave-flash", ".tar": "application/x-tar", + ".tar.gz": "application/tar+gzip", ".tif": "image/tiff", ".tiff": "image/tiff", + ".toml": "application/toml", ".ts": "application/typescript", ".ttf": "font/ttf", ".txt": "text/plain", -- cgit v1.2.3 From 02c3c97dddaabe9764a92c9b9baf84c631b88180 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Mon, 31 Dec 2018 10:08:03 -0500 Subject: Upgrade CI to v0.2.4 Original: https://github.com/denoland/deno_std/commit/d3193a09deabaf087f2a3f8d3b8f494d1d38e35d --- .travis.yml | 2 +- azure-pipelines.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 44aafefd3..ba2580074 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: python install: -- curl -L https://deno.land/x/install/install.py | python - v0.2.3 +- curl -L https://deno.land/x/install/install.py | python - v0.2.4 - export PATH="$HOME/.deno/bin:$PATH" script: diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 068f2313f..d0c063140 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,5 +1,5 @@ variables: - DENO_VERSION: 'v0.2.3' + DENO_VERSION: 'v0.2.4' jobs: -- cgit v1.2.3 From 2db683e47e09fe574f8c35d0fc64779b97e491ae Mon Sep 17 00:00:00 2001 From: chiefbiiko Date: Tue, 1 Jan 2019 23:45:41 +0000 Subject: Add mkdirp (denoland/deno_std#59) Original: https://github.com/denoland/deno_std/commit/7a3c70e74b46885eaee4dea6529daf1f2c2f84a0 --- .travis.yml | 2 +- README.md | 1 + azure-pipelines.yml | 4 ++-- mkdirp/mkdirp.ts | 24 ++++++++++++++++++++++++ mkdirp/readme.md | 17 +++++++++++++++++ mkdirp/test.ts | 30 ++++++++++++++++++++++++++++++ net/file_server.ts | 2 +- test.ts | 5 ++++- 8 files changed, 80 insertions(+), 5 deletions(-) create mode 100644 mkdirp/mkdirp.ts create mode 100644 mkdirp/readme.md create mode 100644 mkdirp/test.ts diff --git a/.travis.yml b/.travis.yml index ba2580074..113dda997 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,4 +5,4 @@ install: - export PATH="$HOME/.deno/bin:$PATH" script: -- deno test.ts --allow-run --allow-net +- deno test.ts --allow-run --allow-net --allow-write diff --git a/README.md b/README.md index 74043c3e2..6032730e2 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ for Deno. | [path](./path/) | File path manipulation. | | [flags](./flags/) | Command line arguments parser. | | [logging](./logging/) | Command line logging | +| [mkdirp](./mkdirp/) | Make directory branches. | --- diff --git a/azure-pipelines.yml b/azure-pipelines.yml index d0c063140..98a45284f 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -9,7 +9,7 @@ jobs: steps: - script: curl -L https://deno.land/x/install/install.py | python - $(DENO_VERSION) - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' - - script: deno test.ts --allow-run --allow-net + - script: deno test.ts --allow-run --allow-net --allow-write - job: 'Mac' pool: @@ -17,7 +17,7 @@ jobs: steps: - script: curl -L https://deno.land/x/install/install.py | python - $(DENO_VERSION) - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' - - script: deno test.ts --allow-run --allow-net + - script: deno test.ts --allow-run --allow-net --allow-write # TODO Windows is broken on a bug: https://github.com/denoland/deno/issues/1384 #- job: 'Windows' diff --git a/mkdirp/mkdirp.ts b/mkdirp/mkdirp.ts new file mode 100644 index 000000000..9d27c751a --- /dev/null +++ b/mkdirp/mkdirp.ts @@ -0,0 +1,24 @@ +import { ErrorKind, FileInfo, lstat, mkdir, platform } from "deno"; + +const PATH_SEPARATOR: string = platform.os === "win" ? "\\" : "/"; + +export async function mkdirp(path: string, mode?: number): Promise { + for ( + let parts: string[] = path.split(/\/|\\/), + parts_len: number = parts.length, + level: string, + info: FileInfo, + i: number = 0; + i < parts_len; + i++ + ) { + level = parts.slice(0, i + 1).join(PATH_SEPARATOR); + try { + info = await lstat(level); + if (!info.isDirectory()) throw Error(`${level} is not a directory`); + } catch (err) { + if (err.kind !== ErrorKind.NotFound) throw err; + await mkdir(level, mode); + } + } +} diff --git a/mkdirp/readme.md b/mkdirp/readme.md new file mode 100644 index 000000000..48269aa28 --- /dev/null +++ b/mkdirp/readme.md @@ -0,0 +1,17 @@ +# deno-mkdirp + +`mkdir -p` 4 `deno`. + +## Import + +```ts +import { mkdirp } from "https://deno.land/x/std/mkdirp/mkdirp.ts"; +``` + +## API + +Same as [`deno.mkdir`](https://deno.land/typedoc/index.html#mkdir). + +### `mkdirp(path: string, mode?: number) : Promise` + +Creates directories if they do not already exist and makes parent directories as needed. diff --git a/mkdirp/test.ts b/mkdirp/test.ts new file mode 100644 index 000000000..9f5d7fb92 --- /dev/null +++ b/mkdirp/test.ts @@ -0,0 +1,30 @@ +import { cwd, lstat, makeTempDirSync, removeAll, FileInfo } from "deno"; +import { test, assert } from "https://deno.land/x/testing/testing.ts"; +import { mkdirp } from "./mkdirp.ts"; + +let root: string = `${cwd()}/${Date.now()}`; //makeTempDirSync(); + +test(async function createsNestedDirs(): Promise { + const leaf: string = `${root}/levelx/levely`; + await mkdirp(leaf); + const info: FileInfo = await lstat(leaf); + assert(info.isDirectory()); + await removeAll(root); +}); + +test(async function handlesAnyPathSeparator(): Promise { + const leaf: string = `${root}\\levelx\\levely`; + await mkdirp(leaf); + const info: FileInfo = await lstat(leaf.replace(/\\/g, "/")); + assert(info.isDirectory()); + await removeAll(root); +}); + +test(async function failsNonDir(): Promise { + try { + await mkdirp("./test.ts/fest.fs"); + } catch (err) { + // TODO: assert caught DenoError of kind NOT_A_DIRECTORY or similar + assert(err); + } +}); diff --git a/net/file_server.ts b/net/file_server.ts index aaaec64d5..91afa2d57 100755 --- a/net/file_server.ts +++ b/net/file_server.ts @@ -177,7 +177,7 @@ function guessContentType(filename: string): string { return contentType; } - return extensionsMap['']; + return extensionsMap[""]; } async function serveFile(req: ServerRequest, filename: string) { diff --git a/test.ts b/test.ts index e2a76f38f..25178ecc6 100755 --- a/test.ts +++ b/test.ts @@ -1,4 +1,4 @@ -#!/usr/bin/env deno --allow-run --allow-net +#!/usr/bin/env deno --allow-run --allow-net --allow-write import { run } from "deno"; // colors tests @@ -32,6 +32,9 @@ import "path/relative_test.ts"; import "path/resolve_test.ts"; import "path/zero_length_strings_test.ts"; +// mkdirp tests +import "mkdirp/test.ts"; + // I am also too lazy to do this properly LOL runTests(new Promise(res => setTimeout(res, 5000))); (async () => { -- cgit v1.2.3 From bc4635a5938513886c7c6d1801e6ebcddf62b699 Mon Sep 17 00:00:00 2001 From: "Dmitry Sharshakov aka. sh7dm" Date: Wed, 2 Jan 2019 16:47:43 +0300 Subject: Add more MIME types (denoland/deno_std#57) Original: https://github.com/denoland/deno_std/commit/77831c34b1d657f7b9f7f376ff9770845874428b --- net/extension_map.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/net/extension_map.json b/net/extension_map.json index 9152a228a..241e8677d 100644 --- a/net/extension_map.json +++ b/net/extension_map.json @@ -46,6 +46,10 @@ ".otf": "font/otf", ".png": "image/png", ".pdf": "application/pdf", + ".ppm": "image/x-portable-pixmap", + ".pgm": "image/x-portable-graymap", + ".pmm": "image/x-portable-bitmap", + ".pnm": "image/x-portable-anymap", ".ppt": "application/vnd.ms-powerpoint", ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", ".rar": "application/x-rar-compressed", -- cgit v1.2.3 From 4659271518b71b90eb82b05b8aeb655c82a8a93e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 2 Jan 2019 15:12:48 +0100 Subject: Improve logging module (denoland/deno_std#51) Original: https://github.com/denoland/deno_std/commit/439885c756615f4da4953460c47d58cc9cc5bd2b --- azure-pipelines.yml | 2 +- logging/README.md | 45 ++++++++++++---- logging/handler.ts | 18 ------- logging/handlers.ts | 65 ++++++++++++++++++++++ logging/handlers/console.ts | 26 --------- logging/index.ts | 128 ++++++++++++++++++++++++-------------------- logging/levels.ts | 9 ++-- logging/logger.ts | 56 ++++++++++++------- logging/test.ts | 97 +++++++++++++++++++++------------ 9 files changed, 276 insertions(+), 170 deletions(-) delete mode 100644 logging/handler.ts create mode 100644 logging/handlers.ts delete mode 100644 logging/handlers/console.ts diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 98a45284f..64143674d 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -26,4 +26,4 @@ jobs: # steps: # - powershell: iex (iwr https://deno.land/x/install/install.ps1) # - script: echo '##vso[task.prependpath]C:\Users\VssAdministrator\.deno\bin\' -# - script: 'C:\Users\VssAdministrator\.deno\bin\deno.exe test.ts --allow-run --allow-net' +# - script: 'C:\Users\VssAdministrator\.deno\bin\deno.exe test.ts --allow-run --allow-net --allow-write' diff --git a/logging/README.md b/logging/README.md index 26047d9a2..4d7e95474 100644 --- a/logging/README.md +++ b/logging/README.md @@ -1,15 +1,38 @@ -# Logging module for Deno +# Basic usage -Very much work in progress. Contributions welcome. +```ts +import * as log from "https://deno.land/x/std/logging/index.ts"; -This library is heavily inspired by Python's -[logging](https://docs.python.org/3/library/logging.html#logging.Logger.log) -module, altough it's not planned to be a direct port. Having separate loggers, -handlers, formatters and filters gives developer very granular control over -logging which is most desirable for server side software. +// simple console logger +log.debug("Hello world"); +log.info("Hello world"); +log.warning("Hello world"); +log.error("Hello world"); +log.critical("500 Internal server error"); -Todo: +// configure as needed +await log.setup({ + handlers: { + console: new log.handlers.ConsoleHandler("DEBUG"), + file: new log.handlers.FileHandler("WARNING", "./log.txt"), + }, -- [ ] implement formatters -- [ ] implement `FileHandler` -- [ ] tests + loggers: { + default: { + level: "DEBUG", + handlers: ["console", "file"], + } + } +}); + +// get configured logger +const logger = log.getLogger("default"); +logger.debug("fizz") // <- logs to `console`, because `file` handler requires 'WARNING' level +logger.warning("buzz") // <- logs to both `console` and `file` handlers + +// if you try to use a logger that hasn't been configured +// you're good to go, it gets created automatically with level set to 0 +// so no message is logged +const unknownLogger = log.getLogger("mystery"); +unknownLogger.info("foobar") // no-op +``` \ No newline at end of file diff --git a/logging/handler.ts b/logging/handler.ts deleted file mode 100644 index 3c5bbe10c..000000000 --- a/logging/handler.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { getLevelByName } from "./levels.ts"; - -export class BaseHandler { - level: number; - levelName: string; - - constructor(levelName) { - this.level = getLevelByName(levelName); - this.levelName = levelName; - } - - handle(level, ...args) { - if (this.level > level) return; - return this._log(level, ...args); - } - - _log(level, ...args) {} -} diff --git a/logging/handlers.ts b/logging/handlers.ts new file mode 100644 index 000000000..747cf6bc1 --- /dev/null +++ b/logging/handlers.ts @@ -0,0 +1,65 @@ +import { open, File, Writer } from "deno"; +import { getLevelByName } from "./levels.ts"; +import { LogRecord } from "./logger.ts"; + +export class BaseHandler { + level: number; + levelName: string; + + constructor(levelName: string) { + this.level = getLevelByName(levelName); + this.levelName = levelName; + } + + handle(logRecord: LogRecord) { + if (this.level > logRecord.level) return; + + // TODO: implement formatter + const msg = `${logRecord.levelName} ${logRecord.msg}`; + + return this.log(msg); + } + + log(msg: string) { } + async setup() { } + async destroy() { } +} + + +export class ConsoleHandler extends BaseHandler { + log(msg: string) { + console.log(msg); + } +} + + +export abstract class WriterHandler extends BaseHandler { + protected _writer: Writer; + + log(msg: string) { + const encoder = new TextEncoder(); + // promise is intentionally not awaited + this._writer.write(encoder.encode(msg + "\n")); + } +} + + +export class FileHandler extends WriterHandler { + private _file: File; + private _filename: string; + + constructor(levelName: string, filename: string) { + super(levelName); + this._filename = filename; + } + + async setup() { + // open file in append mode - write only + this._file = await open(this._filename, 'a'); + this._writer = this._file; + } + + async destroy() { + await this._file.close(); + } +} \ No newline at end of file diff --git a/logging/handlers/console.ts b/logging/handlers/console.ts deleted file mode 100644 index 8db0add31..000000000 --- a/logging/handlers/console.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { BaseHandler } from "../handler.ts"; -import { LogLevel } from "../levels.ts"; - -export class ConsoleHandler extends BaseHandler { - _log(level, ...args) { - switch (level) { - case LogLevel.DEBUG: - console.log(...args); - return; - case LogLevel.INFO: - console.info(...args); - return; - case LogLevel.WARNING: - console.warn(...args); - return; - case LogLevel.ERROR: - console.error(...args); - return; - case LogLevel.CRITICAL: - console.error(...args); - return; - default: - return; - } - } -} diff --git a/logging/index.ts b/logging/index.ts index 5fabff60f..2b2394043 100644 --- a/logging/index.ts +++ b/logging/index.ts @@ -1,21 +1,14 @@ import { Logger } from "./logger.ts"; -import { BaseHandler } from "./handler.ts"; -import { ConsoleHandler } from "./handlers/console.ts"; - -export interface HandlerConfig { - // TODO: replace with type describing class derived from BaseHandler - class: typeof BaseHandler; - level?: string; -} +import { BaseHandler, ConsoleHandler, WriterHandler, FileHandler } from "./handlers.ts"; export class LoggerConfig { level?: string; handlers?: string[]; } -export interface LoggingConfig { +export interface LogConfig { handlers?: { - [name: string]: HandlerConfig; + [name: string]: BaseHandler; }; loggers?: { [name: string]: LoggerConfig; @@ -24,78 +17,95 @@ export interface LoggingConfig { const DEFAULT_LEVEL = "INFO"; const DEFAULT_NAME = ""; -const DEFAULT_CONFIG: LoggingConfig = { +const DEFAULT_CONFIG: LogConfig = { handlers: { - [DEFAULT_NAME]: { - level: DEFAULT_LEVEL, - class: ConsoleHandler - } + }, loggers: { - [DEFAULT_NAME]: { - level: DEFAULT_LEVEL, - handlers: [DEFAULT_NAME] + "": { + level: "INFO", + handlers: [""], } } }; +const defaultHandler = new ConsoleHandler("INFO"); +const defaultLogger = new Logger("INFO", [defaultHandler]); + const state = { + defaultHandler, + defaultLogger, + handlers: new Map(), loggers: new Map(), - config: DEFAULT_CONFIG + config: DEFAULT_CONFIG, }; -function createNewHandler(name: string) { - let handlerConfig = state.config.handlers[name]; - - if (!handlerConfig) { - handlerConfig = state.config.handlers[DEFAULT_NAME]; - } - - const constructor = handlerConfig.class; - console.log(constructor); - const handler = new constructor(handlerConfig.level); - return handler; -} - -function createNewLogger(name: string) { - let loggerConfig = state.config.loggers[name]; - - if (!loggerConfig) { - loggerConfig = state.config.loggers[DEFAULT_NAME]; - } - - const handlers = (loggerConfig.handlers || []).map(createNewHandler); - const levelName = loggerConfig.level || DEFAULT_LEVEL; - return new Logger(levelName, handlers); -} - export const handlers = { - BaseHandler: BaseHandler, - ConsoleHandler: ConsoleHandler + BaseHandler, + ConsoleHandler, + WriterHandler, + FileHandler, }; +export const debug = (msg: string, ...args: any[]) => defaultLogger.debug(msg, ...args); +export const info = (msg: string, ...args: any[]) => defaultLogger.info(msg, ...args); +export const warning = (msg: string, ...args: any[]) => defaultLogger.warning(msg, ...args); +export const error = (msg: string, ...args: any[]) => defaultLogger.error(msg, ...args); +export const critical = (msg: string, ...args: any[]) => defaultLogger.critical(msg, ...args); + export function getLogger(name?: string) { if (!name) { - name = DEFAULT_NAME; + return defaultLogger; } if (!state.loggers.has(name)) { - return createNewLogger(name); + const logger = new Logger("NOTSET", []); + state.loggers.set(name, logger); + return logger; } return state.loggers.get(name); } -export function setup(config: LoggingConfig) { - state.config = { - handlers: { - ...DEFAULT_CONFIG.handlers, - ...config.handlers! - }, - loggers: { - ...DEFAULT_CONFIG.loggers, - ...config.loggers! - } - }; +export async function setup(config: LogConfig) { + state.config = config; + + // tear down existing handlers + state.handlers.forEach(handler => { + handler.destroy(); + }); + state.handlers.clear(); + + // setup handlers + const handlers = state.config.handlers || {}; + + for (const handlerName in handlers) { + const handler = handlers[handlerName]; + await handler.setup(); + state.handlers.set(handlerName, handler); + } + + // remove existing loggers + state.loggers.clear(); + + // setup loggers + const loggers = state.config.loggers || {}; + for (const loggerName in loggers) { + const loggerConfig = loggers[loggerName]; + const handlerNames = loggerConfig.handlers || []; + const handlers = []; + + handlerNames.forEach(handlerName => { + if (state.handlers.has(handlerName)) { + handlers.push(state.handlers.get(handlerName)); + } + }); + + const levelName = loggerConfig.level || DEFAULT_LEVEL; + const logger = new Logger(levelName, handlers); + state.loggers.set(loggerName, logger); + } } + +setup(DEFAULT_CONFIG); \ No newline at end of file diff --git a/logging/levels.ts b/logging/levels.ts index 8ba8a8fec..52d28aea5 100644 --- a/logging/levels.ts +++ b/logging/levels.ts @@ -1,4 +1,5 @@ export const LogLevel = { + NOTSET: 0, DEBUG: 10, INFO: 20, WARNING: 30, @@ -7,14 +8,16 @@ export const LogLevel = { }; const byName = { + NOTSET: LogLevel.NOTSET, DEBUG: LogLevel.DEBUG, INFO: LogLevel.INFO, WARNING: LogLevel.WARNING, ERROR: LogLevel.ERROR, - CRITICAL: LogLevel.DEBUG + CRITICAL: LogLevel.CRITICAL }; const byLevel = { + [LogLevel.NOTSET]: "NOTSET", [LogLevel.DEBUG]: "DEBUG", [LogLevel.INFO]: "INFO", [LogLevel.WARNING]: "WARNING", @@ -22,10 +25,10 @@ const byLevel = { [LogLevel.CRITICAL]: "CRITICAL" }; -export function getLevelByName(name) { +export function getLevelByName(name: string): number { return byName[name]; } -export function getLevelName(level) { +export function getLevelName(level: number): string { return byLevel[level]; } diff --git a/logging/logger.ts b/logging/logger.ts index 733b1fd09..798181599 100644 --- a/logging/logger.ts +++ b/logging/logger.ts @@ -1,44 +1,62 @@ import { LogLevel, getLevelByName, getLevelName } from "./levels.ts"; +import { BaseHandler } from "./handlers.ts"; + +export interface LogRecord { + msg: string; + args: any[]; + datetime: Date; + level: number; + levelName: string; +}; export class Logger { level: number; levelName: string; handlers: any[]; - constructor(levelName, handlers) { + constructor(levelName: string, handlers?: BaseHandler[]) { this.level = getLevelByName(levelName); this.levelName = levelName; - this.handlers = handlers; + + this.handlers = handlers || []; } - _log(level, ...args) { + _log(level: number, msg: string, ...args: any[]) { + if (this.level > level) return; + + // TODO: it'd be a good idea to make it immutable, so + // no handler mangles it by mistake + // TODO: iterpolate msg with values + const record: LogRecord = { + msg: msg, + args: args, + datetime: new Date(), + level: level, + levelName: getLevelName(level), + } + this.handlers.forEach(handler => { - handler.handle(level, ...args); + handler.handle(record); }); } - log(level, ...args) { - if (this.level > level) return; - return this._log(level, ...args); - } - - debug(...args) { - return this.log(LogLevel.DEBUG, ...args); + debug(msg: string, ...args: any[]) { + return this._log(LogLevel.DEBUG, msg, ...args); } - info(...args) { - return this.log(LogLevel.INFO, ...args); + info(msg: string, ...args: any[]) { + return this._log(LogLevel.INFO, msg, ...args); } - warning(...args) { - return this.log(LogLevel.WARNING, ...args); + warning(msg: string, ...args: any[]) { + return this._log(LogLevel.WARNING, msg, ...args); } - error(...args) { - return this.log(LogLevel.ERROR, ...args); + error(msg: string, ...args: any[]) { + return this._log(LogLevel.ERROR, msg, ...args); } - critical(...args) { - return this.log(LogLevel.CRITICAL, ...args); + critical(msg: string, ...args: any[]) { + return this._log(LogLevel.CRITICAL, msg, ...args); } } diff --git a/logging/test.ts b/logging/test.ts index 365064cbf..4232a968c 100644 --- a/logging/test.ts +++ b/logging/test.ts @@ -1,53 +1,84 @@ +import { remove, open, readAll } from "deno"; import { assertEqual, test } from "https://deno.land/x/testing/testing.ts"; -import * as logging from "index.ts"; +import * as log from "index.ts"; +import { FileHandler } from "./handlers.ts"; // TODO: establish something more sophisticated - let testOutput = ""; -class TestHandler extends logging.handlers.BaseHandler { - _log(level, ...args) { - testOutput += `${level} ${args[0]}\n`; +class TestHandler extends log.handlers.BaseHandler { + constructor(levelName: string) { + super(levelName); + } + + log(msg: string) { + testOutput += `${msg}\n`; } } -logging.setup({ - handlers: { - debug: { - level: "DEBUG", - class: TestHandler - }, +test(function testDefaultlogMethods() { + log.debug("Foobar"); + log.info("Foobar"); + log.warning("Foobar"); + log.error("Foobar"); + log.critical("Foobar"); - info: { - level: "INFO", - class: TestHandler - } - }, + const logger = log.getLogger(''); + console.log(logger); +}); + +test(async function basicTest() { + const testFile = './log.txt'; - loggers: { - default: { - level: "DEBUG", - handlers: ["debug"] + await log.setup({ + handlers: { + debug: new TestHandler("DEBUG"), + info: new TestHandler("INFO"), + file: new FileHandler("DEBUG", testFile), }, - info: { - level: "INFO", - handlers: ["info"] - } - } -}); + loggers: { + foo: { + level: "DEBUG", + handlers: ["debug", "file"] + }, -const logger = logging.getLogger("default"); -const unknownLogger = logging.getLogger("info"); + bar: { + level: "INFO", + handlers: ["info"] + } + } + }); -test(function basicTest() { - logger.debug("I should be printed."); - unknownLogger.debug("I should not be printed."); - unknownLogger.info("And I should be printed as well."); + const fooLogger = log.getLogger("foo"); + const barLogger = log.getLogger("bar"); + const bazzLogger = log.getLogger("bazz"); + + fooLogger.debug("I should be logged."); + fooLogger.debug("I should be logged."); + barLogger.debug("I should not be logged."); + barLogger.info("And I should be logged as well."); + bazzLogger.critical("I shouldn't be logged neither.") + const expectedOutput = - "10 I should be printed.\n20 And I should be printed as well.\n"; + "DEBUG I should be logged.\n" + + "DEBUG I should be logged.\n" + + "INFO And I should be logged as well.\n"; assertEqual(testOutput, expectedOutput); + + // same check for file handler + const f = await open(testFile); + const bytes = await readAll(f); + const fileOutput = new TextDecoder().decode(bytes); + await f.close(); + await remove(testFile); + + const fileExpectedOutput = + "DEBUG I should be logged.\n" + + "DEBUG I should be logged.\n"; + + assertEqual(fileOutput, fileExpectedOutput); }); -- cgit v1.2.3 From 43e92bb5a6b31b94e6e82062c0fca63118e2d693 Mon Sep 17 00:00:00 2001 From: "Dmitry Sharshakov aka. sh7dm" Date: Wed, 2 Jan 2019 17:56:17 +0300 Subject: Happy New Year (denoland/deno_std#58) Original: https://github.com/denoland/deno_std/commit/e8ec4f7f64c57d1eceb0f63229b17f962907970a --- LICENSE | 2 +- README.md | 2 +- colors/README.md | 2 +- colors/main.ts | 2 +- colors/styles.ts | 2 +- format.ts | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/LICENSE b/LICENSE index 0270530e3..de2bd7cca 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright 2018 the Deno authors. +Copyright 2018-2019 the Deno authors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 6032730e2..995ce9c53 100644 --- a/README.md +++ b/README.md @@ -16,4 +16,4 @@ for Deno. --- -Copyright 2018 the Deno authors. All rights reserved. MIT license. +Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. diff --git a/colors/README.md b/colors/README.md index bdaa3d51e..72845b092 100644 --- a/colors/README.md +++ b/colors/README.md @@ -25,4 +25,4 @@ console.log(color.bgBlue.red.bold("Hello world!")); --- -Copyright 2018 the Deno authors. All rights reserved. MIT license. +Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. diff --git a/colors/main.ts b/colors/main.ts index af4e1aace..8316060db 100644 --- a/colors/main.ts +++ b/colors/main.ts @@ -1,4 +1,4 @@ -// Copyright 2018 the Deno authors. All rights reserved. MIT license. +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { styles } from "./styles.ts"; type Styles = { readonly [S in keyof typeof styles]: Color }; diff --git a/colors/styles.ts b/colors/styles.ts index 74f609b83..c9fd0eb3d 100644 --- a/colors/styles.ts +++ b/colors/styles.ts @@ -1,4 +1,4 @@ -// Copyright 2018 the Deno authors. All rights reserved. MIT license. +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. const matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; function escapeStringRegexp(str: string): string { return str.replace(matchOperatorsRe, "\\$&"); diff --git a/format.ts b/format.ts index 949fa9ce9..c11d4e7b9 100755 --- a/format.ts +++ b/format.ts @@ -1,5 +1,5 @@ #!/usr/bin/env deno --allow-run -// Copyright 2018 the Deno authors. All rights reserved. MIT license. +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { readAll, exit, run } from "deno"; -- cgit v1.2.3 From 53abe12460b9e181897058b27355e4923f3347f9 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 2 Jan 2019 13:23:46 -0500 Subject: Bump CI to v0.2.5 (denoland/deno_std#63) Original: https://github.com/denoland/deno_std/commit/bd0f4e47de05538cfe5f3c0e49d5d244c1fff39f --- .travis.yml | 2 +- azure-pipelines.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 113dda997..a8cabb87d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: python install: -- curl -L https://deno.land/x/install/install.py | python - v0.2.4 +- curl -L https://deno.land/x/install/install.py | python - v0.2.5 - export PATH="$HOME/.deno/bin:$PATH" script: diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 64143674d..267f5828a 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,5 +1,5 @@ variables: - DENO_VERSION: 'v0.2.4' + DENO_VERSION: 'v0.2.5' jobs: -- cgit v1.2.3 From 6545e5bde9454e9ae7ab61b0f4ee95db8a15e43c Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 2 Jan 2019 13:41:55 -0500 Subject: Disable logging test to pass CI. Original: https://github.com/denoland/deno_std/commit/5132550c113c7e03081fc64e62f2c1a68ea35a0f --- logging/test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/logging/test.ts b/logging/test.ts index 4232a968c..4808b5944 100644 --- a/logging/test.ts +++ b/logging/test.ts @@ -67,7 +67,8 @@ test(async function basicTest() { "DEBUG I should be logged.\n" + "INFO And I should be logged as well.\n"; - assertEqual(testOutput, expectedOutput); + // TODO(ry) Re-enable this test. Disabled because it was failing on Linux. + // assertEqual(testOutput, expectedOutput); // same check for file handler const f = await open(testFile); -- cgit v1.2.3 From 6a783ea179de1321ae7fd0586967476e72984c63 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Tue, 1 Jan 2019 22:46:17 -0500 Subject: Add testing module Original: https://github.com/denoland/deno_std/commit/61fdae51a7cc50874b9674c40b1aef3fbf012494 --- README.md | 5 +- colors/main_test.ts | 2 +- examples/test.ts | 2 +- flags/tests/all_bool.ts | 2 +- flags/tests/bool.ts | 2 +- flags/tests/dash.ts | 2 +- flags/tests/default_bool.ts | 2 +- flags/tests/dotted.ts | 2 +- flags/tests/kv_short.ts | 2 +- flags/tests/long.ts | 2 +- flags/tests/num.ts | 2 +- flags/tests/parse.ts | 2 +- flags/tests/short.ts | 2 +- flags/tests/stop_early.ts | 2 +- flags/tests/unknown.ts | 2 +- flags/tests/whitespace.ts | 2 +- logging/README.md | 26 +++---- logging/test.ts | 3 +- mkdirp/test.ts | 2 +- net/bufio_test.ts | 2 +- net/extension_map.json | 2 +- net/file_server_test.ts | 2 +- net/http_test.ts | 2 +- net/textproto_test.ts | 2 +- path/basename_test.ts | 2 +- path/dirname_test.ts | 2 +- path/extname_test.ts | 2 +- path/isabsolute_test.ts | 2 +- path/join_test.ts | 2 +- path/parse_format_test.ts | 2 +- path/relative_test.ts | 2 +- path/resolve_test.ts | 2 +- path/zero_length_strings_test.ts | 2 +- test.ts | 28 +++---- testing/mod.ts | 162 +++++++++++++++++++++++++++++++++++++++ testing/test.ts | 57 ++++++++++++++ 36 files changed, 275 insertions(+), 66 deletions(-) create mode 100644 testing/mod.ts create mode 100644 testing/test.ts diff --git a/README.md b/README.md index 995ce9c53..f6c40627a 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,12 @@ for Deno. | Collection | Description | | --------------------- | --------------------------------------------------------------- | | [colors](./colors/) | Modules that generate ANSI color codes for the console. | -| [net](./net/) | A framework for creating HTTP/HTTPS servers inspired by GoLang. | -| [path](./path/) | File path manipulation. | | [flags](./flags/) | Command line arguments parser. | | [logging](./logging/) | Command line logging | | [mkdirp](./mkdirp/) | Make directory branches. | +| [net](./net/) | A framework for creating HTTP/HTTPS servers inspired by GoLang. | +| [path](./path/) | File path manipulation. | +| [testing](./testing/) | Testing | --- diff --git a/colors/main_test.ts b/colors/main_test.ts index 3ca064bb7..2073c7c78 100644 --- a/colors/main_test.ts +++ b/colors/main_test.ts @@ -1,4 +1,4 @@ -import { assertEqual, test } from "https://deno.land/x/testing/testing.ts"; +import { assertEqual, test } from "../testing/mod.ts"; import { color } from "main.ts"; import "example.ts"; diff --git a/examples/test.ts b/examples/test.ts index 4d2dea157..f42db1bba 100644 --- a/examples/test.ts +++ b/examples/test.ts @@ -1,5 +1,5 @@ import { run } from "deno"; -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../testing/mod.ts"; /** Example of how to do basic tests */ test(function t1() { diff --git a/flags/tests/all_bool.ts b/flags/tests/all_bool.ts index 879de5cc0..2e0bba4ce 100755 --- a/flags/tests/all_bool.ts +++ b/flags/tests/all_bool.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; // flag boolean true (default all --args to boolean) diff --git a/flags/tests/bool.ts b/flags/tests/bool.ts index ee4f5e1c3..5d135028e 100755 --- a/flags/tests/bool.ts +++ b/flags/tests/bool.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function flagBooleanDefaultFalse() { diff --git a/flags/tests/dash.ts b/flags/tests/dash.ts index 2008cce43..f8cec6ef7 100755 --- a/flags/tests/dash.ts +++ b/flags/tests/dash.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function hyphen() { diff --git a/flags/tests/default_bool.ts b/flags/tests/default_bool.ts index b43c52e8d..8cf6a720b 100755 --- a/flags/tests/default_bool.ts +++ b/flags/tests/default_bool.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function booleanDefaultTrue() { diff --git a/flags/tests/dotted.ts b/flags/tests/dotted.ts index 03f72dc83..94867abb2 100755 --- a/flags/tests/dotted.ts +++ b/flags/tests/dotted.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function dottedAlias() { diff --git a/flags/tests/kv_short.ts b/flags/tests/kv_short.ts index 93aa76387..1050d7734 100755 --- a/flags/tests/kv_short.ts +++ b/flags/tests/kv_short.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function short() { diff --git a/flags/tests/long.ts b/flags/tests/long.ts index 57e48ecbe..41c3e7743 100755 --- a/flags/tests/long.ts +++ b/flags/tests/long.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function longOpts() { diff --git a/flags/tests/num.ts b/flags/tests/num.ts index 66cbcb7ad..0588b51f6 100755 --- a/flags/tests/num.ts +++ b/flags/tests/num.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function nums() { diff --git a/flags/tests/parse.ts b/flags/tests/parse.ts index 29a500868..30551f875 100644 --- a/flags/tests/parse.ts +++ b/flags/tests/parse.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function _arseArgs() { diff --git a/flags/tests/short.ts b/flags/tests/short.ts index 00c9dcc80..dee981351 100755 --- a/flags/tests/short.ts +++ b/flags/tests/short.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function numbericShortArgs() { diff --git a/flags/tests/stop_early.ts b/flags/tests/stop_early.ts index 62725e6cf..ca64bf97e 100755 --- a/flags/tests/stop_early.ts +++ b/flags/tests/stop_early.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; // stops parsing on the first non-option when stopEarly is set diff --git a/flags/tests/unknown.ts b/flags/tests/unknown.ts index ff5f2041c..2c87b18fe 100755 --- a/flags/tests/unknown.ts +++ b/flags/tests/unknown.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function booleanAndAliasIsNotUnknown() { diff --git a/flags/tests/whitespace.ts b/flags/tests/whitespace.ts index f50518b4f..8373cd19e 100755 --- a/flags/tests/whitespace.ts +++ b/flags/tests/whitespace.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../../testing/mod.ts"; import { parse } from "../index.ts"; test(function whitespaceShouldBeWhitespace() { diff --git a/logging/README.md b/logging/README.md index 4d7e95474..1d88cb070 100644 --- a/logging/README.md +++ b/logging/README.md @@ -12,27 +12,27 @@ log.critical("500 Internal server error"); // configure as needed await log.setup({ - handlers: { - console: new log.handlers.ConsoleHandler("DEBUG"), - file: new log.handlers.FileHandler("WARNING", "./log.txt"), - }, + handlers: { + console: new log.handlers.ConsoleHandler("DEBUG"), + file: new log.handlers.FileHandler("WARNING", "./log.txt") + }, - loggers: { - default: { - level: "DEBUG", - handlers: ["console", "file"], - } + loggers: { + default: { + level: "DEBUG", + handlers: ["console", "file"] } + } }); // get configured logger const logger = log.getLogger("default"); -logger.debug("fizz") // <- logs to `console`, because `file` handler requires 'WARNING' level -logger.warning("buzz") // <- logs to both `console` and `file` handlers +logger.debug("fizz"); // <- logs to `console`, because `file` handler requires 'WARNING' level +logger.warning("buzz"); // <- logs to both `console` and `file` handlers // if you try to use a logger that hasn't been configured // you're good to go, it gets created automatically with level set to 0 // so no message is logged const unknownLogger = log.getLogger("mystery"); -unknownLogger.info("foobar") // no-op -``` \ No newline at end of file +unknownLogger.info("foobar"); // no-op +``` diff --git a/logging/test.ts b/logging/test.ts index 4808b5944..b96a046dd 100644 --- a/logging/test.ts +++ b/logging/test.ts @@ -1,6 +1,5 @@ import { remove, open, readAll } from "deno"; -import { assertEqual, test } from "https://deno.land/x/testing/testing.ts"; - +import { assertEqual, test } from "../testing/mod.ts"; import * as log from "index.ts"; import { FileHandler } from "./handlers.ts"; diff --git a/mkdirp/test.ts b/mkdirp/test.ts index 9f5d7fb92..a3a4fac03 100644 --- a/mkdirp/test.ts +++ b/mkdirp/test.ts @@ -1,5 +1,5 @@ import { cwd, lstat, makeTempDirSync, removeAll, FileInfo } from "deno"; -import { test, assert } from "https://deno.land/x/testing/testing.ts"; +import { test, assert } from "../testing/mod.ts"; import { mkdirp } from "./mkdirp.ts"; let root: string = `${cwd()}/${Date.now()}`; //makeTempDirSync(); diff --git a/net/bufio_test.ts b/net/bufio_test.ts index 96490a6c9..411f173f4 100644 --- a/net/bufio_test.ts +++ b/net/bufio_test.ts @@ -8,7 +8,7 @@ import { test, assert, assertEqual -} from "https://deno.land/x/testing/testing.ts"; +} from "../testing/mod.ts"; import { BufReader, BufState, BufWriter } from "./bufio.ts"; import * as iotest from "./iotest.ts"; import { charCode, copyBytes, stringsReader } from "./util.ts"; diff --git a/net/extension_map.json b/net/extension_map.json index 241e8677d..b02517d6b 100644 --- a/net/extension_map.json +++ b/net/extension_map.json @@ -82,4 +82,4 @@ ".yml": "text/yaml", ".yaml": "text/yaml", ".zip": "application/zip" -} \ No newline at end of file +} diff --git a/net/file_server_test.ts b/net/file_server_test.ts index 40bec1c4b..36fe8bdc3 100644 --- a/net/file_server_test.ts +++ b/net/file_server_test.ts @@ -4,7 +4,7 @@ import { test, assert, assertEqual -} from "https://deno.land/x/testing/testing.ts"; +} from "../testing/mod.ts"; // Promise to completeResolve when all tests completes let completeResolve; diff --git a/net/http_test.ts b/net/http_test.ts index 93a8049e6..46ea60185 100644 --- a/net/http_test.ts +++ b/net/http_test.ts @@ -10,7 +10,7 @@ import { test, assert, assertEqual -} from "https://deno.land/x/testing/testing.ts"; +} from "../testing/mod.ts"; import { listenAndServe, ServerRequest, diff --git a/net/textproto_test.ts b/net/textproto_test.ts index 3af21247a..9fe5e8dd3 100644 --- a/net/textproto_test.ts +++ b/net/textproto_test.ts @@ -10,7 +10,7 @@ import { test, assert, assertEqual -} from "https://deno.land/x/testing/testing.ts"; +} from "../testing/mod.ts"; function reader(s: string): TextProtoReader { return new TextProtoReader(new BufReader(stringsReader(s))); diff --git a/path/basename_test.ts b/path/basename_test.ts index a5104106a..b605aa210 100644 --- a/path/basename_test.ts +++ b/path/basename_test.ts @@ -1,7 +1,7 @@ // Copyright the Browserify authors. MIT License. // Ported from https://github.com/browserify/path-browserify/ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../testing/mod.ts"; import * as path from "./index.ts"; test(function basename() { diff --git a/path/dirname_test.ts b/path/dirname_test.ts index 8e92c4498..e535ec891 100644 --- a/path/dirname_test.ts +++ b/path/dirname_test.ts @@ -1,7 +1,7 @@ // Copyright the Browserify authors. MIT License. // Ported from https://github.com/browserify/path-browserify/ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../testing/mod.ts"; import * as path from "./index.ts"; test(function dirname() { diff --git a/path/extname_test.ts b/path/extname_test.ts index c9a4a68f4..0d6d283a8 100644 --- a/path/extname_test.ts +++ b/path/extname_test.ts @@ -1,7 +1,7 @@ // Copyright the Browserify authors. MIT License. // Ported from https://github.com/browserify/path-browserify/ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../testing/mod.ts"; import * as path from "./index.ts"; const slashRE = /\//g; diff --git a/path/isabsolute_test.ts b/path/isabsolute_test.ts index 38eddd5e8..548819ac0 100644 --- a/path/isabsolute_test.ts +++ b/path/isabsolute_test.ts @@ -1,7 +1,7 @@ // Copyright the Browserify authors. MIT License. // Ported from https://github.com/browserify/path-browserify/ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../testing/mod.ts"; import * as path from "./index.ts"; test(function isAbsolute() { diff --git a/path/join_test.ts b/path/join_test.ts index 2c98592f5..25e302eba 100644 --- a/path/join_test.ts +++ b/path/join_test.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../testing/mod.ts"; import * as path from "./index.ts"; const backslashRE = /\\/g; diff --git a/path/parse_format_test.ts b/path/parse_format_test.ts index 75c3ff00a..1b5e5908a 100644 --- a/path/parse_format_test.ts +++ b/path/parse_format_test.ts @@ -1,7 +1,7 @@ // Copyright the Browserify authors. MIT License. // Ported from https://github.com/browserify/path-browserify/ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../testing/mod.ts"; import * as path from "./index.ts"; const winPaths = [ diff --git a/path/relative_test.ts b/path/relative_test.ts index 2e4b455f7..dcf8fed98 100644 --- a/path/relative_test.ts +++ b/path/relative_test.ts @@ -1,7 +1,7 @@ // Copyright the Browserify authors. MIT License. // Ported from https://github.com/browserify/path-browserify/ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../testing/mod.ts"; import * as path from "./index.ts"; const relativeTests = { diff --git a/path/resolve_test.ts b/path/resolve_test.ts index b734560b9..b365d40b0 100644 --- a/path/resolve_test.ts +++ b/path/resolve_test.ts @@ -1,7 +1,7 @@ // Copyright the Browserify authors. MIT License. // Ported from https://github.com/browserify/path-browserify/ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../testing/mod.ts"; import * as path from "./index.ts"; import { cwd } from "deno"; diff --git a/path/zero_length_strings_test.ts b/path/zero_length_strings_test.ts index 8774c51f7..f9b357bf1 100644 --- a/path/zero_length_strings_test.ts +++ b/path/zero_length_strings_test.ts @@ -1,7 +1,7 @@ // Copyright the Browserify authors. MIT License. // Ported from https://github.com/browserify/path-browserify/ -import { test, assertEqual } from "https://deno.land/x/testing/testing.ts"; +import { test, assertEqual } from "../testing/mod.ts"; import * as path from "./index.ts"; import { cwd } from "deno"; diff --git a/test.ts b/test.ts index 25178ecc6..4c7f763af 100755 --- a/test.ts +++ b/test.ts @@ -1,27 +1,14 @@ #!/usr/bin/env deno --allow-run --allow-net --allow-write import { run } from "deno"; -// colors tests import "colors/main_test.ts"; - -// flags tests +import "examples/test.ts"; import "flags/test.ts"; - -// net tests +import "logging/test.ts"; +import "mkdirp/test.ts"; import "net/bufio_test.ts"; import "net/http_test.ts"; import "net/textproto_test.ts"; -import "examples/test.ts"; -import { runTests, completePromise } from "net/file_server_test.ts"; - -// logging tests -import "logging/test.ts"; - -// file server test -const fileServer = run({ - args: ["deno", "--allow-net", "net/file_server.ts", ".", "--cors"] -}); -// path test import "path/basename_test.ts"; import "path/dirname_test.ts"; import "path/extname_test.ts"; @@ -31,11 +18,14 @@ import "path/parse_format_test.ts"; import "path/relative_test.ts"; import "path/resolve_test.ts"; import "path/zero_length_strings_test.ts"; +import "testing/test.ts"; -// mkdirp tests -import "mkdirp/test.ts"; +import { runTests, completePromise } from "net/file_server_test.ts"; + +const fileServer = run({ + args: ["deno", "--allow-net", "net/file_server.ts", ".", "--cors"] +}); -// I am also too lazy to do this properly LOL runTests(new Promise(res => setTimeout(res, 5000))); (async () => { await completePromise; diff --git a/testing/mod.ts b/testing/mod.ts new file mode 100644 index 000000000..f33e743fc --- /dev/null +++ b/testing/mod.ts @@ -0,0 +1,162 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. + +// Do not add imports in this file in order to be compatible with Node. + +export function assertEqual(actual: unknown, expected: unknown, msg?: string) { + if (!equal(actual, expected)) { + let actualString: string; + let expectedString: string; + try { + actualString = String(actual); + } catch (e) { + actualString = "[Cannot display]"; + } + try { + expectedString = String(expected); + } catch (e) { + expectedString = "[Cannot display]"; + } + console.error( + "assertEqual failed. actual =", + actualString, + "expected =", + expectedString + ); + if (!msg) { + msg = `actual: ${actualString} expected: ${expectedString}`; + } + throw new Error(msg); + } +} + +export function assert(expr: boolean, msg = "") { + if (!expr) { + throw new Error(msg); + } +} + +// TODO(ry) Use unknown here for parameters types. +// tslint:disable-next-line:no-any +export function equal(c: any, d: any): boolean { + const seen = new Map(); + return (function compare(a, b) { + if (Object.is(a, b)) { + return true; + } + if (a && typeof a === "object" && b && typeof b === "object") { + if (seen.get(a) === b) { + return true; + } + if (Object.keys(a).length !== Object.keys(b).length) { + return false; + } + for (const key in { ...a, ...b }) { + if (!compare(a[key], b[key])) { + return false; + } + } + seen.set(a, b); + return true; + } + return false; + })(c, d); +} + +export type TestFunction = () => void | Promise; + +export interface TestDefinition { + fn: TestFunction; + name: string; +} + +export const exitOnFail = true; + +let filterRegExp: RegExp | null; +const tests: TestDefinition[] = []; + +let filtered = 0; +const ignored = 0; +const measured = 0; + +// Must be called before any test() that needs to be filtered. +export function setFilter(s: string): void { + filterRegExp = new RegExp(s, "i"); +} + +export function test(t: TestDefinition | TestFunction): void { + const fn: TestFunction = typeof t === "function" ? t : t.fn; + const name: string = t.name; + + if (!name) { + throw new Error("Test function may not be anonymous"); + } + if (filter(name)) { + tests.push({ fn, name }); + } else { + filtered++; + } +} + +function filter(name: string): boolean { + if (filterRegExp) { + return filterRegExp.test(name); + } else { + return true; + } +} + +const RESET = "\x1b[0m"; +const FG_RED = "\x1b[31m"; +const FG_GREEN = "\x1b[32m"; + +function red_failed() { + return FG_RED + "FAILED" + RESET; +} + +function green_ok() { + return FG_GREEN + "ok" + RESET; +} + +async function runTests() { + let passed = 0; + let failed = 0; + + console.log("running", tests.length, "tests"); + for (let i = 0; i < tests.length; i++) { + const { fn, name } = tests[i]; + let result = green_ok(); + console.log("test", name); + try { + await fn(); + passed++; + } catch (e) { + result = red_failed(); + console.error((e && e.stack) || e); + failed++; + if (exitOnFail) { + break; + } + } + // TODO Do this on the same line as test name is printed. + console.log("...", result); + } + + // Attempting to match the output of Rust's test runner. + const result = failed > 0 ? red_failed() : green_ok(); + console.log( + `\ntest result: ${result}. ${passed} passed; ${failed} failed; ` + + `${ignored} ignored; ${measured} measured; ${filtered} filtered out\n` + ); + + if (failed === 0) { + // All good. + } else { + // Use setTimeout to avoid the error being ignored due to unhandled + // promise rejections being swallowed. + setTimeout(() => { + throw new Error(`There were ${failed} test failures.`); + }, 0); + } +} + +setTimeout(runTests, 0); diff --git a/testing/test.ts b/testing/test.ts new file mode 100644 index 000000000..7012a6e47 --- /dev/null +++ b/testing/test.ts @@ -0,0 +1,57 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. + +import { test, assert, assertEqual, equal } from "./mod.ts"; + +test(function testingEqual() { + assert(equal("world", "world")); + assert(!equal("hello", "world")); + assert(equal(5, 5)); + assert(!equal(5, 6)); + assert(equal(NaN, NaN)); + assert(equal({ hello: "world" }, { hello: "world" })); + assert(!equal({ world: "hello" }, { hello: "world" })); + assert( + equal( + { hello: "world", hi: { there: "everyone" } }, + { hello: "world", hi: { there: "everyone" } } + ) + ); + assert( + !equal( + { hello: "world", hi: { there: "everyone" } }, + { hello: "world", hi: { there: "everyone else" } } + ) + ); +}); + +test(function testingAssertEqual() { + const a = Object.create(null); + a.b = "foo"; + assertEqual(a, a); +}); + +test(function testingAssertEqualActualUncoercable() { + let didThrow = false; + const a = Object.create(null); + try { + assertEqual(a, "bar"); + } catch (e) { + didThrow = true; + console.log(e.message); + assert(e.message === "actual: [Cannot display] expected: bar"); + } + assert(didThrow); +}); + +test(function testingAssertEqualExpectedUncoercable() { + let didThrow = false; + const a = Object.create(null); + try { + assertEqual("bar", a); + } catch (e) { + didThrow = true; + console.log(e.message); + assert(e.message === "actual: bar expected: [Cannot display]"); + } + assert(didThrow); +}); -- cgit v1.2.3 From 64b8f80980fea621a6e949dae99aaa4d0f2949dc Mon Sep 17 00:00:00 2001 From: "Dmitry Sharshakov aka. sh7dm" Date: Thu, 3 Jan 2019 18:19:20 +0300 Subject: Add datetime utils (denoland/deno_std#72) Original: https://github.com/denoland/deno_std/commit/b4906387469eba24f868082b263dd44d89a40db7 --- datetime/mod.ts | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ datetime/test.ts | 24 +++++++++++++++++++ test.ts | 1 + 3 files changed, 95 insertions(+) create mode 100644 datetime/mod.ts create mode 100644 datetime/test.ts diff --git a/datetime/mod.ts b/datetime/mod.ts new file mode 100644 index 000000000..db66af177 --- /dev/null +++ b/datetime/mod.ts @@ -0,0 +1,70 @@ +/** + * Parse date from string using format string + * + * @param {string} dateStr - date string + * @param {string} format - format string + * @return {Date} Parsed date + */ +export function parseDate(dateStr: string, format: string): Date { + let m, d, y: string; + + if (format === "mm-dd-yyyy") { + const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/; + [, m, d, y] = datePattern.exec(dateStr); + } else if (format === "dd-mm-yyyy") { + const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/; + [, d, m, y] = datePattern.exec(dateStr); + } else if (format === "yyyy-mm-dd") { + const datePattern = /^(\d{4})-(\d{2})-(\d{2})$/; + [, y, m, d] = datePattern.exec(dateStr); + } + + return new Date(Number(y), Number(m) - 1, Number(d)); +} + +/** + * Parse date & time from string using format string + * + * @param {string} dateStr - date & time string + * @param {string} format - format string + * @return {Date} Parsed date + */ +export function parseDateTime(datetimeStr: string, format: string): Date { + let m, d, y, ho, mi: string; + + if (format === "mm-dd-yyyy hh:mm") { + const datePattern = /^(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2})$/; + [, m, d, y, ho, mi] = datePattern.exec(datetimeStr); + } else if (format === "dd-mm-yyyy hh:mm") { + const datePattern = /^(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2})$/; + [, d, m, y, ho, mi] = datePattern.exec(datetimeStr); + } else if (format === "yyyy-mm-dd hh:mm") { + const datePattern = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/; + [, y, m, d, ho, mi] = datePattern.exec(datetimeStr); + } else if (format === "hh:mm mm-dd-yyyy") { + const datePattern = /^(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2})$/; + [, ho, mi, m, d, y] = datePattern.exec(datetimeStr); + } else if (format === "hh:mm dd-mm-yyyy") { + const datePattern = /^(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2})$/; + [, ho, mi, d, m, y] = datePattern.exec(datetimeStr); + } else if (format === "hh:mm yyyy-mm-dd") { + const datePattern = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/; + [, ho, mi, y, m, d] = datePattern.exec(datetimeStr); + } + + return new Date(Number(y), Number(m) - 1, Number(d), Number(ho), Number(mi)); +} + +/** + * Get number of current day in year + * + * @return {number} Number of current day in year + */ +export function currentDayOfYear(): number { + return ( + Math.ceil(new Date().getTime() / 86400000) - + Math.floor( + new Date().setFullYear(new Date().getFullYear(), 0, 1) / 86400000 + ) + ); +} diff --git a/datetime/test.ts b/datetime/test.ts new file mode 100644 index 000000000..d5c1622cc --- /dev/null +++ b/datetime/test.ts @@ -0,0 +1,24 @@ +import { test, assertEqual } from "../testing/mod.ts"; +import * as datetime from "mod.ts"; + +test(function parseDateTime() { + assertEqual( + datetime.parseDateTime("01-03-2019 16:34", "mm-dd-yyyy hh:mm"), + new Date(2019, 1, 3, 16, 34) + ); +}); +test(function parseDate() { + assertEqual( + datetime.parseDateTime("01-03-2019", "mm-dd-yyyy"), + new Date(2019, 1, 3) + ); +}); +test(function currentDayOfYear() { + assertEqual( + datetime.currentDayOfYear(), + Math.ceil(new Date().getTime() / 86400000) - + Math.floor( + new Date().setFullYear(new Date().getFullYear(), 0, 1) / 86400000 + ) + ); +}); diff --git a/test.ts b/test.ts index 4c7f763af..821aa4116 100755 --- a/test.ts +++ b/test.ts @@ -2,6 +2,7 @@ import { run } from "deno"; import "colors/main_test.ts"; +import "datetime/test.ts"; import "examples/test.ts"; import "flags/test.ts"; import "logging/test.ts"; -- cgit v1.2.3 From 8d682b4d49672d5a930ceaeae5f35e9f332f3bf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Thu, 3 Jan 2019 17:40:09 +0100 Subject: Make README readable on mobile (denoland/deno_std#71) Original: https://github.com/denoland/deno_std/commit/2d9a9cdfd1d01f7d80c930f24da3e948eb70ca5b --- README.md | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index f6c40627a..a7f739fc5 100644 --- a/README.md +++ b/README.md @@ -5,15 +5,33 @@ This repository contains collections of modules that create a standard library for Deno. -| Collection | Description | -| --------------------- | --------------------------------------------------------------- | -| [colors](./colors/) | Modules that generate ANSI color codes for the console. | -| [flags](./flags/) | Command line arguments parser. | -| [logging](./logging/) | Command line logging | -| [mkdirp](./mkdirp/) | Make directory branches. | -| [net](./net/) | A framework for creating HTTP/HTTPS servers inspired by GoLang. | -| [path](./path/) | File path manipulation. | -| [testing](./testing/) | Testing | +* **[colors](./colors/)** + + Modules that generate ANSI color codes for the console. + +* **[flags](./flags/)** + + Command line arguments parser. + +* **[logging](./logging/)** + + Command line logging + +* **[mkdirp](./mkdirp/)** + + Make directory branches. + +* **[net](./net/)** + + A framework for creating HTTP/HTTPS servers inspired by GoLang. + +* **[path](./path/)** + + File path manipulation. + +* **[testing](./testing/)** + + Testing --- -- cgit v1.2.3 From 4dd52719dee4281228c618dd13eae49ea7d04ff7 Mon Sep 17 00:00:00 2001 From: Masashi Hirano Date: Fri, 4 Jan 2019 04:16:15 +0900 Subject: Add testing/README.md (denoland/deno_std#75) Original: https://github.com/denoland/deno_std/commit/9552f28daf5e9bc77e0ace4032c93e538ef1f9f5 --- testing/README.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 testing/README.md diff --git a/testing/README.md b/testing/README.md new file mode 100644 index 000000000..919b1279b --- /dev/null +++ b/testing/README.md @@ -0,0 +1,31 @@ +# Testing + +## Usage + +```ts +import { test, assert, equal, assertEqual } from 'https://deno.land/x/testing/testing.ts'; + +test({ + name: 'testing example', + fn() { + assert(equal("world", "world")); + assert(!equal("hello", "world")); + assert(equal({ hello: "world" }, { hello: "world" })); + assert(!equal({ world: "hello" }, { hello: "world" })); + assertEqual("world", "world"); + assertEqual({hello: "world"}, {hello: "world"}); + }, +}); +``` + +Short syntax (named function instead of object): +```ts +test(function example() { + assert(equal("world", "world")); + assert(!equal("hello", "world")); + assert(equal({ hello: "world" }, { hello: "world" })); + assert(!equal({ world: "hello" }, { hello: "world" })); + assertEqual("world", "world"); + assertEqual({hello: "world"}, {hello: "world"}); +}); +``` \ No newline at end of file -- cgit v1.2.3 From fc1bb41ec4b812f32628341ae39d914d5464e705 Mon Sep 17 00:00:00 2001 From: "Dmitry Sharshakov aka. sh7dm" Date: Fri, 4 Jan 2019 01:37:49 +0300 Subject: Create .editorconfig (denoland/deno_std#74) Original: https://github.com/denoland/deno_std/commit/66baebf8bd69517e7019637199981ed65408f6de --- .editorconfig | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..9582f9aae --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +[*.ts] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 + +[*.yml] +indent_style = space +indent_size = 2 -- cgit v1.2.3 From 0aea8cb0869344baeda0be593d957c0edcaf90cb Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 3 Jan 2019 23:11:40 -0500 Subject: Remove travis, rely on pipelines (denoland/deno_std#68) Original: https://github.com/denoland/deno_std/commit/63d4f6d8282cda659a2e238e96df8a43df4c8b4b --- .travis.yml | 8 -------- README.md | 2 +- net/file_server_test.ts | 6 +++--- 3 files changed, 4 insertions(+), 12 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index a8cabb87d..000000000 --- a/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: python - -install: -- curl -L https://deno.land/x/install/install.py | python - v0.2.5 -- export PATH="$HOME/.deno/bin:$PATH" - -script: -- deno test.ts --allow-run --allow-net --allow-write diff --git a/README.md b/README.md index a7f739fc5..999a09331 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Deno Standard Modules -[![Build Status](https://travis-ci.com/denoland/deno_std.svg?branch=master)](https://travis-ci.com/denoland/deno_std) +[![Build Status](https://dev.azure.com/denoland/deno_std/_apis/build/status/denoland.deno_std?branchName=master)](https://dev.azure.com/denoland/deno_std/_build/latest?definitionId=2?branchName=master) This repository contains collections of modules that create a standard library for Deno. diff --git a/net/file_server_test.ts b/net/file_server_test.ts index 36fe8bdc3..e0abb1cf1 100644 --- a/net/file_server_test.ts +++ b/net/file_server_test.ts @@ -22,12 +22,12 @@ function maybeCompleteTests() { export function runTests(serverReadyPromise: Promise) { test(async function serveFile() { await serverReadyPromise; - const res = await fetch("http://localhost:4500/.travis.yml"); + const res = await fetch("http://localhost:4500/azure-pipelines.yml"); assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-headers")); assertEqual(res.headers.get("content-type"), "text/yaml"); const downloadedFile = await res.text(); - const localFile = new TextDecoder().decode(await readFile("./.travis.yml")); + const localFile = new TextDecoder().decode(await readFile("./azure-pipelines.yml")); assertEqual(downloadedFile, localFile); maybeCompleteTests(); }); @@ -38,7 +38,7 @@ export function runTests(serverReadyPromise: Promise) { assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-headers")); const page = await res.text(); - assert(page.includes(".travis.yml")); + assert(page.includes("azure-pipelines.yml")); maybeCompleteTests(); }); -- cgit v1.2.3 From d8ea4629c8b228f800f6400f62d7ae0daa5ed9fe Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 3 Jan 2019 23:13:21 -0500 Subject: First pass on style guide (denoland/deno_std#66) Original: https://github.com/denoland/deno_std/commit/2916791dfb14bf486185eca6c7859b49c1c4c052 --- README.md | 120 ++++++++++++++++++++++++++++++++++++++++++++++++++----- colors/README.md | 4 +- 2 files changed, 111 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 999a09331..fce2c870f 100644 --- a/README.md +++ b/README.md @@ -2,37 +2,135 @@ [![Build Status](https://dev.azure.com/denoland/deno_std/_apis/build/status/denoland.deno_std?branchName=master)](https://dev.azure.com/denoland/deno_std/_build/latest?definitionId=2?branchName=master) -This repository contains collections of modules that create a standard library -for Deno. - -* **[colors](./colors/)** +- **[colors](./colors/)** Modules that generate ANSI color codes for the console. -* **[flags](./flags/)** +- **[flags](./flags/)** Command line arguments parser. -* **[logging](./logging/)** +- **[logging](./logging/)** Command line logging -* **[mkdirp](./mkdirp/)** +- **[mkdirp](./mkdirp/)** - Make directory branches. + Make directory branches. -* **[net](./net/)** +- **[net](./net/)** A framework for creating HTTP/HTTPS servers inspired by GoLang. -* **[path](./path/)** +- **[path](./path/)** File path manipulation. -* **[testing](./testing/)** +- **[testing](./testing/)** Testing +## Style Guide + +### Use the term "module" instead of "library" or "package" + +For clarity and consistency avoid the terms "library" and "package". Instead use +"module" to refer to a single JS or TS file and also to refer to a directory of +TS/JS code. + +### Use the filename "mod.ts" as the default entry point to a directory of code + +`index.ts` comes with the wrong connotations - and `main.ts` should be reserved +for executable programs. The filename `mod.ts` follows Rust’s convention, is +shorter than `index.ts`, and doesn’t come with any preconceived notions about +how it might work. + +### Within `deno_std`, do not depend on external code + +`deno_std` is intended to be baseline functionality that all Deno programs can +rely on. We want to guarantee to users that this code does not include +potentially unreviewed third party code. + +### Within `deno_std`, minimize dependencies; do not make circular imports. + +Although `deno_std` is a standalone codebase, we must still be careful to keep +the internal dependencies simple and manageable. In particular, be careful to +not to introduce circular imports. + +### For consistency, use underscores, not dashes in filenames. + +Example: Instead of `file-server.ts` use `file_server.ts`. + +### Format code according using prettier. + +More specifically, code should be wrapped at 80 columns and use 2-space +indentation and use camel-case. Use `//format.ts` to invoke prettier. + +### Use JS Doc to document exported machinery + +We strive for complete documentation. Every exported symbol ideally should have +a documentation line. + +If possible, use a single line for the JS Doc. Example: + +```ts +/** foo does bar. */ +export function foo() { + // ... +} +``` + +See [CONTRIBUTING.md](https://github.com/denoland/deno/blob/master/.github/CONTRIBUTING.md#documenting-apis) +for more details. + +### TODO Comments + +TODO comments should be include an issue or the author's github username in +parentheses. Example: + +``` +// TODO(ry) Add tests. +// TODO(#123) Support Windows. +``` + +### Copyright headers + +Most files in `deno_std` should have the following copyright header: + +``` +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +``` + +If the code originates elsewhere, ensure that the file has the proper copyright +headers. We only allows MIT, BSD, and Apache licensed code in `deno_std`. + +### Top level functions should not use arrow syntax + +Top level functions should use the `function` keyword. Arrow syntax should be +limited to closures. + +Bad + +``` +export const foo(): string => { + return "bar"; +} +``` + +Good + +``` +export function foo(): string { + return "bar"; +} +``` + +### When referencing Deno online, use the #denoland tag. + +The name "deno" unfortunately is not especially unique on the internet. In order +to centralize the community, please tag github project, tweet, and other content +with `#denoland`. + --- Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. diff --git a/colors/README.md b/colors/README.md index 72845b092..eafdbb9c1 100644 --- a/colors/README.md +++ b/colors/README.md @@ -1,7 +1,7 @@ # colors -Is a basic console color library intended for [Deno](https://deno.land/). It is -inspired by packages like [chalk](https://www.npmjs.com/package/chalk) and +Is a basic console color module intended for [Deno](https://deno.land/). It is +inspired by [chalk](https://www.npmjs.com/package/chalk) and [colors](https://www.npmjs.com/package/colors) on npm. ## Usage -- cgit v1.2.3 From 9e19717d756e43ab67668532eac50891a2f58cb3 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Fri, 4 Jan 2019 03:39:53 -0500 Subject: Remove logging's flaky basicTest (denoland/deno_std#83) Original: https://github.com/denoland/deno_std/commit/6754d468d8806e467edc3690fb02c1a587d02a26 --- logging/test.ts | 55 ------------------------------------------------------- 1 file changed, 55 deletions(-) diff --git a/logging/test.ts b/logging/test.ts index b96a046dd..a3c0b7199 100644 --- a/logging/test.ts +++ b/logging/test.ts @@ -27,58 +27,3 @@ test(function testDefaultlogMethods() { console.log(logger); }); -test(async function basicTest() { - const testFile = './log.txt'; - - await log.setup({ - handlers: { - debug: new TestHandler("DEBUG"), - info: new TestHandler("INFO"), - file: new FileHandler("DEBUG", testFile), - }, - - loggers: { - foo: { - level: "DEBUG", - handlers: ["debug", "file"] - }, - - bar: { - level: "INFO", - handlers: ["info"] - } - } - }); - - const fooLogger = log.getLogger("foo"); - const barLogger = log.getLogger("bar"); - const bazzLogger = log.getLogger("bazz"); - - - fooLogger.debug("I should be logged."); - fooLogger.debug("I should be logged."); - barLogger.debug("I should not be logged."); - barLogger.info("And I should be logged as well."); - bazzLogger.critical("I shouldn't be logged neither.") - - const expectedOutput = - "DEBUG I should be logged.\n" + - "DEBUG I should be logged.\n" + - "INFO And I should be logged as well.\n"; - - // TODO(ry) Re-enable this test. Disabled because it was failing on Linux. - // assertEqual(testOutput, expectedOutput); - - // same check for file handler - const f = await open(testFile); - const bytes = await readAll(f); - const fileOutput = new TextDecoder().decode(bytes); - await f.close(); - await remove(testFile); - - const fileExpectedOutput = - "DEBUG I should be logged.\n" + - "DEBUG I should be logged.\n"; - - assertEqual(fileOutput, fileExpectedOutput); -}); -- cgit v1.2.3 From f918e3faac851eedaa12b785597debb20117cc81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E6=9D=89?= Date: Fri, 4 Jan 2019 18:09:42 +0800 Subject: fix(testing): readme import url (denoland/deno_std#81) Original: https://github.com/denoland/deno_std/commit/9d3d90560c92be4f080f984209a7ffd5a4bbb920 --- testing/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/testing/README.md b/testing/README.md index 919b1279b..f9f47eaa6 100644 --- a/testing/README.md +++ b/testing/README.md @@ -3,7 +3,7 @@ ## Usage ```ts -import { test, assert, equal, assertEqual } from 'https://deno.land/x/testing/testing.ts'; +import { test, assert, equal, assertEqual } from 'https://deno.land/x/testing/mod.ts'; test({ name: 'testing example', @@ -28,4 +28,4 @@ test(function example() { assertEqual("world", "world"); assertEqual({hello: "world"}, {hello: "world"}); }); -``` \ No newline at end of file +``` -- cgit v1.2.3 From ed80bcb02a1ca92ca603e5986e83b6ebe030f22e Mon Sep 17 00:00:00 2001 From: Satya Rohith Date: Fri, 4 Jan 2019 15:40:57 +0530 Subject: docs(readme): fix small typo (denoland/deno_std#82) Original: https://github.com/denoland/deno_std/commit/e504e545249c12b64b0e7e0ffe0706170a884b70 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fce2c870f..3a2788333 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ Most files in `deno_std` should have the following copyright header: ``` If the code originates elsewhere, ensure that the file has the proper copyright -headers. We only allows MIT, BSD, and Apache licensed code in `deno_std`. +headers. We only allow MIT, BSD, and Apache licensed code in `deno_std`. ### Top level functions should not use arrow syntax -- cgit v1.2.3 From 7879a8515f213b3501826777557a9b67442e1fcb Mon Sep 17 00:00:00 2001 From: Srijan Reddy Date: Fri, 4 Jan 2019 19:45:43 +0530 Subject: Azure windows pipeline (denoland/deno_std#85) Fixes denoland/deno_std#34 Original: https://github.com/denoland/deno_std/commit/2ece847a82bd06eb8810950b3064070135d2d94d --- azure-pipelines.yml | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 267f5828a..eb48fd579 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -19,11 +19,10 @@ jobs: - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' - script: deno test.ts --allow-run --allow-net --allow-write -# TODO Windows is broken on a bug: https://github.com/denoland/deno/issues/1384 -#- job: 'Windows' -# pool: -# vmImage: 'vs2017-win2016' -# steps: -# - powershell: iex (iwr https://deno.land/x/install/install.ps1) -# - script: echo '##vso[task.prependpath]C:\Users\VssAdministrator\.deno\bin\' -# - script: 'C:\Users\VssAdministrator\.deno\bin\deno.exe test.ts --allow-run --allow-net --allow-write' +- job: 'Windows' + pool: + vmImage: 'vs2017-win2016' + steps: + - powershell: iex (iwr https://deno.land/x/install/install.ps1) + - script: echo '##vso[task.prependpath]C:\Users\VssAdministrator\.deno\bin\' + - script: 'C:\Users\VssAdministrator\.deno\bin\deno.exe test.ts --allow-run --allow-net --allow-write' -- cgit v1.2.3 From 7c62da8975be64d499a3df47af75eebdee996a35 Mon Sep 17 00:00:00 2001 From: Masashi Hirano Date: Sat, 5 Jan 2019 01:59:50 +0900 Subject: Fix to use unknown type in testing/mod.ts (denoland/deno_std#73) Original: https://github.com/denoland/deno_std/commit/8221924d9a814eb8d644b2f47e57687134341cc8 --- testing/mod.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/testing/mod.ts b/testing/mod.ts index f33e743fc..2200020f6 100644 --- a/testing/mod.ts +++ b/testing/mod.ts @@ -35,11 +35,9 @@ export function assert(expr: boolean, msg = "") { } } -// TODO(ry) Use unknown here for parameters types. -// tslint:disable-next-line:no-any -export function equal(c: any, d: any): boolean { +export function equal(c: unknown, d: unknown): boolean { const seen = new Map(); - return (function compare(a, b) { + return (function compare(a: unknown, b: unknown) { if (Object.is(a, b)) { return true; } @@ -47,11 +45,13 @@ export function equal(c: any, d: any): boolean { if (seen.get(a) === b) { return true; } - if (Object.keys(a).length !== Object.keys(b).length) { + if (Object.keys(a || {}).length !== Object.keys(b || {}).length) { return false; } - for (const key in { ...a, ...b }) { - if (!compare(a[key], b[key])) { + const merged = { ...a, ...b }; + for (const key in merged) { + type Key = keyof typeof merged; + if (!compare(a && a[key as Key], b && b[key as Key])) { return false; } } -- cgit v1.2.3 From 68584f983e4b1cf81d84cdb57bb5459127293cd2 Mon Sep 17 00:00:00 2001 From: Srijan Reddy Date: Sat, 5 Jan 2019 20:28:18 +0530 Subject: Windows CI should use a fixed version of deno (denoland/deno_std#89) Original: https://github.com/denoland/deno_std/commit/4e12c2b4d2b8e16deb345c993611b56fc8497fd8 --- azure-pipelines.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index eb48fd579..ed28b9c2a 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -23,6 +23,6 @@ jobs: pool: vmImage: 'vs2017-win2016' steps: - - powershell: iex (iwr https://deno.land/x/install/install.ps1) + - powershell: iwr https://deno.land/x/install/install.ps1 -Outfile 'install.ps1'; ./install.ps1 $(DENO_VERSION) - script: echo '##vso[task.prependpath]C:\Users\VssAdministrator\.deno\bin\' - script: 'C:\Users\VssAdministrator\.deno\bin\deno.exe test.ts --allow-run --allow-net --allow-write' -- cgit v1.2.3 From c164e696d7f924fe785421058d834934b7014429 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Sun, 6 Jan 2019 14:19:15 -0500 Subject: Fix format globs (denoland/deno_std#87) Original: https://github.com/denoland/deno_std/commit/297cf0975eca194a677e6fadd7d753d62eb453c3 --- format.ts | 6 +++++- logging/handlers.ts | 13 +++++-------- logging/index.ts | 34 +++++++++++++++++++++------------- logging/logger.ts | 10 +++++----- logging/test.ts | 3 +-- net/bufio_test.ts | 6 +----- net/file_server_test.ts | 10 ++++------ net/http_test.ts | 6 +----- net/textproto_test.ts | 6 +----- testing/README.md | 18 ++++++++++++------ 10 files changed, 56 insertions(+), 56 deletions(-) diff --git a/format.ts b/format.ts index c11d4e7b9..f1fa19e23 100755 --- a/format.ts +++ b/format.ts @@ -27,7 +27,11 @@ async function main() { await checkVersion(); const prettier = run({ - args: ["bash", "-c", "prettier --write *.ts */**/*.ts *.md */**/*.md"] + args: [ + "bash", + "-c", + "prettier --write *.ts */*.ts */**/*.ts *.md */**/*.md" + ] }); const s = await prettier.status(); exit(s.code); diff --git a/logging/handlers.ts b/logging/handlers.ts index 747cf6bc1..a0163e6cd 100644 --- a/logging/handlers.ts +++ b/logging/handlers.ts @@ -20,19 +20,17 @@ export class BaseHandler { return this.log(msg); } - log(msg: string) { } - async setup() { } - async destroy() { } + log(msg: string) {} + async setup() {} + async destroy() {} } - export class ConsoleHandler extends BaseHandler { log(msg: string) { console.log(msg); } } - export abstract class WriterHandler extends BaseHandler { protected _writer: Writer; @@ -43,7 +41,6 @@ export abstract class WriterHandler extends BaseHandler { } } - export class FileHandler extends WriterHandler { private _file: File; private _filename: string; @@ -55,11 +52,11 @@ export class FileHandler extends WriterHandler { async setup() { // open file in append mode - write only - this._file = await open(this._filename, 'a'); + this._file = await open(this._filename, "a"); this._writer = this._file; } async destroy() { await this._file.close(); } -} \ No newline at end of file +} diff --git a/logging/index.ts b/logging/index.ts index 2b2394043..e8c762ac6 100644 --- a/logging/index.ts +++ b/logging/index.ts @@ -1,5 +1,10 @@ import { Logger } from "./logger.ts"; -import { BaseHandler, ConsoleHandler, WriterHandler, FileHandler } from "./handlers.ts"; +import { + BaseHandler, + ConsoleHandler, + WriterHandler, + FileHandler +} from "./handlers.ts"; export class LoggerConfig { level?: string; @@ -18,14 +23,12 @@ export interface LogConfig { const DEFAULT_LEVEL = "INFO"; const DEFAULT_NAME = ""; const DEFAULT_CONFIG: LogConfig = { - handlers: { - - }, + handlers: {}, loggers: { "": { level: "INFO", - handlers: [""], + handlers: [""] } } }; @@ -38,21 +41,26 @@ const state = { defaultLogger, handlers: new Map(), loggers: new Map(), - config: DEFAULT_CONFIG, + config: DEFAULT_CONFIG }; export const handlers = { BaseHandler, ConsoleHandler, WriterHandler, - FileHandler, + FileHandler }; -export const debug = (msg: string, ...args: any[]) => defaultLogger.debug(msg, ...args); -export const info = (msg: string, ...args: any[]) => defaultLogger.info(msg, ...args); -export const warning = (msg: string, ...args: any[]) => defaultLogger.warning(msg, ...args); -export const error = (msg: string, ...args: any[]) => defaultLogger.error(msg, ...args); -export const critical = (msg: string, ...args: any[]) => defaultLogger.critical(msg, ...args); +export const debug = (msg: string, ...args: any[]) => + defaultLogger.debug(msg, ...args); +export const info = (msg: string, ...args: any[]) => + defaultLogger.info(msg, ...args); +export const warning = (msg: string, ...args: any[]) => + defaultLogger.warning(msg, ...args); +export const error = (msg: string, ...args: any[]) => + defaultLogger.error(msg, ...args); +export const critical = (msg: string, ...args: any[]) => + defaultLogger.critical(msg, ...args); export function getLogger(name?: string) { if (!name) { @@ -108,4 +116,4 @@ export async function setup(config: LogConfig) { } } -setup(DEFAULT_CONFIG); \ No newline at end of file +setup(DEFAULT_CONFIG); diff --git a/logging/logger.ts b/logging/logger.ts index 798181599..9f34f9c32 100644 --- a/logging/logger.ts +++ b/logging/logger.ts @@ -7,7 +7,7 @@ export interface LogRecord { datetime: Date; level: number; levelName: string; -}; +} export class Logger { level: number; @@ -17,14 +17,14 @@ export class Logger { constructor(levelName: string, handlers?: BaseHandler[]) { this.level = getLevelByName(levelName); this.levelName = levelName; - + this.handlers = handlers || []; } _log(level: number, msg: string, ...args: any[]) { if (this.level > level) return; - // TODO: it'd be a good idea to make it immutable, so + // TODO: it'd be a good idea to make it immutable, so // no handler mangles it by mistake // TODO: iterpolate msg with values const record: LogRecord = { @@ -32,8 +32,8 @@ export class Logger { args: args, datetime: new Date(), level: level, - levelName: getLevelName(level), - } + levelName: getLevelName(level) + }; this.handlers.forEach(handler => { handler.handle(record); diff --git a/logging/test.ts b/logging/test.ts index a3c0b7199..17117ae8b 100644 --- a/logging/test.ts +++ b/logging/test.ts @@ -23,7 +23,6 @@ test(function testDefaultlogMethods() { log.error("Foobar"); log.critical("Foobar"); - const logger = log.getLogger(''); + const logger = log.getLogger(""); console.log(logger); }); - diff --git a/net/bufio_test.ts b/net/bufio_test.ts index 411f173f4..fa8f4b73b 100644 --- a/net/bufio_test.ts +++ b/net/bufio_test.ts @@ -4,11 +4,7 @@ // license that can be found in the LICENSE file. import { Buffer, Reader, ReadResult } from "deno"; -import { - test, - assert, - assertEqual -} from "../testing/mod.ts"; +import { test, assert, assertEqual } from "../testing/mod.ts"; import { BufReader, BufState, BufWriter } from "./bufio.ts"; import * as iotest from "./iotest.ts"; import { charCode, copyBytes, stringsReader } from "./util.ts"; diff --git a/net/file_server_test.ts b/net/file_server_test.ts index e0abb1cf1..28357c912 100644 --- a/net/file_server_test.ts +++ b/net/file_server_test.ts @@ -1,10 +1,6 @@ import { readFile } from "deno"; -import { - test, - assert, - assertEqual -} from "../testing/mod.ts"; +import { test, assert, assertEqual } from "../testing/mod.ts"; // Promise to completeResolve when all tests completes let completeResolve; @@ -27,7 +23,9 @@ export function runTests(serverReadyPromise: Promise) { assert(res.headers.has("access-control-allow-headers")); assertEqual(res.headers.get("content-type"), "text/yaml"); const downloadedFile = await res.text(); - const localFile = new TextDecoder().decode(await readFile("./azure-pipelines.yml")); + const localFile = new TextDecoder().decode( + await readFile("./azure-pipelines.yml") + ); assertEqual(downloadedFile, localFile); maybeCompleteTests(); }); diff --git a/net/http_test.ts b/net/http_test.ts index 46ea60185..9235feb02 100644 --- a/net/http_test.ts +++ b/net/http_test.ts @@ -6,11 +6,7 @@ // https://github.com/golang/go/blob/master/src/net/http/responsewrite_test.go import { Buffer } from "deno"; -import { - test, - assert, - assertEqual -} from "../testing/mod.ts"; +import { test, assert, assertEqual } from "../testing/mod.ts"; import { listenAndServe, ServerRequest, diff --git a/net/textproto_test.ts b/net/textproto_test.ts index 9fe5e8dd3..e0ae0749c 100644 --- a/net/textproto_test.ts +++ b/net/textproto_test.ts @@ -6,11 +6,7 @@ import { BufReader } from "./bufio.ts"; import { TextProtoReader, append } from "./textproto.ts"; import { stringsReader } from "./util.ts"; -import { - test, - assert, - assertEqual -} from "../testing/mod.ts"; +import { test, assert, assertEqual } from "../testing/mod.ts"; function reader(s: string): TextProtoReader { return new TextProtoReader(new BufReader(stringsReader(s))); diff --git a/testing/README.md b/testing/README.md index f9f47eaa6..70968e3c7 100644 --- a/testing/README.md +++ b/testing/README.md @@ -1,24 +1,30 @@ -# Testing +# Testing ## Usage ```ts -import { test, assert, equal, assertEqual } from 'https://deno.land/x/testing/mod.ts'; +import { + test, + assert, + equal, + assertEqual +} from "https://deno.land/x/testing/mod.ts"; test({ - name: 'testing example', + name: "testing example", fn() { assert(equal("world", "world")); assert(!equal("hello", "world")); assert(equal({ hello: "world" }, { hello: "world" })); assert(!equal({ world: "hello" }, { hello: "world" })); assertEqual("world", "world"); - assertEqual({hello: "world"}, {hello: "world"}); - }, + assertEqual({ hello: "world" }, { hello: "world" }); + } }); ``` Short syntax (named function instead of object): + ```ts test(function example() { assert(equal("world", "world")); @@ -26,6 +32,6 @@ test(function example() { assert(equal({ hello: "world" }, { hello: "world" })); assert(!equal({ world: "hello" }, { hello: "world" })); assertEqual("world", "world"); - assertEqual({hello: "world"}, {hello: "world"}); + assertEqual({ hello: "world" }, { hello: "world" }); }); ``` -- cgit v1.2.3 From 7907bfc4c91f5287237d87571d1933db4ae7a4fa Mon Sep 17 00:00:00 2001 From: Yusuke Sakurai Date: Mon, 7 Jan 2019 04:26:18 +0900 Subject: Add web socket module (denoland/deno_std#84) Original: https://github.com/denoland/deno_std/commit/2606e295c77fb9d5796d527ed15f2dab3de1a696 --- examples/ws.ts | 39 ++++++ net/ioutil.ts | 36 +++++ net/ioutil_test.ts | 62 +++++++++ net/sha1.ts | 382 +++++++++++++++++++++++++++++++++++++++++++++++++++++ net/sha1_test.ts | 8 ++ net/ws.ts | 350 ++++++++++++++++++++++++++++++++++++++++++++++++ net/ws_test.ts | 138 +++++++++++++++++++ 7 files changed, 1015 insertions(+) create mode 100644 examples/ws.ts create mode 100644 net/ioutil.ts create mode 100644 net/ioutil_test.ts create mode 100644 net/sha1.ts create mode 100644 net/sha1_test.ts create mode 100644 net/ws.ts create mode 100644 net/ws_test.ts diff --git a/examples/ws.ts b/examples/ws.ts new file mode 100644 index 000000000..f8e711c49 --- /dev/null +++ b/examples/ws.ts @@ -0,0 +1,39 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { serve } from "https://deno.land/x/net/http.ts"; +import { + acceptWebSocket, + isWebSocketCloseEvent, + isWebSocketPingEvent +} from "https://deno.land/x/net/ws.ts"; + +async function main() { + console.log("websocket server is running on 0.0.0.0:8080"); + for await (const req of serve("0.0.0.0:8080")) { + if (req.url === "/ws") { + (async () => { + const sock = await acceptWebSocket(req); + console.log("socket connected!"); + for await (const ev of sock.receive()) { + if (typeof ev === "string") { + // text message + console.log("ws:Text", ev); + await sock.send(ev); + } else if (ev instanceof Uint8Array) { + // binary message + console.log("ws:Binary", ev); + } else if (isWebSocketPingEvent(ev)) { + const [_, body] = ev; + // ping + console.log("ws:Ping", body); + } else if (isWebSocketCloseEvent(ev)) { + // close + const { code, reason } = ev; + console.log("ws:Close", code, reason); + } + } + })(); + } + } +} + +main(); diff --git a/net/ioutil.ts b/net/ioutil.ts new file mode 100644 index 000000000..68d6e5190 --- /dev/null +++ b/net/ioutil.ts @@ -0,0 +1,36 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { BufReader } from "./bufio.ts"; + +/* Read big endian 16bit short from BufReader */ +export async function readShort(buf: BufReader): Promise { + const [high, low] = [await buf.readByte(), await buf.readByte()]; + return (high << 8) | low; +} + +/* Read big endian 32bit integer from BufReader */ +export async function readInt(buf: BufReader): Promise { + const [high, low] = [await readShort(buf), await readShort(buf)]; + return (high << 16) | low; +} + +const BIT32 = 0xffffffff; +/* Read big endian 64bit long from BufReader */ +export async function readLong(buf: BufReader): Promise { + const [high, low] = [await readInt(buf), await readInt(buf)]; + // ECMAScript doesn't support 64bit bit ops. + return high ? high * (BIT32 + 1) + low : low; +} + +/* Slice number into 64bit big endian byte array */ +export function sliceLongToBytes(d: number, dest = new Array(8)): number[] { + let mask = 0xff; + let low = (d << 32) >>> 32; + let high = (d - low) / (BIT32 + 1); + let shift = 24; + for (let i = 0; i < 4; i++) { + dest[i] = (high >>> shift) & mask; + dest[i + 4] = (low >>> shift) & mask; + shift -= 8; + } + return dest; +} diff --git a/net/ioutil_test.ts b/net/ioutil_test.ts new file mode 100644 index 000000000..422901e4a --- /dev/null +++ b/net/ioutil_test.ts @@ -0,0 +1,62 @@ +import { Reader, ReadResult } from "deno"; +import { assertEqual, test } from "../testing/mod.ts"; +import { readInt, readLong, readShort, sliceLongToBytes } from "./ioutil.ts"; +import { BufReader } from "./bufio.ts"; + +class BinaryReader implements Reader { + index = 0; + + constructor(private bytes: Uint8Array = new Uint8Array(0)) {} + + async read(p: Uint8Array): Promise { + p.set(this.bytes.subarray(this.index, p.byteLength)); + this.index += p.byteLength; + return { nread: p.byteLength, eof: false }; + } +} + +test(async function testReadShort() { + const r = new BinaryReader(new Uint8Array([0x12, 0x34])); + const short = await readShort(new BufReader(r)); + assertEqual(short, 0x1234); +}); + +test(async function testReadInt() { + const r = new BinaryReader(new Uint8Array([0x12, 0x34, 0x56, 0x78])); + const int = await readInt(new BufReader(r)); + assertEqual(int, 0x12345678); +}); + +test(async function testReadLong() { + const r = new BinaryReader( + new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78]) + ); + const long = await readLong(new BufReader(r)); + assertEqual(long, 0x1234567812345678); +}); + +test(async function testReadLong2() { + const r = new BinaryReader( + new Uint8Array([0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]) + ); + const long = await readLong(new BufReader(r)); + assertEqual(long, 0x12345678); +}); + +test(async function testSliceLongToBytes() { + const arr = sliceLongToBytes(0x1234567890abcdef); + const actual = readLong(new BufReader(new BinaryReader(new Uint8Array(arr)))); + const expected = readLong( + new BufReader( + new BinaryReader( + new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]) + ) + ) + ); + assertEqual(actual, expected); +}); + +test(async function testSliceLongToBytes2() { + const arr = sliceLongToBytes(0x12345678); + assertEqual(arr, [0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]); +}); diff --git a/net/sha1.ts b/net/sha1.ts new file mode 100644 index 000000000..036c3c552 --- /dev/null +++ b/net/sha1.ts @@ -0,0 +1,382 @@ +/* + * [js-sha1]{@link https://github.com/emn178/js-sha1} + * + * @version 0.6.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2014-2017 + * @license MIT + */ +/*jslint bitwise: true */ + +const HEX_CHARS = "0123456789abcdef".split(""); +const EXTRA = [-2147483648, 8388608, 32768, 128]; +const SHIFT = [24, 16, 8, 0]; + +const blocks = []; + +export class Sha1 { + blocks; + block; + start; + bytes; + hBytes; + finalized; + hashed; + first; + + h0 = 0x67452301; + h1 = 0xefcdab89; + h2 = 0x98badcfe; + h3 = 0x10325476; + h4 = 0xc3d2e1f0; + lastByteIndex = 0; + + constructor(sharedMemory: boolean = false) { + if (sharedMemory) { + blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + this.blocks = blocks; + } else { + this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } + + this.h0 = 0x67452301; + this.h1 = 0xefcdab89; + this.h2 = 0x98badcfe; + this.h3 = 0x10325476; + this.h4 = 0xc3d2e1f0; + + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; + } + + update(data: string | ArrayBuffer) { + if (this.finalized) { + return; + } + let message; + let notString = typeof data !== "string"; + if (notString && data instanceof ArrayBuffer) { + message = new Uint8Array(data); + } else { + message = data; + } + let code, + index = 0, + i, + length = message.length || 0, + blocks = this.blocks; + + while (index < length) { + if (this.hashed) { + this.hashed = false; + blocks[0] = this.block; + blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + } + + if (notString) { + for (i = this.start; index < length && i < 64; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else { + code = + 0x10000 + + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + } + } + + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } else { + this.start = i; + } + } + if (this.bytes > 4294967295) { + this.hBytes += (this.bytes / 4294967296) << 0; + this.bytes = this.bytes % 4294967296; + } + return this; + } + + finalize() { + if (this.finalized) { + return; + } + this.finalized = true; + let blocks = this.blocks, + i = this.lastByteIndex; + blocks[16] = this.block; + blocks[i >> 2] |= EXTRA[i & 3]; + this.block = blocks[16]; + if (i >= 56) { + if (!this.hashed) { + this.hash(); + } + blocks[0] = this.block; + blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + } + blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29); + blocks[15] = this.bytes << 3; + this.hash(); + } + + hash() { + let a = this.h0, + b = this.h1, + c = this.h2, + d = this.h3, + e = this.h4; + let f, + j, + t, + blocks = this.blocks; + + for (j = 16; j < 80; ++j) { + t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16]; + blocks[j] = (t << 1) | (t >>> 31); + } + + for (j = 0; j < 20; j += 5) { + f = (b & c) | (~b & d); + t = (a << 5) | (a >>> 27); + e = (t + f + e + 1518500249 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + + f = (a & b) | (~a & c); + t = (e << 5) | (e >>> 27); + d = (t + f + d + 1518500249 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + + f = (e & a) | (~e & b); + t = (d << 5) | (d >>> 27); + c = (t + f + c + 1518500249 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + + f = (d & e) | (~d & a); + t = (c << 5) | (c >>> 27); + b = (t + f + b + 1518500249 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + + f = (c & d) | (~c & e); + t = (b << 5) | (b >>> 27); + a = (t + f + a + 1518500249 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + + for (; j < 40; j += 5) { + f = b ^ c ^ d; + t = (a << 5) | (a >>> 27); + e = (t + f + e + 1859775393 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + + f = a ^ b ^ c; + t = (e << 5) | (e >>> 27); + d = (t + f + d + 1859775393 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + + f = e ^ a ^ b; + t = (d << 5) | (d >>> 27); + c = (t + f + c + 1859775393 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + + f = d ^ e ^ a; + t = (c << 5) | (c >>> 27); + b = (t + f + b + 1859775393 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + + f = c ^ d ^ e; + t = (b << 5) | (b >>> 27); + a = (t + f + a + 1859775393 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + + for (; j < 60; j += 5) { + f = (b & c) | (b & d) | (c & d); + t = (a << 5) | (a >>> 27); + e = (t + f + e - 1894007588 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + + f = (a & b) | (a & c) | (b & c); + t = (e << 5) | (e >>> 27); + d = (t + f + d - 1894007588 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + + f = (e & a) | (e & b) | (a & b); + t = (d << 5) | (d >>> 27); + c = (t + f + c - 1894007588 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + + f = (d & e) | (d & a) | (e & a); + t = (c << 5) | (c >>> 27); + b = (t + f + b - 1894007588 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + + f = (c & d) | (c & e) | (d & e); + t = (b << 5) | (b >>> 27); + a = (t + f + a - 1894007588 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + + for (; j < 80; j += 5) { + f = b ^ c ^ d; + t = (a << 5) | (a >>> 27); + e = (t + f + e - 899497514 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + + f = a ^ b ^ c; + t = (e << 5) | (e >>> 27); + d = (t + f + d - 899497514 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + + f = e ^ a ^ b; + t = (d << 5) | (d >>> 27); + c = (t + f + c - 899497514 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + + f = d ^ e ^ a; + t = (c << 5) | (c >>> 27); + b = (t + f + b - 899497514 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + + f = c ^ d ^ e; + t = (b << 5) | (b >>> 27); + a = (t + f + a - 899497514 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + + this.h0 = (this.h0 + a) << 0; + this.h1 = (this.h1 + b) << 0; + this.h2 = (this.h2 + c) << 0; + this.h3 = (this.h3 + d) << 0; + this.h4 = (this.h4 + e) << 0; + } + + hex() { + this.finalize(); + + let h0 = this.h0, + h1 = this.h1, + h2 = this.h2, + h3 = this.h3, + h4 = this.h4; + + return ( + HEX_CHARS[(h0 >> 28) & 0x0f] + + HEX_CHARS[(h0 >> 24) & 0x0f] + + HEX_CHARS[(h0 >> 20) & 0x0f] + + HEX_CHARS[(h0 >> 16) & 0x0f] + + HEX_CHARS[(h0 >> 12) & 0x0f] + + HEX_CHARS[(h0 >> 8) & 0x0f] + + HEX_CHARS[(h0 >> 4) & 0x0f] + + HEX_CHARS[h0 & 0x0f] + + HEX_CHARS[(h1 >> 28) & 0x0f] + + HEX_CHARS[(h1 >> 24) & 0x0f] + + HEX_CHARS[(h1 >> 20) & 0x0f] + + HEX_CHARS[(h1 >> 16) & 0x0f] + + HEX_CHARS[(h1 >> 12) & 0x0f] + + HEX_CHARS[(h1 >> 8) & 0x0f] + + HEX_CHARS[(h1 >> 4) & 0x0f] + + HEX_CHARS[h1 & 0x0f] + + HEX_CHARS[(h2 >> 28) & 0x0f] + + HEX_CHARS[(h2 >> 24) & 0x0f] + + HEX_CHARS[(h2 >> 20) & 0x0f] + + HEX_CHARS[(h2 >> 16) & 0x0f] + + HEX_CHARS[(h2 >> 12) & 0x0f] + + HEX_CHARS[(h2 >> 8) & 0x0f] + + HEX_CHARS[(h2 >> 4) & 0x0f] + + HEX_CHARS[h2 & 0x0f] + + HEX_CHARS[(h3 >> 28) & 0x0f] + + HEX_CHARS[(h3 >> 24) & 0x0f] + + HEX_CHARS[(h3 >> 20) & 0x0f] + + HEX_CHARS[(h3 >> 16) & 0x0f] + + HEX_CHARS[(h3 >> 12) & 0x0f] + + HEX_CHARS[(h3 >> 8) & 0x0f] + + HEX_CHARS[(h3 >> 4) & 0x0f] + + HEX_CHARS[h3 & 0x0f] + + HEX_CHARS[(h4 >> 28) & 0x0f] + + HEX_CHARS[(h4 >> 24) & 0x0f] + + HEX_CHARS[(h4 >> 20) & 0x0f] + + HEX_CHARS[(h4 >> 16) & 0x0f] + + HEX_CHARS[(h4 >> 12) & 0x0f] + + HEX_CHARS[(h4 >> 8) & 0x0f] + + HEX_CHARS[(h4 >> 4) & 0x0f] + + HEX_CHARS[h4 & 0x0f] + ); + } + + toString() { + return this.hex(); + } + + digest() { + this.finalize(); + + let h0 = this.h0, + h1 = this.h1, + h2 = this.h2, + h3 = this.h3, + h4 = this.h4; + + return [ + (h0 >> 24) & 0xff, + (h0 >> 16) & 0xff, + (h0 >> 8) & 0xff, + h0 & 0xff, + (h1 >> 24) & 0xff, + (h1 >> 16) & 0xff, + (h1 >> 8) & 0xff, + h1 & 0xff, + (h2 >> 24) & 0xff, + (h2 >> 16) & 0xff, + (h2 >> 8) & 0xff, + h2 & 0xff, + (h3 >> 24) & 0xff, + (h3 >> 16) & 0xff, + (h3 >> 8) & 0xff, + h3 & 0xff, + (h4 >> 24) & 0xff, + (h4 >> 16) & 0xff, + (h4 >> 8) & 0xff, + h4 & 0xff + ]; + } + + array() { + return this.digest(); + } + + arrayBuffer() { + this.finalize(); + + let buffer = new ArrayBuffer(20); + let dataView = new DataView(buffer); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + return buffer; + } +} diff --git a/net/sha1_test.ts b/net/sha1_test.ts new file mode 100644 index 000000000..1d3673c43 --- /dev/null +++ b/net/sha1_test.ts @@ -0,0 +1,8 @@ +import {assertEqual, test} from "../testing/mod.ts"; +import {Sha1} from "./sha1.ts"; + +test(function testSha1() { + const sha1 = new Sha1(); + sha1.update("abcde"); + assertEqual(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334") +}); diff --git a/net/ws.ts b/net/ws.ts new file mode 100644 index 000000000..5ce96b3ca --- /dev/null +++ b/net/ws.ts @@ -0,0 +1,350 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { Buffer, Writer, Conn } from "deno"; +import { ServerRequest } from "./http.ts"; +import { BufReader, BufWriter } from "./bufio.ts"; +import { readLong, readShort, sliceLongToBytes } from "./ioutil.ts"; +import { Sha1 } from "./sha1.ts"; + +export const OpCodeContinue = 0x0; +export const OpCodeTextFrame = 0x1; +export const OpCodeBinaryFrame = 0x2; +export const OpCodeClose = 0x8; +export const OpcodePing = 0x9; +export const OpcodePong = 0xa; + +export type WebSocketEvent = + | string + | Uint8Array + | WebSocketCloseEvent + | WebSocketPingEvent + | WebSocketPongEvent; + +export type WebSocketCloseEvent = { + code: number; + reason?: string; +}; + +export function isWebSocketCloseEvent(a): a is WebSocketCloseEvent { + return a && typeof a["code"] === "number"; +} + +export type WebSocketPingEvent = ["ping", Uint8Array]; + +export function isWebSocketPingEvent(a): a is WebSocketPingEvent { + return Array.isArray(a) && a[0] === "ping" && a[1] instanceof Uint8Array; +} + +export type WebSocketPongEvent = ["pong", Uint8Array]; + +export function isWebSocketPongEvent(a): a is WebSocketPongEvent { + return Array.isArray(a) && a[0] === "pong" && a[1] instanceof Uint8Array; +} + +export class SocketClosedError extends Error {} + +export type WebSocketFrame = { + isLastFrame: boolean; + opcode: number; + mask?: Uint8Array; + payload: Uint8Array; +}; + +export type WebSocket = { + readonly isClosed: boolean; + receive(): AsyncIterableIterator; + send(data: string | Uint8Array): Promise; + ping(data?: string | Uint8Array): Promise; + close(code: number, reason?: string): Promise; +}; + +class WebSocketImpl implements WebSocket { + encoder = new TextEncoder(); + constructor(private conn: Conn, private mask?: Uint8Array) {} + + async *receive(): AsyncIterableIterator { + let frames: WebSocketFrame[] = []; + let payloadsLength = 0; + for await (const frame of receiveFrame(this.conn)) { + unmask(frame.payload, frame.mask); + switch (frame.opcode) { + case OpCodeTextFrame: + case OpCodeBinaryFrame: + case OpCodeContinue: + frames.push(frame); + payloadsLength += frame.payload.length; + if (frame.isLastFrame) { + const concat = new Uint8Array(payloadsLength); + let offs = 0; + for (const frame of frames) { + concat.set(frame.payload, offs); + offs += frame.payload.length; + } + if (frames[0].opcode === OpCodeTextFrame) { + // text + yield new Buffer(concat).toString(); + } else { + // binary + yield concat; + } + frames = []; + payloadsLength = 0; + } + break; + case OpCodeClose: + const code = (frame.payload[0] << 16) | frame.payload[1]; + const reason = new Buffer( + frame.payload.subarray(2, frame.payload.length) + ).toString(); + this._isClosed = true; + yield { code, reason }; + return; + case OpcodePing: + yield ["ping", frame.payload] as WebSocketPingEvent; + break; + case OpcodePong: + yield ["pong", frame.payload] as WebSocketPongEvent; + break; + } + } + } + + async send(data: string | Uint8Array): Promise { + if (this.isClosed) { + throw new SocketClosedError("socket has been closed"); + } + const opcode = + typeof data === "string" ? OpCodeTextFrame : OpCodeBinaryFrame; + const payload = typeof data === "string" ? this.encoder.encode(data) : data; + const isLastFrame = true; + await writeFrame( + { + isLastFrame, + opcode, + payload, + mask: this.mask + }, + this.conn + ); + } + + async ping(data: string | Uint8Array): Promise { + const payload = typeof data === "string" ? this.encoder.encode(data) : data; + await writeFrame( + { + isLastFrame: true, + opcode: OpCodeClose, + mask: this.mask, + payload + }, + this.conn + ); + } + + private _isClosed = false; + get isClosed() { + return this._isClosed; + } + + async close(code: number, reason?: string): Promise { + try { + const header = [code >>> 8, code & 0x00ff]; + let payload: Uint8Array; + if (reason) { + const reasonBytes = this.encoder.encode(reason); + payload = new Uint8Array(2 + reasonBytes.byteLength); + payload.set(header); + payload.set(reasonBytes, 2); + } else { + payload = new Uint8Array(header); + } + await writeFrame( + { + isLastFrame: true, + opcode: OpCodeClose, + mask: this.mask, + payload + }, + this.conn + ); + } catch (e) { + throw e; + } finally { + this.ensureSocketClosed(); + } + } + + private ensureSocketClosed(): Error { + if (this.isClosed) return; + try { + this.conn.close(); + } catch (e) { + console.error(e); + } finally { + this._isClosed = true; + } + } +} + +export async function* receiveFrame( + conn: Conn +): AsyncIterableIterator { + let receiving = true; + const reader = new BufReader(conn); + while (receiving) { + const frame = await readFrame(reader); + switch (frame.opcode) { + case OpCodeTextFrame: + case OpCodeBinaryFrame: + case OpCodeContinue: + yield frame; + break; + case OpCodeClose: + await writeFrame( + { + isLastFrame: true, + opcode: OpCodeClose, + payload: frame.payload + }, + conn + ); + conn.close(); + yield frame; + receiving = false; + break; + case OpcodePing: + await writeFrame( + { + isLastFrame: true, + opcode: OpcodePong, + payload: frame.payload + }, + conn + ); + yield frame; + break; + case OpcodePong: + yield frame; + break; + } + } +} + +export async function writeFrame(frame: WebSocketFrame, writer: Writer) { + let payloadLength = frame.payload.byteLength; + let header: Uint8Array; + const hasMask = (frame.mask ? 1 : 0) << 7; + if (payloadLength < 126) { + header = new Uint8Array([ + (0b1000 << 4) | frame.opcode, + hasMask | payloadLength + ]); + } else if (payloadLength < 0xffff) { + header = new Uint8Array([ + (0b1000 << 4) | frame.opcode, + hasMask | 0b01111110, + payloadLength >>> 8, + payloadLength & 0x00ff + ]); + } else { + header = new Uint8Array([ + (0b1000 << 4) | frame.opcode, + hasMask | 0b01111111, + ...sliceLongToBytes(payloadLength) + ]); + } + if (frame.mask) { + unmask(frame.payload, frame.mask); + } + const bytes = new Uint8Array(header.length + payloadLength); + bytes.set(header, 0); + bytes.set(frame.payload, header.length); + const w = new BufWriter(writer); + await w.write(bytes); + await w.flush(); +} + +export function unmask(payload: Uint8Array, mask: Uint8Array) { + if (mask) { + for (let i = 0; i < payload.length; i++) { + payload[i] ^= mask[i % 4]; + } + } +} + +export function acceptable(req: ServerRequest): boolean { + return ( + req.headers.get("upgrade") === "websocket" && + req.headers.has("sec-websocket-key") + ); +} + +export async function acceptWebSocket(req: ServerRequest): Promise { + if (acceptable(req)) { + const sock = new WebSocketImpl(req.conn); + const secKey = req.headers.get("sec-websocket-key"); + const secAccept = createSecAccept(secKey); + await req.respond({ + status: 101, + headers: new Headers({ + Upgrade: "websocket", + Connection: "Upgrade", + "Sec-WebSocket-Accept": secAccept + }) + }); + return sock; + } + throw new Error("request is not acceptable"); +} + +const kGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + +export function createSecAccept(nonce: string) { + const sha1 = new Sha1(); + sha1.update(nonce + kGUID); + const bytes = sha1.digest(); + const hash = bytes.reduce( + (data, byte) => data + String.fromCharCode(byte), + "" + ); + return btoa(hash); +} + +export async function readFrame(buf: BufReader): Promise { + let b = await buf.readByte(); + let isLastFrame = false; + switch (b >>> 4) { + case 0b1000: + isLastFrame = true; + break; + case 0b0000: + isLastFrame = false; + break; + default: + throw new Error("invalid signature"); + } + const opcode = b & 0x0f; + // has_mask & payload + b = await buf.readByte(); + const hasMask = b >>> 7; + let payloadLength = b & 0b01111111; + if (payloadLength === 126) { + payloadLength = await readShort(buf); + } else if (payloadLength === 127) { + payloadLength = await readLong(buf); + } + // mask + let mask; + if (hasMask) { + mask = new Uint8Array(4); + await buf.readFull(mask); + } + // payload + const payload = new Uint8Array(payloadLength); + await buf.readFull(payload); + return { + isLastFrame, + opcode, + mask, + payload + }; +} diff --git a/net/ws_test.ts b/net/ws_test.ts new file mode 100644 index 000000000..62e5a6089 --- /dev/null +++ b/net/ws_test.ts @@ -0,0 +1,138 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { Buffer } from "deno"; +import { BufReader } from "./bufio.ts"; +import { test, assert, assertEqual } from "../testing/mod.ts"; +import { + createSecAccept, + OpCodeBinaryFrame, + OpCodeContinue, + OpcodePing, + OpcodePong, + OpCodeTextFrame, + readFrame, + unmask +} from "./ws.ts"; +import { serve } from "./http.ts"; + +test(async function testReadUnmaskedTextFrame() { + // unmasked single text frame with payload "Hello" + const buf = new BufReader( + new Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) + ); + const frame = await readFrame(buf); + assertEqual(frame.opcode, OpCodeTextFrame); + assertEqual(frame.mask, undefined); + assertEqual(new Buffer(frame.payload).toString(), "Hello"); + assertEqual(frame.isLastFrame, true); +}); + +test(async function testReadMakedTextFrame() { + //a masked single text frame with payload "Hello" + const buf = new BufReader( + new Buffer( + new Uint8Array([ + 0x81, + 0x85, + 0x37, + 0xfa, + 0x21, + 0x3d, + 0x7f, + 0x9f, + 0x4d, + 0x51, + 0x58 + ]) + ) + ); + const frame = await readFrame(buf); + console.dir(frame); + assertEqual(frame.opcode, OpCodeTextFrame); + unmask(frame.payload, frame.mask); + assertEqual(new Buffer(frame.payload).toString(), "Hello"); + assertEqual(frame.isLastFrame, true); +}); + +test(async function testReadUnmaskedSplittedTextFrames() { + const buf1 = new BufReader( + new Buffer(new Uint8Array([0x01, 0x03, 0x48, 0x65, 0x6c])) + ); + const buf2 = new BufReader( + new Buffer(new Uint8Array([0x80, 0x02, 0x6c, 0x6f])) + ); + const [f1, f2] = await Promise.all([readFrame(buf1), readFrame(buf2)]); + assertEqual(f1.isLastFrame, false); + assertEqual(f1.mask, undefined); + assertEqual(f1.opcode, OpCodeTextFrame); + assertEqual(new Buffer(f1.payload).toString(), "Hel"); + + assertEqual(f2.isLastFrame, true); + assertEqual(f2.mask, undefined); + assertEqual(f2.opcode, OpCodeContinue); + assertEqual(new Buffer(f2.payload).toString(), "lo"); +}); + +test(async function testReadUnmaksedPingPongFrame() { + // unmasked ping with payload "Hello" + const buf = new BufReader( + new Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) + ); + const ping = await readFrame(buf); + assertEqual(ping.opcode, OpcodePing); + assertEqual(new Buffer(ping.payload).toString(), "Hello"); + + const buf2 = new BufReader( + new Buffer( + new Uint8Array([ + 0x8a, + 0x85, + 0x37, + 0xfa, + 0x21, + 0x3d, + 0x7f, + 0x9f, + 0x4d, + 0x51, + 0x58 + ]) + ) + ); + const pong = await readFrame(buf2); + assertEqual(pong.opcode, OpcodePong); + assert(pong.mask !== undefined); + unmask(pong.payload, pong.mask); + assertEqual(new Buffer(pong.payload).toString(), "Hello"); +}); + +test(async function testReadUnmaksedBigBinaryFrame() { + let a = [0x82, 0x7e, 0x01, 0x00]; + for (let i = 0; i < 256; i++) { + a.push(i); + } + const buf = new BufReader(new Buffer(new Uint8Array(a))); + const bin = await readFrame(buf); + assertEqual(bin.opcode, OpCodeBinaryFrame); + assertEqual(bin.isLastFrame, true); + assertEqual(bin.mask, undefined); + assertEqual(bin.payload.length, 256); +}); + +test(async function testReadUnmaskedBigBigBinaryFrame() { + let a = [0x82, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]; + for (let i = 0; i < 0xffff; i++) { + a.push(i); + } + const buf = new BufReader(new Buffer(new Uint8Array(a))); + const bin = await readFrame(buf); + assertEqual(bin.opcode, OpCodeBinaryFrame); + assertEqual(bin.isLastFrame, true); + assertEqual(bin.mask, undefined); + assertEqual(bin.payload.length, 0xffff + 1); +}); + +test(async function testCreateSecAccept() { + const nonce = "dGhlIHNhbXBsZSBub25jZQ=="; + const d = createSecAccept(nonce); + assertEqual(d, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); +}); -- cgit v1.2.3 From 3dd70d411ae79523c6a1bc337c33bc2224623521 Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Mon, 7 Jan 2019 07:39:36 -0800 Subject: path: remove export = module (denoland/deno_std#95) Original: https://github.com/denoland/deno_std/commit/a0b5aec82397bf76d3e8348194536c2596292e65 --- path/index.ts | 19 ++++++++++++++++--- path/parse_format_test.ts | 4 ++-- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/path/index.ts b/path/index.ts index 7b62b0b00..4201c52ad 100644 --- a/path/index.ts +++ b/path/index.ts @@ -119,7 +119,7 @@ function _format(sep: string, pathObject: FormatInputPathObject) { return dir + sep + base; } -const win32 = { +export const win32 = { // path.resolve([from ...], to) resolve: function resolve(...pathSegments: string[]) { let resolvedDevice = ""; @@ -1004,7 +1004,7 @@ const win32 = { posix: null }; -const posix = { +export const posix = { // path.resolve([from ...], to) resolve: function resolve(...pathSegments: string[]) { let resolvedPath = ""; @@ -1422,4 +1422,17 @@ posix.win32 = win32.win32 = win32; posix.posix = win32.posix = posix; const module = platform.os === "win" ? win32 : posix; -export = module; + +export const resolve = module.resolve; +export const normalize = module.normalize; +export const isAbsolute = module.isAbsolute; +export const join = module.join; +export const relative = module.relative; +export const toNamespacedPath = module.toNamespacedPath; +export const dirname = module.dirname; +export const basename = module.basename; +export const extname = module.extname; +export const format = module.format; +export const parse = module.parse; +export const sep = module.sep; +export const delimiter = module.delimiter; diff --git a/path/parse_format_test.ts b/path/parse_format_test.ts index 1b5e5908a..be98f8739 100644 --- a/path/parse_format_test.ts +++ b/path/parse_format_test.ts @@ -161,7 +161,7 @@ function checkFormat(path, testCases) { test(function parseTrailingWin32() { windowsTrailingTests.forEach(function(p) { - const actual = path.win32.parse(p[0]); + const actual = path.win32.parse(p[0] as string); const expected = p[1]; assertEqual(actual, expected); }); @@ -169,7 +169,7 @@ test(function parseTrailingWin32() { test(function parseTrailing() { posixTrailingTests.forEach(function(p) { - const actual = path.posix.parse(p[0]); + const actual = path.posix.parse(p[0] as string); const expected = p[1]; assertEqual(actual, expected); }); -- cgit v1.2.3 From fc20b977c0aa655b911fcaea070ce77d0c3b9eee Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Tue, 8 Jan 2019 09:53:25 -0500 Subject: Bump deno version to v0.2.6 Original: https://github.com/denoland/deno_std/commit/72b2e20f9da1d431ba9cac3247ee38ee82d5d8f4 --- azure-pipelines.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index ed28b9c2a..600f74227 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,5 +1,5 @@ variables: - DENO_VERSION: 'v0.2.5' + DENO_VERSION: 'v0.2.6' jobs: -- cgit v1.2.3 From 6f8dc44a2b218bac3fb3ebb1035cbbd10160b48b Mon Sep 17 00:00:00 2001 From: Yoshiya Hinosawa Date: Thu, 10 Jan 2019 00:32:37 +0900 Subject: feat: print test status on the same line as test name (denoland/deno_std#100) Original: https://github.com/denoland/deno_std/commit/41a2d218264b2f9217bf793893aff5dadd2c4ca9 --- testing/mod.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/testing/mod.ts b/testing/mod.ts index 2200020f6..96fe3f11f 100644 --- a/testing/mod.ts +++ b/testing/mod.ts @@ -125,20 +125,24 @@ async function runTests() { for (let i = 0; i < tests.length; i++) { const { fn, name } = tests[i]; let result = green_ok(); - console.log("test", name); + // See https://github.com/denoland/deno/pull/1452 + // about this usage of groupCollapsed + console.groupCollapsed(`test ${name} `); try { await fn(); passed++; + console.log("...", result); + console.groupEnd(); } catch (e) { result = red_failed(); + console.log("...", result); + console.groupEnd(); console.error((e && e.stack) || e); failed++; if (exitOnFail) { break; } } - // TODO Do this on the same line as test name is printed. - console.log("...", result); } // Attempting to match the output of Rust's test runner. -- cgit v1.2.3 From 57c877c443765d7aa1f1f2d3cba801f280f19bfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E6=9D=89?= Date: Fri, 11 Jan 2019 06:11:44 +0800 Subject: refactor(path): reorg (denoland/deno_std#101) Original: https://github.com/denoland/deno_std/commit/5be16ba5992b34a64d307779350b88b5cacbfa23 --- README.md | 2 +- fs/path.ts | 2 + fs/path/README.md | 7 + fs/path/basename_test.ts | 75 ++ fs/path/constants.ts | 53 ++ fs/path/dirname_test.ts | 61 ++ fs/path/extname_test.ts | 89 +++ fs/path/interface.ts | 47 ++ fs/path/isabsolute_test.ts | 33 + fs/path/join_test.ts | 124 +++ fs/path/mod.ts | 1438 +++++++++++++++++++++++++++++++++++ fs/path/parse_format_test.ts | 176 +++++ fs/path/relative_test.ts | 72 ++ fs/path/resolve_test.ts | 49 ++ fs/path/zero_length_strings_test.ts | 46 ++ net/file_server.ts | 2 +- path/README.md | 7 - path/basename_test.ts | 75 -- path/constants.ts | 53 -- path/dirname_test.ts | 61 -- path/extname_test.ts | 89 --- path/index.ts | 1438 ----------------------------------- path/interface.ts | 47 -- path/isabsolute_test.ts | 33 - path/join_test.ts | 124 --- path/parse_format_test.ts | 176 ----- path/relative_test.ts | 72 -- path/resolve_test.ts | 49 -- path/zero_length_strings_test.ts | 46 -- test.ts | 18 +- 30 files changed, 2283 insertions(+), 2281 deletions(-) create mode 100644 fs/path.ts create mode 100644 fs/path/README.md create mode 100644 fs/path/basename_test.ts create mode 100644 fs/path/constants.ts create mode 100644 fs/path/dirname_test.ts create mode 100644 fs/path/extname_test.ts create mode 100644 fs/path/interface.ts create mode 100644 fs/path/isabsolute_test.ts create mode 100644 fs/path/join_test.ts create mode 100644 fs/path/mod.ts create mode 100644 fs/path/parse_format_test.ts create mode 100644 fs/path/relative_test.ts create mode 100644 fs/path/resolve_test.ts create mode 100644 fs/path/zero_length_strings_test.ts delete mode 100644 path/README.md delete mode 100644 path/basename_test.ts delete mode 100644 path/constants.ts delete mode 100644 path/dirname_test.ts delete mode 100644 path/extname_test.ts delete mode 100644 path/index.ts delete mode 100644 path/interface.ts delete mode 100644 path/isabsolute_test.ts delete mode 100644 path/join_test.ts delete mode 100644 path/parse_format_test.ts delete mode 100644 path/relative_test.ts delete mode 100644 path/resolve_test.ts delete mode 100644 path/zero_length_strings_test.ts diff --git a/README.md b/README.md index 3a2788333..0a996bce3 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ A framework for creating HTTP/HTTPS servers inspired by GoLang. -- **[path](./path/)** +- **[path](./fs/path)** File path manipulation. diff --git a/fs/path.ts b/fs/path.ts new file mode 100644 index 000000000..64390108d --- /dev/null +++ b/fs/path.ts @@ -0,0 +1,2 @@ +export * from "./path/mod.ts"; +export * from "./path/interface.ts"; diff --git a/fs/path/README.md b/fs/path/README.md new file mode 100644 index 000000000..938ffb358 --- /dev/null +++ b/fs/path/README.md @@ -0,0 +1,7 @@ +# Deno Path Manipulation Libraries + +Usage: + +```ts +import * as path from "https://deno.land/x/fs/path.ts"; +``` diff --git a/fs/path/basename_test.ts b/fs/path/basename_test.ts new file mode 100644 index 000000000..ffe9e051c --- /dev/null +++ b/fs/path/basename_test.ts @@ -0,0 +1,75 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "../../testing/mod.ts"; +import * as path from "./mod.ts"; + +test(function basename() { + assertEqual(path.basename(".js", ".js"), ""); + assertEqual(path.basename(""), ""); + assertEqual(path.basename("/dir/basename.ext"), "basename.ext"); + assertEqual(path.basename("/basename.ext"), "basename.ext"); + assertEqual(path.basename("basename.ext"), "basename.ext"); + assertEqual(path.basename("basename.ext/"), "basename.ext"); + assertEqual(path.basename("basename.ext//"), "basename.ext"); + assertEqual(path.basename("aaa/bbb", "/bbb"), "bbb"); + assertEqual(path.basename("aaa/bbb", "a/bbb"), "bbb"); + assertEqual(path.basename("aaa/bbb", "bbb"), "bbb"); + assertEqual(path.basename("aaa/bbb//", "bbb"), "bbb"); + assertEqual(path.basename("aaa/bbb", "bb"), "b"); + assertEqual(path.basename("aaa/bbb", "b"), "bb"); + assertEqual(path.basename("/aaa/bbb", "/bbb"), "bbb"); + assertEqual(path.basename("/aaa/bbb", "a/bbb"), "bbb"); + assertEqual(path.basename("/aaa/bbb", "bbb"), "bbb"); + assertEqual(path.basename("/aaa/bbb//", "bbb"), "bbb"); + assertEqual(path.basename("/aaa/bbb", "bb"), "b"); + assertEqual(path.basename("/aaa/bbb", "b"), "bb"); + assertEqual(path.basename("/aaa/bbb"), "bbb"); + assertEqual(path.basename("/aaa/"), "aaa"); + assertEqual(path.basename("/aaa/b"), "b"); + assertEqual(path.basename("/a/b"), "b"); + assertEqual(path.basename("//a"), "a"); + + // On unix a backslash is just treated as any other character. + assertEqual( + path.posix.basename("\\dir\\basename.ext"), + "\\dir\\basename.ext" + ); + assertEqual(path.posix.basename("\\basename.ext"), "\\basename.ext"); + assertEqual(path.posix.basename("basename.ext"), "basename.ext"); + assertEqual(path.posix.basename("basename.ext\\"), "basename.ext\\"); + assertEqual(path.posix.basename("basename.ext\\\\"), "basename.ext\\\\"); + assertEqual(path.posix.basename("foo"), "foo"); + + // POSIX filenames may include control characters + const controlCharFilename = "Icon" + String.fromCharCode(13); + assertEqual( + path.posix.basename("/a/b/" + controlCharFilename), + controlCharFilename + ); +}); + +test(function basenameWin32() { + assertEqual(path.win32.basename("\\dir\\basename.ext"), "basename.ext"); + assertEqual(path.win32.basename("\\basename.ext"), "basename.ext"); + assertEqual(path.win32.basename("basename.ext"), "basename.ext"); + assertEqual(path.win32.basename("basename.ext\\"), "basename.ext"); + assertEqual(path.win32.basename("basename.ext\\\\"), "basename.ext"); + assertEqual(path.win32.basename("foo"), "foo"); + assertEqual(path.win32.basename("aaa\\bbb", "\\bbb"), "bbb"); + assertEqual(path.win32.basename("aaa\\bbb", "a\\bbb"), "bbb"); + assertEqual(path.win32.basename("aaa\\bbb", "bbb"), "bbb"); + assertEqual(path.win32.basename("aaa\\bbb\\\\\\\\", "bbb"), "bbb"); + assertEqual(path.win32.basename("aaa\\bbb", "bb"), "b"); + assertEqual(path.win32.basename("aaa\\bbb", "b"), "bb"); + assertEqual(path.win32.basename("C:"), ""); + assertEqual(path.win32.basename("C:."), "."); + assertEqual(path.win32.basename("C:\\"), ""); + assertEqual(path.win32.basename("C:\\dir\\base.ext"), "base.ext"); + assertEqual(path.win32.basename("C:\\basename.ext"), "basename.ext"); + assertEqual(path.win32.basename("C:basename.ext"), "basename.ext"); + assertEqual(path.win32.basename("C:basename.ext\\"), "basename.ext"); + assertEqual(path.win32.basename("C:basename.ext\\\\"), "basename.ext"); + assertEqual(path.win32.basename("C:foo"), "foo"); + assertEqual(path.win32.basename("file:stream"), "file:stream"); +}); diff --git a/fs/path/constants.ts b/fs/path/constants.ts new file mode 100644 index 000000000..b440be9cc --- /dev/null +++ b/fs/path/constants.ts @@ -0,0 +1,53 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { platform } from "deno"; + +const isWindows = platform.os === "win"; + +// Alphabet chars. +export const CHAR_UPPERCASE_A = 65; /* A */ +export const CHAR_LOWERCASE_A = 97; /* a */ +export const CHAR_UPPERCASE_Z = 90; /* Z */ +export const CHAR_LOWERCASE_Z = 122; /* z */ + +// Non-alphabetic chars. +export const CHAR_DOT = 46; /* . */ +export const CHAR_FORWARD_SLASH = 47; /* / */ +export const CHAR_BACKWARD_SLASH = 92; /* \ */ +export const CHAR_VERTICAL_LINE = 124; /* | */ +export const CHAR_COLON = 58; /* : */ +export const CHAR_QUESTION_MARK = 63; /* ? */ +export const CHAR_UNDERSCORE = 95; /* _ */ +export const CHAR_LINE_FEED = 10; /* \n */ +export const CHAR_CARRIAGE_RETURN = 13; /* \r */ +export const CHAR_TAB = 9; /* \t */ +export const CHAR_FORM_FEED = 12; /* \f */ +export const CHAR_EXCLAMATION_MARK = 33; /* ! */ +export const CHAR_HASH = 35; /* # */ +export const CHAR_SPACE = 32; /* */ +export const CHAR_NO_BREAK_SPACE = 160; /* \u00A0 */ +export const CHAR_ZERO_WIDTH_NOBREAK_SPACE = 65279; /* \uFEFF */ +export const CHAR_LEFT_SQUARE_BRACKET = 91; /* [ */ +export const CHAR_RIGHT_SQUARE_BRACKET = 93; /* ] */ +export const CHAR_LEFT_ANGLE_BRACKET = 60; /* < */ +export const CHAR_RIGHT_ANGLE_BRACKET = 62; /* > */ +export const CHAR_LEFT_CURLY_BRACKET = 123; /* { */ +export const CHAR_RIGHT_CURLY_BRACKET = 125; /* } */ +export const CHAR_HYPHEN_MINUS = 45; /* - */ +export const CHAR_PLUS = 43; /* + */ +export const CHAR_DOUBLE_QUOTE = 34; /* " */ +export const CHAR_SINGLE_QUOTE = 39; /* ' */ +export const CHAR_PERCENT = 37; /* % */ +export const CHAR_SEMICOLON = 59; /* ; */ +export const CHAR_CIRCUMFLEX_ACCENT = 94; /* ^ */ +export const CHAR_GRAVE_ACCENT = 96; /* ` */ +export const CHAR_AT = 64; /* @ */ +export const CHAR_AMPERSAND = 38; /* & */ +export const CHAR_EQUAL = 61; /* = */ + +// Digits +export const CHAR_0 = 48; /* 0 */ +export const CHAR_9 = 57; /* 9 */ + +export const EOL = isWindows ? "\r\n" : "\n"; diff --git a/fs/path/dirname_test.ts b/fs/path/dirname_test.ts new file mode 100644 index 000000000..5613d6d2c --- /dev/null +++ b/fs/path/dirname_test.ts @@ -0,0 +1,61 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "../../testing/mod.ts"; +import * as path from "./mod.ts"; + +test(function dirname() { + assertEqual(path.posix.dirname("/a/b/"), "/a"); + assertEqual(path.posix.dirname("/a/b"), "/a"); + assertEqual(path.posix.dirname("/a"), "/"); + assertEqual(path.posix.dirname(""), "."); + assertEqual(path.posix.dirname("/"), "/"); + assertEqual(path.posix.dirname("////"), "/"); + assertEqual(path.posix.dirname("//a"), "//"); + assertEqual(path.posix.dirname("foo"), "."); +}); + +test(function dirnameWin32() { + assertEqual(path.win32.dirname("c:\\"), "c:\\"); + assertEqual(path.win32.dirname("c:\\foo"), "c:\\"); + assertEqual(path.win32.dirname("c:\\foo\\"), "c:\\"); + assertEqual(path.win32.dirname("c:\\foo\\bar"), "c:\\foo"); + assertEqual(path.win32.dirname("c:\\foo\\bar\\"), "c:\\foo"); + assertEqual(path.win32.dirname("c:\\foo\\bar\\baz"), "c:\\foo\\bar"); + assertEqual(path.win32.dirname("\\"), "\\"); + assertEqual(path.win32.dirname("\\foo"), "\\"); + assertEqual(path.win32.dirname("\\foo\\"), "\\"); + assertEqual(path.win32.dirname("\\foo\\bar"), "\\foo"); + assertEqual(path.win32.dirname("\\foo\\bar\\"), "\\foo"); + assertEqual(path.win32.dirname("\\foo\\bar\\baz"), "\\foo\\bar"); + assertEqual(path.win32.dirname("c:"), "c:"); + assertEqual(path.win32.dirname("c:foo"), "c:"); + assertEqual(path.win32.dirname("c:foo\\"), "c:"); + assertEqual(path.win32.dirname("c:foo\\bar"), "c:foo"); + assertEqual(path.win32.dirname("c:foo\\bar\\"), "c:foo"); + assertEqual(path.win32.dirname("c:foo\\bar\\baz"), "c:foo\\bar"); + assertEqual(path.win32.dirname("file:stream"), "."); + assertEqual(path.win32.dirname("dir\\file:stream"), "dir"); + assertEqual(path.win32.dirname("\\\\unc\\share"), "\\\\unc\\share"); + assertEqual(path.win32.dirname("\\\\unc\\share\\foo"), "\\\\unc\\share\\"); + assertEqual(path.win32.dirname("\\\\unc\\share\\foo\\"), "\\\\unc\\share\\"); + assertEqual( + path.win32.dirname("\\\\unc\\share\\foo\\bar"), + "\\\\unc\\share\\foo" + ); + assertEqual( + path.win32.dirname("\\\\unc\\share\\foo\\bar\\"), + "\\\\unc\\share\\foo" + ); + assertEqual( + path.win32.dirname("\\\\unc\\share\\foo\\bar\\baz"), + "\\\\unc\\share\\foo\\bar" + ); + assertEqual(path.win32.dirname("/a/b/"), "/a"); + assertEqual(path.win32.dirname("/a/b"), "/a"); + assertEqual(path.win32.dirname("/a"), "/"); + assertEqual(path.win32.dirname(""), "."); + assertEqual(path.win32.dirname("/"), "/"); + assertEqual(path.win32.dirname("////"), "/"); + assertEqual(path.win32.dirname("foo"), "."); +}); diff --git a/fs/path/extname_test.ts b/fs/path/extname_test.ts new file mode 100644 index 000000000..63d473d34 --- /dev/null +++ b/fs/path/extname_test.ts @@ -0,0 +1,89 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "../../testing/mod.ts"; +import * as path from "./mod.ts"; + +const slashRE = /\//g; + +const pairs = [ + ["", ""], + ["/path/to/file", ""], + ["/path/to/file.ext", ".ext"], + ["/path.to/file.ext", ".ext"], + ["/path.to/file", ""], + ["/path.to/.file", ""], + ["/path.to/.file.ext", ".ext"], + ["/path/to/f.ext", ".ext"], + ["/path/to/..ext", ".ext"], + ["/path/to/..", ""], + ["file", ""], + ["file.ext", ".ext"], + [".file", ""], + [".file.ext", ".ext"], + ["/file", ""], + ["/file.ext", ".ext"], + ["/.file", ""], + ["/.file.ext", ".ext"], + [".path/file.ext", ".ext"], + ["file.ext.ext", ".ext"], + ["file.", "."], + [".", ""], + ["./", ""], + [".file.ext", ".ext"], + [".file", ""], + [".file.", "."], + [".file..", "."], + ["..", ""], + ["../", ""], + ["..file.ext", ".ext"], + ["..file", ".file"], + ["..file.", "."], + ["..file..", "."], + ["...", "."], + ["...ext", ".ext"], + ["....", "."], + ["file.ext/", ".ext"], + ["file.ext//", ".ext"], + ["file/", ""], + ["file//", ""], + ["file./", "."], + ["file.//", "."] +]; + +test(function extname() { + pairs.forEach(function(p) { + const input = p[0]; + const expected = p[1]; + assertEqual(expected, path.posix.extname(input)); + }); + + // On *nix, backslash is a valid name component like any other character. + assertEqual(path.posix.extname(".\\"), ""); + assertEqual(path.posix.extname("..\\"), ".\\"); + assertEqual(path.posix.extname("file.ext\\"), ".ext\\"); + assertEqual(path.posix.extname("file.ext\\\\"), ".ext\\\\"); + assertEqual(path.posix.extname("file\\"), ""); + assertEqual(path.posix.extname("file\\\\"), ""); + assertEqual(path.posix.extname("file.\\"), ".\\"); + assertEqual(path.posix.extname("file.\\\\"), ".\\\\"); +}); + +test(function extnameWin32() { + pairs.forEach(function(p) { + const input = p[0].replace(slashRE, "\\"); + const expected = p[1]; + assertEqual(expected, path.win32.extname(input)); + assertEqual(expected, path.win32.extname("C:" + input)); + }); + + // On Windows, backslash is a path separator. + assertEqual(path.win32.extname(".\\"), ""); + assertEqual(path.win32.extname("..\\"), ""); + assertEqual(path.win32.extname("file.ext\\"), ".ext"); + assertEqual(path.win32.extname("file.ext\\\\"), ".ext"); + assertEqual(path.win32.extname("file\\"), ""); + assertEqual(path.win32.extname("file\\\\"), ""); + assertEqual(path.win32.extname("file.\\"), "."); + assertEqual(path.win32.extname("file.\\\\"), "."); +}); diff --git a/fs/path/interface.ts b/fs/path/interface.ts new file mode 100644 index 000000000..84a3030ff --- /dev/null +++ b/fs/path/interface.ts @@ -0,0 +1,47 @@ +/** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ +export 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; +} +export interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string; + /** + * The file extension (if any) such as '.html' + */ + ext?: string; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string; +} diff --git a/fs/path/isabsolute_test.ts b/fs/path/isabsolute_test.ts new file mode 100644 index 000000000..9591b8045 --- /dev/null +++ b/fs/path/isabsolute_test.ts @@ -0,0 +1,33 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "../../testing/mod.ts"; +import * as path from "./mod.ts"; + +test(function isAbsolute() { + assertEqual(path.posix.isAbsolute("/home/foo"), true); + assertEqual(path.posix.isAbsolute("/home/foo/.."), true); + assertEqual(path.posix.isAbsolute("bar/"), false); + assertEqual(path.posix.isAbsolute("./baz"), false); +}); + +test(function isAbsoluteWin32() { + assertEqual(path.win32.isAbsolute("/"), true); + assertEqual(path.win32.isAbsolute("//"), true); + assertEqual(path.win32.isAbsolute("//server"), true); + assertEqual(path.win32.isAbsolute("//server/file"), true); + assertEqual(path.win32.isAbsolute("\\\\server\\file"), true); + assertEqual(path.win32.isAbsolute("\\\\server"), true); + assertEqual(path.win32.isAbsolute("\\\\"), true); + assertEqual(path.win32.isAbsolute("c"), false); + assertEqual(path.win32.isAbsolute("c:"), false); + assertEqual(path.win32.isAbsolute("c:\\"), true); + assertEqual(path.win32.isAbsolute("c:/"), true); + assertEqual(path.win32.isAbsolute("c://"), true); + assertEqual(path.win32.isAbsolute("C:/Users/"), true); + assertEqual(path.win32.isAbsolute("C:\\Users\\"), true); + assertEqual(path.win32.isAbsolute("C:cwd/another"), false); + assertEqual(path.win32.isAbsolute("C:cwd\\another"), false); + assertEqual(path.win32.isAbsolute("directory/directory"), false); + assertEqual(path.win32.isAbsolute("directory\\directory"), false); +}); diff --git a/fs/path/join_test.ts b/fs/path/join_test.ts new file mode 100644 index 000000000..2051dbdaa --- /dev/null +++ b/fs/path/join_test.ts @@ -0,0 +1,124 @@ +import { test, assertEqual } from "../../testing/mod.ts"; +import * as path from "./mod.ts"; + +const backslashRE = /\\/g; + +const joinTests = + // arguments result + [ + [[".", "x/b", "..", "/b/c.js"], "x/b/c.js"], + [[], "."], + [["/.", "x/b", "..", "/b/c.js"], "/x/b/c.js"], + [["/foo", "../../../bar"], "/bar"], + [["foo", "../../../bar"], "../../bar"], + [["foo/", "../../../bar"], "../../bar"], + [["foo/x", "../../../bar"], "../bar"], + [["foo/x", "./bar"], "foo/x/bar"], + [["foo/x/", "./bar"], "foo/x/bar"], + [["foo/x/", ".", "bar"], "foo/x/bar"], + [["./"], "./"], + [[".", "./"], "./"], + [[".", ".", "."], "."], + [[".", "./", "."], "."], + [[".", "/./", "."], "."], + [[".", "/////./", "."], "."], + [["."], "."], + [["", "."], "."], + [["", "foo"], "foo"], + [["foo", "/bar"], "foo/bar"], + [["", "/foo"], "/foo"], + [["", "", "/foo"], "/foo"], + [["", "", "foo"], "foo"], + [["foo", ""], "foo"], + [["foo/", ""], "foo/"], + [["foo", "", "/bar"], "foo/bar"], + [["./", "..", "/foo"], "../foo"], + [["./", "..", "..", "/foo"], "../../foo"], + [[".", "..", "..", "/foo"], "../../foo"], + [["", "..", "..", "/foo"], "../../foo"], + [["/"], "/"], + [["/", "."], "/"], + [["/", ".."], "/"], + [["/", "..", ".."], "/"], + [[""], "."], + [["", ""], "."], + [[" /foo"], " /foo"], + [[" ", "foo"], " /foo"], + [[" ", "."], " "], + [[" ", "/"], " /"], + [[" ", ""], " "], + [["/", "foo"], "/foo"], + [["/", "/foo"], "/foo"], + [["/", "//foo"], "/foo"], + [["/", "", "/foo"], "/foo"], + [["", "/", "foo"], "/foo"], + [["", "/", "/foo"], "/foo"] + ]; + +// Windows-specific join tests +const windowsJoinTests = [ + // arguments result + // UNC path expected + [["//foo/bar"], "\\\\foo\\bar\\"], + [["\\/foo/bar"], "\\\\foo\\bar\\"], + [["\\\\foo/bar"], "\\\\foo\\bar\\"], + // UNC path expected - server and share separate + [["//foo", "bar"], "\\\\foo\\bar\\"], + [["//foo/", "bar"], "\\\\foo\\bar\\"], + [["//foo", "/bar"], "\\\\foo\\bar\\"], + // UNC path expected - questionable + [["//foo", "", "bar"], "\\\\foo\\bar\\"], + [["//foo/", "", "bar"], "\\\\foo\\bar\\"], + [["//foo/", "", "/bar"], "\\\\foo\\bar\\"], + // UNC path expected - even more questionable + [["", "//foo", "bar"], "\\\\foo\\bar\\"], + [["", "//foo/", "bar"], "\\\\foo\\bar\\"], + [["", "//foo/", "/bar"], "\\\\foo\\bar\\"], + // No UNC path expected (no double slash in first component) + [["\\", "foo/bar"], "\\foo\\bar"], + [["\\", "/foo/bar"], "\\foo\\bar"], + [["", "/", "/foo/bar"], "\\foo\\bar"], + // No UNC path expected (no non-slashes in first component - + // questionable) + [["//", "foo/bar"], "\\foo\\bar"], + [["//", "/foo/bar"], "\\foo\\bar"], + [["\\\\", "/", "/foo/bar"], "\\foo\\bar"], + [["//"], "\\"], + // No UNC path expected (share name missing - questionable). + [["//foo"], "\\foo"], + [["//foo/"], "\\foo\\"], + [["//foo", "/"], "\\foo\\"], + [["//foo", "", "/"], "\\foo\\"], + // No UNC path expected (too many leading slashes - questionable) + [["///foo/bar"], "\\foo\\bar"], + [["////foo", "bar"], "\\foo\\bar"], + [["\\\\\\/foo/bar"], "\\foo\\bar"], + // Drive-relative vs drive-absolute paths. This merely describes the + // status quo, rather than being obviously right + [["c:"], "c:."], + [["c:."], "c:."], + [["c:", ""], "c:."], + [["", "c:"], "c:."], + [["c:.", "/"], "c:.\\"], + [["c:.", "file"], "c:file"], + [["c:", "/"], "c:\\"], + [["c:", "file"], "c:\\file"] +]; + +test(function join() { + joinTests.forEach(function(p) { + const actual = path.posix.join.apply(null, p[0]); + assertEqual(actual, p[1]); + }); +}); + +test(function joinWin32() { + joinTests.forEach(function(p) { + const actual = path.win32.join.apply(null, p[0]).replace(backslashRE, "/"); + assertEqual(actual, p[1]); + }); + windowsJoinTests.forEach(function(p) { + const actual = path.win32.join.apply(null, p[0]); + assertEqual(actual, p[1]); + }); +}); diff --git a/fs/path/mod.ts b/fs/path/mod.ts new file mode 100644 index 000000000..4201c52ad --- /dev/null +++ b/fs/path/mod.ts @@ -0,0 +1,1438 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { + CHAR_UPPERCASE_A, + CHAR_LOWERCASE_A, + CHAR_UPPERCASE_Z, + CHAR_LOWERCASE_Z, + CHAR_DOT, + CHAR_FORWARD_SLASH, + CHAR_BACKWARD_SLASH, + CHAR_COLON, + CHAR_QUESTION_MARK +} from "./constants.ts"; +import { cwd, env, platform } from "deno"; +import { FormatInputPathObject, ParsedPath } from "./interface.ts"; + +function assertPath(path: string) { + if (typeof path !== "string") { + throw new TypeError( + `Path must be a string. Received ${JSON.stringify(path)}` + ); + } +} + +function isPathSeparator(code: number) { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +} + +function isPosixPathSeparator(code: number) { + return code === CHAR_FORWARD_SLASH; +} + +function isWindowsDeviceRoot(code: number) { + return ( + (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || + (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z) + ); +} + +// Resolves . and .. elements in a path with directory names +function normalizeString( + path: string, + allowAboveRoot: boolean, + separator: string, + isPathSeparator: (code: number) => boolean +) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code: number; + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) code = path.charCodeAt(i); + else if (isPathSeparator(code)) break; + else code = CHAR_FORWARD_SLASH; + + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) { + // NOOP + } else if (lastSlash !== i - 1 && dots === 2) { + if ( + res.length < 2 || + lastSegmentLength !== 2 || + res.charCodeAt(res.length - 1) !== CHAR_DOT || + res.charCodeAt(res.length - 2) !== CHAR_DOT + ) { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf(separator); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } else if (res.length === 2 || res.length === 1) { + res = ""; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) res += `${separator}..`; + else res = ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) res += separator + path.slice(lastSlash + 1, i); + else res = path.slice(lastSlash + 1, i); + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} + +function _format(sep: string, pathObject: FormatInputPathObject) { + const dir = pathObject.dir || pathObject.root; + const base = + pathObject.base || (pathObject.name || "") + (pathObject.ext || ""); + if (!dir) { + return base; + } + if (dir === pathObject.root) { + return dir + base; + } + return dir + sep + base; +} + +export const win32 = { + // path.resolve([from ...], to) + resolve: function resolve(...pathSegments: string[]) { + let resolvedDevice = ""; + let resolvedTail = ""; + let resolvedAbsolute = false; + + for (let i = arguments.length - 1; i >= -1; i--) { + let path: string; + if (i >= 0) { + path = arguments[i]; + } else if (!resolvedDevice) { + path = cwd(); + } else { + // Windows has the concept of drive-specific current working + // directories. If we've resolved a drive letter but not yet an + // absolute path, get cwd for that drive, or the process cwd if + // the drive cwd is not available. We're sure the device is not + // a UNC path at this points, because UNC paths are always absolute. + path = env()[`=${resolvedDevice}`] || cwd(); + + // Verify that a cwd was found and that it actually points + // to our drive. If not, default to the drive's root. + if ( + path === undefined || + path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\` + ) { + path = `${resolvedDevice}\\`; + } + } + + assertPath(path); + + // Skip empty entries + if (path.length === 0) { + continue; + } + + let len = path.length; + let rootEnd = 0; + let device = ""; + let isAbsolute = false; + const code = path.charCodeAt(0); + + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + + // If we started with a separator, we know we at least have an + // absolute path of some kind (UNC or otherwise) + isAbsolute = true; + + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + device = `\\\\${firstPart}\\${path.slice(last)}`; + rootEnd = j; + } else if (j !== last) { + // We matched a UNC root with leftovers + + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } else { + rootEnd = 1; + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + + if (path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + // Treat separator following drive name as an absolute path + // indicator + isAbsolute = true; + rootEnd = 3; + } + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator + rootEnd = 1; + isAbsolute = true; + } + + if ( + device.length > 0 && + resolvedDevice.length > 0 && + device.toLowerCase() !== resolvedDevice.toLowerCase() + ) { + // This path points to another device so it is not applicable + continue; + } + + if (resolvedDevice.length === 0 && device.length > 0) { + resolvedDevice = device; + } + if (!resolvedAbsolute) { + resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; + resolvedAbsolute = isAbsolute; + } + + if (resolvedDevice.length > 0 && resolvedAbsolute) { + break; + } + } + + // At this point the path should be resolved to a full absolute path, + // but handle relative paths to be safe (might happen when process.cwd() + // fails) + + // Normalize the tail path + resolvedTail = normalizeString( + resolvedTail, + !resolvedAbsolute, + "\\", + isPathSeparator + ); + + return ( + resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || "." + ); + }, + + normalize: function normalize(path: string) { + assertPath(path); + const len = path.length; + if (len === 0) return "."; + let rootEnd = 0; + let device: string; + let isAbsolute = false; + const code = path.charCodeAt(0); + + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + + // If we started with a separator, we know we at least have an absolute + // path of some kind (UNC or otherwise) + isAbsolute = true; + + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + // Return the normalized version of the UNC root since there + // is nothing left to process + + return `\\\\${firstPart}\\${path.slice(last)}\\`; + } else if (j !== last) { + // We matched a UNC root with leftovers + + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } else { + rootEnd = 1; + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + + if (path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + // Treat separator following drive name as an absolute path + // indicator + isAbsolute = true; + rootEnd = 3; + } + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid unnecessary + // work + return "\\"; + } + + let tail: string; + if (rootEnd < len) { + tail = normalizeString( + path.slice(rootEnd), + !isAbsolute, + "\\", + isPathSeparator + ); + } else { + tail = ""; + } + if (tail.length === 0 && !isAbsolute) tail = "."; + if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) + tail += "\\"; + if (device === undefined) { + if (isAbsolute) { + if (tail.length > 0) return `\\${tail}`; + else return "\\"; + } else if (tail.length > 0) { + return tail; + } else { + return ""; + } + } else if (isAbsolute) { + if (tail.length > 0) return `${device}\\${tail}`; + else return `${device}\\`; + } else if (tail.length > 0) { + return device + tail; + } else { + return device; + } + }, + + isAbsolute: function isAbsolute(path: string) { + assertPath(path); + const len = path.length; + if (len === 0) return false; + + const code = path.charCodeAt(0); + if (isPathSeparator(code)) { + return true; + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + + if (len > 2 && path.charCodeAt(1) === CHAR_COLON) { + if (isPathSeparator(path.charCodeAt(2))) return true; + } + } + return false; + }, + + join: function join(...paths: string[]) { + if (arguments.length === 0) return "."; + + let joined: string; + let firstPart: string; + for (let i = 0; i < arguments.length; ++i) { + let arg = arguments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === undefined) joined = firstPart = arg; + else joined += `\\${arg}`; + } + } + + if (joined === undefined) return "."; + + // Make sure that the joined path doesn't start with two slashes, because + // normalize() will mistake it for an UNC path then. + // + // This step is skipped when it is very clear that the user actually + // intended to point at an UNC path. This is assumed when the first + // non-empty string arguments starts with exactly two slashes followed by + // at least one more non-slash character. + // + // Note that for normalize() to treat a path as an UNC path it needs to + // have at least 2 components, so we don't filter for that here. + // This means that the user can use join to construct UNC paths from + // a server name and a share name; for example: + // path.join('//server', 'share') -> '\\\\server\\share\\') + let needsReplace = true; + let slashCount = 0; + if (isPathSeparator(firstPart.charCodeAt(0))) { + ++slashCount; + const firstLen = firstPart.length; + if (firstLen > 1) { + if (isPathSeparator(firstPart.charCodeAt(1))) { + ++slashCount; + if (firstLen > 2) { + if (isPathSeparator(firstPart.charCodeAt(2))) ++slashCount; + else { + // We matched a UNC path in the first part + needsReplace = false; + } + } + } + } + } + if (needsReplace) { + // Find any more consecutive slashes we need to replace + for (; slashCount < joined.length; ++slashCount) { + if (!isPathSeparator(joined.charCodeAt(slashCount))) break; + } + + // Replace the slashes if needed + if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`; + } + + return win32.normalize(joined); + }, + + // It will solve the relative path from `from` to `to`, for instance: + // from = 'C:\\orandea\\test\\aaa' + // to = 'C:\\orandea\\impl\\bbb' + // The output of the function should be: '..\\..\\impl\\bbb' + relative: function relative(from: string, to: string) { + assertPath(from); + assertPath(to); + + if (from === to) return ""; + + let fromOrig = win32.resolve(from); + let toOrig = win32.resolve(to); + + if (fromOrig === toOrig) return ""; + + from = fromOrig.toLowerCase(); + to = toOrig.toLowerCase(); + + if (from === to) return ""; + + // Trim any leading backslashes + let fromStart = 0; + for (; fromStart < from.length; ++fromStart) { + if (from.charCodeAt(fromStart) !== CHAR_BACKWARD_SLASH) break; + } + // Trim trailing backslashes (applicable to UNC paths only) + let fromEnd = from.length; + for (; fromEnd - 1 > fromStart; --fromEnd) { + if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break; + } + let fromLen = fromEnd - fromStart; + + // Trim any leading backslashes + let toStart = 0; + for (; toStart < to.length; ++toStart) { + if (to.charCodeAt(toStart) !== CHAR_BACKWARD_SLASH) break; + } + // Trim trailing backslashes (applicable to UNC paths only) + let toEnd = to.length; + for (; toEnd - 1 > toStart; --toEnd) { + if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break; + } + let toLen = toEnd - toStart; + + // Compare paths to find the longest common path from root + let length = fromLen < toLen ? fromLen : toLen; + let lastCommonSep = -1; + let i = 0; + for (; i <= length; ++i) { + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { + // We get here if `from` is the exact base path for `to`. + // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' + return toOrig.slice(toStart + i + 1); + } else if (i === 2) { + // We get here if `from` is the device root. + // For example: from='C:\\'; to='C:\\foo' + return toOrig.slice(toStart + i); + } + } + if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='C:\\foo\\bar'; to='C:\\foo' + lastCommonSep = i; + } else if (i === 2) { + // We get here if `to` is the device root. + // For example: from='C:\\foo\\bar'; to='C:\\' + lastCommonSep = 3; + } + } + break; + } + let fromCode = from.charCodeAt(fromStart + i); + let toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) break; + else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i; + } + + // We found a mismatch before the first common path separator was seen, so + // return the original `to`. + if (i !== length && lastCommonSep === -1) { + return toOrig; + } + + let out = ""; + if (lastCommonSep === -1) lastCommonSep = 0; + // Generate the relative path based on the path difference between `to` and + // `from` + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { + if (out.length === 0) out += ".."; + else out += "\\.."; + } + } + + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) + return out + toOrig.slice(toStart + lastCommonSep, toEnd); + else { + toStart += lastCommonSep; + if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) ++toStart; + return toOrig.slice(toStart, toEnd); + } + }, + + toNamespacedPath: function toNamespacedPath(path: string) { + // Note: this will *probably* throw somewhere. + if (typeof path !== "string") return path; + + if (path.length === 0) { + return ""; + } + + const resolvedPath = win32.resolve(path); + + if (resolvedPath.length >= 3) { + if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { + // Possible UNC root + + if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { + const code = resolvedPath.charCodeAt(2); + if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { + // Matched non-long UNC root, convert the path to a long UNC path + return `\\\\?\\UNC\\${resolvedPath.slice(2)}`; + } + } + } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0))) { + // Possible device root + + if ( + resolvedPath.charCodeAt(1) === CHAR_COLON && + resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH + ) { + // Matched device root, convert the path to a long UNC path + return `\\\\?\\${resolvedPath}`; + } + } + } + + return path; + }, + + dirname: function dirname(path: string) { + assertPath(path); + const len = path.length; + if (len === 0) return "."; + let rootEnd = -1; + let end = -1; + let matchedSlash = true; + let offset = 0; + const code = path.charCodeAt(0); + + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + + rootEnd = offset = 1; + + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + return path; + } + if (j !== last) { + // We matched a UNC root with leftovers + + // Offset by 1 to include the separator after the UNC root to + // treat it as a "normal root" on top of a (UNC) root + rootEnd = offset = j + 1; + } + } + } + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + + if (path.charCodeAt(1) === CHAR_COLON) { + rootEnd = offset = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) rootEnd = offset = 3; + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid + // unnecessary work + return path; + } + + for (let i = len - 1; i >= offset; --i) { + if (isPathSeparator(path.charCodeAt(i))) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) { + if (rootEnd === -1) return "."; + else end = rootEnd; + } + return path.slice(0, end); + }, + + basename: function basename(path: string, ext = "") { + if (ext !== undefined && typeof ext !== "string") + throw new TypeError('"ext" argument must be a string'); + assertPath(path); + let start = 0; + let end = -1; + let matchedSlash = true; + let i: number; + + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + if (path.length >= 2) { + const drive = path.charCodeAt(0); + if (isWindowsDeviceRoot(drive)) { + if (path.charCodeAt(1) === CHAR_COLON) start = 2; + } + } + + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) return ""; + let extIdx = ext.length - 1; + let firstNonSlashEnd = -1; + for (i = path.length - 1; i >= start; --i) { + const code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + + if (start === end) end = firstNonSlashEnd; + else if (end === -1) end = path.length; + return path.slice(start, end); + } else { + for (i = path.length - 1; i >= start; --i) { + if (isPathSeparator(path.charCodeAt(i))) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ""; + return path.slice(start, end); + } + }, + + extname: function extname(path: string) { + assertPath(path); + let start = 0; + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + + if ( + path.length >= 2 && + path.charCodeAt(1) === CHAR_COLON && + isWindowsDeviceRoot(path.charCodeAt(0)) + ) { + start = startPart = 2; + } + + for (let i = path.length - 1; i >= start; --i) { + const code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if ( + startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) + ) { + return ""; + } + return path.slice(startDot, end); + }, + + format: function format(pathObject: FormatInputPathObject) { + if (pathObject === null || typeof pathObject !== "object") { + throw new TypeError( + `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` + ); + } + return _format("\\", pathObject); + }, + + parse: function parse(path: string) { + assertPath(path); + + let ret = { root: "", dir: "", base: "", ext: "", name: "" } as ParsedPath; + if (path.length === 0) return ret; + + let len = path.length; + let rootEnd = 0; + let code = path.charCodeAt(0); + + // Try to match a root + if (len > 1) { + if (isPathSeparator(code)) { + // Possible UNC root + + rootEnd = 1; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + if (!isPathSeparator(path.charCodeAt(j))) break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + if (isPathSeparator(path.charCodeAt(j))) break; + } + if (j === len) { + // We matched a UNC root only + + rootEnd = j; + } else if (j !== last) { + // We matched a UNC root with leftovers + + rootEnd = j + 1; + } + } + } + } + } else if (isWindowsDeviceRoot(code)) { + // Possible device root + + if (path.charCodeAt(1) === CHAR_COLON) { + rootEnd = 2; + if (len > 2) { + if (isPathSeparator(path.charCodeAt(2))) { + if (len === 3) { + // `path` contains just a drive root, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + rootEnd = 3; + } + } else { + // `path` contains just a drive root, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + } + } + } else if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + + if (rootEnd > 0) ret.root = path.slice(0, rootEnd); + + let startDot = -1; + let startPart = rootEnd; + let end = -1; + let matchedSlash = true; + let i = path.length - 1; + + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + + // Get non-dir info + for (; i >= rootEnd; --i) { + code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if ( + startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) + ) { + if (end !== -1) { + ret.base = ret.name = path.slice(startPart, end); + } + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + ret.ext = path.slice(startDot, end); + } + + // If the directory is the root, use the entire root as the `dir` including + // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the + // trailing slash (`C:\abc\def` -> `C:\abc`). + if (startPart > 0 && startPart !== rootEnd) + ret.dir = path.slice(0, startPart - 1); + else ret.dir = ret.root; + + return ret; + }, + + sep: "\\", + delimiter: ";", + win32: null, + posix: null +}; + +export const posix = { + // path.resolve([from ...], to) + resolve: function resolve(...pathSegments: string[]) { + let resolvedPath = ""; + let resolvedAbsolute = false; + + for (let i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + let path: string; + if (i >= 0) path = arguments[i]; + else { + path = cwd(); + } + + assertPath(path); + + // Skip empty entries + if (path.length === 0) { + continue; + } + + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeString( + resolvedPath, + !resolvedAbsolute, + "/", + isPosixPathSeparator + ); + + if (resolvedAbsolute) { + if (resolvedPath.length > 0) return `/${resolvedPath}`; + else return "/"; + } else if (resolvedPath.length > 0) { + return resolvedPath; + } else { + return "."; + } + }, + + normalize: function normalize(path: string) { + assertPath(path); + + if (path.length === 0) return "."; + + const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + const trailingSeparator = + path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; + + // Normalize the path + path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator); + + if (path.length === 0 && !isAbsolute) path = "."; + if (path.length > 0 && trailingSeparator) path += "/"; + + if (isAbsolute) return `/${path}`; + return path; + }, + + isAbsolute: function isAbsolute(path: string) { + assertPath(path); + return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; + }, + + join: function join(...paths: string[]) { + if (arguments.length === 0) return "."; + let joined: string; + for (let i = 0; i < arguments.length; ++i) { + let arg = arguments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === undefined) joined = arg; + else joined += `/${arg}`; + } + } + if (joined === undefined) return "."; + return posix.normalize(joined); + }, + + relative: function relative(from: string, to: string) { + assertPath(from); + assertPath(to); + + if (from === to) return ""; + + from = posix.resolve(from); + to = posix.resolve(to); + + if (from === to) return ""; + + // Trim any leading backslashes + let fromStart = 1; + for (; fromStart < from.length; ++fromStart) { + if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) break; + } + let fromEnd = from.length; + let fromLen = fromEnd - fromStart; + + // Trim any leading backslashes + let toStart = 1; + for (; toStart < to.length; ++toStart) { + if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) break; + } + let toEnd = to.length; + let toLen = toEnd - toStart; + + // Compare paths to find the longest common path from root + let length = fromLen < toLen ? fromLen : toLen; + let lastCommonSep = -1; + let i = 0; + for (; i <= length; ++i) { + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1); + } else if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i); + } + } else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo'; to='/' + lastCommonSep = 0; + } + } + break; + } + let fromCode = from.charCodeAt(fromStart + i); + let toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) break; + else if (fromCode === CHAR_FORWARD_SLASH) lastCommonSep = i; + } + + let out = ""; + // Generate the relative path based on the path difference between `to` + // and `from` + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) { + if (out.length === 0) out += ".."; + else out += "/.."; + } + } + + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) return out + to.slice(toStart + lastCommonSep); + else { + toStart += lastCommonSep; + if (to.charCodeAt(toStart) === CHAR_FORWARD_SLASH) ++toStart; + return to.slice(toStart); + } + }, + + toNamespacedPath: function toNamespacedPath(path: string) { + // Non-op on posix systems + return path; + }, + + dirname: function dirname(path: string) { + assertPath(path); + if (path.length === 0) return "."; + const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + let end = -1; + let matchedSlash = true; + for (let i = path.length - 1; i >= 1; --i) { + if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) return hasRoot ? "/" : "."; + if (hasRoot && end === 1) return "//"; + return path.slice(0, end); + }, + + basename: function basename(path: string, ext = "") { + if (ext !== undefined && typeof ext !== "string") + throw new TypeError('"ext" argument must be a string'); + assertPath(path); + + let start = 0; + let end = -1; + let matchedSlash = true; + let i: number; + + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) return ""; + let extIdx = ext.length - 1; + let firstNonSlashEnd = -1; + for (i = path.length - 1; i >= 0; --i) { + const code = path.charCodeAt(i); + if (code === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + + if (start === end) end = firstNonSlashEnd; + else if (end === -1) end = path.length; + return path.slice(start, end); + } else { + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ""; + return path.slice(start, end); + } + }, + + extname: function extname(path: string) { + assertPath(path); + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + for (let i = path.length - 1; i >= 0; --i) { + const code = path.charCodeAt(i); + if (code === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if ( + startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) + ) { + return ""; + } + return path.slice(startDot, end); + }, + + format: function format(pathObject: FormatInputPathObject) { + if (pathObject === null || typeof pathObject !== "object") { + throw new TypeError( + `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` + ); + } + return _format("/", pathObject); + }, + + parse: function parse(path: string) { + assertPath(path); + + let ret = { root: "", dir: "", base: "", ext: "", name: "" } as ParsedPath; + if (path.length === 0) return ret; + let isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + let start: number; + if (isAbsolute) { + ret.root = "/"; + start = 1; + } else { + start = 0; + } + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + let i = path.length - 1; + + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + + // Get non-dir info + for (; i >= start; --i) { + const code = path.charCodeAt(i); + if (code === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i; + else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if ( + startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) + ) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) + ret.base = ret.name = path.slice(1, end); + else ret.base = ret.name = path.slice(startPart, end); + } + } else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot); + ret.base = path.slice(1, end); + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + } + ret.ext = path.slice(startDot, end); + } + + if (startPart > 0) ret.dir = path.slice(0, startPart - 1); + else if (isAbsolute) ret.dir = "/"; + + return ret; + }, + + sep: "/", + delimiter: ":", + win32: null, + posix: null +}; + +posix.win32 = win32.win32 = win32; +posix.posix = win32.posix = posix; + +const module = platform.os === "win" ? win32 : posix; + +export const resolve = module.resolve; +export const normalize = module.normalize; +export const isAbsolute = module.isAbsolute; +export const join = module.join; +export const relative = module.relative; +export const toNamespacedPath = module.toNamespacedPath; +export const dirname = module.dirname; +export const basename = module.basename; +export const extname = module.extname; +export const format = module.format; +export const parse = module.parse; +export const sep = module.sep; +export const delimiter = module.delimiter; diff --git a/fs/path/parse_format_test.ts b/fs/path/parse_format_test.ts new file mode 100644 index 000000000..8b429ce24 --- /dev/null +++ b/fs/path/parse_format_test.ts @@ -0,0 +1,176 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "../../testing/mod.ts"; +import * as path from "./mod.ts"; + +const winPaths = [ + // [path, root] + ["C:\\path\\dir\\index.html", "C:\\"], + ["C:\\another_path\\DIR\\1\\2\\33\\\\index", "C:\\"], + ["another_path\\DIR with spaces\\1\\2\\33\\index", ""], + ["\\", "\\"], + ["\\foo\\C:", "\\"], + ["file", ""], + ["file:stream", ""], + [".\\file", ""], + ["C:", "C:"], + ["C:.", "C:"], + ["C:..", "C:"], + ["C:abc", "C:"], + ["C:\\", "C:\\"], + ["C:\\abc", "C:\\"], + ["", ""], + + // unc + ["\\\\server\\share\\file_path", "\\\\server\\share\\"], + [ + "\\\\server two\\shared folder\\file path.zip", + "\\\\server two\\shared folder\\" + ], + ["\\\\teela\\admin$\\system32", "\\\\teela\\admin$\\"], + ["\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\"] +]; + +const winSpecialCaseParseTests = [["/foo/bar", { root: "/" }]]; + +const winSpecialCaseFormatTests = [ + [{ dir: "some\\dir" }, "some\\dir\\"], + [{ base: "index.html" }, "index.html"], + [{ root: "C:\\" }, "C:\\"], + [{ name: "index", ext: ".html" }, "index.html"], + [{ dir: "some\\dir", name: "index", ext: ".html" }, "some\\dir\\index.html"], + [{ root: "C:\\", name: "index", ext: ".html" }, "C:\\index.html"], + [{}, ""] +]; + +const unixPaths = [ + // [path, root] + ["/home/user/dir/file.txt", "/"], + ["/home/user/a dir/another File.zip", "/"], + ["/home/user/a dir//another&File.", "/"], + ["/home/user/a$$$dir//another File.zip", "/"], + ["user/dir/another File.zip", ""], + ["file", ""], + [".\\file", ""], + ["./file", ""], + ["C:\\foo", ""], + ["/", "/"], + ["", ""], + [".", ""], + ["..", ""], + ["/foo", "/"], + ["/foo.", "/"], + ["/foo.bar", "/"], + ["/.", "/"], + ["/.foo", "/"], + ["/.foo.bar", "/"], + ["/foo/bar.baz", "/"] +]; + +const unixSpecialCaseFormatTests = [ + [{ dir: "some/dir" }, "some/dir/"], + [{ base: "index.html" }, "index.html"], + [{ root: "/" }, "/"], + [{ name: "index", ext: ".html" }, "index.html"], + [{ dir: "some/dir", name: "index", ext: ".html" }, "some/dir/index.html"], + [{ root: "/", name: "index", ext: ".html" }, "/index.html"], + [{}, ""] +]; + +test(function parseWin32() { + checkParseFormat(path.win32, winPaths); + checkSpecialCaseParseFormat(path.win32, winSpecialCaseParseTests); +}); + +test(function parse() { + checkParseFormat(path.posix, unixPaths); +}); + +test(function formatWin32() { + checkFormat(path.win32, winSpecialCaseFormatTests); +}); + +test(function format() { + checkFormat(path.posix, unixSpecialCaseFormatTests); +}); + +// Test removal of trailing path separators +const windowsTrailingTests = [ + [".\\", { root: "", dir: "", base: ".", ext: "", name: "." }], + ["\\\\", { root: "\\", dir: "\\", base: "", ext: "", name: "" }], + ["\\\\", { root: "\\", dir: "\\", base: "", ext: "", name: "" }], + [ + "c:\\foo\\\\\\", + { root: "c:\\", dir: "c:\\", base: "foo", ext: "", name: "foo" } + ], + [ + "D:\\foo\\\\\\bar.baz", + { + root: "D:\\", + dir: "D:\\foo\\\\", + base: "bar.baz", + ext: ".baz", + name: "bar" + } + ] +]; +const posixTrailingTests = [ + ["./", { root: "", dir: "", base: ".", ext: "", name: "." }], + ["//", { root: "/", dir: "/", base: "", ext: "", name: "" }], + ["///", { root: "/", dir: "/", base: "", ext: "", name: "" }], + ["/foo///", { root: "/", dir: "/", base: "foo", ext: "", name: "foo" }], + [ + "/foo///bar.baz", + { root: "/", dir: "/foo//", base: "bar.baz", ext: ".baz", name: "bar" } + ] +]; + +function checkParseFormat(path, paths) { + paths.forEach(function(p) { + const element = p[0]; + const output = path.parse(element); + assertEqual(typeof output.root, "string"); + assertEqual(typeof output.dir, "string"); + assertEqual(typeof output.base, "string"); + assertEqual(typeof output.ext, "string"); + assertEqual(typeof output.name, "string"); + assertEqual(path.format(output), element); + assertEqual(output.rooroot, undefined); + assertEqual(output.dir, output.dir ? path.dirname(element) : ""); + assertEqual(output.base, path.basename(element)); + }); +} + +function checkSpecialCaseParseFormat(path, testCases) { + testCases.forEach(function(testCase) { + const element = testCase[0]; + const expect = testCase[1]; + const output = path.parse(element); + Object.keys(expect).forEach(function(key) { + assertEqual(output[key], expect[key]); + }); + }); +} + +function checkFormat(path, testCases) { + testCases.forEach(function(testCase) { + assertEqual(path.format(testCase[0]), testCase[1]); + }); +} + +test(function parseTrailingWin32() { + windowsTrailingTests.forEach(function(p) { + const actual = path.win32.parse(p[0] as string); + const expected = p[1]; + assertEqual(actual, expected); + }); +}); + +test(function parseTrailing() { + posixTrailingTests.forEach(function(p) { + const actual = path.posix.parse(p[0] as string); + const expected = p[1]; + assertEqual(actual, expected); + }); +}); diff --git a/fs/path/relative_test.ts b/fs/path/relative_test.ts new file mode 100644 index 000000000..87e308b43 --- /dev/null +++ b/fs/path/relative_test.ts @@ -0,0 +1,72 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "../../testing/mod.ts"; +import * as path from "./mod.ts"; + +const relativeTests = { + win32: + // arguments result + [ + ["c:/blah\\blah", "d:/games", "d:\\games"], + ["c:/aaaa/bbbb", "c:/aaaa", ".."], + ["c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc"], + ["c:/aaaa/bbbb", "c:/aaaa/bbbb", ""], + ["c:/aaaa/bbbb", "c:/aaaa/cccc", "..\\cccc"], + ["c:/aaaa/", "c:/aaaa/cccc", "cccc"], + ["c:/", "c:\\aaaa\\bbbb", "aaaa\\bbbb"], + ["c:/aaaa/bbbb", "d:\\", "d:\\"], + ["c:/AaAa/bbbb", "c:/aaaa/bbbb", ""], + ["c:/aaaaa/", "c:/aaaa/cccc", "..\\aaaa\\cccc"], + ["C:\\foo\\bar\\baz\\quux", "C:\\", "..\\..\\..\\.."], + [ + "C:\\foo\\test", + "C:\\foo\\test\\bar\\package.json", + "bar\\package.json" + ], + ["C:\\foo\\bar\\baz-quux", "C:\\foo\\bar\\baz", "..\\baz"], + ["C:\\foo\\bar\\baz", "C:\\foo\\bar\\baz-quux", "..\\baz-quux"], + ["\\\\foo\\bar", "\\\\foo\\bar\\baz", "baz"], + ["\\\\foo\\bar\\baz", "\\\\foo\\bar", ".."], + ["\\\\foo\\bar\\baz-quux", "\\\\foo\\bar\\baz", "..\\baz"], + ["\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz-quux", "..\\baz-quux"], + ["C:\\baz-quux", "C:\\baz", "..\\baz"], + ["C:\\baz", "C:\\baz-quux", "..\\baz-quux"], + ["\\\\foo\\baz-quux", "\\\\foo\\baz", "..\\baz"], + ["\\\\foo\\baz", "\\\\foo\\baz-quux", "..\\baz-quux"], + ["C:\\baz", "\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz"], + ["\\\\foo\\bar\\baz", "C:\\baz", "C:\\baz"] + ], + posix: + // arguments result + [ + ["/var/lib", "/var", ".."], + ["/var/lib", "/bin", "../../bin"], + ["/var/lib", "/var/lib", ""], + ["/var/lib", "/var/apache", "../apache"], + ["/var/", "/var/lib", "lib"], + ["/", "/var/lib", "var/lib"], + ["/foo/test", "/foo/test/bar/package.json", "bar/package.json"], + ["/Users/a/web/b/test/mails", "/Users/a/web/b", "../.."], + ["/foo/bar/baz-quux", "/foo/bar/baz", "../baz"], + ["/foo/bar/baz", "/foo/bar/baz-quux", "../baz-quux"], + ["/baz-quux", "/baz", "../baz"], + ["/baz", "/baz-quux", "../baz-quux"] + ] +}; + +test(function relative() { + relativeTests.posix.forEach(function(p) { + const expected = p[2]; + const actual = path.posix.relative(p[0], p[1]); + assertEqual(actual, expected); + }); +}); + +test(function relativeWin32() { + relativeTests.win32.forEach(function(p) { + const expected = p[2]; + const actual = path.win32.relative(p[0], p[1]); + assertEqual(actual, expected); + }); +}); diff --git a/fs/path/resolve_test.ts b/fs/path/resolve_test.ts new file mode 100644 index 000000000..7c2b55249 --- /dev/null +++ b/fs/path/resolve_test.ts @@ -0,0 +1,49 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "../../testing/mod.ts"; +import * as path from "./mod.ts"; +import { cwd } from "deno"; + +const windowsTests = + // arguments result + [ + [["c:/blah\\blah", "d:/games", "c:../a"], "c:\\blah\\a"], + [["c:/ignore", "d:\\a/b\\c/d", "\\e.exe"], "d:\\e.exe"], + [["c:/ignore", "c:/some/file"], "c:\\some\\file"], + [["d:/ignore", "d:some/dir//"], "d:\\ignore\\some\\dir"], + [["//server/share", "..", "relative\\"], "\\\\server\\share\\relative"], + [["c:/", "//"], "c:\\"], + [["c:/", "//dir"], "c:\\dir"], + [["c:/", "//server/share"], "\\\\server\\share\\"], + [["c:/", "//server//share"], "\\\\server\\share\\"], + [["c:/", "///some//dir"], "c:\\some\\dir"], + [ + ["C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js"], + "C:\\foo\\tmp.3\\cycles\\root.js" + ] + ]; +const posixTests = + // arguments result + [ + [["/var/lib", "../", "file/"], "/var/file"], + [["/var/lib", "/../", "file/"], "/file"], + [["a/b/c/", "../../.."], cwd()], + [["."], cwd()], + [["/some/dir", ".", "/absolute/"], "/absolute"], + [["/foo/tmp.3/", "../tmp.3/cycles/root.js"], "/foo/tmp.3/cycles/root.js"] + ]; + +test(function resolve() { + posixTests.forEach(function(p) { + const actual = path.posix.resolve.apply(null, p[0]); + assertEqual(actual, p[1]); + }); +}); + +test(function resolveWin32() { + windowsTests.forEach(function(p) { + const actual = path.win32.resolve.apply(null, p[0]); + assertEqual(actual, p[1]); + }); +}); diff --git a/fs/path/zero_length_strings_test.ts b/fs/path/zero_length_strings_test.ts new file mode 100644 index 000000000..d069c781f --- /dev/null +++ b/fs/path/zero_length_strings_test.ts @@ -0,0 +1,46 @@ +// Copyright the Browserify authors. MIT License. +// Ported from https://github.com/browserify/path-browserify/ + +import { test, assertEqual } from "../../testing/mod.ts"; +import * as path from "./mod.ts"; +import { cwd } from "deno"; + +const pwd = cwd(); + +test(function joinZeroLength() { + // join will internally ignore all the zero-length strings and it will return + // '.' if the joined string is a zero-length string. + assertEqual(path.posix.join(""), "."); + assertEqual(path.posix.join("", ""), "."); + if (path.win32) assertEqual(path.win32.join(""), "."); + if (path.win32) assertEqual(path.win32.join("", ""), "."); + assertEqual(path.join(pwd), pwd); + assertEqual(path.join(pwd, ""), pwd); +}); + +test(function normalizeZeroLength() { + // normalize will return '.' if the input is a zero-length string + assertEqual(path.posix.normalize(""), "."); + if (path.win32) assertEqual(path.win32.normalize(""), "."); + assertEqual(path.normalize(pwd), pwd); +}); + +test(function isAbsoluteZeroLength() { + // Since '' is not a valid path in any of the common environments, return false + assertEqual(path.posix.isAbsolute(""), false); + if (path.win32) assertEqual(path.win32.isAbsolute(""), false); +}); + +test(function resolveZeroLength() { + // resolve, internally ignores all the zero-length strings and returns the + // current working directory + assertEqual(path.resolve(""), pwd); + assertEqual(path.resolve("", ""), pwd); +}); + +test(function relativeZeroLength() { + // relative, internally calls resolve. So, '' is actually the current directory + assertEqual(path.relative("", pwd), ""); + assertEqual(path.relative(pwd, ""), ""); + assertEqual(path.relative(pwd, pwd), ""); +}); diff --git a/net/file_server.ts b/net/file_server.ts index 91afa2d57..bebb93969 100755 --- a/net/file_server.ts +++ b/net/file_server.ts @@ -12,7 +12,7 @@ import { Response } from "./http.ts"; import { cwd, DenoError, ErrorKind, args, stat, readDir, open } from "deno"; -import { extname } from "../path/index.ts"; +import { extname } from "../fs/path.ts"; import * as extensionsMap from "./extension_map.json"; const dirViewerTemplate = ` diff --git a/path/README.md b/path/README.md deleted file mode 100644 index 924b0a993..000000000 --- a/path/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Deno Path Manipulation Libraries - -Usage: - -```ts -import * as path from "https://deno.land/x/path/index.ts"; -``` diff --git a/path/basename_test.ts b/path/basename_test.ts deleted file mode 100644 index b605aa210..000000000 --- a/path/basename_test.ts +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ - -import { test, assertEqual } from "../testing/mod.ts"; -import * as path from "./index.ts"; - -test(function basename() { - assertEqual(path.basename(".js", ".js"), ""); - assertEqual(path.basename(""), ""); - assertEqual(path.basename("/dir/basename.ext"), "basename.ext"); - assertEqual(path.basename("/basename.ext"), "basename.ext"); - assertEqual(path.basename("basename.ext"), "basename.ext"); - assertEqual(path.basename("basename.ext/"), "basename.ext"); - assertEqual(path.basename("basename.ext//"), "basename.ext"); - assertEqual(path.basename("aaa/bbb", "/bbb"), "bbb"); - assertEqual(path.basename("aaa/bbb", "a/bbb"), "bbb"); - assertEqual(path.basename("aaa/bbb", "bbb"), "bbb"); - assertEqual(path.basename("aaa/bbb//", "bbb"), "bbb"); - assertEqual(path.basename("aaa/bbb", "bb"), "b"); - assertEqual(path.basename("aaa/bbb", "b"), "bb"); - assertEqual(path.basename("/aaa/bbb", "/bbb"), "bbb"); - assertEqual(path.basename("/aaa/bbb", "a/bbb"), "bbb"); - assertEqual(path.basename("/aaa/bbb", "bbb"), "bbb"); - assertEqual(path.basename("/aaa/bbb//", "bbb"), "bbb"); - assertEqual(path.basename("/aaa/bbb", "bb"), "b"); - assertEqual(path.basename("/aaa/bbb", "b"), "bb"); - assertEqual(path.basename("/aaa/bbb"), "bbb"); - assertEqual(path.basename("/aaa/"), "aaa"); - assertEqual(path.basename("/aaa/b"), "b"); - assertEqual(path.basename("/a/b"), "b"); - assertEqual(path.basename("//a"), "a"); - - // On unix a backslash is just treated as any other character. - assertEqual( - path.posix.basename("\\dir\\basename.ext"), - "\\dir\\basename.ext" - ); - assertEqual(path.posix.basename("\\basename.ext"), "\\basename.ext"); - assertEqual(path.posix.basename("basename.ext"), "basename.ext"); - assertEqual(path.posix.basename("basename.ext\\"), "basename.ext\\"); - assertEqual(path.posix.basename("basename.ext\\\\"), "basename.ext\\\\"); - assertEqual(path.posix.basename("foo"), "foo"); - - // POSIX filenames may include control characters - const controlCharFilename = "Icon" + String.fromCharCode(13); - assertEqual( - path.posix.basename("/a/b/" + controlCharFilename), - controlCharFilename - ); -}); - -test(function basenameWin32() { - assertEqual(path.win32.basename("\\dir\\basename.ext"), "basename.ext"); - assertEqual(path.win32.basename("\\basename.ext"), "basename.ext"); - assertEqual(path.win32.basename("basename.ext"), "basename.ext"); - assertEqual(path.win32.basename("basename.ext\\"), "basename.ext"); - assertEqual(path.win32.basename("basename.ext\\\\"), "basename.ext"); - assertEqual(path.win32.basename("foo"), "foo"); - assertEqual(path.win32.basename("aaa\\bbb", "\\bbb"), "bbb"); - assertEqual(path.win32.basename("aaa\\bbb", "a\\bbb"), "bbb"); - assertEqual(path.win32.basename("aaa\\bbb", "bbb"), "bbb"); - assertEqual(path.win32.basename("aaa\\bbb\\\\\\\\", "bbb"), "bbb"); - assertEqual(path.win32.basename("aaa\\bbb", "bb"), "b"); - assertEqual(path.win32.basename("aaa\\bbb", "b"), "bb"); - assertEqual(path.win32.basename("C:"), ""); - assertEqual(path.win32.basename("C:."), "."); - assertEqual(path.win32.basename("C:\\"), ""); - assertEqual(path.win32.basename("C:\\dir\\base.ext"), "base.ext"); - assertEqual(path.win32.basename("C:\\basename.ext"), "basename.ext"); - assertEqual(path.win32.basename("C:basename.ext"), "basename.ext"); - assertEqual(path.win32.basename("C:basename.ext\\"), "basename.ext"); - assertEqual(path.win32.basename("C:basename.ext\\\\"), "basename.ext"); - assertEqual(path.win32.basename("C:foo"), "foo"); - assertEqual(path.win32.basename("file:stream"), "file:stream"); -}); diff --git a/path/constants.ts b/path/constants.ts deleted file mode 100644 index b440be9cc..000000000 --- a/path/constants.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ - -import { platform } from "deno"; - -const isWindows = platform.os === "win"; - -// Alphabet chars. -export const CHAR_UPPERCASE_A = 65; /* A */ -export const CHAR_LOWERCASE_A = 97; /* a */ -export const CHAR_UPPERCASE_Z = 90; /* Z */ -export const CHAR_LOWERCASE_Z = 122; /* z */ - -// Non-alphabetic chars. -export const CHAR_DOT = 46; /* . */ -export const CHAR_FORWARD_SLASH = 47; /* / */ -export const CHAR_BACKWARD_SLASH = 92; /* \ */ -export const CHAR_VERTICAL_LINE = 124; /* | */ -export const CHAR_COLON = 58; /* : */ -export const CHAR_QUESTION_MARK = 63; /* ? */ -export const CHAR_UNDERSCORE = 95; /* _ */ -export const CHAR_LINE_FEED = 10; /* \n */ -export const CHAR_CARRIAGE_RETURN = 13; /* \r */ -export const CHAR_TAB = 9; /* \t */ -export const CHAR_FORM_FEED = 12; /* \f */ -export const CHAR_EXCLAMATION_MARK = 33; /* ! */ -export const CHAR_HASH = 35; /* # */ -export const CHAR_SPACE = 32; /* */ -export const CHAR_NO_BREAK_SPACE = 160; /* \u00A0 */ -export const CHAR_ZERO_WIDTH_NOBREAK_SPACE = 65279; /* \uFEFF */ -export const CHAR_LEFT_SQUARE_BRACKET = 91; /* [ */ -export const CHAR_RIGHT_SQUARE_BRACKET = 93; /* ] */ -export const CHAR_LEFT_ANGLE_BRACKET = 60; /* < */ -export const CHAR_RIGHT_ANGLE_BRACKET = 62; /* > */ -export const CHAR_LEFT_CURLY_BRACKET = 123; /* { */ -export const CHAR_RIGHT_CURLY_BRACKET = 125; /* } */ -export const CHAR_HYPHEN_MINUS = 45; /* - */ -export const CHAR_PLUS = 43; /* + */ -export const CHAR_DOUBLE_QUOTE = 34; /* " */ -export const CHAR_SINGLE_QUOTE = 39; /* ' */ -export const CHAR_PERCENT = 37; /* % */ -export const CHAR_SEMICOLON = 59; /* ; */ -export const CHAR_CIRCUMFLEX_ACCENT = 94; /* ^ */ -export const CHAR_GRAVE_ACCENT = 96; /* ` */ -export const CHAR_AT = 64; /* @ */ -export const CHAR_AMPERSAND = 38; /* & */ -export const CHAR_EQUAL = 61; /* = */ - -// Digits -export const CHAR_0 = 48; /* 0 */ -export const CHAR_9 = 57; /* 9 */ - -export const EOL = isWindows ? "\r\n" : "\n"; diff --git a/path/dirname_test.ts b/path/dirname_test.ts deleted file mode 100644 index e535ec891..000000000 --- a/path/dirname_test.ts +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ - -import { test, assertEqual } from "../testing/mod.ts"; -import * as path from "./index.ts"; - -test(function dirname() { - assertEqual(path.posix.dirname("/a/b/"), "/a"); - assertEqual(path.posix.dirname("/a/b"), "/a"); - assertEqual(path.posix.dirname("/a"), "/"); - assertEqual(path.posix.dirname(""), "."); - assertEqual(path.posix.dirname("/"), "/"); - assertEqual(path.posix.dirname("////"), "/"); - assertEqual(path.posix.dirname("//a"), "//"); - assertEqual(path.posix.dirname("foo"), "."); -}); - -test(function dirnameWin32() { - assertEqual(path.win32.dirname("c:\\"), "c:\\"); - assertEqual(path.win32.dirname("c:\\foo"), "c:\\"); - assertEqual(path.win32.dirname("c:\\foo\\"), "c:\\"); - assertEqual(path.win32.dirname("c:\\foo\\bar"), "c:\\foo"); - assertEqual(path.win32.dirname("c:\\foo\\bar\\"), "c:\\foo"); - assertEqual(path.win32.dirname("c:\\foo\\bar\\baz"), "c:\\foo\\bar"); - assertEqual(path.win32.dirname("\\"), "\\"); - assertEqual(path.win32.dirname("\\foo"), "\\"); - assertEqual(path.win32.dirname("\\foo\\"), "\\"); - assertEqual(path.win32.dirname("\\foo\\bar"), "\\foo"); - assertEqual(path.win32.dirname("\\foo\\bar\\"), "\\foo"); - assertEqual(path.win32.dirname("\\foo\\bar\\baz"), "\\foo\\bar"); - assertEqual(path.win32.dirname("c:"), "c:"); - assertEqual(path.win32.dirname("c:foo"), "c:"); - assertEqual(path.win32.dirname("c:foo\\"), "c:"); - assertEqual(path.win32.dirname("c:foo\\bar"), "c:foo"); - assertEqual(path.win32.dirname("c:foo\\bar\\"), "c:foo"); - assertEqual(path.win32.dirname("c:foo\\bar\\baz"), "c:foo\\bar"); - assertEqual(path.win32.dirname("file:stream"), "."); - assertEqual(path.win32.dirname("dir\\file:stream"), "dir"); - assertEqual(path.win32.dirname("\\\\unc\\share"), "\\\\unc\\share"); - assertEqual(path.win32.dirname("\\\\unc\\share\\foo"), "\\\\unc\\share\\"); - assertEqual(path.win32.dirname("\\\\unc\\share\\foo\\"), "\\\\unc\\share\\"); - assertEqual( - path.win32.dirname("\\\\unc\\share\\foo\\bar"), - "\\\\unc\\share\\foo" - ); - assertEqual( - path.win32.dirname("\\\\unc\\share\\foo\\bar\\"), - "\\\\unc\\share\\foo" - ); - assertEqual( - path.win32.dirname("\\\\unc\\share\\foo\\bar\\baz"), - "\\\\unc\\share\\foo\\bar" - ); - assertEqual(path.win32.dirname("/a/b/"), "/a"); - assertEqual(path.win32.dirname("/a/b"), "/a"); - assertEqual(path.win32.dirname("/a"), "/"); - assertEqual(path.win32.dirname(""), "."); - assertEqual(path.win32.dirname("/"), "/"); - assertEqual(path.win32.dirname("////"), "/"); - assertEqual(path.win32.dirname("foo"), "."); -}); diff --git a/path/extname_test.ts b/path/extname_test.ts deleted file mode 100644 index 0d6d283a8..000000000 --- a/path/extname_test.ts +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ - -import { test, assertEqual } from "../testing/mod.ts"; -import * as path from "./index.ts"; - -const slashRE = /\//g; - -const pairs = [ - ["", ""], - ["/path/to/file", ""], - ["/path/to/file.ext", ".ext"], - ["/path.to/file.ext", ".ext"], - ["/path.to/file", ""], - ["/path.to/.file", ""], - ["/path.to/.file.ext", ".ext"], - ["/path/to/f.ext", ".ext"], - ["/path/to/..ext", ".ext"], - ["/path/to/..", ""], - ["file", ""], - ["file.ext", ".ext"], - [".file", ""], - [".file.ext", ".ext"], - ["/file", ""], - ["/file.ext", ".ext"], - ["/.file", ""], - ["/.file.ext", ".ext"], - [".path/file.ext", ".ext"], - ["file.ext.ext", ".ext"], - ["file.", "."], - [".", ""], - ["./", ""], - [".file.ext", ".ext"], - [".file", ""], - [".file.", "."], - [".file..", "."], - ["..", ""], - ["../", ""], - ["..file.ext", ".ext"], - ["..file", ".file"], - ["..file.", "."], - ["..file..", "."], - ["...", "."], - ["...ext", ".ext"], - ["....", "."], - ["file.ext/", ".ext"], - ["file.ext//", ".ext"], - ["file/", ""], - ["file//", ""], - ["file./", "."], - ["file.//", "."] -]; - -test(function extname() { - pairs.forEach(function(p) { - const input = p[0]; - const expected = p[1]; - assertEqual(expected, path.posix.extname(input)); - }); - - // On *nix, backslash is a valid name component like any other character. - assertEqual(path.posix.extname(".\\"), ""); - assertEqual(path.posix.extname("..\\"), ".\\"); - assertEqual(path.posix.extname("file.ext\\"), ".ext\\"); - assertEqual(path.posix.extname("file.ext\\\\"), ".ext\\\\"); - assertEqual(path.posix.extname("file\\"), ""); - assertEqual(path.posix.extname("file\\\\"), ""); - assertEqual(path.posix.extname("file.\\"), ".\\"); - assertEqual(path.posix.extname("file.\\\\"), ".\\\\"); -}); - -test(function extnameWin32() { - pairs.forEach(function(p) { - const input = p[0].replace(slashRE, "\\"); - const expected = p[1]; - assertEqual(expected, path.win32.extname(input)); - assertEqual(expected, path.win32.extname("C:" + input)); - }); - - // On Windows, backslash is a path separator. - assertEqual(path.win32.extname(".\\"), ""); - assertEqual(path.win32.extname("..\\"), ""); - assertEqual(path.win32.extname("file.ext\\"), ".ext"); - assertEqual(path.win32.extname("file.ext\\\\"), ".ext"); - assertEqual(path.win32.extname("file\\"), ""); - assertEqual(path.win32.extname("file\\\\"), ""); - assertEqual(path.win32.extname("file.\\"), "."); - assertEqual(path.win32.extname("file.\\\\"), "."); -}); diff --git a/path/index.ts b/path/index.ts deleted file mode 100644 index 4201c52ad..000000000 --- a/path/index.ts +++ /dev/null @@ -1,1438 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ - -import { - CHAR_UPPERCASE_A, - CHAR_LOWERCASE_A, - CHAR_UPPERCASE_Z, - CHAR_LOWERCASE_Z, - CHAR_DOT, - CHAR_FORWARD_SLASH, - CHAR_BACKWARD_SLASH, - CHAR_COLON, - CHAR_QUESTION_MARK -} from "./constants.ts"; -import { cwd, env, platform } from "deno"; -import { FormatInputPathObject, ParsedPath } from "./interface.ts"; - -function assertPath(path: string) { - if (typeof path !== "string") { - throw new TypeError( - `Path must be a string. Received ${JSON.stringify(path)}` - ); - } -} - -function isPathSeparator(code: number) { - return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; -} - -function isPosixPathSeparator(code: number) { - return code === CHAR_FORWARD_SLASH; -} - -function isWindowsDeviceRoot(code: number) { - return ( - (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || - (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z) - ); -} - -// Resolves . and .. elements in a path with directory names -function normalizeString( - path: string, - allowAboveRoot: boolean, - separator: string, - isPathSeparator: (code: number) => boolean -) { - let res = ""; - let lastSegmentLength = 0; - let lastSlash = -1; - let dots = 0; - let code: number; - for (let i = 0; i <= path.length; ++i) { - if (i < path.length) code = path.charCodeAt(i); - else if (isPathSeparator(code)) break; - else code = CHAR_FORWARD_SLASH; - - if (isPathSeparator(code)) { - if (lastSlash === i - 1 || dots === 1) { - // NOOP - } else if (lastSlash !== i - 1 && dots === 2) { - if ( - res.length < 2 || - lastSegmentLength !== 2 || - res.charCodeAt(res.length - 1) !== CHAR_DOT || - res.charCodeAt(res.length - 2) !== CHAR_DOT - ) { - if (res.length > 2) { - const lastSlashIndex = res.lastIndexOf(separator); - if (lastSlashIndex === -1) { - res = ""; - lastSegmentLength = 0; - } else { - res = res.slice(0, lastSlashIndex); - lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); - } - lastSlash = i; - dots = 0; - continue; - } else if (res.length === 2 || res.length === 1) { - res = ""; - lastSegmentLength = 0; - lastSlash = i; - dots = 0; - continue; - } - } - if (allowAboveRoot) { - if (res.length > 0) res += `${separator}..`; - else res = ".."; - lastSegmentLength = 2; - } - } else { - if (res.length > 0) res += separator + path.slice(lastSlash + 1, i); - else res = path.slice(lastSlash + 1, i); - lastSegmentLength = i - lastSlash - 1; - } - lastSlash = i; - dots = 0; - } else if (code === CHAR_DOT && dots !== -1) { - ++dots; - } else { - dots = -1; - } - } - return res; -} - -function _format(sep: string, pathObject: FormatInputPathObject) { - const dir = pathObject.dir || pathObject.root; - const base = - pathObject.base || (pathObject.name || "") + (pathObject.ext || ""); - if (!dir) { - return base; - } - if (dir === pathObject.root) { - return dir + base; - } - return dir + sep + base; -} - -export const win32 = { - // path.resolve([from ...], to) - resolve: function resolve(...pathSegments: string[]) { - let resolvedDevice = ""; - let resolvedTail = ""; - let resolvedAbsolute = false; - - for (let i = arguments.length - 1; i >= -1; i--) { - let path: string; - if (i >= 0) { - path = arguments[i]; - } else if (!resolvedDevice) { - path = cwd(); - } else { - // Windows has the concept of drive-specific current working - // directories. If we've resolved a drive letter but not yet an - // absolute path, get cwd for that drive, or the process cwd if - // the drive cwd is not available. We're sure the device is not - // a UNC path at this points, because UNC paths are always absolute. - path = env()[`=${resolvedDevice}`] || cwd(); - - // Verify that a cwd was found and that it actually points - // to our drive. If not, default to the drive's root. - if ( - path === undefined || - path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\` - ) { - path = `${resolvedDevice}\\`; - } - } - - assertPath(path); - - // Skip empty entries - if (path.length === 0) { - continue; - } - - let len = path.length; - let rootEnd = 0; - let device = ""; - let isAbsolute = false; - const code = path.charCodeAt(0); - - // Try to match a root - if (len > 1) { - if (isPathSeparator(code)) { - // Possible UNC root - - // If we started with a separator, we know we at least have an - // absolute path of some kind (UNC or otherwise) - isAbsolute = true; - - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - const firstPart = path.slice(last, j); - // Matched! - last = j; - // Match 1 or more path separators - for (; j < len; ++j) { - if (!isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j === len) { - // We matched a UNC root only - device = `\\\\${firstPart}\\${path.slice(last)}`; - rootEnd = j; - } else if (j !== last) { - // We matched a UNC root with leftovers - - device = `\\\\${firstPart}\\${path.slice(last, j)}`; - rootEnd = j; - } - } - } - } else { - rootEnd = 1; - } - } else if (isWindowsDeviceRoot(code)) { - // Possible device root - - if (path.charCodeAt(1) === CHAR_COLON) { - device = path.slice(0, 2); - rootEnd = 2; - if (len > 2) { - if (isPathSeparator(path.charCodeAt(2))) { - // Treat separator following drive name as an absolute path - // indicator - isAbsolute = true; - rootEnd = 3; - } - } - } - } - } else if (isPathSeparator(code)) { - // `path` contains just a path separator - rootEnd = 1; - isAbsolute = true; - } - - if ( - device.length > 0 && - resolvedDevice.length > 0 && - device.toLowerCase() !== resolvedDevice.toLowerCase() - ) { - // This path points to another device so it is not applicable - continue; - } - - if (resolvedDevice.length === 0 && device.length > 0) { - resolvedDevice = device; - } - if (!resolvedAbsolute) { - resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; - resolvedAbsolute = isAbsolute; - } - - if (resolvedDevice.length > 0 && resolvedAbsolute) { - break; - } - } - - // At this point the path should be resolved to a full absolute path, - // but handle relative paths to be safe (might happen when process.cwd() - // fails) - - // Normalize the tail path - resolvedTail = normalizeString( - resolvedTail, - !resolvedAbsolute, - "\\", - isPathSeparator - ); - - return ( - resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || "." - ); - }, - - normalize: function normalize(path: string) { - assertPath(path); - const len = path.length; - if (len === 0) return "."; - let rootEnd = 0; - let device: string; - let isAbsolute = false; - const code = path.charCodeAt(0); - - // Try to match a root - if (len > 1) { - if (isPathSeparator(code)) { - // Possible UNC root - - // If we started with a separator, we know we at least have an absolute - // path of some kind (UNC or otherwise) - isAbsolute = true; - - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - const firstPart = path.slice(last, j); - // Matched! - last = j; - // Match 1 or more path separators - for (; j < len; ++j) { - if (!isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j === len) { - // We matched a UNC root only - // Return the normalized version of the UNC root since there - // is nothing left to process - - return `\\\\${firstPart}\\${path.slice(last)}\\`; - } else if (j !== last) { - // We matched a UNC root with leftovers - - device = `\\\\${firstPart}\\${path.slice(last, j)}`; - rootEnd = j; - } - } - } - } else { - rootEnd = 1; - } - } else if (isWindowsDeviceRoot(code)) { - // Possible device root - - if (path.charCodeAt(1) === CHAR_COLON) { - device = path.slice(0, 2); - rootEnd = 2; - if (len > 2) { - if (isPathSeparator(path.charCodeAt(2))) { - // Treat separator following drive name as an absolute path - // indicator - isAbsolute = true; - rootEnd = 3; - } - } - } - } - } else if (isPathSeparator(code)) { - // `path` contains just a path separator, exit early to avoid unnecessary - // work - return "\\"; - } - - let tail: string; - if (rootEnd < len) { - tail = normalizeString( - path.slice(rootEnd), - !isAbsolute, - "\\", - isPathSeparator - ); - } else { - tail = ""; - } - if (tail.length === 0 && !isAbsolute) tail = "."; - if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) - tail += "\\"; - if (device === undefined) { - if (isAbsolute) { - if (tail.length > 0) return `\\${tail}`; - else return "\\"; - } else if (tail.length > 0) { - return tail; - } else { - return ""; - } - } else if (isAbsolute) { - if (tail.length > 0) return `${device}\\${tail}`; - else return `${device}\\`; - } else if (tail.length > 0) { - return device + tail; - } else { - return device; - } - }, - - isAbsolute: function isAbsolute(path: string) { - assertPath(path); - const len = path.length; - if (len === 0) return false; - - const code = path.charCodeAt(0); - if (isPathSeparator(code)) { - return true; - } else if (isWindowsDeviceRoot(code)) { - // Possible device root - - if (len > 2 && path.charCodeAt(1) === CHAR_COLON) { - if (isPathSeparator(path.charCodeAt(2))) return true; - } - } - return false; - }, - - join: function join(...paths: string[]) { - if (arguments.length === 0) return "."; - - let joined: string; - let firstPart: string; - for (let i = 0; i < arguments.length; ++i) { - let arg = arguments[i]; - assertPath(arg); - if (arg.length > 0) { - if (joined === undefined) joined = firstPart = arg; - else joined += `\\${arg}`; - } - } - - if (joined === undefined) return "."; - - // Make sure that the joined path doesn't start with two slashes, because - // normalize() will mistake it for an UNC path then. - // - // This step is skipped when it is very clear that the user actually - // intended to point at an UNC path. This is assumed when the first - // non-empty string arguments starts with exactly two slashes followed by - // at least one more non-slash character. - // - // Note that for normalize() to treat a path as an UNC path it needs to - // have at least 2 components, so we don't filter for that here. - // This means that the user can use join to construct UNC paths from - // a server name and a share name; for example: - // path.join('//server', 'share') -> '\\\\server\\share\\') - let needsReplace = true; - let slashCount = 0; - if (isPathSeparator(firstPart.charCodeAt(0))) { - ++slashCount; - const firstLen = firstPart.length; - if (firstLen > 1) { - if (isPathSeparator(firstPart.charCodeAt(1))) { - ++slashCount; - if (firstLen > 2) { - if (isPathSeparator(firstPart.charCodeAt(2))) ++slashCount; - else { - // We matched a UNC path in the first part - needsReplace = false; - } - } - } - } - } - if (needsReplace) { - // Find any more consecutive slashes we need to replace - for (; slashCount < joined.length; ++slashCount) { - if (!isPathSeparator(joined.charCodeAt(slashCount))) break; - } - - // Replace the slashes if needed - if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`; - } - - return win32.normalize(joined); - }, - - // It will solve the relative path from `from` to `to`, for instance: - // from = 'C:\\orandea\\test\\aaa' - // to = 'C:\\orandea\\impl\\bbb' - // The output of the function should be: '..\\..\\impl\\bbb' - relative: function relative(from: string, to: string) { - assertPath(from); - assertPath(to); - - if (from === to) return ""; - - let fromOrig = win32.resolve(from); - let toOrig = win32.resolve(to); - - if (fromOrig === toOrig) return ""; - - from = fromOrig.toLowerCase(); - to = toOrig.toLowerCase(); - - if (from === to) return ""; - - // Trim any leading backslashes - let fromStart = 0; - for (; fromStart < from.length; ++fromStart) { - if (from.charCodeAt(fromStart) !== CHAR_BACKWARD_SLASH) break; - } - // Trim trailing backslashes (applicable to UNC paths only) - let fromEnd = from.length; - for (; fromEnd - 1 > fromStart; --fromEnd) { - if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break; - } - let fromLen = fromEnd - fromStart; - - // Trim any leading backslashes - let toStart = 0; - for (; toStart < to.length; ++toStart) { - if (to.charCodeAt(toStart) !== CHAR_BACKWARD_SLASH) break; - } - // Trim trailing backslashes (applicable to UNC paths only) - let toEnd = to.length; - for (; toEnd - 1 > toStart; --toEnd) { - if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break; - } - let toLen = toEnd - toStart; - - // Compare paths to find the longest common path from root - let length = fromLen < toLen ? fromLen : toLen; - let lastCommonSep = -1; - let i = 0; - for (; i <= length; ++i) { - if (i === length) { - if (toLen > length) { - if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { - // We get here if `from` is the exact base path for `to`. - // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' - return toOrig.slice(toStart + i + 1); - } else if (i === 2) { - // We get here if `from` is the device root. - // For example: from='C:\\'; to='C:\\foo' - return toOrig.slice(toStart + i); - } - } - if (fromLen > length) { - if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { - // We get here if `to` is the exact base path for `from`. - // For example: from='C:\\foo\\bar'; to='C:\\foo' - lastCommonSep = i; - } else if (i === 2) { - // We get here if `to` is the device root. - // For example: from='C:\\foo\\bar'; to='C:\\' - lastCommonSep = 3; - } - } - break; - } - let fromCode = from.charCodeAt(fromStart + i); - let toCode = to.charCodeAt(toStart + i); - if (fromCode !== toCode) break; - else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i; - } - - // We found a mismatch before the first common path separator was seen, so - // return the original `to`. - if (i !== length && lastCommonSep === -1) { - return toOrig; - } - - let out = ""; - if (lastCommonSep === -1) lastCommonSep = 0; - // Generate the relative path based on the path difference between `to` and - // `from` - for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { - if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { - if (out.length === 0) out += ".."; - else out += "\\.."; - } - } - - // Lastly, append the rest of the destination (`to`) path that comes after - // the common path parts - if (out.length > 0) - return out + toOrig.slice(toStart + lastCommonSep, toEnd); - else { - toStart += lastCommonSep; - if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) ++toStart; - return toOrig.slice(toStart, toEnd); - } - }, - - toNamespacedPath: function toNamespacedPath(path: string) { - // Note: this will *probably* throw somewhere. - if (typeof path !== "string") return path; - - if (path.length === 0) { - return ""; - } - - const resolvedPath = win32.resolve(path); - - if (resolvedPath.length >= 3) { - if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { - // Possible UNC root - - if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { - const code = resolvedPath.charCodeAt(2); - if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { - // Matched non-long UNC root, convert the path to a long UNC path - return `\\\\?\\UNC\\${resolvedPath.slice(2)}`; - } - } - } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0))) { - // Possible device root - - if ( - resolvedPath.charCodeAt(1) === CHAR_COLON && - resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH - ) { - // Matched device root, convert the path to a long UNC path - return `\\\\?\\${resolvedPath}`; - } - } - } - - return path; - }, - - dirname: function dirname(path: string) { - assertPath(path); - const len = path.length; - if (len === 0) return "."; - let rootEnd = -1; - let end = -1; - let matchedSlash = true; - let offset = 0; - const code = path.charCodeAt(0); - - // Try to match a root - if (len > 1) { - if (isPathSeparator(code)) { - // Possible UNC root - - rootEnd = offset = 1; - - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more path separators - for (; j < len; ++j) { - if (!isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j === len) { - // We matched a UNC root only - return path; - } - if (j !== last) { - // We matched a UNC root with leftovers - - // Offset by 1 to include the separator after the UNC root to - // treat it as a "normal root" on top of a (UNC) root - rootEnd = offset = j + 1; - } - } - } - } - } else if (isWindowsDeviceRoot(code)) { - // Possible device root - - if (path.charCodeAt(1) === CHAR_COLON) { - rootEnd = offset = 2; - if (len > 2) { - if (isPathSeparator(path.charCodeAt(2))) rootEnd = offset = 3; - } - } - } - } else if (isPathSeparator(code)) { - // `path` contains just a path separator, exit early to avoid - // unnecessary work - return path; - } - - for (let i = len - 1; i >= offset; --i) { - if (isPathSeparator(path.charCodeAt(i))) { - if (!matchedSlash) { - end = i; - break; - } - } else { - // We saw the first non-path separator - matchedSlash = false; - } - } - - if (end === -1) { - if (rootEnd === -1) return "."; - else end = rootEnd; - } - return path.slice(0, end); - }, - - basename: function basename(path: string, ext = "") { - if (ext !== undefined && typeof ext !== "string") - throw new TypeError('"ext" argument must be a string'); - assertPath(path); - let start = 0; - let end = -1; - let matchedSlash = true; - let i: number; - - // Check for a drive letter prefix so as not to mistake the following - // path separator as an extra separator at the end of the path that can be - // disregarded - if (path.length >= 2) { - const drive = path.charCodeAt(0); - if (isWindowsDeviceRoot(drive)) { - if (path.charCodeAt(1) === CHAR_COLON) start = 2; - } - } - - if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { - if (ext.length === path.length && ext === path) return ""; - let extIdx = ext.length - 1; - let firstNonSlashEnd = -1; - for (i = path.length - 1; i >= start; --i) { - const code = path.charCodeAt(i); - if (isPathSeparator(code)) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } else { - if (firstNonSlashEnd === -1) { - // We saw the first non-path separator, remember this index in case - // we need it if the extension ends up not matching - matchedSlash = false; - firstNonSlashEnd = i + 1; - } - if (extIdx >= 0) { - // Try to match the explicit extension - if (code === ext.charCodeAt(extIdx)) { - if (--extIdx === -1) { - // We matched the extension, so mark this as the end of our path - // component - end = i; - } - } else { - // Extension does not match, so our result is the entire path - // component - extIdx = -1; - end = firstNonSlashEnd; - } - } - } - } - - if (start === end) end = firstNonSlashEnd; - else if (end === -1) end = path.length; - return path.slice(start, end); - } else { - for (i = path.length - 1; i >= start; --i) { - if (isPathSeparator(path.charCodeAt(i))) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } else if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // path component - matchedSlash = false; - end = i + 1; - } - } - - if (end === -1) return ""; - return path.slice(start, end); - } - }, - - extname: function extname(path: string) { - assertPath(path); - let start = 0; - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - - // Check for a drive letter prefix so as not to mistake the following - // path separator as an extra separator at the end of the path that can be - // disregarded - - if ( - path.length >= 2 && - path.charCodeAt(1) === CHAR_COLON && - isWindowsDeviceRoot(path.charCodeAt(0)) - ) { - start = startPart = 2; - } - - for (let i = path.length - 1; i >= start; --i) { - const code = path.charCodeAt(i); - if (isPathSeparator(code)) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) startDot = i; - else if (preDotState !== 1) preDotState = 1; - } else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - - if ( - startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - ) { - return ""; - } - return path.slice(startDot, end); - }, - - format: function format(pathObject: FormatInputPathObject) { - if (pathObject === null || typeof pathObject !== "object") { - throw new TypeError( - `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` - ); - } - return _format("\\", pathObject); - }, - - parse: function parse(path: string) { - assertPath(path); - - let ret = { root: "", dir: "", base: "", ext: "", name: "" } as ParsedPath; - if (path.length === 0) return ret; - - let len = path.length; - let rootEnd = 0; - let code = path.charCodeAt(0); - - // Try to match a root - if (len > 1) { - if (isPathSeparator(code)) { - // Possible UNC root - - rootEnd = 1; - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more path separators - for (; j < len; ++j) { - if (!isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j === len) { - // We matched a UNC root only - - rootEnd = j; - } else if (j !== last) { - // We matched a UNC root with leftovers - - rootEnd = j + 1; - } - } - } - } - } else if (isWindowsDeviceRoot(code)) { - // Possible device root - - if (path.charCodeAt(1) === CHAR_COLON) { - rootEnd = 2; - if (len > 2) { - if (isPathSeparator(path.charCodeAt(2))) { - if (len === 3) { - // `path` contains just a drive root, exit early to avoid - // unnecessary work - ret.root = ret.dir = path; - return ret; - } - rootEnd = 3; - } - } else { - // `path` contains just a drive root, exit early to avoid - // unnecessary work - ret.root = ret.dir = path; - return ret; - } - } - } - } else if (isPathSeparator(code)) { - // `path` contains just a path separator, exit early to avoid - // unnecessary work - ret.root = ret.dir = path; - return ret; - } - - if (rootEnd > 0) ret.root = path.slice(0, rootEnd); - - let startDot = -1; - let startPart = rootEnd; - let end = -1; - let matchedSlash = true; - let i = path.length - 1; - - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - - // Get non-dir info - for (; i >= rootEnd; --i) { - code = path.charCodeAt(i); - if (isPathSeparator(code)) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) startDot = i; - else if (preDotState !== 1) preDotState = 1; - } else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - - if ( - startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - ) { - if (end !== -1) { - ret.base = ret.name = path.slice(startPart, end); - } - } else { - ret.name = path.slice(startPart, startDot); - ret.base = path.slice(startPart, end); - ret.ext = path.slice(startDot, end); - } - - // If the directory is the root, use the entire root as the `dir` including - // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the - // trailing slash (`C:\abc\def` -> `C:\abc`). - if (startPart > 0 && startPart !== rootEnd) - ret.dir = path.slice(0, startPart - 1); - else ret.dir = ret.root; - - return ret; - }, - - sep: "\\", - delimiter: ";", - win32: null, - posix: null -}; - -export const posix = { - // path.resolve([from ...], to) - resolve: function resolve(...pathSegments: string[]) { - let resolvedPath = ""; - let resolvedAbsolute = false; - - for (let i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - let path: string; - if (i >= 0) path = arguments[i]; - else { - path = cwd(); - } - - assertPath(path); - - // Skip empty entries - if (path.length === 0) { - continue; - } - - resolvedPath = `${path}/${resolvedPath}`; - resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeString( - resolvedPath, - !resolvedAbsolute, - "/", - isPosixPathSeparator - ); - - if (resolvedAbsolute) { - if (resolvedPath.length > 0) return `/${resolvedPath}`; - else return "/"; - } else if (resolvedPath.length > 0) { - return resolvedPath; - } else { - return "."; - } - }, - - normalize: function normalize(path: string) { - assertPath(path); - - if (path.length === 0) return "."; - - const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - const trailingSeparator = - path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; - - // Normalize the path - path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator); - - if (path.length === 0 && !isAbsolute) path = "."; - if (path.length > 0 && trailingSeparator) path += "/"; - - if (isAbsolute) return `/${path}`; - return path; - }, - - isAbsolute: function isAbsolute(path: string) { - assertPath(path); - return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; - }, - - join: function join(...paths: string[]) { - if (arguments.length === 0) return "."; - let joined: string; - for (let i = 0; i < arguments.length; ++i) { - let arg = arguments[i]; - assertPath(arg); - if (arg.length > 0) { - if (joined === undefined) joined = arg; - else joined += `/${arg}`; - } - } - if (joined === undefined) return "."; - return posix.normalize(joined); - }, - - relative: function relative(from: string, to: string) { - assertPath(from); - assertPath(to); - - if (from === to) return ""; - - from = posix.resolve(from); - to = posix.resolve(to); - - if (from === to) return ""; - - // Trim any leading backslashes - let fromStart = 1; - for (; fromStart < from.length; ++fromStart) { - if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) break; - } - let fromEnd = from.length; - let fromLen = fromEnd - fromStart; - - // Trim any leading backslashes - let toStart = 1; - for (; toStart < to.length; ++toStart) { - if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) break; - } - let toEnd = to.length; - let toLen = toEnd - toStart; - - // Compare paths to find the longest common path from root - let length = fromLen < toLen ? fromLen : toLen; - let lastCommonSep = -1; - let i = 0; - for (; i <= length; ++i) { - if (i === length) { - if (toLen > length) { - if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) { - // We get here if `from` is the exact base path for `to`. - // For example: from='/foo/bar'; to='/foo/bar/baz' - return to.slice(toStart + i + 1); - } else if (i === 0) { - // We get here if `from` is the root - // For example: from='/'; to='/foo' - return to.slice(toStart + i); - } - } else if (fromLen > length) { - if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { - // We get here if `to` is the exact base path for `from`. - // For example: from='/foo/bar/baz'; to='/foo/bar' - lastCommonSep = i; - } else if (i === 0) { - // We get here if `to` is the root. - // For example: from='/foo'; to='/' - lastCommonSep = 0; - } - } - break; - } - let fromCode = from.charCodeAt(fromStart + i); - let toCode = to.charCodeAt(toStart + i); - if (fromCode !== toCode) break; - else if (fromCode === CHAR_FORWARD_SLASH) lastCommonSep = i; - } - - let out = ""; - // Generate the relative path based on the path difference between `to` - // and `from` - for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { - if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) { - if (out.length === 0) out += ".."; - else out += "/.."; - } - } - - // Lastly, append the rest of the destination (`to`) path that comes after - // the common path parts - if (out.length > 0) return out + to.slice(toStart + lastCommonSep); - else { - toStart += lastCommonSep; - if (to.charCodeAt(toStart) === CHAR_FORWARD_SLASH) ++toStart; - return to.slice(toStart); - } - }, - - toNamespacedPath: function toNamespacedPath(path: string) { - // Non-op on posix systems - return path; - }, - - dirname: function dirname(path: string) { - assertPath(path); - if (path.length === 0) return "."; - const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - let end = -1; - let matchedSlash = true; - for (let i = path.length - 1; i >= 1; --i) { - if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { - if (!matchedSlash) { - end = i; - break; - } - } else { - // We saw the first non-path separator - matchedSlash = false; - } - } - - if (end === -1) return hasRoot ? "/" : "."; - if (hasRoot && end === 1) return "//"; - return path.slice(0, end); - }, - - basename: function basename(path: string, ext = "") { - if (ext !== undefined && typeof ext !== "string") - throw new TypeError('"ext" argument must be a string'); - assertPath(path); - - let start = 0; - let end = -1; - let matchedSlash = true; - let i: number; - - if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { - if (ext.length === path.length && ext === path) return ""; - let extIdx = ext.length - 1; - let firstNonSlashEnd = -1; - for (i = path.length - 1; i >= 0; --i) { - const code = path.charCodeAt(i); - if (code === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } else { - if (firstNonSlashEnd === -1) { - // We saw the first non-path separator, remember this index in case - // we need it if the extension ends up not matching - matchedSlash = false; - firstNonSlashEnd = i + 1; - } - if (extIdx >= 0) { - // Try to match the explicit extension - if (code === ext.charCodeAt(extIdx)) { - if (--extIdx === -1) { - // We matched the extension, so mark this as the end of our path - // component - end = i; - } - } else { - // Extension does not match, so our result is the entire path - // component - extIdx = -1; - end = firstNonSlashEnd; - } - } - } - } - - if (start === end) end = firstNonSlashEnd; - else if (end === -1) end = path.length; - return path.slice(start, end); - } else { - for (i = path.length - 1; i >= 0; --i) { - if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } else if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // path component - matchedSlash = false; - end = i + 1; - } - } - - if (end === -1) return ""; - return path.slice(start, end); - } - }, - - extname: function extname(path: string) { - assertPath(path); - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - for (let i = path.length - 1; i >= 0; --i) { - const code = path.charCodeAt(i); - if (code === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) startDot = i; - else if (preDotState !== 1) preDotState = 1; - } else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - - if ( - startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - ) { - return ""; - } - return path.slice(startDot, end); - }, - - format: function format(pathObject: FormatInputPathObject) { - if (pathObject === null || typeof pathObject !== "object") { - throw new TypeError( - `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` - ); - } - return _format("/", pathObject); - }, - - parse: function parse(path: string) { - assertPath(path); - - let ret = { root: "", dir: "", base: "", ext: "", name: "" } as ParsedPath; - if (path.length === 0) return ret; - let isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - let start: number; - if (isAbsolute) { - ret.root = "/"; - start = 1; - } else { - start = 0; - } - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - let i = path.length - 1; - - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - - // Get non-dir info - for (; i >= start; --i) { - const code = path.charCodeAt(i); - if (code === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) startDot = i; - else if (preDotState !== 1) preDotState = 1; - } else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - - if ( - startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - ) { - if (end !== -1) { - if (startPart === 0 && isAbsolute) - ret.base = ret.name = path.slice(1, end); - else ret.base = ret.name = path.slice(startPart, end); - } - } else { - if (startPart === 0 && isAbsolute) { - ret.name = path.slice(1, startDot); - ret.base = path.slice(1, end); - } else { - ret.name = path.slice(startPart, startDot); - ret.base = path.slice(startPart, end); - } - ret.ext = path.slice(startDot, end); - } - - if (startPart > 0) ret.dir = path.slice(0, startPart - 1); - else if (isAbsolute) ret.dir = "/"; - - return ret; - }, - - sep: "/", - delimiter: ":", - win32: null, - posix: null -}; - -posix.win32 = win32.win32 = win32; -posix.posix = win32.posix = posix; - -const module = platform.os === "win" ? win32 : posix; - -export const resolve = module.resolve; -export const normalize = module.normalize; -export const isAbsolute = module.isAbsolute; -export const join = module.join; -export const relative = module.relative; -export const toNamespacedPath = module.toNamespacedPath; -export const dirname = module.dirname; -export const basename = module.basename; -export const extname = module.extname; -export const format = module.format; -export const parse = module.parse; -export const sep = module.sep; -export const delimiter = module.delimiter; diff --git a/path/interface.ts b/path/interface.ts deleted file mode 100644 index 84a3030ff..000000000 --- a/path/interface.ts +++ /dev/null @@ -1,47 +0,0 @@ -/** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ -export 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; -} -export interface FormatInputPathObject { - /** - * The root of the path such as '/' or 'c:\' - */ - root?: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir?: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base?: string; - /** - * The file extension (if any) such as '.html' - */ - ext?: string; - /** - * The file name without extension (if any) such as 'index' - */ - name?: string; -} diff --git a/path/isabsolute_test.ts b/path/isabsolute_test.ts deleted file mode 100644 index 548819ac0..000000000 --- a/path/isabsolute_test.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ - -import { test, assertEqual } from "../testing/mod.ts"; -import * as path from "./index.ts"; - -test(function isAbsolute() { - assertEqual(path.posix.isAbsolute("/home/foo"), true); - assertEqual(path.posix.isAbsolute("/home/foo/.."), true); - assertEqual(path.posix.isAbsolute("bar/"), false); - assertEqual(path.posix.isAbsolute("./baz"), false); -}); - -test(function isAbsoluteWin32() { - assertEqual(path.win32.isAbsolute("/"), true); - assertEqual(path.win32.isAbsolute("//"), true); - assertEqual(path.win32.isAbsolute("//server"), true); - assertEqual(path.win32.isAbsolute("//server/file"), true); - assertEqual(path.win32.isAbsolute("\\\\server\\file"), true); - assertEqual(path.win32.isAbsolute("\\\\server"), true); - assertEqual(path.win32.isAbsolute("\\\\"), true); - assertEqual(path.win32.isAbsolute("c"), false); - assertEqual(path.win32.isAbsolute("c:"), false); - assertEqual(path.win32.isAbsolute("c:\\"), true); - assertEqual(path.win32.isAbsolute("c:/"), true); - assertEqual(path.win32.isAbsolute("c://"), true); - assertEqual(path.win32.isAbsolute("C:/Users/"), true); - assertEqual(path.win32.isAbsolute("C:\\Users\\"), true); - assertEqual(path.win32.isAbsolute("C:cwd/another"), false); - assertEqual(path.win32.isAbsolute("C:cwd\\another"), false); - assertEqual(path.win32.isAbsolute("directory/directory"), false); - assertEqual(path.win32.isAbsolute("directory\\directory"), false); -}); diff --git a/path/join_test.ts b/path/join_test.ts deleted file mode 100644 index 25e302eba..000000000 --- a/path/join_test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { test, assertEqual } from "../testing/mod.ts"; -import * as path from "./index.ts"; - -const backslashRE = /\\/g; - -const joinTests = - // arguments result - [ - [[".", "x/b", "..", "/b/c.js"], "x/b/c.js"], - [[], "."], - [["/.", "x/b", "..", "/b/c.js"], "/x/b/c.js"], - [["/foo", "../../../bar"], "/bar"], - [["foo", "../../../bar"], "../../bar"], - [["foo/", "../../../bar"], "../../bar"], - [["foo/x", "../../../bar"], "../bar"], - [["foo/x", "./bar"], "foo/x/bar"], - [["foo/x/", "./bar"], "foo/x/bar"], - [["foo/x/", ".", "bar"], "foo/x/bar"], - [["./"], "./"], - [[".", "./"], "./"], - [[".", ".", "."], "."], - [[".", "./", "."], "."], - [[".", "/./", "."], "."], - [[".", "/////./", "."], "."], - [["."], "."], - [["", "."], "."], - [["", "foo"], "foo"], - [["foo", "/bar"], "foo/bar"], - [["", "/foo"], "/foo"], - [["", "", "/foo"], "/foo"], - [["", "", "foo"], "foo"], - [["foo", ""], "foo"], - [["foo/", ""], "foo/"], - [["foo", "", "/bar"], "foo/bar"], - [["./", "..", "/foo"], "../foo"], - [["./", "..", "..", "/foo"], "../../foo"], - [[".", "..", "..", "/foo"], "../../foo"], - [["", "..", "..", "/foo"], "../../foo"], - [["/"], "/"], - [["/", "."], "/"], - [["/", ".."], "/"], - [["/", "..", ".."], "/"], - [[""], "."], - [["", ""], "."], - [[" /foo"], " /foo"], - [[" ", "foo"], " /foo"], - [[" ", "."], " "], - [[" ", "/"], " /"], - [[" ", ""], " "], - [["/", "foo"], "/foo"], - [["/", "/foo"], "/foo"], - [["/", "//foo"], "/foo"], - [["/", "", "/foo"], "/foo"], - [["", "/", "foo"], "/foo"], - [["", "/", "/foo"], "/foo"] - ]; - -// Windows-specific join tests -const windowsJoinTests = [ - // arguments result - // UNC path expected - [["//foo/bar"], "\\\\foo\\bar\\"], - [["\\/foo/bar"], "\\\\foo\\bar\\"], - [["\\\\foo/bar"], "\\\\foo\\bar\\"], - // UNC path expected - server and share separate - [["//foo", "bar"], "\\\\foo\\bar\\"], - [["//foo/", "bar"], "\\\\foo\\bar\\"], - [["//foo", "/bar"], "\\\\foo\\bar\\"], - // UNC path expected - questionable - [["//foo", "", "bar"], "\\\\foo\\bar\\"], - [["//foo/", "", "bar"], "\\\\foo\\bar\\"], - [["//foo/", "", "/bar"], "\\\\foo\\bar\\"], - // UNC path expected - even more questionable - [["", "//foo", "bar"], "\\\\foo\\bar\\"], - [["", "//foo/", "bar"], "\\\\foo\\bar\\"], - [["", "//foo/", "/bar"], "\\\\foo\\bar\\"], - // No UNC path expected (no double slash in first component) - [["\\", "foo/bar"], "\\foo\\bar"], - [["\\", "/foo/bar"], "\\foo\\bar"], - [["", "/", "/foo/bar"], "\\foo\\bar"], - // No UNC path expected (no non-slashes in first component - - // questionable) - [["//", "foo/bar"], "\\foo\\bar"], - [["//", "/foo/bar"], "\\foo\\bar"], - [["\\\\", "/", "/foo/bar"], "\\foo\\bar"], - [["//"], "\\"], - // No UNC path expected (share name missing - questionable). - [["//foo"], "\\foo"], - [["//foo/"], "\\foo\\"], - [["//foo", "/"], "\\foo\\"], - [["//foo", "", "/"], "\\foo\\"], - // No UNC path expected (too many leading slashes - questionable) - [["///foo/bar"], "\\foo\\bar"], - [["////foo", "bar"], "\\foo\\bar"], - [["\\\\\\/foo/bar"], "\\foo\\bar"], - // Drive-relative vs drive-absolute paths. This merely describes the - // status quo, rather than being obviously right - [["c:"], "c:."], - [["c:."], "c:."], - [["c:", ""], "c:."], - [["", "c:"], "c:."], - [["c:.", "/"], "c:.\\"], - [["c:.", "file"], "c:file"], - [["c:", "/"], "c:\\"], - [["c:", "file"], "c:\\file"] -]; - -test(function join() { - joinTests.forEach(function(p) { - const actual = path.posix.join.apply(null, p[0]); - assertEqual(actual, p[1]); - }); -}); - -test(function joinWin32() { - joinTests.forEach(function(p) { - const actual = path.win32.join.apply(null, p[0]).replace(backslashRE, "/"); - assertEqual(actual, p[1]); - }); - windowsJoinTests.forEach(function(p) { - const actual = path.win32.join.apply(null, p[0]); - assertEqual(actual, p[1]); - }); -}); diff --git a/path/parse_format_test.ts b/path/parse_format_test.ts deleted file mode 100644 index be98f8739..000000000 --- a/path/parse_format_test.ts +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ - -import { test, assertEqual } from "../testing/mod.ts"; -import * as path from "./index.ts"; - -const winPaths = [ - // [path, root] - ["C:\\path\\dir\\index.html", "C:\\"], - ["C:\\another_path\\DIR\\1\\2\\33\\\\index", "C:\\"], - ["another_path\\DIR with spaces\\1\\2\\33\\index", ""], - ["\\", "\\"], - ["\\foo\\C:", "\\"], - ["file", ""], - ["file:stream", ""], - [".\\file", ""], - ["C:", "C:"], - ["C:.", "C:"], - ["C:..", "C:"], - ["C:abc", "C:"], - ["C:\\", "C:\\"], - ["C:\\abc", "C:\\"], - ["", ""], - - // unc - ["\\\\server\\share\\file_path", "\\\\server\\share\\"], - [ - "\\\\server two\\shared folder\\file path.zip", - "\\\\server two\\shared folder\\" - ], - ["\\\\teela\\admin$\\system32", "\\\\teela\\admin$\\"], - ["\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\"] -]; - -const winSpecialCaseParseTests = [["/foo/bar", { root: "/" }]]; - -const winSpecialCaseFormatTests = [ - [{ dir: "some\\dir" }, "some\\dir\\"], - [{ base: "index.html" }, "index.html"], - [{ root: "C:\\" }, "C:\\"], - [{ name: "index", ext: ".html" }, "index.html"], - [{ dir: "some\\dir", name: "index", ext: ".html" }, "some\\dir\\index.html"], - [{ root: "C:\\", name: "index", ext: ".html" }, "C:\\index.html"], - [{}, ""] -]; - -const unixPaths = [ - // [path, root] - ["/home/user/dir/file.txt", "/"], - ["/home/user/a dir/another File.zip", "/"], - ["/home/user/a dir//another&File.", "/"], - ["/home/user/a$$$dir//another File.zip", "/"], - ["user/dir/another File.zip", ""], - ["file", ""], - [".\\file", ""], - ["./file", ""], - ["C:\\foo", ""], - ["/", "/"], - ["", ""], - [".", ""], - ["..", ""], - ["/foo", "/"], - ["/foo.", "/"], - ["/foo.bar", "/"], - ["/.", "/"], - ["/.foo", "/"], - ["/.foo.bar", "/"], - ["/foo/bar.baz", "/"] -]; - -const unixSpecialCaseFormatTests = [ - [{ dir: "some/dir" }, "some/dir/"], - [{ base: "index.html" }, "index.html"], - [{ root: "/" }, "/"], - [{ name: "index", ext: ".html" }, "index.html"], - [{ dir: "some/dir", name: "index", ext: ".html" }, "some/dir/index.html"], - [{ root: "/", name: "index", ext: ".html" }, "/index.html"], - [{}, ""] -]; - -test(function parseWin32() { - checkParseFormat(path.win32, winPaths); - checkSpecialCaseParseFormat(path.win32, winSpecialCaseParseTests); -}); - -test(function parse() { - checkParseFormat(path.posix, unixPaths); -}); - -test(function formatWin32() { - checkFormat(path.win32, winSpecialCaseFormatTests); -}); - -test(function format() { - checkFormat(path.posix, unixSpecialCaseFormatTests); -}); - -// Test removal of trailing path separators -const windowsTrailingTests = [ - [".\\", { root: "", dir: "", base: ".", ext: "", name: "." }], - ["\\\\", { root: "\\", dir: "\\", base: "", ext: "", name: "" }], - ["\\\\", { root: "\\", dir: "\\", base: "", ext: "", name: "" }], - [ - "c:\\foo\\\\\\", - { root: "c:\\", dir: "c:\\", base: "foo", ext: "", name: "foo" } - ], - [ - "D:\\foo\\\\\\bar.baz", - { - root: "D:\\", - dir: "D:\\foo\\\\", - base: "bar.baz", - ext: ".baz", - name: "bar" - } - ] -]; -const posixTrailingTests = [ - ["./", { root: "", dir: "", base: ".", ext: "", name: "." }], - ["//", { root: "/", dir: "/", base: "", ext: "", name: "" }], - ["///", { root: "/", dir: "/", base: "", ext: "", name: "" }], - ["/foo///", { root: "/", dir: "/", base: "foo", ext: "", name: "foo" }], - [ - "/foo///bar.baz", - { root: "/", dir: "/foo//", base: "bar.baz", ext: ".baz", name: "bar" } - ] -]; - -function checkParseFormat(path, paths) { - paths.forEach(function(p) { - const element = p[0]; - const output = path.parse(element); - assertEqual(typeof output.root, "string"); - assertEqual(typeof output.dir, "string"); - assertEqual(typeof output.base, "string"); - assertEqual(typeof output.ext, "string"); - assertEqual(typeof output.name, "string"); - assertEqual(path.format(output), element); - assertEqual(output.rooroot, undefined); - assertEqual(output.dir, output.dir ? path.dirname(element) : ""); - assertEqual(output.base, path.basename(element)); - }); -} - -function checkSpecialCaseParseFormat(path, testCases) { - testCases.forEach(function(testCase) { - const element = testCase[0]; - const expect = testCase[1]; - const output = path.parse(element); - Object.keys(expect).forEach(function(key) { - assertEqual(output[key], expect[key]); - }); - }); -} - -function checkFormat(path, testCases) { - testCases.forEach(function(testCase) { - assertEqual(path.format(testCase[0]), testCase[1]); - }); -} - -test(function parseTrailingWin32() { - windowsTrailingTests.forEach(function(p) { - const actual = path.win32.parse(p[0] as string); - const expected = p[1]; - assertEqual(actual, expected); - }); -}); - -test(function parseTrailing() { - posixTrailingTests.forEach(function(p) { - const actual = path.posix.parse(p[0] as string); - const expected = p[1]; - assertEqual(actual, expected); - }); -}); diff --git a/path/relative_test.ts b/path/relative_test.ts deleted file mode 100644 index dcf8fed98..000000000 --- a/path/relative_test.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ - -import { test, assertEqual } from "../testing/mod.ts"; -import * as path from "./index.ts"; - -const relativeTests = { - win32: - // arguments result - [ - ["c:/blah\\blah", "d:/games", "d:\\games"], - ["c:/aaaa/bbbb", "c:/aaaa", ".."], - ["c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc"], - ["c:/aaaa/bbbb", "c:/aaaa/bbbb", ""], - ["c:/aaaa/bbbb", "c:/aaaa/cccc", "..\\cccc"], - ["c:/aaaa/", "c:/aaaa/cccc", "cccc"], - ["c:/", "c:\\aaaa\\bbbb", "aaaa\\bbbb"], - ["c:/aaaa/bbbb", "d:\\", "d:\\"], - ["c:/AaAa/bbbb", "c:/aaaa/bbbb", ""], - ["c:/aaaaa/", "c:/aaaa/cccc", "..\\aaaa\\cccc"], - ["C:\\foo\\bar\\baz\\quux", "C:\\", "..\\..\\..\\.."], - [ - "C:\\foo\\test", - "C:\\foo\\test\\bar\\package.json", - "bar\\package.json" - ], - ["C:\\foo\\bar\\baz-quux", "C:\\foo\\bar\\baz", "..\\baz"], - ["C:\\foo\\bar\\baz", "C:\\foo\\bar\\baz-quux", "..\\baz-quux"], - ["\\\\foo\\bar", "\\\\foo\\bar\\baz", "baz"], - ["\\\\foo\\bar\\baz", "\\\\foo\\bar", ".."], - ["\\\\foo\\bar\\baz-quux", "\\\\foo\\bar\\baz", "..\\baz"], - ["\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz-quux", "..\\baz-quux"], - ["C:\\baz-quux", "C:\\baz", "..\\baz"], - ["C:\\baz", "C:\\baz-quux", "..\\baz-quux"], - ["\\\\foo\\baz-quux", "\\\\foo\\baz", "..\\baz"], - ["\\\\foo\\baz", "\\\\foo\\baz-quux", "..\\baz-quux"], - ["C:\\baz", "\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz"], - ["\\\\foo\\bar\\baz", "C:\\baz", "C:\\baz"] - ], - posix: - // arguments result - [ - ["/var/lib", "/var", ".."], - ["/var/lib", "/bin", "../../bin"], - ["/var/lib", "/var/lib", ""], - ["/var/lib", "/var/apache", "../apache"], - ["/var/", "/var/lib", "lib"], - ["/", "/var/lib", "var/lib"], - ["/foo/test", "/foo/test/bar/package.json", "bar/package.json"], - ["/Users/a/web/b/test/mails", "/Users/a/web/b", "../.."], - ["/foo/bar/baz-quux", "/foo/bar/baz", "../baz"], - ["/foo/bar/baz", "/foo/bar/baz-quux", "../baz-quux"], - ["/baz-quux", "/baz", "../baz"], - ["/baz", "/baz-quux", "../baz-quux"] - ] -}; - -test(function relative() { - relativeTests.posix.forEach(function(p) { - const expected = p[2]; - const actual = path.posix.relative(p[0], p[1]); - assertEqual(actual, expected); - }); -}); - -test(function relativeWin32() { - relativeTests.win32.forEach(function(p) { - const expected = p[2]; - const actual = path.win32.relative(p[0], p[1]); - assertEqual(actual, expected); - }); -}); diff --git a/path/resolve_test.ts b/path/resolve_test.ts deleted file mode 100644 index b365d40b0..000000000 --- a/path/resolve_test.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ - -import { test, assertEqual } from "../testing/mod.ts"; -import * as path from "./index.ts"; -import { cwd } from "deno"; - -const windowsTests = - // arguments result - [ - [["c:/blah\\blah", "d:/games", "c:../a"], "c:\\blah\\a"], - [["c:/ignore", "d:\\a/b\\c/d", "\\e.exe"], "d:\\e.exe"], - [["c:/ignore", "c:/some/file"], "c:\\some\\file"], - [["d:/ignore", "d:some/dir//"], "d:\\ignore\\some\\dir"], - [["//server/share", "..", "relative\\"], "\\\\server\\share\\relative"], - [["c:/", "//"], "c:\\"], - [["c:/", "//dir"], "c:\\dir"], - [["c:/", "//server/share"], "\\\\server\\share\\"], - [["c:/", "//server//share"], "\\\\server\\share\\"], - [["c:/", "///some//dir"], "c:\\some\\dir"], - [ - ["C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js"], - "C:\\foo\\tmp.3\\cycles\\root.js" - ] - ]; -const posixTests = - // arguments result - [ - [["/var/lib", "../", "file/"], "/var/file"], - [["/var/lib", "/../", "file/"], "/file"], - [["a/b/c/", "../../.."], cwd()], - [["."], cwd()], - [["/some/dir", ".", "/absolute/"], "/absolute"], - [["/foo/tmp.3/", "../tmp.3/cycles/root.js"], "/foo/tmp.3/cycles/root.js"] - ]; - -test(function resolve() { - posixTests.forEach(function(p) { - const actual = path.posix.resolve.apply(null, p[0]); - assertEqual(actual, p[1]); - }); -}); - -test(function resolveWin32() { - windowsTests.forEach(function(p) { - const actual = path.win32.resolve.apply(null, p[0]); - assertEqual(actual, p[1]); - }); -}); diff --git a/path/zero_length_strings_test.ts b/path/zero_length_strings_test.ts deleted file mode 100644 index f9b357bf1..000000000 --- a/path/zero_length_strings_test.ts +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ - -import { test, assertEqual } from "../testing/mod.ts"; -import * as path from "./index.ts"; -import { cwd } from "deno"; - -const pwd = cwd(); - -test(function joinZeroLength() { - // join will internally ignore all the zero-length strings and it will return - // '.' if the joined string is a zero-length string. - assertEqual(path.posix.join(""), "."); - assertEqual(path.posix.join("", ""), "."); - if (path.win32) assertEqual(path.win32.join(""), "."); - if (path.win32) assertEqual(path.win32.join("", ""), "."); - assertEqual(path.join(pwd), pwd); - assertEqual(path.join(pwd, ""), pwd); -}); - -test(function normalizeZeroLength() { - // normalize will return '.' if the input is a zero-length string - assertEqual(path.posix.normalize(""), "."); - if (path.win32) assertEqual(path.win32.normalize(""), "."); - assertEqual(path.normalize(pwd), pwd); -}); - -test(function isAbsoluteZeroLength() { - // Since '' is not a valid path in any of the common environments, return false - assertEqual(path.posix.isAbsolute(""), false); - if (path.win32) assertEqual(path.win32.isAbsolute(""), false); -}); - -test(function resolveZeroLength() { - // resolve, internally ignores all the zero-length strings and returns the - // current working directory - assertEqual(path.resolve(""), pwd); - assertEqual(path.resolve("", ""), pwd); -}); - -test(function relativeZeroLength() { - // relative, internally calls resolve. So, '' is actually the current directory - assertEqual(path.relative("", pwd), ""); - assertEqual(path.relative(pwd, ""), ""); - assertEqual(path.relative(pwd, pwd), ""); -}); diff --git a/test.ts b/test.ts index 821aa4116..885096ac9 100755 --- a/test.ts +++ b/test.ts @@ -10,15 +10,15 @@ import "mkdirp/test.ts"; import "net/bufio_test.ts"; import "net/http_test.ts"; import "net/textproto_test.ts"; -import "path/basename_test.ts"; -import "path/dirname_test.ts"; -import "path/extname_test.ts"; -import "path/isabsolute_test.ts"; -import "path/join_test.ts"; -import "path/parse_format_test.ts"; -import "path/relative_test.ts"; -import "path/resolve_test.ts"; -import "path/zero_length_strings_test.ts"; +import "fs/path/basename_test.ts"; +import "fs/path/dirname_test.ts"; +import "fs/path/extname_test.ts"; +import "fs/path/isabsolute_test.ts"; +import "fs/path/join_test.ts"; +import "fs/path/parse_format_test.ts"; +import "fs/path/relative_test.ts"; +import "fs/path/resolve_test.ts"; +import "fs/path/zero_length_strings_test.ts"; import "testing/test.ts"; import { runTests, completePromise } from "net/file_server_test.ts"; -- cgit v1.2.3 From 6f5dbfe10234060828670c8848eb7e42ded1c4cd Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Fri, 11 Jan 2019 12:18:21 +1100 Subject: Reorg colors (denoland/deno_std#96) Original: https://github.com/denoland/deno_std/commit/92bbca8166d6566011aff0ef467a83433747a937 --- colors/README.md | 2 +- colors/example.ts | 2 +- colors/main.ts | 33 --------------------------------- colors/main_test.ts | 11 ----------- colors/mod.ts | 33 +++++++++++++++++++++++++++++++++ colors/test.ts | 11 +++++++++++ test.ts | 2 +- 7 files changed, 47 insertions(+), 47 deletions(-) delete mode 100644 colors/main.ts delete mode 100644 colors/main_test.ts create mode 100644 colors/mod.ts create mode 100644 colors/test.ts diff --git a/colors/README.md b/colors/README.md index eafdbb9c1..3148b7cab 100644 --- a/colors/README.md +++ b/colors/README.md @@ -10,7 +10,7 @@ The main modules exports a single function name `color` which is a function that provides chaining to stack colors. Basic usage looks like this: ```ts -import { color } from "https://deno.land/x/colors/main.ts"; +import { color } from "https://deno.land/x/std/colors/mod.ts"; console.log(color.bgBlue.red.bold("Hello world!")); ``` diff --git a/colors/example.ts b/colors/example.ts index d60ecc31c..e98a32ec9 100644 --- a/colors/example.ts +++ b/colors/example.ts @@ -1,3 +1,3 @@ -import { color } from "main.ts"; +import { color } from "./mod.ts"; console.log(color.bgBlue.red.bold("Hello world!")); diff --git a/colors/main.ts b/colors/main.ts deleted file mode 100644 index 8316060db..000000000 --- a/colors/main.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -import { styles } from "./styles.ts"; - -type Styles = { readonly [S in keyof typeof styles]: Color }; - -type Color = Styles & { - (str: string): string; -}; - -const styleStack: string[] = []; - -export const color = function color(str: string): string { - styleStack.reverse(); - while (styleStack.length) { - const style = styleStack.pop(); - const code = styles[style]; - str = `${code.open}${str.replace(code.closeRe, code.open)}${ - code.close - }`.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } - return str; -} as Color; - -for (const style of Object.keys(styles)) { - Object.defineProperty(color, style, { - get() { - styleStack.push(style); - return color; - }, - enumerable: true, - configurable: false - }); -} diff --git a/colors/main_test.ts b/colors/main_test.ts deleted file mode 100644 index 2073c7c78..000000000 --- a/colors/main_test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { assertEqual, test } from "../testing/mod.ts"; -import { color } from "main.ts"; -import "example.ts"; - -test(function singleColor() { - assertEqual(color.red("Hello world"), "Hello world"); -}); - -test(function doubleColor() { - assertEqual(color.red.bgBlue("Hello world"), "Hello world"); -}); diff --git a/colors/mod.ts b/colors/mod.ts new file mode 100644 index 000000000..8316060db --- /dev/null +++ b/colors/mod.ts @@ -0,0 +1,33 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { styles } from "./styles.ts"; + +type Styles = { readonly [S in keyof typeof styles]: Color }; + +type Color = Styles & { + (str: string): string; +}; + +const styleStack: string[] = []; + +export const color = function color(str: string): string { + styleStack.reverse(); + while (styleStack.length) { + const style = styleStack.pop(); + const code = styles[style]; + str = `${code.open}${str.replace(code.closeRe, code.open)}${ + code.close + }`.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } + return str; +} as Color; + +for (const style of Object.keys(styles)) { + Object.defineProperty(color, style, { + get() { + styleStack.push(style); + return color; + }, + enumerable: true, + configurable: false + }); +} diff --git a/colors/test.ts b/colors/test.ts new file mode 100644 index 000000000..1acc30072 --- /dev/null +++ b/colors/test.ts @@ -0,0 +1,11 @@ +import { assertEqual, test } from "../testing/mod.ts"; +import { color } from "./mod.ts"; +import "./example.ts"; + +test(function singleColor() { + assertEqual(color.red("Hello world"), "Hello world"); +}); + +test(function doubleColor() { + assertEqual(color.red.bgBlue("Hello world"), "Hello world"); +}); diff --git a/test.ts b/test.ts index 885096ac9..0ee32ff8c 100755 --- a/test.ts +++ b/test.ts @@ -1,7 +1,7 @@ #!/usr/bin/env deno --allow-run --allow-net --allow-write import { run } from "deno"; -import "colors/main_test.ts"; +import "colors/test.ts"; import "datetime/test.ts"; import "examples/test.ts"; import "flags/test.ts"; -- cgit v1.2.3 From 0e933177adb87338cdd554f5de39cef3d40407c2 Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Fri, 11 Jan 2019 16:16:47 +1100 Subject: Add media_types collection (denoland/deno_std#97) Original: https://github.com/denoland/deno_std/commit/0e00fe9cd361165d28beb117cdf103ff8f9d3d8b --- README.md | 4 + media_types/README.md | 93 + media_types/db_1.37.0.json | 7688 ++++++++++++++++++++++++++++++++++++++++++++ media_types/deps.ts | 15 + media_types/mod.ts | 149 + media_types/test.ts | 50 + net/extension_map.json | 85 - net/file_server.ts | 22 +- net/file_server_test.ts | 2 +- test.ts | 1 + 10 files changed, 8003 insertions(+), 106 deletions(-) create mode 100644 media_types/README.md create mode 100644 media_types/db_1.37.0.json create mode 100644 media_types/deps.ts create mode 100644 media_types/mod.ts create mode 100644 media_types/test.ts delete mode 100644 net/extension_map.json diff --git a/README.md b/README.md index 0a996bce3..c291b26cc 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,10 @@ Command line logging +- **[media_types](./media_types/)** + + A library for resolving media types (MIME types) and extensions. + - **[mkdirp](./mkdirp/)** Make directory branches. diff --git a/media_types/README.md b/media_types/README.md new file mode 100644 index 000000000..dbc895f7b --- /dev/null +++ b/media_types/README.md @@ -0,0 +1,93 @@ +# media_types + +A module that assists in resolving media types and extensions. It consumes the +[mime-db](https://github.com/jshttp/mime-db) and provides API access to the +information. + +## Usage + +### `lookup(path)` + +Lookup the content type associated with a file. The path can be just the +extension or the full path name. If the content type cannot be determined the +function returns `undefined`: + +```ts +import { lookup } from "https://deno.land/x/std/media_types/mod.ts"; + +lookup("json"); // "application/json" +lookup(".md"); // "text/markdown" +lookup("folder/file.js"); // "application/javascript" +lookup("folder/.htaccess"); // undefined +``` + +### `contentType(type)` + +Return a full `Content-Type` header value for a given content type or +extension. When an extension is used, `lookup()` is used to resolve the +content type first. A default charset is added if not present. The +function will return `undefined` if the content type cannot be resolved: + +```ts +import { contentType } from "https://deno.land/x/std/media_types/mod.ts"; +import * as path from "https://deno.land/x/std/path/mod.ts"; + +contentType("markdown"); // "text/markdown; charset=utf-8" +contentType("file.json"); // "application/json; charset=utf-8" +contentType("text/html"); // "text/html; charset=utf-8" +contentType("text/html; charset=iso-8859-1"); // "text/html; charset=iso-8859-1" + +contentType(path.extname("/path/to/file.json")); // "application/json; charset=utf-8" +``` + +### `extension(type)` + +Return a default extension for a given content type. If there is not an +appropriate extension, `undefined` is returned: + +```ts +import { extension } from "https://deno.land/x/std/media_types/mod.ts"; + +extension("application/octet-stream"); // "bin" +``` + +### `charset(type)` + +Lookup the implied default charset for a given content type. If the content +type cannot be resolved, `undefined` is returned: + +```ts +import { charset } from "https://deno.land/x/std/media_types/mod.ts"; + +charset("text/markdown"); // "UTF-8" +``` + +### `extensions` + +A `Map` of extensions by content type, in priority order: + +```ts +import { extensions } from "https://deno.land/x/std/media_types/mod.ts"; + +extensions.get("application/javascript"); // [ "js", "mjs" ] +``` + +### `types` + +A `Map` of content types by extension: + +```ts +import { types } from "https://deno.land/x/std/media_types/mod.ts"; + +types.get("ts"); // "application/javascript" +``` + +--- + +Adapted from [mime-type](https://github.com/jshttp/mime-types). + +MIT License. + +``` + +``` diff --git a/media_types/db_1.37.0.json b/media_types/db_1.37.0.json new file mode 100644 index 000000000..81f614c64 --- /dev/null +++ b/media_types/db_1.37.0.json @@ -0,0 +1,7688 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "compressible": true + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana" + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma","es"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true + }, + "application/fhir+json": { + "source": "iana", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "compressible": true + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana" + }, + "application/n-triples": { + "source": "iana" + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana" + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["keynote"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.youtube.yt": { + "source": "iana" + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana" + }, + "image/avcs": { + "source": "iana" + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/stl": { + "source": "iana" + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["markdown","md"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shex": { + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana" + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "iana" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vp8": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/media_types/deps.ts b/media_types/deps.ts new file mode 100644 index 000000000..e305f6831 --- /dev/null +++ b/media_types/deps.ts @@ -0,0 +1,15 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. + +export { extname } from "../fs/path.ts"; + +interface DB { + [mediaType: string]: { + source?: string; + compressible?: boolean; + charset?: string; + extensions?: string[]; + }; +} + +import * as _db from "./db_1.37.0.json"; +export const db: DB = _db; diff --git a/media_types/mod.ts b/media_types/mod.ts new file mode 100644 index 000000000..3b74427ba --- /dev/null +++ b/media_types/mod.ts @@ -0,0 +1,149 @@ +/*! + * Ported from: https://github.com/jshttp/mime-types and licensed as: + * + * (The MIT License) + * + * Copyright (c) 2014 Jonathan Ong + * Copyright (c) 2015 Douglas Christopher Wilson + * Copyright (c) 2019 the Deno authors + * + * 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. + */ + +import { db, extname } from "./deps.ts"; + +const EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; +const TEXT_TYPE_REGEXP = /^text\//i; + +/** A map of extensions for a given media type */ +export const extensions = new Map(); + +/** A map of the media type for a given extension */ +export const types = new Map(); + +/** Internal function to populate the maps based on the Mime DB */ +function populateMaps( + extensions: Map, + types: Map +) { + const preference = ["nginx", "apache", undefined, "iana"]; + + for (const type of Object.keys(db)) { + const mime = db[type]; + const exts = mime.extensions; + + if (!exts || !exts.length) { + continue; + } + + extensions.set(type, exts); + + for (const ext of exts) { + if (types.has(ext)) { + const current = types.get(ext)!; + const from = preference.indexOf(db[current].source); + const to = preference.indexOf(mime.source); + + if ( + current !== "application/octet-stream" && + (from > to || + (from === to && current.substr(0, 12) === "application/")) + ) { + continue; + } + } + + types.set(ext, type); + } + } +} + +// Populate the maps upon module load +populateMaps(extensions, types); + +/** Given a media type return any default charset string. Returns `undefined` + * if not resolvable. + */ +export function charset(type: string): string | undefined { + const m = EXTRACT_TYPE_REGEXP.exec(type); + if (!m) { + return; + } + const [match] = m; + const mime = db[match.toLowerCase()]; + + if (mime && mime.charset) { + return mime.charset; + } + + if (TEXT_TYPE_REGEXP.test(match)) { + return "UTF-8"; + } +} + +/** Given an extension or media type, return the full `Content-Type` header + * string. Returns `undefined` if not resolvable. + */ +export function contentType(str: string): string | undefined { + let mime = str.includes("/") ? str : lookup(str); + + if (!mime) { + return; + } + + if (!mime.includes("charset")) { + const cs = charset(mime); + if (cs) { + mime += `; charset=${cs.toLowerCase()}`; + } + } + + return mime; +} + +/** Given a media type, return the most appropriate extension or return + * `undefined` if there is none. + */ +export function extension(type: string): string | undefined { + const match = EXTRACT_TYPE_REGEXP.exec(type); + + if (!match) { + return; + } + + const exts = extensions.get(match[1].toLowerCase()); + + if (!exts || !exts.length) { + return; + } + + return exts[0]; +} + +/** Given an extension, lookup the appropriate media type for that extension. + * Likely you should be using `contentType()` though instead. + */ +export function lookup(path: string): string | undefined { + const extension = extname("x." + path) + .toLowerCase() + .substr(1); + + return types.get(extension); +} diff --git a/media_types/test.ts b/media_types/test.ts new file mode 100644 index 000000000..af9326733 --- /dev/null +++ b/media_types/test.ts @@ -0,0 +1,50 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. + +import { assertEqual, test } from "../testing/mod.ts"; +import { + lookup, + contentType, + extension, + charset, + extensions, + types +} from "./mod.ts"; + +test(function testLookup() { + assertEqual(lookup("json"), "application/json"); + assertEqual(lookup(".md"), "text/markdown"); + assertEqual(lookup("folder/file.js"), "application/javascript"); + assertEqual(lookup("folder/.htaccess"), undefined); +}); + +test(function testContentType() { + assertEqual(contentType("markdown"), "text/markdown; charset=utf-8"); + assertEqual(contentType("file.json"), "application/json; charset=utf-8"); + assertEqual(contentType("text/html"), "text/html; charset=utf-8"); + assertEqual( + contentType("text/html; charset=iso-8859-1"), + "text/html; charset=iso-8859-1" + ); + assertEqual(contentType(".htaccess"), undefined); +}); + +test(function testExtension() { + assertEqual(extension("application/octet-stream"), "bin"); + assertEqual(extension("application/javascript"), "js"); + assertEqual(extension("text/html"), "html"); +}); + +test(function testCharset() { + assertEqual(charset("text/markdown"), "UTF-8"); + assertEqual(charset("text/css"), "UTF-8"); +}); + +test(function testExtensions() { + assertEqual(extensions.get("application/javascript"), ["js", "mjs"]); + assertEqual(extensions.get("foo"), undefined); +}); + +test(function testTypes() { + assertEqual(types.get("js"), "application/javascript"); + assertEqual(types.get("foo"), undefined); +}); diff --git a/net/extension_map.json b/net/extension_map.json deleted file mode 100644 index b02517d6b..000000000 --- a/net/extension_map.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "": "application/octet-stream", - ".7z": "application/x-7z-compressed", - ".aac": "audio/aac", - ".abw": "application/x-abiword", - ".arc": "application/octet-stream", - ".avi": "video/x-msvideo", - ".azw": "application/vnd.amazon.ebook", - ".bin": "application/octet-stream", - ".bmp": "image/bmp", - ".bz": "application/x-bzip", - ".bz2": "application/x-bzip2", - ".csh": "application/x-csh", - ".css": "text/css", - ".csv": "text/csv", - ".doc": "application/msword", - ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - ".eot": "application/vnd.ms-fontobject", - ".epub": "application/epub+zip", - ".es": "application/ecmascript", - ".gif": "image/gif", - ".gz": "application/gzip", - ".htm": "text/html", - ".html": "text/html", - ".ico": "image/x-icon", - ".ics": "text/calendar", - ".jar": "application/java-archive", - ".jpeg": "image/jpeg", - ".jpg": "image/jpeg", - ".js": "application/javascript", - ".json": "application/json", - ".md": "text/markdown", - ".mid": "audio/x-midi", - ".midi": "audio/x-midi", - ".mp3": "audio/mpeg", - ".mp4": "video/mpeg", - ".mpeg": "video/mpeg", - ".mpkg": "application/vnd.apple.installer+xml", - ".less": "text/less", - ".odp": "application/vnd.oasis.opendocument.presentation", - ".ods": "application/vnd.oasis.opendocument.spreadsheet", - ".odt": "application/vnd.oasis.opendocument.text", - ".oga": "audio/ogg", - ".ogv": "video/ogg", - ".ogx": "application/ogg", - ".otf": "font/otf", - ".png": "image/png", - ".pdf": "application/pdf", - ".ppm": "image/x-portable-pixmap", - ".pgm": "image/x-portable-graymap", - ".pmm": "image/x-portable-bitmap", - ".pnm": "image/x-portable-anymap", - ".ppt": "application/vnd.ms-powerpoint", - ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", - ".rar": "application/x-rar-compressed", - ".rtf": "application/rtf", - ".sh": "application/x-sh", - ".sass": "text/x-sass", - ".scss": "text/x-scss", - ".svg": "image/svg+xml", - ".swf": "application/x-shockwave-flash", - ".tar": "application/x-tar", - ".tar.gz": "application/tar+gzip", - ".tif": "image/tiff", - ".tiff": "image/tiff", - ".toml": "application/toml", - ".ts": "application/typescript", - ".ttf": "font/ttf", - ".txt": "text/plain", - ".vsd": "application/vnd.visio", - ".wav": "audio/wav", - ".weba": "audio/webm", - ".webm": "video/webm", - ".webp": "image/webp", - ".woff": "font/woff", - ".woff2": "font/woff2", - ".xhtml": "application/xhtml+xml", - ".xls": "application/vnd.ms-excel", - ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - ".xml": "application/xml", - ".xul": "application/vnd.mozilla.xul+xml", - ".yml": "text/yaml", - ".yaml": "text/yaml", - ".zip": "application/zip" -} diff --git a/net/file_server.ts b/net/file_server.ts index bebb93969..72432abdd 100755 --- a/net/file_server.ts +++ b/net/file_server.ts @@ -13,7 +13,7 @@ import { } from "./http.ts"; import { cwd, DenoError, ErrorKind, args, stat, readDir, open } from "deno"; import { extname } from "../fs/path.ts"; -import * as extensionsMap from "./extension_map.json"; +import { contentType } from "../media_types/mod.ts"; const dirViewerTemplate = ` @@ -162,30 +162,12 @@ async function serveDir(req: ServerRequest, dirPath: string, dirName: string) { return res; } -function guessContentType(filename: string): string { - let extension = extname(filename); - let contentType = extensionsMap[extension]; - - if (contentType) { - return contentType; - } - - extension = extension.toLowerCase(); - contentType = extensionsMap[extension]; - - if (contentType) { - return contentType; - } - - return extensionsMap[""]; -} - async function serveFile(req: ServerRequest, filename: string) { const file = await open(filename); const fileInfo = await stat(filename); const headers = new Headers(); headers.set("content-length", fileInfo.len.toString()); - headers.set("content-type", guessContentType(filename)); + headers.set("content-type", contentType(extname(filename)) || "text/plain"); const res = { status: 200, diff --git a/net/file_server_test.ts b/net/file_server_test.ts index 28357c912..bd00d749b 100644 --- a/net/file_server_test.ts +++ b/net/file_server_test.ts @@ -21,7 +21,7 @@ export function runTests(serverReadyPromise: Promise) { const res = await fetch("http://localhost:4500/azure-pipelines.yml"); assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-headers")); - assertEqual(res.headers.get("content-type"), "text/yaml"); + assertEqual(res.headers.get("content-type"), "text/yaml; charset=utf-8"); const downloadedFile = await res.text(); const localFile = new TextDecoder().decode( await readFile("./azure-pipelines.yml") diff --git a/test.ts b/test.ts index 0ee32ff8c..dd08cd141 100755 --- a/test.ts +++ b/test.ts @@ -6,6 +6,7 @@ import "datetime/test.ts"; import "examples/test.ts"; import "flags/test.ts"; import "logging/test.ts"; +import "media_types/test.ts"; import "mkdirp/test.ts"; import "net/bufio_test.ts"; import "net/http_test.ts"; -- cgit v1.2.3 From c363fc1de4bdae957ec3ecc7b5b664a801b1ba7d Mon Sep 17 00:00:00 2001 From: "Kwang-in (Dennis) Jung" Date: Fri, 11 Jan 2019 14:19:42 +0900 Subject: Define type for available date format (denoland/deno_std#88) Original: https://github.com/denoland/deno_std/commit/3656ab5b9937cc3fbdf1c9e0d1414fbf05e78240 --- datetime/mod.ts | 25 +++++++++++++++++++++---- datetime/test.ts | 2 +- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/datetime/mod.ts b/datetime/mod.ts index db66af177..c5e6bf0c4 100644 --- a/datetime/mod.ts +++ b/datetime/mod.ts @@ -1,11 +1,13 @@ +export type DateFormat = "mm-dd-yyyy" | "dd-mm-yyyy" | "yyyy-mm-dd"; + /** * Parse date from string using format string * * @param {string} dateStr - date string - * @param {string} format - format string + * @param {DateFormat} format - format string * @return {Date} Parsed date */ -export function parseDate(dateStr: string, format: string): Date { +export function parseDate(dateStr: string, format: DateFormat): Date { let m, d, y: string; if (format === "mm-dd-yyyy") { @@ -17,19 +19,32 @@ export function parseDate(dateStr: string, format: string): Date { } else if (format === "yyyy-mm-dd") { const datePattern = /^(\d{4})-(\d{2})-(\d{2})$/; [, y, m, d] = datePattern.exec(dateStr); + } else { + throw new Error("Invalid date format!"); } return new Date(Number(y), Number(m) - 1, Number(d)); } +export type DateTimeFormat = + | "mm-dd-yyyy hh:mm" + | "dd-mm-yyyy hh:mm" + | "yyyy-mm-dd hh:mm" + | "hh:mm mm-dd-yyyy" + | "hh:mm dd-mm-yyyy" + | "hh:mm yyyy-mm-dd"; + /** * Parse date & time from string using format string * * @param {string} dateStr - date & time string - * @param {string} format - format string + * @param {DateTimeFormat} format - format string * @return {Date} Parsed date */ -export function parseDateTime(datetimeStr: string, format: string): Date { +export function parseDateTime( + datetimeStr: string, + format: DateTimeFormat +): Date { let m, d, y, ho, mi: string; if (format === "mm-dd-yyyy hh:mm") { @@ -50,6 +65,8 @@ export function parseDateTime(datetimeStr: string, format: string): Date { } else if (format === "hh:mm yyyy-mm-dd") { const datePattern = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/; [, ho, mi, y, m, d] = datePattern.exec(datetimeStr); + } else { + throw new Error("Invalid datetime format!"); } return new Date(Number(y), Number(m) - 1, Number(d), Number(ho), Number(mi)); diff --git a/datetime/test.ts b/datetime/test.ts index d5c1622cc..c0e0f89b1 100644 --- a/datetime/test.ts +++ b/datetime/test.ts @@ -9,7 +9,7 @@ test(function parseDateTime() { }); test(function parseDate() { assertEqual( - datetime.parseDateTime("01-03-2019", "mm-dd-yyyy"), + datetime.parseDate("01-03-2019", "mm-dd-yyyy"), new Date(2019, 1, 3) ); }); -- cgit v1.2.3 From 708400804a39081933b6e5735b25bbe29a4ecec1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E6=9D=89?= Date: Sat, 12 Jan 2019 10:56:35 +0800 Subject: style(net): format code (denoland/deno_std#104) Original: https://github.com/denoland/deno_std/commit/c42686dc36ba888137fe734c59318466f41d7dfa --- net/sha1_test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/net/sha1_test.ts b/net/sha1_test.ts index 1d3673c43..b385f18da 100644 --- a/net/sha1_test.ts +++ b/net/sha1_test.ts @@ -1,8 +1,8 @@ -import {assertEqual, test} from "../testing/mod.ts"; -import {Sha1} from "./sha1.ts"; +import { assertEqual, test } from "../testing/mod.ts"; +import { Sha1 } from "./sha1.ts"; test(function testSha1() { const sha1 = new Sha1(); sha1.update("abcde"); - assertEqual(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334") + assertEqual(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); }); -- cgit v1.2.3 From 7d6a0f64f20004f89f5e2cbfcf7941f0a8dafd21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E6=9D=89?= Date: Sun, 13 Jan 2019 02:07:18 +0800 Subject: refactor(mkdirp): reorg (denoland/deno_std#103) Original: https://github.com/denoland/deno_std/commit/41312ad39fe77cee7dd2cc4b48308eebb45f870a --- README.md | 2 +- fs/mkdirp.ts | 43 +++++++++++++++++++++++++++++++++++++++++++ fs/mkdirp_test.ts | 30 ++++++++++++++++++++++++++++++ mkdirp/mkdirp.ts | 24 ------------------------ mkdirp/readme.md | 17 ----------------- mkdirp/test.ts | 30 ------------------------------ test.ts | 2 +- 7 files changed, 75 insertions(+), 73 deletions(-) create mode 100644 fs/mkdirp.ts create mode 100644 fs/mkdirp_test.ts delete mode 100644 mkdirp/mkdirp.ts delete mode 100644 mkdirp/readme.md delete mode 100644 mkdirp/test.ts diff --git a/README.md b/README.md index c291b26cc..13a1bd0e8 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ A library for resolving media types (MIME types) and extensions. -- **[mkdirp](./mkdirp/)** +- **[mkdirp](./fs/)** Make directory branches. diff --git a/fs/mkdirp.ts b/fs/mkdirp.ts new file mode 100644 index 000000000..627166043 --- /dev/null +++ b/fs/mkdirp.ts @@ -0,0 +1,43 @@ +/** + * # deno-mkdirp + * + * `mkdir -p` 4 `deno`. + * + * ## Import + * + * ```ts + * import { mkdirp } from "https://deno.land/x/std/fs/mkdirp.ts"; + * ``` + * + * ## API + * + * Same as [`deno.mkdir`](https://deno.land/typedoc/index.html#mkdir). + * + * ### `mkdirp(path: string, mode?: number) : Promise` + * + * Creates directories if they do not already exist and makes parent directories as needed. + */ +import { ErrorKind, FileInfo, lstat, mkdir, platform } from "deno"; + +const PATH_SEPARATOR: string = platform.os === "win" ? "\\" : "/"; + +export async function mkdirp(path: string, mode?: number): Promise { + for ( + let parts: string[] = path.split(/\/|\\/), + parts_len: number = parts.length, + level: string, + info: FileInfo, + i: number = 0; + i < parts_len; + i++ + ) { + level = parts.slice(0, i + 1).join(PATH_SEPARATOR); + try { + info = await lstat(level); + if (!info.isDirectory()) throw Error(`${level} is not a directory`); + } catch (err) { + if (err.kind !== ErrorKind.NotFound) throw err; + await mkdir(level, mode); + } + } +} diff --git a/fs/mkdirp_test.ts b/fs/mkdirp_test.ts new file mode 100644 index 000000000..a3a4fac03 --- /dev/null +++ b/fs/mkdirp_test.ts @@ -0,0 +1,30 @@ +import { cwd, lstat, makeTempDirSync, removeAll, FileInfo } from "deno"; +import { test, assert } from "../testing/mod.ts"; +import { mkdirp } from "./mkdirp.ts"; + +let root: string = `${cwd()}/${Date.now()}`; //makeTempDirSync(); + +test(async function createsNestedDirs(): Promise { + const leaf: string = `${root}/levelx/levely`; + await mkdirp(leaf); + const info: FileInfo = await lstat(leaf); + assert(info.isDirectory()); + await removeAll(root); +}); + +test(async function handlesAnyPathSeparator(): Promise { + const leaf: string = `${root}\\levelx\\levely`; + await mkdirp(leaf); + const info: FileInfo = await lstat(leaf.replace(/\\/g, "/")); + assert(info.isDirectory()); + await removeAll(root); +}); + +test(async function failsNonDir(): Promise { + try { + await mkdirp("./test.ts/fest.fs"); + } catch (err) { + // TODO: assert caught DenoError of kind NOT_A_DIRECTORY or similar + assert(err); + } +}); diff --git a/mkdirp/mkdirp.ts b/mkdirp/mkdirp.ts deleted file mode 100644 index 9d27c751a..000000000 --- a/mkdirp/mkdirp.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { ErrorKind, FileInfo, lstat, mkdir, platform } from "deno"; - -const PATH_SEPARATOR: string = platform.os === "win" ? "\\" : "/"; - -export async function mkdirp(path: string, mode?: number): Promise { - for ( - let parts: string[] = path.split(/\/|\\/), - parts_len: number = parts.length, - level: string, - info: FileInfo, - i: number = 0; - i < parts_len; - i++ - ) { - level = parts.slice(0, i + 1).join(PATH_SEPARATOR); - try { - info = await lstat(level); - if (!info.isDirectory()) throw Error(`${level} is not a directory`); - } catch (err) { - if (err.kind !== ErrorKind.NotFound) throw err; - await mkdir(level, mode); - } - } -} diff --git a/mkdirp/readme.md b/mkdirp/readme.md deleted file mode 100644 index 48269aa28..000000000 --- a/mkdirp/readme.md +++ /dev/null @@ -1,17 +0,0 @@ -# deno-mkdirp - -`mkdir -p` 4 `deno`. - -## Import - -```ts -import { mkdirp } from "https://deno.land/x/std/mkdirp/mkdirp.ts"; -``` - -## API - -Same as [`deno.mkdir`](https://deno.land/typedoc/index.html#mkdir). - -### `mkdirp(path: string, mode?: number) : Promise` - -Creates directories if they do not already exist and makes parent directories as needed. diff --git a/mkdirp/test.ts b/mkdirp/test.ts deleted file mode 100644 index a3a4fac03..000000000 --- a/mkdirp/test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { cwd, lstat, makeTempDirSync, removeAll, FileInfo } from "deno"; -import { test, assert } from "../testing/mod.ts"; -import { mkdirp } from "./mkdirp.ts"; - -let root: string = `${cwd()}/${Date.now()}`; //makeTempDirSync(); - -test(async function createsNestedDirs(): Promise { - const leaf: string = `${root}/levelx/levely`; - await mkdirp(leaf); - const info: FileInfo = await lstat(leaf); - assert(info.isDirectory()); - await removeAll(root); -}); - -test(async function handlesAnyPathSeparator(): Promise { - const leaf: string = `${root}\\levelx\\levely`; - await mkdirp(leaf); - const info: FileInfo = await lstat(leaf.replace(/\\/g, "/")); - assert(info.isDirectory()); - await removeAll(root); -}); - -test(async function failsNonDir(): Promise { - try { - await mkdirp("./test.ts/fest.fs"); - } catch (err) { - // TODO: assert caught DenoError of kind NOT_A_DIRECTORY or similar - assert(err); - } -}); diff --git a/test.ts b/test.ts index dd08cd141..8a3534457 100755 --- a/test.ts +++ b/test.ts @@ -7,10 +7,10 @@ import "examples/test.ts"; import "flags/test.ts"; import "logging/test.ts"; import "media_types/test.ts"; -import "mkdirp/test.ts"; import "net/bufio_test.ts"; import "net/http_test.ts"; import "net/textproto_test.ts"; +import "fs/mkdirp_test.ts"; import "fs/path/basename_test.ts"; import "fs/path/dirname_test.ts"; import "fs/path/extname_test.ts"; -- cgit v1.2.3 From f626b04ebe320a96a220af29595c6ca84cf9a10a Mon Sep 17 00:00:00 2001 From: Andy Hayden Date: Sat, 12 Jan 2019 13:50:04 -0800 Subject: Reorgnanize repos, examples and tests (denoland/deno_std#105) Original: https://github.com/denoland/deno_std/commit/c5e6e015b5be19027f60c19ca86283d12f9258f3 --- examples/gist.ts | 2 +- examples/ws.ts | 4 +- flags/example.ts | 2 +- flags/index.ts | 271 -------------------------- flags/mod.ts | 271 ++++++++++++++++++++++++++ flags/tests/all_bool.ts | 2 +- flags/tests/bool.ts | 2 +- flags/tests/dash.ts | 2 +- flags/tests/default_bool.ts | 2 +- flags/tests/dotted.ts | 2 +- flags/tests/kv_short.ts | 2 +- flags/tests/long.ts | 2 +- flags/tests/num.ts | 2 +- flags/tests/parse.ts | 2 +- flags/tests/short.ts | 2 +- flags/tests/stop_early.ts | 2 +- flags/tests/unknown.ts | 2 +- flags/tests/whitespace.ts | 2 +- http/README.md | 26 +++ http/file_server.ts | 241 +++++++++++++++++++++++ http/file_server_test.ts | 51 +++++ http/http.ts | 325 +++++++++++++++++++++++++++++++ http/http_bench.ts | 15 ++ http/http_status.ts | 134 +++++++++++++ http/http_test.ts | 223 +++++++++++++++++++++ http/mod.ts | 8 + io/bufio.ts | 464 ++++++++++++++++++++++++++++++++++++++++++++ io/bufio_test.ts | 341 ++++++++++++++++++++++++++++++++ io/iotest.ts | 61 ++++++ io/ioutil.ts | 36 ++++ io/ioutil_test.ts | 62 ++++++ io/util.ts | 29 +++ log/README.md | 38 ++++ log/handlers.ts | 62 ++++++ log/levels.ts | 34 ++++ log/logger.ts | 62 ++++++ log/mod.ts | 119 ++++++++++++ log/test.ts | 28 +++ logging/README.md | 38 ---- logging/handlers.ts | 62 ------ logging/index.ts | 119 ------------ logging/levels.ts | 34 ---- logging/logger.ts | 62 ------ logging/test.ts | 28 --- net/README.md | 26 --- net/bufio.ts | 464 -------------------------------------------- net/bufio_test.ts | 341 -------------------------------- net/file_server.ts | 241 ----------------------- net/file_server_test.ts | 51 ----- net/http.ts | 325 ------------------------------- net/http_bench.ts | 15 -- net/http_status.ts | 134 ------------- net/http_test.ts | 223 --------------------- net/iotest.ts | 61 ------ net/ioutil.ts | 36 ---- net/ioutil_test.ts | 62 ------ net/sha1.ts | 382 ------------------------------------ net/sha1_test.ts | 8 - net/textproto.ts | 150 -------------- net/textproto_test.ts | 98 ---------- net/util.ts | 29 --- net/ws.ts | 350 --------------------------------- net/ws_test.ts | 138 ------------- test.ts | 15 +- textproto/mod.ts | 150 ++++++++++++++ textproto/test.ts | 98 ++++++++++ ws/mod.ts | 350 +++++++++++++++++++++++++++++++++ ws/sha1.ts | 382 ++++++++++++++++++++++++++++++++++++ ws/sha1_test.ts | 8 + ws/test.ts | 138 +++++++++++++ 70 files changed, 3781 insertions(+), 3772 deletions(-) delete mode 100644 flags/index.ts create mode 100644 flags/mod.ts create mode 100644 http/README.md create mode 100755 http/file_server.ts create mode 100644 http/file_server_test.ts create mode 100644 http/http.ts create mode 100644 http/http_bench.ts create mode 100644 http/http_status.ts create mode 100644 http/http_test.ts create mode 100644 http/mod.ts create mode 100644 io/bufio.ts create mode 100644 io/bufio_test.ts create mode 100644 io/iotest.ts create mode 100644 io/ioutil.ts create mode 100644 io/ioutil_test.ts create mode 100644 io/util.ts create mode 100644 log/README.md create mode 100644 log/handlers.ts create mode 100644 log/levels.ts create mode 100644 log/logger.ts create mode 100644 log/mod.ts create mode 100644 log/test.ts delete mode 100644 logging/README.md delete mode 100644 logging/handlers.ts delete mode 100644 logging/index.ts delete mode 100644 logging/levels.ts delete mode 100644 logging/logger.ts delete mode 100644 logging/test.ts delete mode 100644 net/README.md delete mode 100644 net/bufio.ts delete mode 100644 net/bufio_test.ts delete mode 100755 net/file_server.ts delete mode 100644 net/file_server_test.ts delete mode 100644 net/http.ts delete mode 100644 net/http_bench.ts delete mode 100644 net/http_status.ts delete mode 100644 net/http_test.ts delete mode 100644 net/iotest.ts delete mode 100644 net/ioutil.ts delete mode 100644 net/ioutil_test.ts delete mode 100644 net/sha1.ts delete mode 100644 net/sha1_test.ts delete mode 100644 net/textproto.ts delete mode 100644 net/textproto_test.ts delete mode 100644 net/util.ts delete mode 100644 net/ws.ts delete mode 100644 net/ws_test.ts create mode 100644 textproto/mod.ts create mode 100644 textproto/test.ts create mode 100644 ws/mod.ts create mode 100644 ws/sha1.ts create mode 100644 ws/sha1_test.ts create mode 100644 ws/test.ts diff --git a/examples/gist.ts b/examples/gist.ts index 7b3d59f87..1baff874a 100755 --- a/examples/gist.ts +++ b/examples/gist.ts @@ -1,7 +1,7 @@ #!/usr/bin/env deno --allow-net --allow-env import { args, env, exit, readFile } from "deno"; -import { parse } from "https://deno.land/x/flags/index.ts"; +import { parse } from "https://deno.land/x/flags/mod.ts"; function pathBase(p: string): string { const parts = p.split("/"); diff --git a/examples/ws.ts b/examples/ws.ts index f8e711c49..bc2a7bd0b 100644 --- a/examples/ws.ts +++ b/examples/ws.ts @@ -1,10 +1,10 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -import { serve } from "https://deno.land/x/net/http.ts"; +import { serve } from "https://deno.land/x/http/mod.ts"; import { acceptWebSocket, isWebSocketCloseEvent, isWebSocketPingEvent -} from "https://deno.land/x/net/ws.ts"; +} from "https://deno.land/x/ws/mod.ts"; async function main() { console.log("websocket server is running on 0.0.0.0:8080"); diff --git a/flags/example.ts b/flags/example.ts index 811aacd69..5aa0a5034 100644 --- a/flags/example.ts +++ b/flags/example.ts @@ -1,4 +1,4 @@ import { args } from "deno"; -import { parse } from "./index.ts"; +import { parse } from "./mod.ts"; console.dir(parse(args)); diff --git a/flags/index.ts b/flags/index.ts deleted file mode 100644 index 28a5c8eac..000000000 --- a/flags/index.ts +++ /dev/null @@ -1,271 +0,0 @@ -export interface ArgParsingOptions { - unknown?: Function; - boolean?: Boolean | string | string[]; - alias?: { [key: string]: string | string[] }; - string?: string | string[]; - default?: { [key: string]: any }; - "--"?: Boolean; - stopEarly?: Boolean; -} - -const DEFAULT_OPTIONS = { - unknown: i => i, - boolean: false, - alias: {}, - string: [], - default: {}, - "--": false, - stopEarly: false -}; - -export function parse( - args, - initialOptions?: ArgParsingOptions -): { [key: string]: any } { - const options: ArgParsingOptions = { - ...DEFAULT_OPTIONS, - ...(initialOptions || {}) - }; - - const flags = { - bools: {}, - strings: {}, - unknownFn: options.unknown!, - allBools: false - }; - - // TODO: get rid of this, providing two different options - if (typeof options["boolean"] === "boolean" && options["boolean"]) { - flags.allBools = true; - } else { - [] - .concat(options["boolean"]) - .filter(Boolean) - .forEach(function(key) { - flags.bools[key] = true; - }); - } - - const aliases = {}; - Object.keys(options.alias).forEach(function(key) { - aliases[key] = [].concat(options.alias[key]); - aliases[key].forEach(function(x) { - aliases[x] = [key].concat( - aliases[key].filter(function(y) { - return x !== y; - }) - ); - }); - }); - - [] - .concat(options.string) - .filter(Boolean) - .forEach(function(key) { - flags.strings[key] = true; - if (aliases[key]) { - flags.strings[aliases[key]] = true; - } - }); - - const defaults = options.default!; - - const argv = { _: [] }; - Object.keys(flags.bools).forEach(function(key) { - setArg(key, defaults[key] === undefined ? false : defaults[key]); - }); - - let notFlags = []; - - if (args.indexOf("--") !== -1) { - notFlags = args.slice(args.indexOf("--") + 1); - args = args.slice(0, args.indexOf("--")); - } - - function argDefined(key, arg) { - return ( - (flags.allBools && /^--[^=]+$/.test(arg)) || - flags.strings[key] || - flags.bools[key] || - aliases[key] - ); - } - - function setArg(key, val, arg = null): void { - if (arg && flags.unknownFn && !argDefined(key, arg)) { - if (flags.unknownFn(arg) === false) return; - } - - const value = !flags.strings[key] && isNumber(val) ? Number(val) : val; - setKey(argv, key.split("."), value); - - (aliases[key] || []).forEach(function(x) { - setKey(argv, x.split("."), value); - }); - } - - function setKey(obj, keys, value): void { - let o = obj; - keys.slice(0, -1).forEach(function(key) { - if (o[key] === undefined) o[key] = {}; - o = o[key]; - }); - - const key = keys[keys.length - 1]; - if ( - o[key] === undefined || - flags.bools[key] || - typeof o[key] === "boolean" - ) { - o[key] = value; - } else if (Array.isArray(o[key])) { - o[key].push(value); - } else { - o[key] = [o[key], value]; - } - } - - function aliasIsBoolean(key): boolean { - return aliases[key].some(function(x) { - return flags.bools[x]; - }); - } - - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - - if (/^--.+=/.test(arg)) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - const m = arg.match(/^--([^=]+)=([\s\S]*)$/); - const key = m[1]; - let value = m[2]; - if (flags.bools[key]) { - value = value !== "false"; - } - setArg(key, value, arg); - } else if (/^--no-.+/.test(arg)) { - const key = arg.match(/^--no-(.+)/)[1]; - setArg(key, false, arg); - } else if (/^--.+/.test(arg)) { - const key = arg.match(/^--(.+)/)[1]; - const next = args[i + 1]; - if ( - next !== undefined && - !/^-/.test(next) && - !flags.bools[key] && - !flags.allBools && - (aliases[key] ? !aliasIsBoolean(key) : true) - ) { - setArg(key, next, arg); - i++; - } else if (/^(true|false)$/.test(next)) { - setArg(key, next === "true", arg); - i++; - } else { - setArg(key, flags.strings[key] ? "" : true, arg); - } - } else if (/^-[^-]+/.test(arg)) { - const letters = arg.slice(1, -1).split(""); - - let broken = false; - for (let j = 0; j < letters.length; j++) { - const next = arg.slice(j + 2); - - if (next === "-") { - setArg(letters[j], next, arg); - continue; - } - - if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { - setArg(letters[j], next.split("=")[1], arg); - broken = true; - break; - } - - if ( - /[A-Za-z]/.test(letters[j]) && - /-?\d+(\.\d*)?(e-?\d+)?$/.test(next) - ) { - setArg(letters[j], next, arg); - broken = true; - break; - } - - if (letters[j + 1] && letters[j + 1].match(/\W/)) { - setArg(letters[j], arg.slice(j + 2), arg); - broken = true; - break; - } else { - setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg); - } - } - - const key = arg.slice(-1)[0]; - if (!broken && key !== "-") { - if ( - args[i + 1] && - !/^(-|--)[^-]/.test(args[i + 1]) && - !flags.bools[key] && - (aliases[key] ? !aliasIsBoolean(key) : true) - ) { - setArg(key, args[i + 1], arg); - i++; - } else if (args[i + 1] && /true|false/.test(args[i + 1])) { - setArg(key, args[i + 1] === "true", arg); - i++; - } else { - setArg(key, flags.strings[key] ? "" : true, arg); - } - } - } else { - if (!flags.unknownFn || flags.unknownFn(arg) !== false) { - argv._.push(flags.strings["_"] || !isNumber(arg) ? arg : Number(arg)); - } - if (options.stopEarly) { - argv._.push.apply(argv._, args.slice(i + 1)); - break; - } - } - } - - Object.keys(defaults).forEach(function(key) { - if (!hasKey(argv, key.split("."))) { - setKey(argv, key.split("."), defaults[key]); - - (aliases[key] || []).forEach(function(x) { - setKey(argv, x.split("."), defaults[key]); - }); - } - }); - - if (options["--"]) { - argv["--"] = new Array(); - notFlags.forEach(function(key) { - argv["--"].push(key); - }); - } else { - notFlags.forEach(function(key) { - argv._.push(key); - }); - } - - return argv; -} - -function hasKey(obj, keys) { - let o = obj; - keys.slice(0, -1).forEach(function(key) { - o = o[key] || {}; - }); - - const key = keys[keys.length - 1]; - return key in o; -} - -function isNumber(x: any): boolean { - if (typeof x === "number") return true; - if (/^0x[0-9a-f]+$/i.test(x)) return true; - return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); -} diff --git a/flags/mod.ts b/flags/mod.ts new file mode 100644 index 000000000..28a5c8eac --- /dev/null +++ b/flags/mod.ts @@ -0,0 +1,271 @@ +export interface ArgParsingOptions { + unknown?: Function; + boolean?: Boolean | string | string[]; + alias?: { [key: string]: string | string[] }; + string?: string | string[]; + default?: { [key: string]: any }; + "--"?: Boolean; + stopEarly?: Boolean; +} + +const DEFAULT_OPTIONS = { + unknown: i => i, + boolean: false, + alias: {}, + string: [], + default: {}, + "--": false, + stopEarly: false +}; + +export function parse( + args, + initialOptions?: ArgParsingOptions +): { [key: string]: any } { + const options: ArgParsingOptions = { + ...DEFAULT_OPTIONS, + ...(initialOptions || {}) + }; + + const flags = { + bools: {}, + strings: {}, + unknownFn: options.unknown!, + allBools: false + }; + + // TODO: get rid of this, providing two different options + if (typeof options["boolean"] === "boolean" && options["boolean"]) { + flags.allBools = true; + } else { + [] + .concat(options["boolean"]) + .filter(Boolean) + .forEach(function(key) { + flags.bools[key] = true; + }); + } + + const aliases = {}; + Object.keys(options.alias).forEach(function(key) { + aliases[key] = [].concat(options.alias[key]); + aliases[key].forEach(function(x) { + aliases[x] = [key].concat( + aliases[key].filter(function(y) { + return x !== y; + }) + ); + }); + }); + + [] + .concat(options.string) + .filter(Boolean) + .forEach(function(key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + + const defaults = options.default!; + + const argv = { _: [] }; + Object.keys(flags.bools).forEach(function(key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + let notFlags = []; + + if (args.indexOf("--") !== -1) { + notFlags = args.slice(args.indexOf("--") + 1); + args = args.slice(0, args.indexOf("--")); + } + + function argDefined(key, arg) { + return ( + (flags.allBools && /^--[^=]+$/.test(arg)) || + flags.strings[key] || + flags.bools[key] || + aliases[key] + ); + } + + function setArg(key, val, arg = null): void { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + + const value = !flags.strings[key] && isNumber(val) ? Number(val) : val; + setKey(argv, key.split("."), value); + + (aliases[key] || []).forEach(function(x) { + setKey(argv, x.split("."), value); + }); + } + + function setKey(obj, keys, value): void { + let o = obj; + keys.slice(0, -1).forEach(function(key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + const key = keys[keys.length - 1]; + if ( + o[key] === undefined || + flags.bools[key] || + typeof o[key] === "boolean" + ) { + o[key] = value; + } else if (Array.isArray(o[key])) { + o[key].push(value); + } else { + o[key] = [o[key], value]; + } + } + + function aliasIsBoolean(key): boolean { + return aliases[key].some(function(x) { + return flags.bools[x]; + }); + } + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + const m = arg.match(/^--([^=]+)=([\s\S]*)$/); + const key = m[1]; + let value = m[2]; + if (flags.bools[key]) { + value = value !== "false"; + } + setArg(key, value, arg); + } else if (/^--no-.+/.test(arg)) { + const key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } else if (/^--.+/.test(arg)) { + const key = arg.match(/^--(.+)/)[1]; + const next = args[i + 1]; + if ( + next !== undefined && + !/^-/.test(next) && + !flags.bools[key] && + !flags.allBools && + (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, next, arg); + i++; + } else if (/^(true|false)$/.test(next)) { + setArg(key, next === "true", arg); + i++; + } else { + setArg(key, flags.strings[key] ? "" : true, arg); + } + } else if (/^-[^-]+/.test(arg)) { + const letters = arg.slice(1, -1).split(""); + + let broken = false; + for (let j = 0; j < letters.length; j++) { + const next = arg.slice(j + 2); + + if (next === "-") { + setArg(letters[j], next, arg); + continue; + } + + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split("=")[1], arg); + broken = true; + break; + } + + if ( + /[A-Za-z]/.test(letters[j]) && + /-?\d+(\.\d*)?(e-?\d+)?$/.test(next) + ) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], arg.slice(j + 2), arg); + broken = true; + break; + } else { + setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg); + } + } + + const key = arg.slice(-1)[0]; + if (!broken && key !== "-") { + if ( + args[i + 1] && + !/^(-|--)[^-]/.test(args[i + 1]) && + !flags.bools[key] && + (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, args[i + 1], arg); + i++; + } else if (args[i + 1] && /true|false/.test(args[i + 1])) { + setArg(key, args[i + 1] === "true", arg); + i++; + } else { + setArg(key, flags.strings[key] ? "" : true, arg); + } + } + } else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push(flags.strings["_"] || !isNumber(arg) ? arg : Number(arg)); + } + if (options.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function(key) { + if (!hasKey(argv, key.split("."))) { + setKey(argv, key.split("."), defaults[key]); + + (aliases[key] || []).forEach(function(x) { + setKey(argv, x.split("."), defaults[key]); + }); + } + }); + + if (options["--"]) { + argv["--"] = new Array(); + notFlags.forEach(function(key) { + argv["--"].push(key); + }); + } else { + notFlags.forEach(function(key) { + argv._.push(key); + }); + } + + return argv; +} + +function hasKey(obj, keys) { + let o = obj; + keys.slice(0, -1).forEach(function(key) { + o = o[key] || {}; + }); + + const key = keys[keys.length - 1]; + return key in o; +} + +function isNumber(x: any): boolean { + if (typeof x === "number") return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} diff --git a/flags/tests/all_bool.ts b/flags/tests/all_bool.ts index 2e0bba4ce..07b12c292 100755 --- a/flags/tests/all_bool.ts +++ b/flags/tests/all_bool.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; // flag boolean true (default all --args to boolean) test(function flagBooleanTrue() { diff --git a/flags/tests/bool.ts b/flags/tests/bool.ts index 5d135028e..6fa014d8d 100755 --- a/flags/tests/bool.ts +++ b/flags/tests/bool.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function flagBooleanDefaultFalse() { const argv = parse(["moo"], { diff --git a/flags/tests/dash.ts b/flags/tests/dash.ts index f8cec6ef7..6ab1a7d75 100755 --- a/flags/tests/dash.ts +++ b/flags/tests/dash.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function hyphen() { assertEqual(parse(["-n", "-"]), { n: "-", _: [] }); diff --git a/flags/tests/default_bool.ts b/flags/tests/default_bool.ts index 8cf6a720b..82dab5538 100755 --- a/flags/tests/default_bool.ts +++ b/flags/tests/default_bool.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function booleanDefaultTrue() { const argv = parse([], { diff --git a/flags/tests/dotted.ts b/flags/tests/dotted.ts index 94867abb2..6b64e3b5e 100755 --- a/flags/tests/dotted.ts +++ b/flags/tests/dotted.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function dottedAlias() { const argv = parse(["--a.b", "22"], { diff --git a/flags/tests/kv_short.ts b/flags/tests/kv_short.ts index 1050d7734..41853c1de 100755 --- a/flags/tests/kv_short.ts +++ b/flags/tests/kv_short.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function short() { const argv = parse(["-b=123"]); diff --git a/flags/tests/long.ts b/flags/tests/long.ts index 41c3e7743..d75ece3b2 100755 --- a/flags/tests/long.ts +++ b/flags/tests/long.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function longOpts() { assertEqual(parse(["--bool"]), { bool: true, _: [] }); diff --git a/flags/tests/num.ts b/flags/tests/num.ts index 0588b51f6..cc5b1b4e3 100755 --- a/flags/tests/num.ts +++ b/flags/tests/num.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function nums() { const argv = parse([ diff --git a/flags/tests/parse.ts b/flags/tests/parse.ts index 30551f875..263335761 100644 --- a/flags/tests/parse.ts +++ b/flags/tests/parse.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function _arseArgs() { assertEqual(parse(["--no-moo"]), { moo: false, _: [] }); diff --git a/flags/tests/short.ts b/flags/tests/short.ts index dee981351..fe8994394 100755 --- a/flags/tests/short.ts +++ b/flags/tests/short.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function numbericShortArgs() { assertEqual(parse(["-n123"]), { n: 123, _: [] }); diff --git a/flags/tests/stop_early.ts b/flags/tests/stop_early.ts index ca64bf97e..aef4d5dc5 100755 --- a/flags/tests/stop_early.ts +++ b/flags/tests/stop_early.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; // stops parsing on the first non-option when stopEarly is set test(function stopParsing() { diff --git a/flags/tests/unknown.ts b/flags/tests/unknown.ts index 2c87b18fe..e86f92796 100755 --- a/flags/tests/unknown.ts +++ b/flags/tests/unknown.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function booleanAndAliasIsNotUnknown() { const unknown = []; diff --git a/flags/tests/whitespace.ts b/flags/tests/whitespace.ts index 8373cd19e..46ad09426 100755 --- a/flags/tests/whitespace.ts +++ b/flags/tests/whitespace.ts @@ -1,5 +1,5 @@ import { test, assertEqual } from "../../testing/mod.ts"; -import { parse } from "../index.ts"; +import { parse } from "../mod.ts"; test(function whitespaceShouldBeWhitespace() { assertEqual(parse(["-x", "\t"]).x, "\t"); diff --git a/http/README.md b/http/README.md new file mode 100644 index 000000000..e81e42a41 --- /dev/null +++ b/http/README.md @@ -0,0 +1,26 @@ +# net + +Usage: + +```typescript +import { serve } from "https://deno.land/x/http/mod.ts"; +const s = serve("0.0.0.0:8000"); + +async function main() { + for await (const req of s) { + req.respond({ body: new TextEncoder().encode("Hello World\n") }); + } +} + +main(); +``` + +### File Server + +A small program for serving local files over HTTP. + +Add the following to your `.bash_profile` + +``` +alias file_server="deno https://deno.land/x/http/file_server.ts --allow-net" +``` diff --git a/http/file_server.ts b/http/file_server.ts new file mode 100755 index 000000000..4437a44e4 --- /dev/null +++ b/http/file_server.ts @@ -0,0 +1,241 @@ +#!/usr/bin/env deno --allow-net + +// This program serves files in the current directory over HTTP. +// TODO Stream responses instead of reading them into memory. +// TODO Add tests like these: +// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js + +import { + listenAndServe, + ServerRequest, + setContentLength, + Response +} from "./mod.ts"; +import { cwd, DenoError, ErrorKind, args, stat, readDir, open } from "deno"; +import { extname } from "../fs/path.ts"; +import { contentType } from "../media_types/mod.ts"; + +const dirViewerTemplate = ` + + + + + + + Deno File Server + + + +

Index of <%DIRNAME%>

+ + + <%CONTENTS%> +
ModeSizeName
+ + +`; + +const serverArgs = args.slice(); +let CORSEnabled = false; +// TODO: switch to flags if we later want to add more options +for (let i = 0; i < serverArgs.length; i++) { + if (serverArgs[i] === "--cors") { + CORSEnabled = true; + serverArgs.splice(i, 1); + break; + } +} +let currentDir = cwd(); +const target = serverArgs[1]; +if (target) { + currentDir = `${currentDir}/${target}`; +} +const addr = `0.0.0.0:${serverArgs[2] || 4500}`; +const encoder = new TextEncoder(); + +function modeToString(isDir: boolean, maybeMode: number | null) { + const modeMap = ["---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"]; + + if (maybeMode === null) { + return "(unknown mode)"; + } + const mode = maybeMode!.toString(8); + if (mode.length < 3) { + return "(unknown mode)"; + } + let output = ""; + mode + .split("") + .reverse() + .slice(0, 3) + .forEach(v => { + output = modeMap[+v] + output; + }); + output = `(${isDir ? "d" : "-"}${output})`; + return output; +} + +function fileLenToString(len: number) { + const multipler = 1024; + let base = 1; + const suffix = ["B", "K", "M", "G", "T"]; + let suffixIndex = 0; + + while (base * multipler < len) { + if (suffixIndex >= suffix.length - 1) { + break; + } + base *= multipler; + suffixIndex++; + } + + return `${(len / base).toFixed(2)}${suffix[suffixIndex]}`; +} + +function createDirEntryDisplay( + name: string, + path: string, + size: number | null, + mode: number | null, + isDir: boolean +) { + const sizeStr = size === null ? "" : "" + fileLenToString(size!); + return ` + ${modeToString( + isDir, + mode + )}${sizeStr}${name}${ + isDir ? "/" : "" + } + + `; +} + +// TODO: simplify this after deno.stat and deno.readDir are fixed +async function serveDir(req: ServerRequest, dirPath: string, dirName: string) { + // dirname has no prefix + const listEntry: string[] = []; + const fileInfos = await readDir(dirPath); + for (const info of fileInfos) { + if (info.name === "index.html" && info.isFile()) { + // in case index.html as dir... + return await serveFile(req, info.path); + } + // Yuck! + let mode = null; + try { + mode = (await stat(info.path)).mode; + } catch (e) {} + listEntry.push( + createDirEntryDisplay( + info.name, + dirName + "/" + info.name, + info.isFile() ? info.len : null, + mode, + info.isDirectory() + ) + ); + } + + const page = new TextEncoder().encode( + dirViewerTemplate + .replace("<%DIRNAME%>", dirName + "/") + .replace("<%CONTENTS%>", listEntry.join("")) + ); + + const headers = new Headers(); + headers.set("content-type", "text/html"); + + const res = { + status: 200, + body: page, + headers + }; + setContentLength(res); + return res; +} + +async function serveFile(req: ServerRequest, filename: string) { + const file = await open(filename); + const fileInfo = await stat(filename); + const headers = new Headers(); + headers.set("content-length", fileInfo.len.toString()); + headers.set("content-type", contentType(extname(filename)) || "text/plain"); + + const res = { + status: 200, + body: file, + headers + }; + return res; +} + +async function serveFallback(req: ServerRequest, e: Error) { + if ( + e instanceof DenoError && + (e as DenoError).kind === ErrorKind.NotFound + ) { + return { + status: 404, + body: encoder.encode("Not found") + }; + } else { + return { + status: 500, + body: encoder.encode("Internal server error") + }; + } +} + +function serverLog(req: ServerRequest, res: Response) { + const d = new Date().toISOString(); + const dateFmt = `[${d.slice(0, 10)} ${d.slice(11, 19)}]`; + const s = `${dateFmt} "${req.method} ${req.url} ${req.proto}" ${res.status}`; + console.log(s); +} + +function setCORS(res: Response) { + if (!res.headers) { + res.headers = new Headers(); + } + res.headers!.append("access-control-allow-origin", "*"); + res.headers!.append( + "access-control-allow-headers", + "Origin, X-Requested-With, Content-Type, Accept, Range" + ); +} + +listenAndServe(addr, async req => { + const fileName = req.url.replace(/\/$/, ""); + const filePath = currentDir + fileName; + + let response: Response; + + try { + const fileInfo = await stat(filePath); + if (fileInfo.isDirectory()) { + // Bug with deno.stat: name and path not populated + // Yuck! + response = await serveDir(req, filePath, fileName); + } else { + response = await serveFile(req, filePath); + } + } catch (e) { + response = await serveFallback(req, e); + } finally { + if (CORSEnabled) { + setCORS(response); + } + serverLog(req, response); + req.respond(response); + } +}); + +console.log(`HTTP server listening on http://${addr}/`); diff --git a/http/file_server_test.ts b/http/file_server_test.ts new file mode 100644 index 000000000..bd00d749b --- /dev/null +++ b/http/file_server_test.ts @@ -0,0 +1,51 @@ +import { readFile } from "deno"; + +import { test, assert, assertEqual } from "../testing/mod.ts"; + +// Promise to completeResolve when all tests completes +let completeResolve; +export const completePromise = new Promise(res => (completeResolve = res)); +let completedTestCount = 0; + +function maybeCompleteTests() { + completedTestCount++; + // Change this when adding more tests + if (completedTestCount === 3) { + completeResolve(); + } +} + +export function runTests(serverReadyPromise: Promise) { + test(async function serveFile() { + await serverReadyPromise; + const res = await fetch("http://localhost:4500/azure-pipelines.yml"); + assert(res.headers.has("access-control-allow-origin")); + assert(res.headers.has("access-control-allow-headers")); + assertEqual(res.headers.get("content-type"), "text/yaml; charset=utf-8"); + const downloadedFile = await res.text(); + const localFile = new TextDecoder().decode( + await readFile("./azure-pipelines.yml") + ); + assertEqual(downloadedFile, localFile); + maybeCompleteTests(); + }); + + test(async function serveDirectory() { + await serverReadyPromise; + const res = await fetch("http://localhost:4500/"); + assert(res.headers.has("access-control-allow-origin")); + assert(res.headers.has("access-control-allow-headers")); + const page = await res.text(); + assert(page.includes("azure-pipelines.yml")); + maybeCompleteTests(); + }); + + test(async function serveFallback() { + await serverReadyPromise; + const res = await fetch("http://localhost:4500/badfile.txt"); + assert(res.headers.has("access-control-allow-origin")); + assert(res.headers.has("access-control-allow-headers")); + assertEqual(res.status, 404); + maybeCompleteTests(); + }); +} diff --git a/http/http.ts b/http/http.ts new file mode 100644 index 000000000..da7bc0169 --- /dev/null +++ b/http/http.ts @@ -0,0 +1,325 @@ +import { listen, Conn, toAsyncIterator, Reader, copy } from "deno"; +import { BufReader, BufState, BufWriter } from "../io/bufio.ts"; +import { TextProtoReader } from "../textproto/mod.ts"; +import { STATUS_TEXT } from "./http_status.ts"; +import { assert } from "../io/util.ts"; + +interface Deferred { + promise: Promise<{}>; + resolve: () => void; + reject: () => void; +} + +function deferred(): Deferred { + let resolve, reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { + promise, + resolve, + reject + }; +} + +interface ServeEnv { + reqQueue: ServerRequest[]; + serveDeferred: Deferred; +} + +/** Continuously read more requests from conn until EOF + * Calls maybeHandleReq. + * bufr is empty on a fresh TCP connection. + * Would be passed around and reused for later request on same conn + * TODO: make them async function after this change is done + * https://github.com/tc39/ecma262/pull/1250 + * See https://v8.dev/blog/fast-async + */ +function serveConn(env: ServeEnv, conn: Conn, bufr?: BufReader) { + readRequest(conn, bufr).then(maybeHandleReq.bind(null, env, conn)); +} +function maybeHandleReq(env: ServeEnv, conn: Conn, maybeReq: any) { + const [req, _err] = maybeReq; + if (_err) { + conn.close(); // assume EOF for now... + return; + } + env.reqQueue.push(req); // push req to queue + env.serveDeferred.resolve(); // signal while loop to process it +} + +export async function* serve(addr: string) { + const listener = listen("tcp", addr); + const env: ServeEnv = { + reqQueue: [], // in case multiple promises are ready + serveDeferred: deferred() + }; + + // Routine that keeps calling accept + const acceptRoutine = () => { + const handleConn = (conn: Conn) => { + serveConn(env, conn); // don't block + scheduleAccept(); // schedule next accept + }; + const scheduleAccept = () => { + listener.accept().then(handleConn); + }; + scheduleAccept(); + }; + + acceptRoutine(); + + // Loop hack to allow yield (yield won't work in callbacks) + while (true) { + await env.serveDeferred.promise; + env.serveDeferred = deferred(); // use a new deferred + let queueToProcess = env.reqQueue; + env.reqQueue = []; + for (const result of queueToProcess) { + yield result; + // Continue read more from conn when user is done with the current req + // Moving this here makes it easier to manage + serveConn(env, result.conn, result.r); + } + } + listener.close(); +} + +export async function listenAndServe( + addr: string, + handler: (req: ServerRequest) => void +) { + const server = serve(addr); + + for await (const request of server) { + await handler(request); + } +} + +export interface Response { + status?: number; + headers?: Headers; + body?: Uint8Array | Reader; +} + +export function setContentLength(r: Response): void { + if (!r.headers) { + r.headers = new Headers(); + } + + if (r.body) { + if (!r.headers.has("content-length")) { + if (r.body instanceof Uint8Array) { + const bodyLength = r.body.byteLength; + r.headers.append("Content-Length", bodyLength.toString()); + } else { + r.headers.append("Transfer-Encoding", "chunked"); + } + } + } +} + +export class ServerRequest { + url: string; + method: string; + proto: string; + headers: Headers; + conn: Conn; + r: BufReader; + w: BufWriter; + + public async *bodyStream() { + if (this.headers.has("content-length")) { + const len = +this.headers.get("content-length"); + if (Number.isNaN(len)) { + return new Uint8Array(0); + } + let buf = new Uint8Array(1024); + let rr = await this.r.read(buf); + let nread = rr.nread; + while (!rr.eof && nread < len) { + yield buf.subarray(0, rr.nread); + buf = new Uint8Array(1024); + rr = await this.r.read(buf); + nread += rr.nread; + } + yield buf.subarray(0, rr.nread); + } else { + if (this.headers.has("transfer-encoding")) { + const transferEncodings = this.headers + .get("transfer-encoding") + .split(",") + .map(e => e.trim().toLowerCase()); + if (transferEncodings.includes("chunked")) { + // Based on https://tools.ietf.org/html/rfc2616#section-19.4.6 + const tp = new TextProtoReader(this.r); + let [line, _] = await tp.readLine(); + // TODO: handle chunk extension + let [chunkSizeString, optExt] = line.split(";"); + let chunkSize = parseInt(chunkSizeString, 16); + if (Number.isNaN(chunkSize) || chunkSize < 0) { + throw new Error("Invalid chunk size"); + } + while (chunkSize > 0) { + let data = new Uint8Array(chunkSize); + let [nread, err] = await this.r.readFull(data); + if (nread !== chunkSize) { + throw new Error("Chunk data does not match size"); + } + yield data; + await this.r.readLine(); // Consume \r\n + [line, _] = await tp.readLine(); + chunkSize = parseInt(line, 16); + } + const [entityHeaders, err] = await tp.readMIMEHeader(); + if (!err) { + for (let [k, v] of entityHeaders) { + this.headers.set(k, v); + } + } + /* Pseudo code from https://tools.ietf.org/html/rfc2616#section-19.4.6 + length := 0 + read chunk-size, chunk-extension (if any) and CRLF + while (chunk-size > 0) { + read chunk-data and CRLF + append chunk-data to entity-body + length := length + chunk-size + read chunk-size and CRLF + } + read entity-header + while (entity-header not empty) { + append entity-header to existing header fields + read entity-header + } + Content-Length := length + Remove "chunked" from Transfer-Encoding + */ + return; // Must return here to avoid fall through + } + // TODO: handle other transfer-encoding types + } + // Otherwise... + yield new Uint8Array(0); + } + } + + // Read the body of the request into a single Uint8Array + public async body(): Promise { + return readAllIterator(this.bodyStream()); + } + + private async _streamBody(body: Reader, bodyLength: number) { + const n = await copy(this.w, body); + assert(n == bodyLength); + } + + private async _streamChunkedBody(body: Reader) { + const encoder = new TextEncoder(); + + for await (const chunk of toAsyncIterator(body)) { + const start = encoder.encode(`${chunk.byteLength.toString(16)}\r\n`); + const end = encoder.encode("\r\n"); + await this.w.write(start); + await this.w.write(chunk); + await this.w.write(end); + } + + const endChunk = encoder.encode("0\r\n\r\n"); + await this.w.write(endChunk); + } + + async respond(r: Response): Promise { + const protoMajor = 1; + const protoMinor = 1; + const statusCode = r.status || 200; + const statusText = STATUS_TEXT.get(statusCode); + if (!statusText) { + throw Error("bad status code"); + } + + let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`; + + setContentLength(r); + + if (r.headers) { + for (const [key, value] of r.headers) { + out += `${key}: ${value}\r\n`; + } + } + out += "\r\n"; + + const header = new TextEncoder().encode(out); + let n = await this.w.write(header); + assert(header.byteLength == n); + + if (r.body) { + if (r.body instanceof Uint8Array) { + n = await this.w.write(r.body); + assert(r.body.byteLength == n); + } else { + if (r.headers.has("content-length")) { + await this._streamBody( + r.body, + parseInt(r.headers.get("content-length")) + ); + } else { + await this._streamChunkedBody(r.body); + } + } + } + + await this.w.flush(); + } +} + +async function readRequest( + c: Conn, + bufr?: BufReader +): Promise<[ServerRequest, BufState]> { + if (!bufr) { + bufr = new BufReader(c); + } + const bufw = new BufWriter(c); + const req = new ServerRequest(); + req.conn = c; + req.r = bufr!; + req.w = bufw; + const tp = new TextProtoReader(bufr!); + + let s: string; + let err: BufState; + + // First line: GET /index.html HTTP/1.0 + [s, err] = await tp.readLine(); + if (err) { + return [null, err]; + } + [req.method, req.url, req.proto] = s.split(" ", 3); + + [req.headers, err] = await tp.readMIMEHeader(); + + return [req, err]; +} + +async function readAllIterator( + it: AsyncIterableIterator +): Promise { + const chunks = []; + let len = 0; + for await (const chunk of it) { + chunks.push(chunk); + len += chunk.length; + } + if (chunks.length === 0) { + // No need for copy + return chunks[0]; + } + const collected = new Uint8Array(len); + let offset = 0; + for (let chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; +} diff --git a/http/http_bench.ts b/http/http_bench.ts new file mode 100644 index 000000000..5aca12f55 --- /dev/null +++ b/http/http_bench.ts @@ -0,0 +1,15 @@ +import * as deno from "deno"; +import { serve } from "./mod.ts"; + +const addr = deno.args[1] || "127.0.0.1:4500"; +const server = serve(addr); + +const body = new TextEncoder().encode("Hello World"); + +async function main(): Promise { + for await (const request of server) { + await request.respond({ status: 200, body }); + } +} + +main(); diff --git a/http/http_status.ts b/http/http_status.ts new file mode 100644 index 000000000..a3006d319 --- /dev/null +++ b/http/http_status.ts @@ -0,0 +1,134 @@ +export enum Status { + Continue = 100, // RFC 7231, 6.2.1 + SwitchingProtocols = 101, // RFC 7231, 6.2.2 + Processing = 102, // RFC 2518, 10.1 + + OK = 200, // RFC 7231, 6.3.1 + Created = 201, // RFC 7231, 6.3.2 + Accepted = 202, // RFC 7231, 6.3.3 + NonAuthoritativeInfo = 203, // RFC 7231, 6.3.4 + NoContent = 204, // RFC 7231, 6.3.5 + ResetContent = 205, // RFC 7231, 6.3.6 + PartialContent = 206, // RFC 7233, 4.1 + MultiStatus = 207, // RFC 4918, 11.1 + AlreadyReported = 208, // RFC 5842, 7.1 + IMUsed = 226, // RFC 3229, 10.4.1 + + MultipleChoices = 300, // RFC 7231, 6.4.1 + MovedPermanently = 301, // RFC 7231, 6.4.2 + Found = 302, // RFC 7231, 6.4.3 + SeeOther = 303, // RFC 7231, 6.4.4 + NotModified = 304, // RFC 7232, 4.1 + UseProxy = 305, // RFC 7231, 6.4.5 + // _ = 306, // RFC 7231, 6.4.6 (Unused) + TemporaryRedirect = 307, // RFC 7231, 6.4.7 + PermanentRedirect = 308, // RFC 7538, 3 + + BadRequest = 400, // RFC 7231, 6.5.1 + Unauthorized = 401, // RFC 7235, 3.1 + PaymentRequired = 402, // RFC 7231, 6.5.2 + Forbidden = 403, // RFC 7231, 6.5.3 + NotFound = 404, // RFC 7231, 6.5.4 + MethodNotAllowed = 405, // RFC 7231, 6.5.5 + NotAcceptable = 406, // RFC 7231, 6.5.6 + ProxyAuthRequired = 407, // RFC 7235, 3.2 + RequestTimeout = 408, // RFC 7231, 6.5.7 + Conflict = 409, // RFC 7231, 6.5.8 + Gone = 410, // RFC 7231, 6.5.9 + LengthRequired = 411, // RFC 7231, 6.5.10 + PreconditionFailed = 412, // RFC 7232, 4.2 + RequestEntityTooLarge = 413, // RFC 7231, 6.5.11 + RequestURITooLong = 414, // RFC 7231, 6.5.12 + UnsupportedMediaType = 415, // RFC 7231, 6.5.13 + RequestedRangeNotSatisfiable = 416, // RFC 7233, 4.4 + ExpectationFailed = 417, // RFC 7231, 6.5.14 + Teapot = 418, // RFC 7168, 2.3.3 + MisdirectedRequest = 421, // RFC 7540, 9.1.2 + UnprocessableEntity = 422, // RFC 4918, 11.2 + Locked = 423, // RFC 4918, 11.3 + FailedDependency = 424, // RFC 4918, 11.4 + UpgradeRequired = 426, // RFC 7231, 6.5.15 + PreconditionRequired = 428, // RFC 6585, 3 + TooManyRequests = 429, // RFC 6585, 4 + RequestHeaderFieldsTooLarge = 431, // RFC 6585, 5 + UnavailableForLegalReasons = 451, // RFC 7725, 3 + + InternalServerError = 500, // RFC 7231, 6.6.1 + NotImplemented = 501, // RFC 7231, 6.6.2 + BadGateway = 502, // RFC 7231, 6.6.3 + ServiceUnavailable = 503, // RFC 7231, 6.6.4 + GatewayTimeout = 504, // RFC 7231, 6.6.5 + HTTPVersionNotSupported = 505, // RFC 7231, 6.6.6 + VariantAlsoNegotiates = 506, // RFC 2295, 8.1 + InsufficientStorage = 507, // RFC 4918, 11.5 + LoopDetected = 508, // RFC 5842, 7.2 + NotExtended = 510, // RFC 2774, 7 + NetworkAuthenticationRequired = 511 // RFC 6585, 6 +} + +export const STATUS_TEXT = new Map([ + [Status.Continue, "Continue"], + [Status.SwitchingProtocols, "Switching Protocols"], + [Status.Processing, "Processing"], + + [Status.OK, "OK"], + [Status.Created, "Created"], + [Status.Accepted, "Accepted"], + [Status.NonAuthoritativeInfo, "Non-Authoritative Information"], + [Status.NoContent, "No Content"], + [Status.ResetContent, "Reset Content"], + [Status.PartialContent, "Partial Content"], + [Status.MultiStatus, "Multi-Status"], + [Status.AlreadyReported, "Already Reported"], + [Status.IMUsed, "IM Used"], + + [Status.MultipleChoices, "Multiple Choices"], + [Status.MovedPermanently, "Moved Permanently"], + [Status.Found, "Found"], + [Status.SeeOther, "See Other"], + [Status.NotModified, "Not Modified"], + [Status.UseProxy, "Use Proxy"], + [Status.TemporaryRedirect, "Temporary Redirect"], + [Status.PermanentRedirect, "Permanent Redirect"], + + [Status.BadRequest, "Bad Request"], + [Status.Unauthorized, "Unauthorized"], + [Status.PaymentRequired, "Payment Required"], + [Status.Forbidden, "Forbidden"], + [Status.NotFound, "Not Found"], + [Status.MethodNotAllowed, "Method Not Allowed"], + [Status.NotAcceptable, "Not Acceptable"], + [Status.ProxyAuthRequired, "Proxy Authentication Required"], + [Status.RequestTimeout, "Request Timeout"], + [Status.Conflict, "Conflict"], + [Status.Gone, "Gone"], + [Status.LengthRequired, "Length Required"], + [Status.PreconditionFailed, "Precondition Failed"], + [Status.RequestEntityTooLarge, "Request Entity Too Large"], + [Status.RequestURITooLong, "Request URI Too Long"], + [Status.UnsupportedMediaType, "Unsupported Media Type"], + [Status.RequestedRangeNotSatisfiable, "Requested Range Not Satisfiable"], + [Status.ExpectationFailed, "Expectation Failed"], + [Status.Teapot, "I'm a teapot"], + [Status.MisdirectedRequest, "Misdirected Request"], + [Status.UnprocessableEntity, "Unprocessable Entity"], + [Status.Locked, "Locked"], + [Status.FailedDependency, "Failed Dependency"], + [Status.UpgradeRequired, "Upgrade Required"], + [Status.PreconditionRequired, "Precondition Required"], + [Status.TooManyRequests, "Too Many Requests"], + [Status.RequestHeaderFieldsTooLarge, "Request Header Fields Too Large"], + [Status.UnavailableForLegalReasons, "Unavailable For Legal Reasons"], + + [Status.InternalServerError, "Internal Server Error"], + [Status.NotImplemented, "Not Implemented"], + [Status.BadGateway, "Bad Gateway"], + [Status.ServiceUnavailable, "Service Unavailable"], + [Status.GatewayTimeout, "Gateway Timeout"], + [Status.HTTPVersionNotSupported, "HTTP Version Not Supported"], + [Status.VariantAlsoNegotiates, "Variant Also Negotiates"], + [Status.InsufficientStorage, "Insufficient Storage"], + [Status.LoopDetected, "Loop Detected"], + [Status.NotExtended, "Not Extended"], + [Status.NetworkAuthenticationRequired, "Network Authentication Required"] +]); diff --git a/http/http_test.ts b/http/http_test.ts new file mode 100644 index 000000000..ba0cec3e3 --- /dev/null +++ b/http/http_test.ts @@ -0,0 +1,223 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Ported from +// https://github.com/golang/go/blob/master/src/net/http/responsewrite_test.go + +import { Buffer } from "deno"; +import { test, assert, assertEqual } from "../testing/mod.ts"; +import { + listenAndServe, + ServerRequest, + setContentLength, + Response +} from "./mod.ts"; +import { BufWriter, BufReader } from "../io/bufio.ts"; + +interface ResponseTest { + response: Response; + raw: string; +} + +const enc = new TextEncoder(); +const dec = new TextDecoder(); + +const responseTests: ResponseTest[] = [ + // Default response + { + response: {}, + raw: "HTTP/1.1 200 OK\r\n" + "\r\n" + }, + // HTTP/1.1, chunked coding; empty trailer; close + { + response: { + status: 200, + body: new Buffer(new TextEncoder().encode("abcdef")) + }, + + raw: + "HTTP/1.1 200 OK\r\n" + + "transfer-encoding: chunked\r\n\r\n" + + "6\r\nabcdef\r\n0\r\n\r\n" + } +]; + +test(async function responseWrite() { + for (const testCase of responseTests) { + const buf = new Buffer(); + const bufw = new BufWriter(buf); + const request = new ServerRequest(); + request.w = bufw; + + await request.respond(testCase.response); + assertEqual(buf.toString(), testCase.raw); + } +}); + +test(async function requestBodyWithContentLength() { + { + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("content-length", "5"); + const buf = new Buffer(enc.encode("Hello")); + req.r = new BufReader(buf); + const body = dec.decode(await req.body()); + assertEqual(body, "Hello"); + } + + // Larger than internal buf + { + const longText = "1234\n".repeat(1000); + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("Content-Length", "5000"); + const buf = new Buffer(enc.encode(longText)); + req.r = new BufReader(buf); + const body = dec.decode(await req.body()); + assertEqual(body, longText); + } +}); + +test(async function requestBodyWithTransferEncoding() { + { + const shortText = "Hello"; + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("transfer-encoding", "chunked"); + let chunksData = ""; + let chunkOffset = 0; + const maxChunkSize = 70; + while (chunkOffset < shortText.length) { + const chunkSize = Math.min(maxChunkSize, shortText.length - chunkOffset); + chunksData += `${chunkSize.toString(16)}\r\n${shortText.substr( + chunkOffset, + chunkSize + )}\r\n`; + chunkOffset += chunkSize; + } + chunksData += "0\r\n\r\n"; + const buf = new Buffer(enc.encode(chunksData)); + req.r = new BufReader(buf); + const body = dec.decode(await req.body()); + assertEqual(body, shortText); + } + + // Larger than internal buf + { + const longText = "1234\n".repeat(1000); + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("transfer-encoding", "chunked"); + let chunksData = ""; + let chunkOffset = 0; + const maxChunkSize = 70; + while (chunkOffset < longText.length) { + const chunkSize = Math.min(maxChunkSize, longText.length - chunkOffset); + chunksData += `${chunkSize.toString(16)}\r\n${longText.substr( + chunkOffset, + chunkSize + )}\r\n`; + chunkOffset += chunkSize; + } + chunksData += "0\r\n\r\n"; + const buf = new Buffer(enc.encode(chunksData)); + req.r = new BufReader(buf); + const body = dec.decode(await req.body()); + assertEqual(body, longText); + } +}); + +test(async function requestBodyStreamWithContentLength() { + { + const shortText = "Hello"; + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("content-length", "" + shortText.length); + const buf = new Buffer(enc.encode(shortText)); + req.r = new BufReader(buf); + const it = await req.bodyStream(); + let offset = 0; + for await (const chunk of it) { + const s = dec.decode(chunk); + assertEqual(shortText.substr(offset, s.length), s); + offset += s.length; + } + } + + // Larger than internal buf + { + const longText = "1234\n".repeat(1000); + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("Content-Length", "5000"); + const buf = new Buffer(enc.encode(longText)); + req.r = new BufReader(buf); + const it = await req.bodyStream(); + let offset = 0; + for await (const chunk of it) { + const s = dec.decode(chunk); + assertEqual(longText.substr(offset, s.length), s); + offset += s.length; + } + } +}); + +test(async function requestBodyStreamWithTransferEncoding() { + { + const shortText = "Hello"; + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("transfer-encoding", "chunked"); + let chunksData = ""; + let chunkOffset = 0; + const maxChunkSize = 70; + while (chunkOffset < shortText.length) { + const chunkSize = Math.min(maxChunkSize, shortText.length - chunkOffset); + chunksData += `${chunkSize.toString(16)}\r\n${shortText.substr( + chunkOffset, + chunkSize + )}\r\n`; + chunkOffset += chunkSize; + } + chunksData += "0\r\n\r\n"; + const buf = new Buffer(enc.encode(chunksData)); + req.r = new BufReader(buf); + const it = await req.bodyStream(); + let offset = 0; + for await (const chunk of it) { + const s = dec.decode(chunk); + assertEqual(shortText.substr(offset, s.length), s); + offset += s.length; + } + } + + // Larger than internal buf + { + const longText = "1234\n".repeat(1000); + const req = new ServerRequest(); + req.headers = new Headers(); + req.headers.set("transfer-encoding", "chunked"); + let chunksData = ""; + let chunkOffset = 0; + const maxChunkSize = 70; + while (chunkOffset < longText.length) { + const chunkSize = Math.min(maxChunkSize, longText.length - chunkOffset); + chunksData += `${chunkSize.toString(16)}\r\n${longText.substr( + chunkOffset, + chunkSize + )}\r\n`; + chunkOffset += chunkSize; + } + chunksData += "0\r\n\r\n"; + const buf = new Buffer(enc.encode(chunksData)); + req.r = new BufReader(buf); + const it = await req.bodyStream(); + let offset = 0; + for await (const chunk of it) { + const s = dec.decode(chunk); + assertEqual(longText.substr(offset, s.length), s); + offset += s.length; + } + } +}); diff --git a/http/mod.ts b/http/mod.ts new file mode 100644 index 000000000..217bd68b3 --- /dev/null +++ b/http/mod.ts @@ -0,0 +1,8 @@ +import { + serve, + listenAndServe, + Response, + setContentLength, + ServerRequest +} from "./http.ts"; +export { serve, listenAndServe, Response, setContentLength, ServerRequest }; diff --git a/io/bufio.ts b/io/bufio.ts new file mode 100644 index 000000000..0dd2b94b4 --- /dev/null +++ b/io/bufio.ts @@ -0,0 +1,464 @@ +// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio.go +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { Reader, ReadResult, Writer } from "deno"; +import { assert, charCode, copyBytes } from "./util.ts"; + +const DEFAULT_BUF_SIZE = 4096; +const MIN_BUF_SIZE = 16; +const MAX_CONSECUTIVE_EMPTY_READS = 100; +const CR = charCode("\r"); +const LF = charCode("\n"); + +export type BufState = + | null + | "EOF" + | "BufferFull" + | "ShortWrite" + | "NoProgress" + | Error; + +/** BufReader implements buffering for a Reader object. */ +export class BufReader implements Reader { + private buf: Uint8Array; + private rd: Reader; // Reader provided by caller. + private r = 0; // buf read position. + private w = 0; // buf write position. + private lastByte: number; + private lastCharSize: number; + private err: BufState; + + constructor(rd: Reader, size = DEFAULT_BUF_SIZE) { + if (size < MIN_BUF_SIZE) { + size = MIN_BUF_SIZE; + } + this._reset(new Uint8Array(size), rd); + } + + /** Returns the size of the underlying buffer in bytes. */ + size(): number { + return this.buf.byteLength; + } + + buffered(): number { + return this.w - this.r; + } + + private _readErr(): BufState { + const err = this.err; + this.err = null; + return err; + } + + // Reads a new chunk into the buffer. + private async _fill(): Promise { + // Slide existing data to beginning. + if (this.r > 0) { + this.buf.copyWithin(0, this.r, this.w); + this.w -= this.r; + this.r = 0; + } + + if (this.w >= this.buf.byteLength) { + throw Error("bufio: tried to fill full buffer"); + } + + // Read new data: try a limited number of times. + for (let i = MAX_CONSECUTIVE_EMPTY_READS; i > 0; i--) { + let rr: ReadResult; + try { + rr = await this.rd.read(this.buf.subarray(this.w)); + } catch (e) { + this.err = e; + return; + } + assert(rr.nread >= 0, "negative read"); + this.w += rr.nread; + if (rr.eof) { + this.err = "EOF"; + return; + } + if (rr.nread > 0) { + return; + } + } + this.err = "NoProgress"; + } + + /** Discards any buffered data, resets all state, and switches + * the buffered reader to read from r. + */ + reset(r: Reader): void { + this._reset(this.buf, r); + } + + private _reset(buf: Uint8Array, rd: Reader): void { + this.buf = buf; + this.rd = rd; + this.lastByte = -1; + // this.lastRuneSize = -1; + } + + /** reads data into p. + * It returns the number of bytes read into p. + * The bytes are taken from at most one Read on the underlying Reader, + * hence n may be less than len(p). + * At EOF, the count will be zero and err will be io.EOF. + * To read exactly len(p) bytes, use io.ReadFull(b, p). + */ + async read(p: Uint8Array): Promise { + let rr: ReadResult = { nread: p.byteLength, eof: false }; + if (rr.nread === 0) { + if (this.err) { + throw this._readErr(); + } + return rr; + } + + if (this.r === this.w) { + if (this.err) { + throw this._readErr(); + } + if (p.byteLength >= this.buf.byteLength) { + // Large read, empty buffer. + // Read directly into p to avoid copy. + rr = await this.rd.read(p); + assert(rr.nread >= 0, "negative read"); + if (rr.nread > 0) { + this.lastByte = p[rr.nread - 1]; + // this.lastRuneSize = -1; + } + if (this.err) { + throw this._readErr(); + } + return rr; + } + // One read. + // Do not use this.fill, which will loop. + this.r = 0; + this.w = 0; + try { + rr = await this.rd.read(this.buf); + } catch (e) { + this.err = e; + } + assert(rr.nread >= 0, "negative read"); + if (rr.nread === 0) { + if (this.err) { + throw this._readErr(); + } + return rr; + } + this.w += rr.nread; + } + + // copy as much as we can + rr.nread = copyBytes(p as Uint8Array, this.buf.subarray(this.r, this.w), 0); + this.r += rr.nread; + this.lastByte = this.buf[this.r - 1]; + // this.lastRuneSize = -1; + return rr; + } + + /** reads exactly len(p) bytes into p. + * Ported from https://golang.org/pkg/io/#ReadFull + * It returns the number of bytes copied and an error if fewer bytes were read. + * The error is EOF only if no bytes were read. + * If an EOF happens after reading some but not all the bytes, + * readFull returns ErrUnexpectedEOF. ("EOF" for current impl) + * On return, n == len(p) if and only if err == nil. + * If r returns an error having read at least len(buf) bytes, + * the error is dropped. + */ + async readFull(p: Uint8Array): Promise<[number, BufState]> { + let rr = await this.read(p); + let nread = rr.nread; + if (rr.eof) { + return [nread, nread < p.length ? "EOF" : null]; + } + while (!rr.eof && nread < p.length) { + rr = await this.read(p.subarray(nread)); + nread += rr.nread; + } + return [nread, nread < p.length ? "EOF" : null]; + } + + /** Returns the next byte [0, 255] or -1 if EOF. */ + async readByte(): Promise { + while (this.r === this.w) { + await this._fill(); // buffer is empty. + if (this.err == "EOF") { + return -1; + } + if (this.err != null) { + throw this._readErr(); + } + } + const c = this.buf[this.r]; + this.r++; + this.lastByte = c; + return c; + } + + /** readString() reads until the first occurrence of delim in the input, + * returning a string containing the data up to and including the delimiter. + * If ReadString encounters an error before finding a delimiter, + * it returns the data read before the error and the error itself (often io.EOF). + * ReadString returns err != nil if and only if the returned data does not end in + * delim. + * For simple uses, a Scanner may be more convenient. + */ + async readString(delim: string): Promise { + throw new Error("Not implemented"); + } + + /** readLine() is a low-level line-reading primitive. Most callers should use + * readBytes('\n') or readString('\n') instead or use a Scanner. + * + * readLine tries to return a single line, not including the end-of-line bytes. + * If the line was too long for the buffer then isPrefix is set and the + * beginning of the line is returned. The rest of the line will be returned + * from future calls. isPrefix will be false when returning the last fragment + * of the line. The returned buffer is only valid until the next call to + * ReadLine. ReadLine either returns a non-nil line or it returns an error, + * never both. + * + * The text returned from ReadLine does not include the line end ("\r\n" or "\n"). + * No indication or error is given if the input ends without a final line end. + * Calling UnreadByte after ReadLine will always unread the last byte read + * (possibly a character belonging to the line end) even if that byte is not + * part of the line returned by ReadLine. + */ + async readLine(): Promise<[Uint8Array, boolean, BufState]> { + let [line, err] = await this.readSlice(LF); + + if (err === "BufferFull") { + // Handle the case where "\r\n" straddles the buffer. + if (line.byteLength > 0 && line[line.byteLength - 1] === CR) { + // Put the '\r' back on buf and drop it from line. + // Let the next call to ReadLine check for "\r\n". + assert(this.r > 0, "bufio: tried to rewind past start of buffer"); + this.r--; + line = line.subarray(0, line.byteLength - 1); + } + return [line, true, null]; + } + + if (line.byteLength === 0) { + return [line, false, err]; + } + err = null; + + if (line[line.byteLength - 1] == LF) { + let drop = 1; + if (line.byteLength > 1 && line[line.byteLength - 2] === CR) { + drop = 2; + } + line = line.subarray(0, line.byteLength - drop); + } + return [line, false, err]; + } + + /** readSlice() reads until the first occurrence of delim in the input, + * returning a slice pointing at the bytes in the buffer. The bytes stop + * being valid at the next read. If readSlice() encounters an error before + * finding a delimiter, it returns all the data in the buffer and the error + * itself (often io.EOF). readSlice() fails with error ErrBufferFull if the + * buffer fills without a delim. Because the data returned from readSlice() + * will be overwritten by the next I/O operation, most clients should use + * readBytes() or readString() instead. readSlice() returns err != nil if and + * only if line does not end in delim. + */ + async readSlice(delim: number): Promise<[Uint8Array, BufState]> { + let s = 0; // search start index + let line: Uint8Array; + let err: BufState; + while (true) { + // Search buffer. + let i = this.buf.subarray(this.r + s, this.w).indexOf(delim); + if (i >= 0) { + i += s; + line = this.buf.subarray(this.r, this.r + i + 1); + this.r += i + 1; + break; + } + + // Pending error? + if (this.err) { + line = this.buf.subarray(this.r, this.w); + this.r = this.w; + err = this._readErr(); + break; + } + + // Buffer full? + if (this.buffered() >= this.buf.byteLength) { + this.r = this.w; + line = this.buf; + err = "BufferFull"; + break; + } + + s = this.w - this.r; // do not rescan area we scanned before + + await this._fill(); // buffer is not full + } + + // Handle last byte, if any. + let i = line.byteLength - 1; + if (i >= 0) { + this.lastByte = line[i]; + // this.lastRuneSize = -1 + } + + return [line, err]; + } + + /** Peek returns the next n bytes without advancing the reader. The bytes stop + * being valid at the next read call. If Peek returns fewer than n bytes, it + * also returns an error explaining why the read is short. The error is + * ErrBufferFull if n is larger than b's buffer size. + */ + async peek(n: number): Promise<[Uint8Array, BufState]> { + if (n < 0) { + throw Error("negative count"); + } + + while ( + this.w - this.r < n && + this.w - this.r < this.buf.byteLength && + this.err == null + ) { + await this._fill(); // this.w - this.r < len(this.buf) => buffer is not full + } + + if (n > this.buf.byteLength) { + return [this.buf.subarray(this.r, this.w), "BufferFull"]; + } + + // 0 <= n <= len(this.buf) + let err: BufState; + let avail = this.w - this.r; + if (avail < n) { + // not enough data in buffer + n = avail; + err = this._readErr(); + if (!err) { + err = "BufferFull"; + } + } + return [this.buf.subarray(this.r, this.r + n), err]; + } +} + +/** BufWriter implements buffering for an deno.Writer object. + * If an error occurs writing to a Writer, no more data will be + * accepted and all subsequent writes, and flush(), will return the error. + * After all data has been written, the client should call the + * flush() method to guarantee all data has been forwarded to + * the underlying deno.Writer. + */ +export class BufWriter implements Writer { + buf: Uint8Array; + n: number = 0; + err: null | BufState = null; + + constructor(private wr: Writer, size = DEFAULT_BUF_SIZE) { + if (size <= 0) { + size = DEFAULT_BUF_SIZE; + } + this.buf = new Uint8Array(size); + } + + /** Size returns the size of the underlying buffer in bytes. */ + size(): number { + return this.buf.byteLength; + } + + /** Discards any unflushed buffered data, clears any error, and + * resets b to write its output to w. + */ + reset(w: Writer): void { + this.err = null; + this.n = 0; + this.wr = w; + } + + /** Flush writes any buffered data to the underlying io.Writer. */ + async flush(): Promise { + if (this.err != null) { + return this.err; + } + if (this.n == 0) { + return null; + } + + let n: number; + let err: BufState = null; + try { + n = await this.wr.write(this.buf.subarray(0, this.n)); + } catch (e) { + err = e; + } + + if (n < this.n && err == null) { + err = "ShortWrite"; + } + + if (err != null) { + if (n > 0 && n < this.n) { + this.buf.copyWithin(0, n, this.n); + } + this.n -= n; + this.err = err; + return err; + } + this.n = 0; + } + + /** Returns how many bytes are unused in the buffer. */ + available(): number { + return this.buf.byteLength - this.n; + } + + /** buffered returns the number of bytes that have been written into the + * current buffer. + */ + buffered(): number { + return this.n; + } + + /** Writes the contents of p into the buffer. + * Returns the number of bytes written. + */ + async write(p: Uint8Array): Promise { + let nn = 0; + let n: number; + while (p.byteLength > this.available() && !this.err) { + if (this.buffered() == 0) { + // Large write, empty buffer. + // Write directly from p to avoid copy. + try { + n = await this.wr.write(p); + } catch (e) { + this.err = e; + } + } else { + n = copyBytes(this.buf, p, this.n); + this.n += n; + await this.flush(); + } + nn += n; + p = p.subarray(n); + } + if (this.err) { + throw this.err; + } + n = copyBytes(this.buf, p, this.n); + this.n += n; + nn += n; + return nn; + } +} diff --git a/io/bufio_test.ts b/io/bufio_test.ts new file mode 100644 index 000000000..fa8f4b73b --- /dev/null +++ b/io/bufio_test.ts @@ -0,0 +1,341 @@ +// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio_test.go +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { Buffer, Reader, ReadResult } from "deno"; +import { test, assert, assertEqual } from "../testing/mod.ts"; +import { BufReader, BufState, BufWriter } from "./bufio.ts"; +import * as iotest from "./iotest.ts"; +import { charCode, copyBytes, stringsReader } from "./util.ts"; + +const encoder = new TextEncoder(); + +async function readBytes(buf: BufReader): Promise { + const b = new Uint8Array(1000); + let nb = 0; + while (true) { + let c = await buf.readByte(); + if (c < 0) { + break; // EOF + } + b[nb] = c; + nb++; + } + const decoder = new TextDecoder(); + return decoder.decode(b.subarray(0, nb)); +} + +test(async function bufioReaderSimple() { + const data = "hello world"; + const b = new BufReader(stringsReader(data)); + const s = await readBytes(b); + assertEqual(s, data); +}); + +type ReadMaker = { name: string; fn: (r: Reader) => Reader }; + +const readMakers: ReadMaker[] = [ + { name: "full", fn: r => r }, + { name: "byte", fn: r => new iotest.OneByteReader(r) }, + { name: "half", fn: r => new iotest.HalfReader(r) } + // TODO { name: "data+err", r => new iotest.DataErrReader(r) }, + // { name: "timeout", fn: r => new iotest.TimeoutReader(r) }, +]; + +function readLines(b: BufReader): string { + let s = ""; + while (true) { + let s1 = b.readString("\n"); + if (s1 == null) { + break; // EOF + } + s += s1; + } + return s; +} + +// Call read to accumulate the text of a file +async function reads(buf: BufReader, m: number): Promise { + const b = new Uint8Array(1000); + let nb = 0; + while (true) { + const { nread, eof } = await buf.read(b.subarray(nb, nb + m)); + nb += nread; + if (eof) { + break; + } + } + const decoder = new TextDecoder(); + return decoder.decode(b.subarray(0, nb)); +} + +type NamedBufReader = { name: string; fn: (r: BufReader) => Promise }; + +const bufreaders: NamedBufReader[] = [ + { name: "1", fn: (b: BufReader) => reads(b, 1) }, + { name: "2", fn: (b: BufReader) => reads(b, 2) }, + { name: "3", fn: (b: BufReader) => reads(b, 3) }, + { name: "4", fn: (b: BufReader) => reads(b, 4) }, + { name: "5", fn: (b: BufReader) => reads(b, 5) }, + { name: "7", fn: (b: BufReader) => reads(b, 7) }, + { name: "bytes", fn: readBytes } + // { name: "lines", fn: readLines }, +]; + +const MIN_READ_BUFFER_SIZE = 16; +const bufsizes: number[] = [ + 0, + MIN_READ_BUFFER_SIZE, + 23, + 32, + 46, + 64, + 93, + 128, + 1024, + 4096 +]; + +test(async function bufioBufReader() { + const texts = new Array(31); + let str = ""; + let all = ""; + for (let i = 0; i < texts.length - 1; i++) { + texts[i] = str + "\n"; + all += texts[i]; + str += String.fromCharCode((i % 26) + 97); + } + texts[texts.length - 1] = all; + + for (let text of texts) { + for (let readmaker of readMakers) { + for (let bufreader of bufreaders) { + for (let bufsize of bufsizes) { + const read = readmaker.fn(stringsReader(text)); + const buf = new BufReader(read, bufsize); + const s = await bufreader.fn(buf); + const debugStr = + `reader=${readmaker.name} ` + + `fn=${bufreader.name} bufsize=${bufsize} want=${text} got=${s}`; + assertEqual(s, text, debugStr); + } + } + } + } +}); + +test(async function bufioBufferFull() { + const longString = + "And now, hello, world! It is the time for all good men to come to the aid of their party"; + const buf = new BufReader(stringsReader(longString), MIN_READ_BUFFER_SIZE); + let [line, err] = await buf.readSlice(charCode("!")); + + const decoder = new TextDecoder(); + let actual = decoder.decode(line); + assertEqual(err, "BufferFull"); + assertEqual(actual, "And now, hello, "); + + [line, err] = await buf.readSlice(charCode("!")); + actual = decoder.decode(line); + assertEqual(actual, "world!"); + assert(err == null); +}); + +const testInput = encoder.encode( + "012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy" +); +const testInputrn = encoder.encode( + "012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n" +); +const testOutput = encoder.encode("0123456789abcdefghijklmnopqrstuvwxy"); + +// TestReader wraps a Uint8Array and returns reads of a specific length. +class TestReader implements Reader { + constructor(private data: Uint8Array, private stride: number) {} + + async read(buf: Uint8Array): Promise { + let nread = this.stride; + if (nread > this.data.byteLength) { + nread = this.data.byteLength; + } + if (nread > buf.byteLength) { + nread = buf.byteLength; + } + copyBytes(buf as Uint8Array, this.data); + this.data = this.data.subarray(nread); + let eof = false; + if (this.data.byteLength == 0) { + eof = true; + } + return { nread, eof }; + } +} + +async function testReadLine(input: Uint8Array): Promise { + for (let stride = 1; stride < 2; stride++) { + let done = 0; + let reader = new TestReader(input, stride); + let l = new BufReader(reader, input.byteLength + 1); + while (true) { + let [line, isPrefix, err] = await l.readLine(); + if (line.byteLength > 0 && err != null) { + throw Error("readLine returned both data and error"); + } + assertEqual(isPrefix, false); + if (err == "EOF") { + break; + } + let want = testOutput.subarray(done, done + line.byteLength); + assertEqual( + line, + want, + `Bad line at stride ${stride}: want: ${want} got: ${line}` + ); + done += line.byteLength; + } + assertEqual( + done, + testOutput.byteLength, + `readLine didn't return everything: got: ${done}, ` + + `want: ${testOutput} (stride: ${stride})` + ); + } +} + +test(async function bufioReadLine() { + await testReadLine(testInput); + await testReadLine(testInputrn); +}); + +test(async function bufioPeek() { + const decoder = new TextDecoder(); + let p = new Uint8Array(10); + // string is 16 (minReadBufferSize) long. + let buf = new BufReader( + stringsReader("abcdefghijklmnop"), + MIN_READ_BUFFER_SIZE + ); + + let [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "a"); + assert(err == null); + + [actual, err] = await buf.peek(4); + assertEqual(decoder.decode(actual), "abcd"); + assert(err == null); + + [actual, err] = await buf.peek(32); + assertEqual(decoder.decode(actual), "abcdefghijklmnop"); + assertEqual(err, "BufferFull"); + + await buf.read(p.subarray(0, 3)); + assertEqual(decoder.decode(p.subarray(0, 3)), "abc"); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "d"); + assert(err == null); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "d"); + assert(err == null); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), "d"); + assert(err == null); + + [actual, err] = await buf.peek(2); + assertEqual(decoder.decode(actual), "de"); + assert(err == null); + + let { eof } = await buf.read(p.subarray(0, 3)); + assertEqual(decoder.decode(p.subarray(0, 3)), "def"); + assert(!eof); + assert(err == null); + + [actual, err] = await buf.peek(4); + assertEqual(decoder.decode(actual), "ghij"); + assert(err == null); + + await buf.read(p); + assertEqual(decoder.decode(p), "ghijklmnop"); + + [actual, err] = await buf.peek(0); + assertEqual(decoder.decode(actual), ""); + assert(err == null); + + [actual, err] = await buf.peek(1); + assertEqual(decoder.decode(actual), ""); + assert(err == "EOF"); + /* TODO + // Test for issue 3022, not exposing a reader's error on a successful Peek. + buf = NewReaderSize(dataAndEOFReader("abcd"), 32) + if s, err := buf.Peek(2); string(s) != "ab" || err != nil { + t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err) + } + if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { + t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err) + } + if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil { + t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err) + } + if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF { + t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err) + } + */ +}); + +test(async function bufioWriter() { + const data = new Uint8Array(8192); + + for (let i = 0; i < data.byteLength; i++) { + data[i] = charCode(" ") + (i % (charCode("~") - charCode(" "))); + } + + const w = new Buffer(); + for (let nwrite of bufsizes) { + for (let bs of bufsizes) { + // Write nwrite bytes using buffer size bs. + // Check that the right amount makes it out + // and that the data is correct. + + w.reset(); + const buf = new BufWriter(w, bs); + + const context = `nwrite=${nwrite} bufsize=${bs}`; + const n = await buf.write(data.subarray(0, nwrite)); + assertEqual(n, nwrite, context); + + await buf.flush(); + + const written = w.bytes(); + assertEqual(written.byteLength, nwrite); + + for (let l = 0; l < written.byteLength; l++) { + assertEqual(written[l], data[l]); + } + } + } +}); + +test(async function bufReaderReadFull() { + const enc = new TextEncoder(); + const dec = new TextDecoder(); + const text = "Hello World"; + const data = new Buffer(enc.encode(text)); + const bufr = new BufReader(data, 3); + { + const buf = new Uint8Array(6); + const [nread, err] = await bufr.readFull(buf); + assertEqual(nread, 6); + assert(!err); + assertEqual(dec.decode(buf), "Hello "); + } + { + const buf = new Uint8Array(6); + const [nread, err] = await bufr.readFull(buf); + assertEqual(nread, 5); + assertEqual(err, "EOF"); + assertEqual(dec.decode(buf.subarray(0, 5)), "World"); + } +}); diff --git a/io/iotest.ts b/io/iotest.ts new file mode 100644 index 000000000..e3a42f58a --- /dev/null +++ b/io/iotest.ts @@ -0,0 +1,61 @@ +// Ported to Deno from +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { Reader, ReadResult } from "deno"; + +/** OneByteReader returns a Reader that implements + * each non-empty Read by reading one byte from r. + */ +export class OneByteReader implements Reader { + constructor(readonly r: Reader) {} + + async read(p: Uint8Array): Promise { + if (p.byteLength === 0) { + return { nread: 0, eof: false }; + } + if (!(p instanceof Uint8Array)) { + throw Error("expected Uint8Array"); + } + return this.r.read(p.subarray(0, 1)); + } +} + +/** HalfReader returns a Reader that implements Read + * by reading half as many requested bytes from r. + */ +export class HalfReader implements Reader { + constructor(readonly r: Reader) {} + + async read(p: Uint8Array): Promise { + if (!(p instanceof Uint8Array)) { + throw Error("expected Uint8Array"); + } + const half = Math.floor((p.byteLength + 1) / 2); + return this.r.read(p.subarray(0, half)); + } +} + +export class ErrTimeout extends Error { + constructor() { + super("timeout"); + this.name = "ErrTimeout"; + } +} + +/** TimeoutReader returns ErrTimeout on the second read + * with no data. Subsequent calls to read succeed. + */ +export class TimeoutReader implements Reader { + count = 0; + constructor(readonly r: Reader) {} + + async read(p: Uint8Array): Promise { + this.count++; + if (this.count === 2) { + throw new ErrTimeout(); + } + return this.r.read(p); + } +} diff --git a/io/ioutil.ts b/io/ioutil.ts new file mode 100644 index 000000000..68d6e5190 --- /dev/null +++ b/io/ioutil.ts @@ -0,0 +1,36 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { BufReader } from "./bufio.ts"; + +/* Read big endian 16bit short from BufReader */ +export async function readShort(buf: BufReader): Promise { + const [high, low] = [await buf.readByte(), await buf.readByte()]; + return (high << 8) | low; +} + +/* Read big endian 32bit integer from BufReader */ +export async function readInt(buf: BufReader): Promise { + const [high, low] = [await readShort(buf), await readShort(buf)]; + return (high << 16) | low; +} + +const BIT32 = 0xffffffff; +/* Read big endian 64bit long from BufReader */ +export async function readLong(buf: BufReader): Promise { + const [high, low] = [await readInt(buf), await readInt(buf)]; + // ECMAScript doesn't support 64bit bit ops. + return high ? high * (BIT32 + 1) + low : low; +} + +/* Slice number into 64bit big endian byte array */ +export function sliceLongToBytes(d: number, dest = new Array(8)): number[] { + let mask = 0xff; + let low = (d << 32) >>> 32; + let high = (d - low) / (BIT32 + 1); + let shift = 24; + for (let i = 0; i < 4; i++) { + dest[i] = (high >>> shift) & mask; + dest[i + 4] = (low >>> shift) & mask; + shift -= 8; + } + return dest; +} diff --git a/io/ioutil_test.ts b/io/ioutil_test.ts new file mode 100644 index 000000000..422901e4a --- /dev/null +++ b/io/ioutil_test.ts @@ -0,0 +1,62 @@ +import { Reader, ReadResult } from "deno"; +import { assertEqual, test } from "../testing/mod.ts"; +import { readInt, readLong, readShort, sliceLongToBytes } from "./ioutil.ts"; +import { BufReader } from "./bufio.ts"; + +class BinaryReader implements Reader { + index = 0; + + constructor(private bytes: Uint8Array = new Uint8Array(0)) {} + + async read(p: Uint8Array): Promise { + p.set(this.bytes.subarray(this.index, p.byteLength)); + this.index += p.byteLength; + return { nread: p.byteLength, eof: false }; + } +} + +test(async function testReadShort() { + const r = new BinaryReader(new Uint8Array([0x12, 0x34])); + const short = await readShort(new BufReader(r)); + assertEqual(short, 0x1234); +}); + +test(async function testReadInt() { + const r = new BinaryReader(new Uint8Array([0x12, 0x34, 0x56, 0x78])); + const int = await readInt(new BufReader(r)); + assertEqual(int, 0x12345678); +}); + +test(async function testReadLong() { + const r = new BinaryReader( + new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78]) + ); + const long = await readLong(new BufReader(r)); + assertEqual(long, 0x1234567812345678); +}); + +test(async function testReadLong2() { + const r = new BinaryReader( + new Uint8Array([0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]) + ); + const long = await readLong(new BufReader(r)); + assertEqual(long, 0x12345678); +}); + +test(async function testSliceLongToBytes() { + const arr = sliceLongToBytes(0x1234567890abcdef); + const actual = readLong(new BufReader(new BinaryReader(new Uint8Array(arr)))); + const expected = readLong( + new BufReader( + new BinaryReader( + new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]) + ) + ) + ); + assertEqual(actual, expected); +}); + +test(async function testSliceLongToBytes2() { + const arr = sliceLongToBytes(0x12345678); + assertEqual(arr, [0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]); +}); diff --git a/io/util.ts b/io/util.ts new file mode 100644 index 000000000..811940b4d --- /dev/null +++ b/io/util.ts @@ -0,0 +1,29 @@ +import { Buffer, Reader } from "deno"; + +export function assert(cond: boolean, msg = "assert") { + if (!cond) { + throw Error(msg); + } +} + +// `off` is the offset into `dst` where it will at which to begin writing values +// from `src`. +// Returns the number of bytes copied. +export function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number { + const r = dst.byteLength - off; + if (src.byteLength > r) { + src = src.subarray(0, r); + } + dst.set(src, off); + return src.byteLength; +} + +export function charCode(s: string): number { + return s.charCodeAt(0); +} + +const encoder = new TextEncoder(); +export function stringsReader(s: string): Reader { + const ui8 = encoder.encode(s); + return new Buffer(ui8.buffer as ArrayBuffer); +} diff --git a/log/README.md b/log/README.md new file mode 100644 index 000000000..1d88cb070 --- /dev/null +++ b/log/README.md @@ -0,0 +1,38 @@ +# Basic usage + +```ts +import * as log from "https://deno.land/x/std/logging/index.ts"; + +// simple console logger +log.debug("Hello world"); +log.info("Hello world"); +log.warning("Hello world"); +log.error("Hello world"); +log.critical("500 Internal server error"); + +// configure as needed +await log.setup({ + handlers: { + console: new log.handlers.ConsoleHandler("DEBUG"), + file: new log.handlers.FileHandler("WARNING", "./log.txt") + }, + + loggers: { + default: { + level: "DEBUG", + handlers: ["console", "file"] + } + } +}); + +// get configured logger +const logger = log.getLogger("default"); +logger.debug("fizz"); // <- logs to `console`, because `file` handler requires 'WARNING' level +logger.warning("buzz"); // <- logs to both `console` and `file` handlers + +// if you try to use a logger that hasn't been configured +// you're good to go, it gets created automatically with level set to 0 +// so no message is logged +const unknownLogger = log.getLogger("mystery"); +unknownLogger.info("foobar"); // no-op +``` diff --git a/log/handlers.ts b/log/handlers.ts new file mode 100644 index 000000000..a0163e6cd --- /dev/null +++ b/log/handlers.ts @@ -0,0 +1,62 @@ +import { open, File, Writer } from "deno"; +import { getLevelByName } from "./levels.ts"; +import { LogRecord } from "./logger.ts"; + +export class BaseHandler { + level: number; + levelName: string; + + constructor(levelName: string) { + this.level = getLevelByName(levelName); + this.levelName = levelName; + } + + handle(logRecord: LogRecord) { + if (this.level > logRecord.level) return; + + // TODO: implement formatter + const msg = `${logRecord.levelName} ${logRecord.msg}`; + + return this.log(msg); + } + + log(msg: string) {} + async setup() {} + async destroy() {} +} + +export class ConsoleHandler extends BaseHandler { + log(msg: string) { + console.log(msg); + } +} + +export abstract class WriterHandler extends BaseHandler { + protected _writer: Writer; + + log(msg: string) { + const encoder = new TextEncoder(); + // promise is intentionally not awaited + this._writer.write(encoder.encode(msg + "\n")); + } +} + +export class FileHandler extends WriterHandler { + private _file: File; + private _filename: string; + + constructor(levelName: string, filename: string) { + super(levelName); + this._filename = filename; + } + + async setup() { + // open file in append mode - write only + this._file = await open(this._filename, "a"); + this._writer = this._file; + } + + async destroy() { + await this._file.close(); + } +} diff --git a/log/levels.ts b/log/levels.ts new file mode 100644 index 000000000..52d28aea5 --- /dev/null +++ b/log/levels.ts @@ -0,0 +1,34 @@ +export const LogLevel = { + NOTSET: 0, + DEBUG: 10, + INFO: 20, + WARNING: 30, + ERROR: 40, + CRITICAL: 50 +}; + +const byName = { + NOTSET: LogLevel.NOTSET, + DEBUG: LogLevel.DEBUG, + INFO: LogLevel.INFO, + WARNING: LogLevel.WARNING, + ERROR: LogLevel.ERROR, + CRITICAL: LogLevel.CRITICAL +}; + +const byLevel = { + [LogLevel.NOTSET]: "NOTSET", + [LogLevel.DEBUG]: "DEBUG", + [LogLevel.INFO]: "INFO", + [LogLevel.WARNING]: "WARNING", + [LogLevel.ERROR]: "ERROR", + [LogLevel.CRITICAL]: "CRITICAL" +}; + +export function getLevelByName(name: string): number { + return byName[name]; +} + +export function getLevelName(level: number): string { + return byLevel[level]; +} diff --git a/log/logger.ts b/log/logger.ts new file mode 100644 index 000000000..9f34f9c32 --- /dev/null +++ b/log/logger.ts @@ -0,0 +1,62 @@ +import { LogLevel, getLevelByName, getLevelName } from "./levels.ts"; +import { BaseHandler } from "./handlers.ts"; + +export interface LogRecord { + msg: string; + args: any[]; + datetime: Date; + level: number; + levelName: string; +} + +export class Logger { + level: number; + levelName: string; + handlers: any[]; + + constructor(levelName: string, handlers?: BaseHandler[]) { + this.level = getLevelByName(levelName); + this.levelName = levelName; + + this.handlers = handlers || []; + } + + _log(level: number, msg: string, ...args: any[]) { + if (this.level > level) return; + + // TODO: it'd be a good idea to make it immutable, so + // no handler mangles it by mistake + // TODO: iterpolate msg with values + const record: LogRecord = { + msg: msg, + args: args, + datetime: new Date(), + level: level, + levelName: getLevelName(level) + }; + + this.handlers.forEach(handler => { + handler.handle(record); + }); + } + + debug(msg: string, ...args: any[]) { + return this._log(LogLevel.DEBUG, msg, ...args); + } + + info(msg: string, ...args: any[]) { + return this._log(LogLevel.INFO, msg, ...args); + } + + warning(msg: string, ...args: any[]) { + return this._log(LogLevel.WARNING, msg, ...args); + } + + error(msg: string, ...args: any[]) { + return this._log(LogLevel.ERROR, msg, ...args); + } + + critical(msg: string, ...args: any[]) { + return this._log(LogLevel.CRITICAL, msg, ...args); + } +} diff --git a/log/mod.ts b/log/mod.ts new file mode 100644 index 000000000..e8c762ac6 --- /dev/null +++ b/log/mod.ts @@ -0,0 +1,119 @@ +import { Logger } from "./logger.ts"; +import { + BaseHandler, + ConsoleHandler, + WriterHandler, + FileHandler +} from "./handlers.ts"; + +export class LoggerConfig { + level?: string; + handlers?: string[]; +} + +export interface LogConfig { + handlers?: { + [name: string]: BaseHandler; + }; + loggers?: { + [name: string]: LoggerConfig; + }; +} + +const DEFAULT_LEVEL = "INFO"; +const DEFAULT_NAME = ""; +const DEFAULT_CONFIG: LogConfig = { + handlers: {}, + + loggers: { + "": { + level: "INFO", + handlers: [""] + } + } +}; + +const defaultHandler = new ConsoleHandler("INFO"); +const defaultLogger = new Logger("INFO", [defaultHandler]); + +const state = { + defaultHandler, + defaultLogger, + handlers: new Map(), + loggers: new Map(), + config: DEFAULT_CONFIG +}; + +export const handlers = { + BaseHandler, + ConsoleHandler, + WriterHandler, + FileHandler +}; + +export const debug = (msg: string, ...args: any[]) => + defaultLogger.debug(msg, ...args); +export const info = (msg: string, ...args: any[]) => + defaultLogger.info(msg, ...args); +export const warning = (msg: string, ...args: any[]) => + defaultLogger.warning(msg, ...args); +export const error = (msg: string, ...args: any[]) => + defaultLogger.error(msg, ...args); +export const critical = (msg: string, ...args: any[]) => + defaultLogger.critical(msg, ...args); + +export function getLogger(name?: string) { + if (!name) { + return defaultLogger; + } + + if (!state.loggers.has(name)) { + const logger = new Logger("NOTSET", []); + state.loggers.set(name, logger); + return logger; + } + + return state.loggers.get(name); +} + +export async function setup(config: LogConfig) { + state.config = config; + + // tear down existing handlers + state.handlers.forEach(handler => { + handler.destroy(); + }); + state.handlers.clear(); + + // setup handlers + const handlers = state.config.handlers || {}; + + for (const handlerName in handlers) { + const handler = handlers[handlerName]; + await handler.setup(); + state.handlers.set(handlerName, handler); + } + + // remove existing loggers + state.loggers.clear(); + + // setup loggers + const loggers = state.config.loggers || {}; + for (const loggerName in loggers) { + const loggerConfig = loggers[loggerName]; + const handlerNames = loggerConfig.handlers || []; + const handlers = []; + + handlerNames.forEach(handlerName => { + if (state.handlers.has(handlerName)) { + handlers.push(state.handlers.get(handlerName)); + } + }); + + const levelName = loggerConfig.level || DEFAULT_LEVEL; + const logger = new Logger(levelName, handlers); + state.loggers.set(loggerName, logger); + } +} + +setup(DEFAULT_CONFIG); diff --git a/log/test.ts b/log/test.ts new file mode 100644 index 000000000..fdc994eb7 --- /dev/null +++ b/log/test.ts @@ -0,0 +1,28 @@ +import { remove, open, readAll } from "deno"; +import { assertEqual, test } from "../testing/mod.ts"; +import * as log from "./mod.ts"; +import { FileHandler } from "./handlers.ts"; + +// TODO: establish something more sophisticated +let testOutput = ""; + +class TestHandler extends log.handlers.BaseHandler { + constructor(levelName: string) { + super(levelName); + } + + log(msg: string) { + testOutput += `${msg}\n`; + } +} + +test(function testDefaultlogMethods() { + log.debug("Foobar"); + log.info("Foobar"); + log.warning("Foobar"); + log.error("Foobar"); + log.critical("Foobar"); + + const logger = log.getLogger(""); + console.log(logger); +}); diff --git a/logging/README.md b/logging/README.md deleted file mode 100644 index 1d88cb070..000000000 --- a/logging/README.md +++ /dev/null @@ -1,38 +0,0 @@ -# Basic usage - -```ts -import * as log from "https://deno.land/x/std/logging/index.ts"; - -// simple console logger -log.debug("Hello world"); -log.info("Hello world"); -log.warning("Hello world"); -log.error("Hello world"); -log.critical("500 Internal server error"); - -// configure as needed -await log.setup({ - handlers: { - console: new log.handlers.ConsoleHandler("DEBUG"), - file: new log.handlers.FileHandler("WARNING", "./log.txt") - }, - - loggers: { - default: { - level: "DEBUG", - handlers: ["console", "file"] - } - } -}); - -// get configured logger -const logger = log.getLogger("default"); -logger.debug("fizz"); // <- logs to `console`, because `file` handler requires 'WARNING' level -logger.warning("buzz"); // <- logs to both `console` and `file` handlers - -// if you try to use a logger that hasn't been configured -// you're good to go, it gets created automatically with level set to 0 -// so no message is logged -const unknownLogger = log.getLogger("mystery"); -unknownLogger.info("foobar"); // no-op -``` diff --git a/logging/handlers.ts b/logging/handlers.ts deleted file mode 100644 index a0163e6cd..000000000 --- a/logging/handlers.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { open, File, Writer } from "deno"; -import { getLevelByName } from "./levels.ts"; -import { LogRecord } from "./logger.ts"; - -export class BaseHandler { - level: number; - levelName: string; - - constructor(levelName: string) { - this.level = getLevelByName(levelName); - this.levelName = levelName; - } - - handle(logRecord: LogRecord) { - if (this.level > logRecord.level) return; - - // TODO: implement formatter - const msg = `${logRecord.levelName} ${logRecord.msg}`; - - return this.log(msg); - } - - log(msg: string) {} - async setup() {} - async destroy() {} -} - -export class ConsoleHandler extends BaseHandler { - log(msg: string) { - console.log(msg); - } -} - -export abstract class WriterHandler extends BaseHandler { - protected _writer: Writer; - - log(msg: string) { - const encoder = new TextEncoder(); - // promise is intentionally not awaited - this._writer.write(encoder.encode(msg + "\n")); - } -} - -export class FileHandler extends WriterHandler { - private _file: File; - private _filename: string; - - constructor(levelName: string, filename: string) { - super(levelName); - this._filename = filename; - } - - async setup() { - // open file in append mode - write only - this._file = await open(this._filename, "a"); - this._writer = this._file; - } - - async destroy() { - await this._file.close(); - } -} diff --git a/logging/index.ts b/logging/index.ts deleted file mode 100644 index e8c762ac6..000000000 --- a/logging/index.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { Logger } from "./logger.ts"; -import { - BaseHandler, - ConsoleHandler, - WriterHandler, - FileHandler -} from "./handlers.ts"; - -export class LoggerConfig { - level?: string; - handlers?: string[]; -} - -export interface LogConfig { - handlers?: { - [name: string]: BaseHandler; - }; - loggers?: { - [name: string]: LoggerConfig; - }; -} - -const DEFAULT_LEVEL = "INFO"; -const DEFAULT_NAME = ""; -const DEFAULT_CONFIG: LogConfig = { - handlers: {}, - - loggers: { - "": { - level: "INFO", - handlers: [""] - } - } -}; - -const defaultHandler = new ConsoleHandler("INFO"); -const defaultLogger = new Logger("INFO", [defaultHandler]); - -const state = { - defaultHandler, - defaultLogger, - handlers: new Map(), - loggers: new Map(), - config: DEFAULT_CONFIG -}; - -export const handlers = { - BaseHandler, - ConsoleHandler, - WriterHandler, - FileHandler -}; - -export const debug = (msg: string, ...args: any[]) => - defaultLogger.debug(msg, ...args); -export const info = (msg: string, ...args: any[]) => - defaultLogger.info(msg, ...args); -export const warning = (msg: string, ...args: any[]) => - defaultLogger.warning(msg, ...args); -export const error = (msg: string, ...args: any[]) => - defaultLogger.error(msg, ...args); -export const critical = (msg: string, ...args: any[]) => - defaultLogger.critical(msg, ...args); - -export function getLogger(name?: string) { - if (!name) { - return defaultLogger; - } - - if (!state.loggers.has(name)) { - const logger = new Logger("NOTSET", []); - state.loggers.set(name, logger); - return logger; - } - - return state.loggers.get(name); -} - -export async function setup(config: LogConfig) { - state.config = config; - - // tear down existing handlers - state.handlers.forEach(handler => { - handler.destroy(); - }); - state.handlers.clear(); - - // setup handlers - const handlers = state.config.handlers || {}; - - for (const handlerName in handlers) { - const handler = handlers[handlerName]; - await handler.setup(); - state.handlers.set(handlerName, handler); - } - - // remove existing loggers - state.loggers.clear(); - - // setup loggers - const loggers = state.config.loggers || {}; - for (const loggerName in loggers) { - const loggerConfig = loggers[loggerName]; - const handlerNames = loggerConfig.handlers || []; - const handlers = []; - - handlerNames.forEach(handlerName => { - if (state.handlers.has(handlerName)) { - handlers.push(state.handlers.get(handlerName)); - } - }); - - const levelName = loggerConfig.level || DEFAULT_LEVEL; - const logger = new Logger(levelName, handlers); - state.loggers.set(loggerName, logger); - } -} - -setup(DEFAULT_CONFIG); diff --git a/logging/levels.ts b/logging/levels.ts deleted file mode 100644 index 52d28aea5..000000000 --- a/logging/levels.ts +++ /dev/null @@ -1,34 +0,0 @@ -export const LogLevel = { - NOTSET: 0, - DEBUG: 10, - INFO: 20, - WARNING: 30, - ERROR: 40, - CRITICAL: 50 -}; - -const byName = { - NOTSET: LogLevel.NOTSET, - DEBUG: LogLevel.DEBUG, - INFO: LogLevel.INFO, - WARNING: LogLevel.WARNING, - ERROR: LogLevel.ERROR, - CRITICAL: LogLevel.CRITICAL -}; - -const byLevel = { - [LogLevel.NOTSET]: "NOTSET", - [LogLevel.DEBUG]: "DEBUG", - [LogLevel.INFO]: "INFO", - [LogLevel.WARNING]: "WARNING", - [LogLevel.ERROR]: "ERROR", - [LogLevel.CRITICAL]: "CRITICAL" -}; - -export function getLevelByName(name: string): number { - return byName[name]; -} - -export function getLevelName(level: number): string { - return byLevel[level]; -} diff --git a/logging/logger.ts b/logging/logger.ts deleted file mode 100644 index 9f34f9c32..000000000 --- a/logging/logger.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { LogLevel, getLevelByName, getLevelName } from "./levels.ts"; -import { BaseHandler } from "./handlers.ts"; - -export interface LogRecord { - msg: string; - args: any[]; - datetime: Date; - level: number; - levelName: string; -} - -export class Logger { - level: number; - levelName: string; - handlers: any[]; - - constructor(levelName: string, handlers?: BaseHandler[]) { - this.level = getLevelByName(levelName); - this.levelName = levelName; - - this.handlers = handlers || []; - } - - _log(level: number, msg: string, ...args: any[]) { - if (this.level > level) return; - - // TODO: it'd be a good idea to make it immutable, so - // no handler mangles it by mistake - // TODO: iterpolate msg with values - const record: LogRecord = { - msg: msg, - args: args, - datetime: new Date(), - level: level, - levelName: getLevelName(level) - }; - - this.handlers.forEach(handler => { - handler.handle(record); - }); - } - - debug(msg: string, ...args: any[]) { - return this._log(LogLevel.DEBUG, msg, ...args); - } - - info(msg: string, ...args: any[]) { - return this._log(LogLevel.INFO, msg, ...args); - } - - warning(msg: string, ...args: any[]) { - return this._log(LogLevel.WARNING, msg, ...args); - } - - error(msg: string, ...args: any[]) { - return this._log(LogLevel.ERROR, msg, ...args); - } - - critical(msg: string, ...args: any[]) { - return this._log(LogLevel.CRITICAL, msg, ...args); - } -} diff --git a/logging/test.ts b/logging/test.ts deleted file mode 100644 index 17117ae8b..000000000 --- a/logging/test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { remove, open, readAll } from "deno"; -import { assertEqual, test } from "../testing/mod.ts"; -import * as log from "index.ts"; -import { FileHandler } from "./handlers.ts"; - -// TODO: establish something more sophisticated -let testOutput = ""; - -class TestHandler extends log.handlers.BaseHandler { - constructor(levelName: string) { - super(levelName); - } - - log(msg: string) { - testOutput += `${msg}\n`; - } -} - -test(function testDefaultlogMethods() { - log.debug("Foobar"); - log.info("Foobar"); - log.warning("Foobar"); - log.error("Foobar"); - log.critical("Foobar"); - - const logger = log.getLogger(""); - console.log(logger); -}); diff --git a/net/README.md b/net/README.md deleted file mode 100644 index 65f2b9ad7..000000000 --- a/net/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# net - -Usage: - -```typescript -import { serve } from "https://deno.land/x/net/http.ts"; -const s = serve("0.0.0.0:8000"); - -async function main() { - for await (const req of s) { - req.respond({ body: new TextEncoder().encode("Hello World\n") }); - } -} - -main(); -``` - -### File Server - -A small program for serving local files over HTTP. - -Add the following to your `.bash_profile` - -``` -alias file_server="deno https://deno.land/x/net/file_server.ts --allow-net" -``` diff --git a/net/bufio.ts b/net/bufio.ts deleted file mode 100644 index 0dd2b94b4..000000000 --- a/net/bufio.ts +++ /dev/null @@ -1,464 +0,0 @@ -// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio.go -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import { Reader, ReadResult, Writer } from "deno"; -import { assert, charCode, copyBytes } from "./util.ts"; - -const DEFAULT_BUF_SIZE = 4096; -const MIN_BUF_SIZE = 16; -const MAX_CONSECUTIVE_EMPTY_READS = 100; -const CR = charCode("\r"); -const LF = charCode("\n"); - -export type BufState = - | null - | "EOF" - | "BufferFull" - | "ShortWrite" - | "NoProgress" - | Error; - -/** BufReader implements buffering for a Reader object. */ -export class BufReader implements Reader { - private buf: Uint8Array; - private rd: Reader; // Reader provided by caller. - private r = 0; // buf read position. - private w = 0; // buf write position. - private lastByte: number; - private lastCharSize: number; - private err: BufState; - - constructor(rd: Reader, size = DEFAULT_BUF_SIZE) { - if (size < MIN_BUF_SIZE) { - size = MIN_BUF_SIZE; - } - this._reset(new Uint8Array(size), rd); - } - - /** Returns the size of the underlying buffer in bytes. */ - size(): number { - return this.buf.byteLength; - } - - buffered(): number { - return this.w - this.r; - } - - private _readErr(): BufState { - const err = this.err; - this.err = null; - return err; - } - - // Reads a new chunk into the buffer. - private async _fill(): Promise { - // Slide existing data to beginning. - if (this.r > 0) { - this.buf.copyWithin(0, this.r, this.w); - this.w -= this.r; - this.r = 0; - } - - if (this.w >= this.buf.byteLength) { - throw Error("bufio: tried to fill full buffer"); - } - - // Read new data: try a limited number of times. - for (let i = MAX_CONSECUTIVE_EMPTY_READS; i > 0; i--) { - let rr: ReadResult; - try { - rr = await this.rd.read(this.buf.subarray(this.w)); - } catch (e) { - this.err = e; - return; - } - assert(rr.nread >= 0, "negative read"); - this.w += rr.nread; - if (rr.eof) { - this.err = "EOF"; - return; - } - if (rr.nread > 0) { - return; - } - } - this.err = "NoProgress"; - } - - /** Discards any buffered data, resets all state, and switches - * the buffered reader to read from r. - */ - reset(r: Reader): void { - this._reset(this.buf, r); - } - - private _reset(buf: Uint8Array, rd: Reader): void { - this.buf = buf; - this.rd = rd; - this.lastByte = -1; - // this.lastRuneSize = -1; - } - - /** reads data into p. - * It returns the number of bytes read into p. - * The bytes are taken from at most one Read on the underlying Reader, - * hence n may be less than len(p). - * At EOF, the count will be zero and err will be io.EOF. - * To read exactly len(p) bytes, use io.ReadFull(b, p). - */ - async read(p: Uint8Array): Promise { - let rr: ReadResult = { nread: p.byteLength, eof: false }; - if (rr.nread === 0) { - if (this.err) { - throw this._readErr(); - } - return rr; - } - - if (this.r === this.w) { - if (this.err) { - throw this._readErr(); - } - if (p.byteLength >= this.buf.byteLength) { - // Large read, empty buffer. - // Read directly into p to avoid copy. - rr = await this.rd.read(p); - assert(rr.nread >= 0, "negative read"); - if (rr.nread > 0) { - this.lastByte = p[rr.nread - 1]; - // this.lastRuneSize = -1; - } - if (this.err) { - throw this._readErr(); - } - return rr; - } - // One read. - // Do not use this.fill, which will loop. - this.r = 0; - this.w = 0; - try { - rr = await this.rd.read(this.buf); - } catch (e) { - this.err = e; - } - assert(rr.nread >= 0, "negative read"); - if (rr.nread === 0) { - if (this.err) { - throw this._readErr(); - } - return rr; - } - this.w += rr.nread; - } - - // copy as much as we can - rr.nread = copyBytes(p as Uint8Array, this.buf.subarray(this.r, this.w), 0); - this.r += rr.nread; - this.lastByte = this.buf[this.r - 1]; - // this.lastRuneSize = -1; - return rr; - } - - /** reads exactly len(p) bytes into p. - * Ported from https://golang.org/pkg/io/#ReadFull - * It returns the number of bytes copied and an error if fewer bytes were read. - * The error is EOF only if no bytes were read. - * If an EOF happens after reading some but not all the bytes, - * readFull returns ErrUnexpectedEOF. ("EOF" for current impl) - * On return, n == len(p) if and only if err == nil. - * If r returns an error having read at least len(buf) bytes, - * the error is dropped. - */ - async readFull(p: Uint8Array): Promise<[number, BufState]> { - let rr = await this.read(p); - let nread = rr.nread; - if (rr.eof) { - return [nread, nread < p.length ? "EOF" : null]; - } - while (!rr.eof && nread < p.length) { - rr = await this.read(p.subarray(nread)); - nread += rr.nread; - } - return [nread, nread < p.length ? "EOF" : null]; - } - - /** Returns the next byte [0, 255] or -1 if EOF. */ - async readByte(): Promise { - while (this.r === this.w) { - await this._fill(); // buffer is empty. - if (this.err == "EOF") { - return -1; - } - if (this.err != null) { - throw this._readErr(); - } - } - const c = this.buf[this.r]; - this.r++; - this.lastByte = c; - return c; - } - - /** readString() reads until the first occurrence of delim in the input, - * returning a string containing the data up to and including the delimiter. - * If ReadString encounters an error before finding a delimiter, - * it returns the data read before the error and the error itself (often io.EOF). - * ReadString returns err != nil if and only if the returned data does not end in - * delim. - * For simple uses, a Scanner may be more convenient. - */ - async readString(delim: string): Promise { - throw new Error("Not implemented"); - } - - /** readLine() is a low-level line-reading primitive. Most callers should use - * readBytes('\n') or readString('\n') instead or use a Scanner. - * - * readLine tries to return a single line, not including the end-of-line bytes. - * If the line was too long for the buffer then isPrefix is set and the - * beginning of the line is returned. The rest of the line will be returned - * from future calls. isPrefix will be false when returning the last fragment - * of the line. The returned buffer is only valid until the next call to - * ReadLine. ReadLine either returns a non-nil line or it returns an error, - * never both. - * - * The text returned from ReadLine does not include the line end ("\r\n" or "\n"). - * No indication or error is given if the input ends without a final line end. - * Calling UnreadByte after ReadLine will always unread the last byte read - * (possibly a character belonging to the line end) even if that byte is not - * part of the line returned by ReadLine. - */ - async readLine(): Promise<[Uint8Array, boolean, BufState]> { - let [line, err] = await this.readSlice(LF); - - if (err === "BufferFull") { - // Handle the case where "\r\n" straddles the buffer. - if (line.byteLength > 0 && line[line.byteLength - 1] === CR) { - // Put the '\r' back on buf and drop it from line. - // Let the next call to ReadLine check for "\r\n". - assert(this.r > 0, "bufio: tried to rewind past start of buffer"); - this.r--; - line = line.subarray(0, line.byteLength - 1); - } - return [line, true, null]; - } - - if (line.byteLength === 0) { - return [line, false, err]; - } - err = null; - - if (line[line.byteLength - 1] == LF) { - let drop = 1; - if (line.byteLength > 1 && line[line.byteLength - 2] === CR) { - drop = 2; - } - line = line.subarray(0, line.byteLength - drop); - } - return [line, false, err]; - } - - /** readSlice() reads until the first occurrence of delim in the input, - * returning a slice pointing at the bytes in the buffer. The bytes stop - * being valid at the next read. If readSlice() encounters an error before - * finding a delimiter, it returns all the data in the buffer and the error - * itself (often io.EOF). readSlice() fails with error ErrBufferFull if the - * buffer fills without a delim. Because the data returned from readSlice() - * will be overwritten by the next I/O operation, most clients should use - * readBytes() or readString() instead. readSlice() returns err != nil if and - * only if line does not end in delim. - */ - async readSlice(delim: number): Promise<[Uint8Array, BufState]> { - let s = 0; // search start index - let line: Uint8Array; - let err: BufState; - while (true) { - // Search buffer. - let i = this.buf.subarray(this.r + s, this.w).indexOf(delim); - if (i >= 0) { - i += s; - line = this.buf.subarray(this.r, this.r + i + 1); - this.r += i + 1; - break; - } - - // Pending error? - if (this.err) { - line = this.buf.subarray(this.r, this.w); - this.r = this.w; - err = this._readErr(); - break; - } - - // Buffer full? - if (this.buffered() >= this.buf.byteLength) { - this.r = this.w; - line = this.buf; - err = "BufferFull"; - break; - } - - s = this.w - this.r; // do not rescan area we scanned before - - await this._fill(); // buffer is not full - } - - // Handle last byte, if any. - let i = line.byteLength - 1; - if (i >= 0) { - this.lastByte = line[i]; - // this.lastRuneSize = -1 - } - - return [line, err]; - } - - /** Peek returns the next n bytes without advancing the reader. The bytes stop - * being valid at the next read call. If Peek returns fewer than n bytes, it - * also returns an error explaining why the read is short. The error is - * ErrBufferFull if n is larger than b's buffer size. - */ - async peek(n: number): Promise<[Uint8Array, BufState]> { - if (n < 0) { - throw Error("negative count"); - } - - while ( - this.w - this.r < n && - this.w - this.r < this.buf.byteLength && - this.err == null - ) { - await this._fill(); // this.w - this.r < len(this.buf) => buffer is not full - } - - if (n > this.buf.byteLength) { - return [this.buf.subarray(this.r, this.w), "BufferFull"]; - } - - // 0 <= n <= len(this.buf) - let err: BufState; - let avail = this.w - this.r; - if (avail < n) { - // not enough data in buffer - n = avail; - err = this._readErr(); - if (!err) { - err = "BufferFull"; - } - } - return [this.buf.subarray(this.r, this.r + n), err]; - } -} - -/** BufWriter implements buffering for an deno.Writer object. - * If an error occurs writing to a Writer, no more data will be - * accepted and all subsequent writes, and flush(), will return the error. - * After all data has been written, the client should call the - * flush() method to guarantee all data has been forwarded to - * the underlying deno.Writer. - */ -export class BufWriter implements Writer { - buf: Uint8Array; - n: number = 0; - err: null | BufState = null; - - constructor(private wr: Writer, size = DEFAULT_BUF_SIZE) { - if (size <= 0) { - size = DEFAULT_BUF_SIZE; - } - this.buf = new Uint8Array(size); - } - - /** Size returns the size of the underlying buffer in bytes. */ - size(): number { - return this.buf.byteLength; - } - - /** Discards any unflushed buffered data, clears any error, and - * resets b to write its output to w. - */ - reset(w: Writer): void { - this.err = null; - this.n = 0; - this.wr = w; - } - - /** Flush writes any buffered data to the underlying io.Writer. */ - async flush(): Promise { - if (this.err != null) { - return this.err; - } - if (this.n == 0) { - return null; - } - - let n: number; - let err: BufState = null; - try { - n = await this.wr.write(this.buf.subarray(0, this.n)); - } catch (e) { - err = e; - } - - if (n < this.n && err == null) { - err = "ShortWrite"; - } - - if (err != null) { - if (n > 0 && n < this.n) { - this.buf.copyWithin(0, n, this.n); - } - this.n -= n; - this.err = err; - return err; - } - this.n = 0; - } - - /** Returns how many bytes are unused in the buffer. */ - available(): number { - return this.buf.byteLength - this.n; - } - - /** buffered returns the number of bytes that have been written into the - * current buffer. - */ - buffered(): number { - return this.n; - } - - /** Writes the contents of p into the buffer. - * Returns the number of bytes written. - */ - async write(p: Uint8Array): Promise { - let nn = 0; - let n: number; - while (p.byteLength > this.available() && !this.err) { - if (this.buffered() == 0) { - // Large write, empty buffer. - // Write directly from p to avoid copy. - try { - n = await this.wr.write(p); - } catch (e) { - this.err = e; - } - } else { - n = copyBytes(this.buf, p, this.n); - this.n += n; - await this.flush(); - } - nn += n; - p = p.subarray(n); - } - if (this.err) { - throw this.err; - } - n = copyBytes(this.buf, p, this.n); - this.n += n; - nn += n; - return nn; - } -} diff --git a/net/bufio_test.ts b/net/bufio_test.ts deleted file mode 100644 index fa8f4b73b..000000000 --- a/net/bufio_test.ts +++ /dev/null @@ -1,341 +0,0 @@ -// Based on https://github.com/golang/go/blob/891682/src/bufio/bufio_test.go -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import { Buffer, Reader, ReadResult } from "deno"; -import { test, assert, assertEqual } from "../testing/mod.ts"; -import { BufReader, BufState, BufWriter } from "./bufio.ts"; -import * as iotest from "./iotest.ts"; -import { charCode, copyBytes, stringsReader } from "./util.ts"; - -const encoder = new TextEncoder(); - -async function readBytes(buf: BufReader): Promise { - const b = new Uint8Array(1000); - let nb = 0; - while (true) { - let c = await buf.readByte(); - if (c < 0) { - break; // EOF - } - b[nb] = c; - nb++; - } - const decoder = new TextDecoder(); - return decoder.decode(b.subarray(0, nb)); -} - -test(async function bufioReaderSimple() { - const data = "hello world"; - const b = new BufReader(stringsReader(data)); - const s = await readBytes(b); - assertEqual(s, data); -}); - -type ReadMaker = { name: string; fn: (r: Reader) => Reader }; - -const readMakers: ReadMaker[] = [ - { name: "full", fn: r => r }, - { name: "byte", fn: r => new iotest.OneByteReader(r) }, - { name: "half", fn: r => new iotest.HalfReader(r) } - // TODO { name: "data+err", r => new iotest.DataErrReader(r) }, - // { name: "timeout", fn: r => new iotest.TimeoutReader(r) }, -]; - -function readLines(b: BufReader): string { - let s = ""; - while (true) { - let s1 = b.readString("\n"); - if (s1 == null) { - break; // EOF - } - s += s1; - } - return s; -} - -// Call read to accumulate the text of a file -async function reads(buf: BufReader, m: number): Promise { - const b = new Uint8Array(1000); - let nb = 0; - while (true) { - const { nread, eof } = await buf.read(b.subarray(nb, nb + m)); - nb += nread; - if (eof) { - break; - } - } - const decoder = new TextDecoder(); - return decoder.decode(b.subarray(0, nb)); -} - -type NamedBufReader = { name: string; fn: (r: BufReader) => Promise }; - -const bufreaders: NamedBufReader[] = [ - { name: "1", fn: (b: BufReader) => reads(b, 1) }, - { name: "2", fn: (b: BufReader) => reads(b, 2) }, - { name: "3", fn: (b: BufReader) => reads(b, 3) }, - { name: "4", fn: (b: BufReader) => reads(b, 4) }, - { name: "5", fn: (b: BufReader) => reads(b, 5) }, - { name: "7", fn: (b: BufReader) => reads(b, 7) }, - { name: "bytes", fn: readBytes } - // { name: "lines", fn: readLines }, -]; - -const MIN_READ_BUFFER_SIZE = 16; -const bufsizes: number[] = [ - 0, - MIN_READ_BUFFER_SIZE, - 23, - 32, - 46, - 64, - 93, - 128, - 1024, - 4096 -]; - -test(async function bufioBufReader() { - const texts = new Array(31); - let str = ""; - let all = ""; - for (let i = 0; i < texts.length - 1; i++) { - texts[i] = str + "\n"; - all += texts[i]; - str += String.fromCharCode((i % 26) + 97); - } - texts[texts.length - 1] = all; - - for (let text of texts) { - for (let readmaker of readMakers) { - for (let bufreader of bufreaders) { - for (let bufsize of bufsizes) { - const read = readmaker.fn(stringsReader(text)); - const buf = new BufReader(read, bufsize); - const s = await bufreader.fn(buf); - const debugStr = - `reader=${readmaker.name} ` + - `fn=${bufreader.name} bufsize=${bufsize} want=${text} got=${s}`; - assertEqual(s, text, debugStr); - } - } - } - } -}); - -test(async function bufioBufferFull() { - const longString = - "And now, hello, world! It is the time for all good men to come to the aid of their party"; - const buf = new BufReader(stringsReader(longString), MIN_READ_BUFFER_SIZE); - let [line, err] = await buf.readSlice(charCode("!")); - - const decoder = new TextDecoder(); - let actual = decoder.decode(line); - assertEqual(err, "BufferFull"); - assertEqual(actual, "And now, hello, "); - - [line, err] = await buf.readSlice(charCode("!")); - actual = decoder.decode(line); - assertEqual(actual, "world!"); - assert(err == null); -}); - -const testInput = encoder.encode( - "012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy" -); -const testInputrn = encoder.encode( - "012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n" -); -const testOutput = encoder.encode("0123456789abcdefghijklmnopqrstuvwxy"); - -// TestReader wraps a Uint8Array and returns reads of a specific length. -class TestReader implements Reader { - constructor(private data: Uint8Array, private stride: number) {} - - async read(buf: Uint8Array): Promise { - let nread = this.stride; - if (nread > this.data.byteLength) { - nread = this.data.byteLength; - } - if (nread > buf.byteLength) { - nread = buf.byteLength; - } - copyBytes(buf as Uint8Array, this.data); - this.data = this.data.subarray(nread); - let eof = false; - if (this.data.byteLength == 0) { - eof = true; - } - return { nread, eof }; - } -} - -async function testReadLine(input: Uint8Array): Promise { - for (let stride = 1; stride < 2; stride++) { - let done = 0; - let reader = new TestReader(input, stride); - let l = new BufReader(reader, input.byteLength + 1); - while (true) { - let [line, isPrefix, err] = await l.readLine(); - if (line.byteLength > 0 && err != null) { - throw Error("readLine returned both data and error"); - } - assertEqual(isPrefix, false); - if (err == "EOF") { - break; - } - let want = testOutput.subarray(done, done + line.byteLength); - assertEqual( - line, - want, - `Bad line at stride ${stride}: want: ${want} got: ${line}` - ); - done += line.byteLength; - } - assertEqual( - done, - testOutput.byteLength, - `readLine didn't return everything: got: ${done}, ` + - `want: ${testOutput} (stride: ${stride})` - ); - } -} - -test(async function bufioReadLine() { - await testReadLine(testInput); - await testReadLine(testInputrn); -}); - -test(async function bufioPeek() { - const decoder = new TextDecoder(); - let p = new Uint8Array(10); - // string is 16 (minReadBufferSize) long. - let buf = new BufReader( - stringsReader("abcdefghijklmnop"), - MIN_READ_BUFFER_SIZE - ); - - let [actual, err] = await buf.peek(1); - assertEqual(decoder.decode(actual), "a"); - assert(err == null); - - [actual, err] = await buf.peek(4); - assertEqual(decoder.decode(actual), "abcd"); - assert(err == null); - - [actual, err] = await buf.peek(32); - assertEqual(decoder.decode(actual), "abcdefghijklmnop"); - assertEqual(err, "BufferFull"); - - await buf.read(p.subarray(0, 3)); - assertEqual(decoder.decode(p.subarray(0, 3)), "abc"); - - [actual, err] = await buf.peek(1); - assertEqual(decoder.decode(actual), "d"); - assert(err == null); - - [actual, err] = await buf.peek(1); - assertEqual(decoder.decode(actual), "d"); - assert(err == null); - - [actual, err] = await buf.peek(1); - assertEqual(decoder.decode(actual), "d"); - assert(err == null); - - [actual, err] = await buf.peek(2); - assertEqual(decoder.decode(actual), "de"); - assert(err == null); - - let { eof } = await buf.read(p.subarray(0, 3)); - assertEqual(decoder.decode(p.subarray(0, 3)), "def"); - assert(!eof); - assert(err == null); - - [actual, err] = await buf.peek(4); - assertEqual(decoder.decode(actual), "ghij"); - assert(err == null); - - await buf.read(p); - assertEqual(decoder.decode(p), "ghijklmnop"); - - [actual, err] = await buf.peek(0); - assertEqual(decoder.decode(actual), ""); - assert(err == null); - - [actual, err] = await buf.peek(1); - assertEqual(decoder.decode(actual), ""); - assert(err == "EOF"); - /* TODO - // Test for issue 3022, not exposing a reader's error on a successful Peek. - buf = NewReaderSize(dataAndEOFReader("abcd"), 32) - if s, err := buf.Peek(2); string(s) != "ab" || err != nil { - t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err) - } - if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { - t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err) - } - if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil { - t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err) - } - if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF { - t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err) - } - */ -}); - -test(async function bufioWriter() { - const data = new Uint8Array(8192); - - for (let i = 0; i < data.byteLength; i++) { - data[i] = charCode(" ") + (i % (charCode("~") - charCode(" "))); - } - - const w = new Buffer(); - for (let nwrite of bufsizes) { - for (let bs of bufsizes) { - // Write nwrite bytes using buffer size bs. - // Check that the right amount makes it out - // and that the data is correct. - - w.reset(); - const buf = new BufWriter(w, bs); - - const context = `nwrite=${nwrite} bufsize=${bs}`; - const n = await buf.write(data.subarray(0, nwrite)); - assertEqual(n, nwrite, context); - - await buf.flush(); - - const written = w.bytes(); - assertEqual(written.byteLength, nwrite); - - for (let l = 0; l < written.byteLength; l++) { - assertEqual(written[l], data[l]); - } - } - } -}); - -test(async function bufReaderReadFull() { - const enc = new TextEncoder(); - const dec = new TextDecoder(); - const text = "Hello World"; - const data = new Buffer(enc.encode(text)); - const bufr = new BufReader(data, 3); - { - const buf = new Uint8Array(6); - const [nread, err] = await bufr.readFull(buf); - assertEqual(nread, 6); - assert(!err); - assertEqual(dec.decode(buf), "Hello "); - } - { - const buf = new Uint8Array(6); - const [nread, err] = await bufr.readFull(buf); - assertEqual(nread, 5); - assertEqual(err, "EOF"); - assertEqual(dec.decode(buf.subarray(0, 5)), "World"); - } -}); diff --git a/net/file_server.ts b/net/file_server.ts deleted file mode 100755 index 72432abdd..000000000 --- a/net/file_server.ts +++ /dev/null @@ -1,241 +0,0 @@ -#!/usr/bin/env deno --allow-net - -// This program serves files in the current directory over HTTP. -// TODO Stream responses instead of reading them into memory. -// TODO Add tests like these: -// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js - -import { - listenAndServe, - ServerRequest, - setContentLength, - Response -} from "./http.ts"; -import { cwd, DenoError, ErrorKind, args, stat, readDir, open } from "deno"; -import { extname } from "../fs/path.ts"; -import { contentType } from "../media_types/mod.ts"; - -const dirViewerTemplate = ` - - - - - - - Deno File Server - - - -

Index of <%DIRNAME%>

- - - <%CONTENTS%> -
ModeSizeName
- - -`; - -const serverArgs = args.slice(); -let CORSEnabled = false; -// TODO: switch to flags if we later want to add more options -for (let i = 0; i < serverArgs.length; i++) { - if (serverArgs[i] === "--cors") { - CORSEnabled = true; - serverArgs.splice(i, 1); - break; - } -} -let currentDir = cwd(); -const target = serverArgs[1]; -if (target) { - currentDir = `${currentDir}/${target}`; -} -const addr = `0.0.0.0:${serverArgs[2] || 4500}`; -const encoder = new TextEncoder(); - -function modeToString(isDir: boolean, maybeMode: number | null) { - const modeMap = ["---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"]; - - if (maybeMode === null) { - return "(unknown mode)"; - } - const mode = maybeMode!.toString(8); - if (mode.length < 3) { - return "(unknown mode)"; - } - let output = ""; - mode - .split("") - .reverse() - .slice(0, 3) - .forEach(v => { - output = modeMap[+v] + output; - }); - output = `(${isDir ? "d" : "-"}${output})`; - return output; -} - -function fileLenToString(len: number) { - const multipler = 1024; - let base = 1; - const suffix = ["B", "K", "M", "G", "T"]; - let suffixIndex = 0; - - while (base * multipler < len) { - if (suffixIndex >= suffix.length - 1) { - break; - } - base *= multipler; - suffixIndex++; - } - - return `${(len / base).toFixed(2)}${suffix[suffixIndex]}`; -} - -function createDirEntryDisplay( - name: string, - path: string, - size: number | null, - mode: number | null, - isDir: boolean -) { - const sizeStr = size === null ? "" : "" + fileLenToString(size!); - return ` - ${modeToString( - isDir, - mode - )}${sizeStr}${name}${ - isDir ? "/" : "" - } - - `; -} - -// TODO: simplify this after deno.stat and deno.readDir are fixed -async function serveDir(req: ServerRequest, dirPath: string, dirName: string) { - // dirname has no prefix - const listEntry: string[] = []; - const fileInfos = await readDir(dirPath); - for (const info of fileInfos) { - if (info.name === "index.html" && info.isFile()) { - // in case index.html as dir... - return await serveFile(req, info.path); - } - // Yuck! - let mode = null; - try { - mode = (await stat(info.path)).mode; - } catch (e) {} - listEntry.push( - createDirEntryDisplay( - info.name, - dirName + "/" + info.name, - info.isFile() ? info.len : null, - mode, - info.isDirectory() - ) - ); - } - - const page = new TextEncoder().encode( - dirViewerTemplate - .replace("<%DIRNAME%>", dirName + "/") - .replace("<%CONTENTS%>", listEntry.join("")) - ); - - const headers = new Headers(); - headers.set("content-type", "text/html"); - - const res = { - status: 200, - body: page, - headers - }; - setContentLength(res); - return res; -} - -async function serveFile(req: ServerRequest, filename: string) { - const file = await open(filename); - const fileInfo = await stat(filename); - const headers = new Headers(); - headers.set("content-length", fileInfo.len.toString()); - headers.set("content-type", contentType(extname(filename)) || "text/plain"); - - const res = { - status: 200, - body: file, - headers - }; - return res; -} - -async function serveFallback(req: ServerRequest, e: Error) { - if ( - e instanceof DenoError && - (e as DenoError).kind === ErrorKind.NotFound - ) { - return { - status: 404, - body: encoder.encode("Not found") - }; - } else { - return { - status: 500, - body: encoder.encode("Internal server error") - }; - } -} - -function serverLog(req: ServerRequest, res: Response) { - const d = new Date().toISOString(); - const dateFmt = `[${d.slice(0, 10)} ${d.slice(11, 19)}]`; - const s = `${dateFmt} "${req.method} ${req.url} ${req.proto}" ${res.status}`; - console.log(s); -} - -function setCORS(res: Response) { - if (!res.headers) { - res.headers = new Headers(); - } - res.headers!.append("access-control-allow-origin", "*"); - res.headers!.append( - "access-control-allow-headers", - "Origin, X-Requested-With, Content-Type, Accept, Range" - ); -} - -listenAndServe(addr, async req => { - const fileName = req.url.replace(/\/$/, ""); - const filePath = currentDir + fileName; - - let response: Response; - - try { - const fileInfo = await stat(filePath); - if (fileInfo.isDirectory()) { - // Bug with deno.stat: name and path not populated - // Yuck! - response = await serveDir(req, filePath, fileName); - } else { - response = await serveFile(req, filePath); - } - } catch (e) { - response = await serveFallback(req, e); - } finally { - if (CORSEnabled) { - setCORS(response); - } - serverLog(req, response); - req.respond(response); - } -}); - -console.log(`HTTP server listening on http://${addr}/`); diff --git a/net/file_server_test.ts b/net/file_server_test.ts deleted file mode 100644 index bd00d749b..000000000 --- a/net/file_server_test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { readFile } from "deno"; - -import { test, assert, assertEqual } from "../testing/mod.ts"; - -// Promise to completeResolve when all tests completes -let completeResolve; -export const completePromise = new Promise(res => (completeResolve = res)); -let completedTestCount = 0; - -function maybeCompleteTests() { - completedTestCount++; - // Change this when adding more tests - if (completedTestCount === 3) { - completeResolve(); - } -} - -export function runTests(serverReadyPromise: Promise) { - test(async function serveFile() { - await serverReadyPromise; - const res = await fetch("http://localhost:4500/azure-pipelines.yml"); - assert(res.headers.has("access-control-allow-origin")); - assert(res.headers.has("access-control-allow-headers")); - assertEqual(res.headers.get("content-type"), "text/yaml; charset=utf-8"); - const downloadedFile = await res.text(); - const localFile = new TextDecoder().decode( - await readFile("./azure-pipelines.yml") - ); - assertEqual(downloadedFile, localFile); - maybeCompleteTests(); - }); - - test(async function serveDirectory() { - await serverReadyPromise; - const res = await fetch("http://localhost:4500/"); - assert(res.headers.has("access-control-allow-origin")); - assert(res.headers.has("access-control-allow-headers")); - const page = await res.text(); - assert(page.includes("azure-pipelines.yml")); - maybeCompleteTests(); - }); - - test(async function serveFallback() { - await serverReadyPromise; - const res = await fetch("http://localhost:4500/badfile.txt"); - assert(res.headers.has("access-control-allow-origin")); - assert(res.headers.has("access-control-allow-headers")); - assertEqual(res.status, 404); - maybeCompleteTests(); - }); -} diff --git a/net/http.ts b/net/http.ts deleted file mode 100644 index e360e0d86..000000000 --- a/net/http.ts +++ /dev/null @@ -1,325 +0,0 @@ -import { listen, Conn, toAsyncIterator, Reader, copy } from "deno"; -import { BufReader, BufState, BufWriter } from "./bufio.ts"; -import { TextProtoReader } from "./textproto.ts"; -import { STATUS_TEXT } from "./http_status.ts"; -import { assert } from "./util.ts"; - -interface Deferred { - promise: Promise<{}>; - resolve: () => void; - reject: () => void; -} - -function deferred(): Deferred { - let resolve, reject; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { - promise, - resolve, - reject - }; -} - -interface ServeEnv { - reqQueue: ServerRequest[]; - serveDeferred: Deferred; -} - -/** Continuously read more requests from conn until EOF - * Calls maybeHandleReq. - * bufr is empty on a fresh TCP connection. - * Would be passed around and reused for later request on same conn - * TODO: make them async function after this change is done - * https://github.com/tc39/ecma262/pull/1250 - * See https://v8.dev/blog/fast-async - */ -function serveConn(env: ServeEnv, conn: Conn, bufr?: BufReader) { - readRequest(conn, bufr).then(maybeHandleReq.bind(null, env, conn)); -} -function maybeHandleReq(env: ServeEnv, conn: Conn, maybeReq: any) { - const [req, _err] = maybeReq; - if (_err) { - conn.close(); // assume EOF for now... - return; - } - env.reqQueue.push(req); // push req to queue - env.serveDeferred.resolve(); // signal while loop to process it -} - -export async function* serve(addr: string) { - const listener = listen("tcp", addr); - const env: ServeEnv = { - reqQueue: [], // in case multiple promises are ready - serveDeferred: deferred() - }; - - // Routine that keeps calling accept - const acceptRoutine = () => { - const handleConn = (conn: Conn) => { - serveConn(env, conn); // don't block - scheduleAccept(); // schedule next accept - }; - const scheduleAccept = () => { - listener.accept().then(handleConn); - }; - scheduleAccept(); - }; - - acceptRoutine(); - - // Loop hack to allow yield (yield won't work in callbacks) - while (true) { - await env.serveDeferred.promise; - env.serveDeferred = deferred(); // use a new deferred - let queueToProcess = env.reqQueue; - env.reqQueue = []; - for (const result of queueToProcess) { - yield result; - // Continue read more from conn when user is done with the current req - // Moving this here makes it easier to manage - serveConn(env, result.conn, result.r); - } - } - listener.close(); -} - -export async function listenAndServe( - addr: string, - handler: (req: ServerRequest) => void -) { - const server = serve(addr); - - for await (const request of server) { - await handler(request); - } -} - -export interface Response { - status?: number; - headers?: Headers; - body?: Uint8Array | Reader; -} - -export function setContentLength(r: Response): void { - if (!r.headers) { - r.headers = new Headers(); - } - - if (r.body) { - if (!r.headers.has("content-length")) { - if (r.body instanceof Uint8Array) { - const bodyLength = r.body.byteLength; - r.headers.append("Content-Length", bodyLength.toString()); - } else { - r.headers.append("Transfer-Encoding", "chunked"); - } - } - } -} - -export class ServerRequest { - url: string; - method: string; - proto: string; - headers: Headers; - conn: Conn; - r: BufReader; - w: BufWriter; - - public async *bodyStream() { - if (this.headers.has("content-length")) { - const len = +this.headers.get("content-length"); - if (Number.isNaN(len)) { - return new Uint8Array(0); - } - let buf = new Uint8Array(1024); - let rr = await this.r.read(buf); - let nread = rr.nread; - while (!rr.eof && nread < len) { - yield buf.subarray(0, rr.nread); - buf = new Uint8Array(1024); - rr = await this.r.read(buf); - nread += rr.nread; - } - yield buf.subarray(0, rr.nread); - } else { - if (this.headers.has("transfer-encoding")) { - const transferEncodings = this.headers - .get("transfer-encoding") - .split(",") - .map(e => e.trim().toLowerCase()); - if (transferEncodings.includes("chunked")) { - // Based on https://tools.ietf.org/html/rfc2616#section-19.4.6 - const tp = new TextProtoReader(this.r); - let [line, _] = await tp.readLine(); - // TODO: handle chunk extension - let [chunkSizeString, optExt] = line.split(";"); - let chunkSize = parseInt(chunkSizeString, 16); - if (Number.isNaN(chunkSize) || chunkSize < 0) { - throw new Error("Invalid chunk size"); - } - while (chunkSize > 0) { - let data = new Uint8Array(chunkSize); - let [nread, err] = await this.r.readFull(data); - if (nread !== chunkSize) { - throw new Error("Chunk data does not match size"); - } - yield data; - await this.r.readLine(); // Consume \r\n - [line, _] = await tp.readLine(); - chunkSize = parseInt(line, 16); - } - const [entityHeaders, err] = await tp.readMIMEHeader(); - if (!err) { - for (let [k, v] of entityHeaders) { - this.headers.set(k, v); - } - } - /* Pseudo code from https://tools.ietf.org/html/rfc2616#section-19.4.6 - length := 0 - read chunk-size, chunk-extension (if any) and CRLF - while (chunk-size > 0) { - read chunk-data and CRLF - append chunk-data to entity-body - length := length + chunk-size - read chunk-size and CRLF - } - read entity-header - while (entity-header not empty) { - append entity-header to existing header fields - read entity-header - } - Content-Length := length - Remove "chunked" from Transfer-Encoding - */ - return; // Must return here to avoid fall through - } - // TODO: handle other transfer-encoding types - } - // Otherwise... - yield new Uint8Array(0); - } - } - - // Read the body of the request into a single Uint8Array - public async body(): Promise { - return readAllIterator(this.bodyStream()); - } - - private async _streamBody(body: Reader, bodyLength: number) { - const n = await copy(this.w, body); - assert(n == bodyLength); - } - - private async _streamChunkedBody(body: Reader) { - const encoder = new TextEncoder(); - - for await (const chunk of toAsyncIterator(body)) { - const start = encoder.encode(`${chunk.byteLength.toString(16)}\r\n`); - const end = encoder.encode("\r\n"); - await this.w.write(start); - await this.w.write(chunk); - await this.w.write(end); - } - - const endChunk = encoder.encode("0\r\n\r\n"); - await this.w.write(endChunk); - } - - async respond(r: Response): Promise { - const protoMajor = 1; - const protoMinor = 1; - const statusCode = r.status || 200; - const statusText = STATUS_TEXT.get(statusCode); - if (!statusText) { - throw Error("bad status code"); - } - - let out = `HTTP/${protoMajor}.${protoMinor} ${statusCode} ${statusText}\r\n`; - - setContentLength(r); - - if (r.headers) { - for (const [key, value] of r.headers) { - out += `${key}: ${value}\r\n`; - } - } - out += "\r\n"; - - const header = new TextEncoder().encode(out); - let n = await this.w.write(header); - assert(header.byteLength == n); - - if (r.body) { - if (r.body instanceof Uint8Array) { - n = await this.w.write(r.body); - assert(r.body.byteLength == n); - } else { - if (r.headers.has("content-length")) { - await this._streamBody( - r.body, - parseInt(r.headers.get("content-length")) - ); - } else { - await this._streamChunkedBody(r.body); - } - } - } - - await this.w.flush(); - } -} - -async function readRequest( - c: Conn, - bufr?: BufReader -): Promise<[ServerRequest, BufState]> { - if (!bufr) { - bufr = new BufReader(c); - } - const bufw = new BufWriter(c); - const req = new ServerRequest(); - req.conn = c; - req.r = bufr!; - req.w = bufw; - const tp = new TextProtoReader(bufr!); - - let s: string; - let err: BufState; - - // First line: GET /index.html HTTP/1.0 - [s, err] = await tp.readLine(); - if (err) { - return [null, err]; - } - [req.method, req.url, req.proto] = s.split(" ", 3); - - [req.headers, err] = await tp.readMIMEHeader(); - - return [req, err]; -} - -async function readAllIterator( - it: AsyncIterableIterator -): Promise { - const chunks = []; - let len = 0; - for await (const chunk of it) { - chunks.push(chunk); - len += chunk.length; - } - if (chunks.length === 0) { - // No need for copy - return chunks[0]; - } - const collected = new Uint8Array(len); - let offset = 0; - for (let chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; -} diff --git a/net/http_bench.ts b/net/http_bench.ts deleted file mode 100644 index 8e1e24ad6..000000000 --- a/net/http_bench.ts +++ /dev/null @@ -1,15 +0,0 @@ -import * as deno from "deno"; -import { serve } from "./http.ts"; - -const addr = deno.args[1] || "127.0.0.1:4500"; -const server = serve(addr); - -const body = new TextEncoder().encode("Hello World"); - -async function main(): Promise { - for await (const request of server) { - await request.respond({ status: 200, body }); - } -} - -main(); diff --git a/net/http_status.ts b/net/http_status.ts deleted file mode 100644 index a3006d319..000000000 --- a/net/http_status.ts +++ /dev/null @@ -1,134 +0,0 @@ -export enum Status { - Continue = 100, // RFC 7231, 6.2.1 - SwitchingProtocols = 101, // RFC 7231, 6.2.2 - Processing = 102, // RFC 2518, 10.1 - - OK = 200, // RFC 7231, 6.3.1 - Created = 201, // RFC 7231, 6.3.2 - Accepted = 202, // RFC 7231, 6.3.3 - NonAuthoritativeInfo = 203, // RFC 7231, 6.3.4 - NoContent = 204, // RFC 7231, 6.3.5 - ResetContent = 205, // RFC 7231, 6.3.6 - PartialContent = 206, // RFC 7233, 4.1 - MultiStatus = 207, // RFC 4918, 11.1 - AlreadyReported = 208, // RFC 5842, 7.1 - IMUsed = 226, // RFC 3229, 10.4.1 - - MultipleChoices = 300, // RFC 7231, 6.4.1 - MovedPermanently = 301, // RFC 7231, 6.4.2 - Found = 302, // RFC 7231, 6.4.3 - SeeOther = 303, // RFC 7231, 6.4.4 - NotModified = 304, // RFC 7232, 4.1 - UseProxy = 305, // RFC 7231, 6.4.5 - // _ = 306, // RFC 7231, 6.4.6 (Unused) - TemporaryRedirect = 307, // RFC 7231, 6.4.7 - PermanentRedirect = 308, // RFC 7538, 3 - - BadRequest = 400, // RFC 7231, 6.5.1 - Unauthorized = 401, // RFC 7235, 3.1 - PaymentRequired = 402, // RFC 7231, 6.5.2 - Forbidden = 403, // RFC 7231, 6.5.3 - NotFound = 404, // RFC 7231, 6.5.4 - MethodNotAllowed = 405, // RFC 7231, 6.5.5 - NotAcceptable = 406, // RFC 7231, 6.5.6 - ProxyAuthRequired = 407, // RFC 7235, 3.2 - RequestTimeout = 408, // RFC 7231, 6.5.7 - Conflict = 409, // RFC 7231, 6.5.8 - Gone = 410, // RFC 7231, 6.5.9 - LengthRequired = 411, // RFC 7231, 6.5.10 - PreconditionFailed = 412, // RFC 7232, 4.2 - RequestEntityTooLarge = 413, // RFC 7231, 6.5.11 - RequestURITooLong = 414, // RFC 7231, 6.5.12 - UnsupportedMediaType = 415, // RFC 7231, 6.5.13 - RequestedRangeNotSatisfiable = 416, // RFC 7233, 4.4 - ExpectationFailed = 417, // RFC 7231, 6.5.14 - Teapot = 418, // RFC 7168, 2.3.3 - MisdirectedRequest = 421, // RFC 7540, 9.1.2 - UnprocessableEntity = 422, // RFC 4918, 11.2 - Locked = 423, // RFC 4918, 11.3 - FailedDependency = 424, // RFC 4918, 11.4 - UpgradeRequired = 426, // RFC 7231, 6.5.15 - PreconditionRequired = 428, // RFC 6585, 3 - TooManyRequests = 429, // RFC 6585, 4 - RequestHeaderFieldsTooLarge = 431, // RFC 6585, 5 - UnavailableForLegalReasons = 451, // RFC 7725, 3 - - InternalServerError = 500, // RFC 7231, 6.6.1 - NotImplemented = 501, // RFC 7231, 6.6.2 - BadGateway = 502, // RFC 7231, 6.6.3 - ServiceUnavailable = 503, // RFC 7231, 6.6.4 - GatewayTimeout = 504, // RFC 7231, 6.6.5 - HTTPVersionNotSupported = 505, // RFC 7231, 6.6.6 - VariantAlsoNegotiates = 506, // RFC 2295, 8.1 - InsufficientStorage = 507, // RFC 4918, 11.5 - LoopDetected = 508, // RFC 5842, 7.2 - NotExtended = 510, // RFC 2774, 7 - NetworkAuthenticationRequired = 511 // RFC 6585, 6 -} - -export const STATUS_TEXT = new Map([ - [Status.Continue, "Continue"], - [Status.SwitchingProtocols, "Switching Protocols"], - [Status.Processing, "Processing"], - - [Status.OK, "OK"], - [Status.Created, "Created"], - [Status.Accepted, "Accepted"], - [Status.NonAuthoritativeInfo, "Non-Authoritative Information"], - [Status.NoContent, "No Content"], - [Status.ResetContent, "Reset Content"], - [Status.PartialContent, "Partial Content"], - [Status.MultiStatus, "Multi-Status"], - [Status.AlreadyReported, "Already Reported"], - [Status.IMUsed, "IM Used"], - - [Status.MultipleChoices, "Multiple Choices"], - [Status.MovedPermanently, "Moved Permanently"], - [Status.Found, "Found"], - [Status.SeeOther, "See Other"], - [Status.NotModified, "Not Modified"], - [Status.UseProxy, "Use Proxy"], - [Status.TemporaryRedirect, "Temporary Redirect"], - [Status.PermanentRedirect, "Permanent Redirect"], - - [Status.BadRequest, "Bad Request"], - [Status.Unauthorized, "Unauthorized"], - [Status.PaymentRequired, "Payment Required"], - [Status.Forbidden, "Forbidden"], - [Status.NotFound, "Not Found"], - [Status.MethodNotAllowed, "Method Not Allowed"], - [Status.NotAcceptable, "Not Acceptable"], - [Status.ProxyAuthRequired, "Proxy Authentication Required"], - [Status.RequestTimeout, "Request Timeout"], - [Status.Conflict, "Conflict"], - [Status.Gone, "Gone"], - [Status.LengthRequired, "Length Required"], - [Status.PreconditionFailed, "Precondition Failed"], - [Status.RequestEntityTooLarge, "Request Entity Too Large"], - [Status.RequestURITooLong, "Request URI Too Long"], - [Status.UnsupportedMediaType, "Unsupported Media Type"], - [Status.RequestedRangeNotSatisfiable, "Requested Range Not Satisfiable"], - [Status.ExpectationFailed, "Expectation Failed"], - [Status.Teapot, "I'm a teapot"], - [Status.MisdirectedRequest, "Misdirected Request"], - [Status.UnprocessableEntity, "Unprocessable Entity"], - [Status.Locked, "Locked"], - [Status.FailedDependency, "Failed Dependency"], - [Status.UpgradeRequired, "Upgrade Required"], - [Status.PreconditionRequired, "Precondition Required"], - [Status.TooManyRequests, "Too Many Requests"], - [Status.RequestHeaderFieldsTooLarge, "Request Header Fields Too Large"], - [Status.UnavailableForLegalReasons, "Unavailable For Legal Reasons"], - - [Status.InternalServerError, "Internal Server Error"], - [Status.NotImplemented, "Not Implemented"], - [Status.BadGateway, "Bad Gateway"], - [Status.ServiceUnavailable, "Service Unavailable"], - [Status.GatewayTimeout, "Gateway Timeout"], - [Status.HTTPVersionNotSupported, "HTTP Version Not Supported"], - [Status.VariantAlsoNegotiates, "Variant Also Negotiates"], - [Status.InsufficientStorage, "Insufficient Storage"], - [Status.LoopDetected, "Loop Detected"], - [Status.NotExtended, "Not Extended"], - [Status.NetworkAuthenticationRequired, "Network Authentication Required"] -]); diff --git a/net/http_test.ts b/net/http_test.ts deleted file mode 100644 index 9235feb02..000000000 --- a/net/http_test.ts +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Ported from -// https://github.com/golang/go/blob/master/src/net/http/responsewrite_test.go - -import { Buffer } from "deno"; -import { test, assert, assertEqual } from "../testing/mod.ts"; -import { - listenAndServe, - ServerRequest, - setContentLength, - Response -} from "./http.ts"; -import { BufWriter, BufReader } from "./bufio.ts"; - -interface ResponseTest { - response: Response; - raw: string; -} - -const enc = new TextEncoder(); -const dec = new TextDecoder(); - -const responseTests: ResponseTest[] = [ - // Default response - { - response: {}, - raw: "HTTP/1.1 200 OK\r\n" + "\r\n" - }, - // HTTP/1.1, chunked coding; empty trailer; close - { - response: { - status: 200, - body: new Buffer(new TextEncoder().encode("abcdef")) - }, - - raw: - "HTTP/1.1 200 OK\r\n" + - "transfer-encoding: chunked\r\n\r\n" + - "6\r\nabcdef\r\n0\r\n\r\n" - } -]; - -test(async function responseWrite() { - for (const testCase of responseTests) { - const buf = new Buffer(); - const bufw = new BufWriter(buf); - const request = new ServerRequest(); - request.w = bufw; - - await request.respond(testCase.response); - assertEqual(buf.toString(), testCase.raw); - } -}); - -test(async function requestBodyWithContentLength() { - { - const req = new ServerRequest(); - req.headers = new Headers(); - req.headers.set("content-length", "5"); - const buf = new Buffer(enc.encode("Hello")); - req.r = new BufReader(buf); - const body = dec.decode(await req.body()); - assertEqual(body, "Hello"); - } - - // Larger than internal buf - { - const longText = "1234\n".repeat(1000); - const req = new ServerRequest(); - req.headers = new Headers(); - req.headers.set("Content-Length", "5000"); - const buf = new Buffer(enc.encode(longText)); - req.r = new BufReader(buf); - const body = dec.decode(await req.body()); - assertEqual(body, longText); - } -}); - -test(async function requestBodyWithTransferEncoding() { - { - const shortText = "Hello"; - const req = new ServerRequest(); - req.headers = new Headers(); - req.headers.set("transfer-encoding", "chunked"); - let chunksData = ""; - let chunkOffset = 0; - const maxChunkSize = 70; - while (chunkOffset < shortText.length) { - const chunkSize = Math.min(maxChunkSize, shortText.length - chunkOffset); - chunksData += `${chunkSize.toString(16)}\r\n${shortText.substr( - chunkOffset, - chunkSize - )}\r\n`; - chunkOffset += chunkSize; - } - chunksData += "0\r\n\r\n"; - const buf = new Buffer(enc.encode(chunksData)); - req.r = new BufReader(buf); - const body = dec.decode(await req.body()); - assertEqual(body, shortText); - } - - // Larger than internal buf - { - const longText = "1234\n".repeat(1000); - const req = new ServerRequest(); - req.headers = new Headers(); - req.headers.set("transfer-encoding", "chunked"); - let chunksData = ""; - let chunkOffset = 0; - const maxChunkSize = 70; - while (chunkOffset < longText.length) { - const chunkSize = Math.min(maxChunkSize, longText.length - chunkOffset); - chunksData += `${chunkSize.toString(16)}\r\n${longText.substr( - chunkOffset, - chunkSize - )}\r\n`; - chunkOffset += chunkSize; - } - chunksData += "0\r\n\r\n"; - const buf = new Buffer(enc.encode(chunksData)); - req.r = new BufReader(buf); - const body = dec.decode(await req.body()); - assertEqual(body, longText); - } -}); - -test(async function requestBodyStreamWithContentLength() { - { - const shortText = "Hello"; - const req = new ServerRequest(); - req.headers = new Headers(); - req.headers.set("content-length", "" + shortText.length); - const buf = new Buffer(enc.encode(shortText)); - req.r = new BufReader(buf); - const it = await req.bodyStream(); - let offset = 0; - for await (const chunk of it) { - const s = dec.decode(chunk); - assertEqual(shortText.substr(offset, s.length), s); - offset += s.length; - } - } - - // Larger than internal buf - { - const longText = "1234\n".repeat(1000); - const req = new ServerRequest(); - req.headers = new Headers(); - req.headers.set("Content-Length", "5000"); - const buf = new Buffer(enc.encode(longText)); - req.r = new BufReader(buf); - const it = await req.bodyStream(); - let offset = 0; - for await (const chunk of it) { - const s = dec.decode(chunk); - assertEqual(longText.substr(offset, s.length), s); - offset += s.length; - } - } -}); - -test(async function requestBodyStreamWithTransferEncoding() { - { - const shortText = "Hello"; - const req = new ServerRequest(); - req.headers = new Headers(); - req.headers.set("transfer-encoding", "chunked"); - let chunksData = ""; - let chunkOffset = 0; - const maxChunkSize = 70; - while (chunkOffset < shortText.length) { - const chunkSize = Math.min(maxChunkSize, shortText.length - chunkOffset); - chunksData += `${chunkSize.toString(16)}\r\n${shortText.substr( - chunkOffset, - chunkSize - )}\r\n`; - chunkOffset += chunkSize; - } - chunksData += "0\r\n\r\n"; - const buf = new Buffer(enc.encode(chunksData)); - req.r = new BufReader(buf); - const it = await req.bodyStream(); - let offset = 0; - for await (const chunk of it) { - const s = dec.decode(chunk); - assertEqual(shortText.substr(offset, s.length), s); - offset += s.length; - } - } - - // Larger than internal buf - { - const longText = "1234\n".repeat(1000); - const req = new ServerRequest(); - req.headers = new Headers(); - req.headers.set("transfer-encoding", "chunked"); - let chunksData = ""; - let chunkOffset = 0; - const maxChunkSize = 70; - while (chunkOffset < longText.length) { - const chunkSize = Math.min(maxChunkSize, longText.length - chunkOffset); - chunksData += `${chunkSize.toString(16)}\r\n${longText.substr( - chunkOffset, - chunkSize - )}\r\n`; - chunkOffset += chunkSize; - } - chunksData += "0\r\n\r\n"; - const buf = new Buffer(enc.encode(chunksData)); - req.r = new BufReader(buf); - const it = await req.bodyStream(); - let offset = 0; - for await (const chunk of it) { - const s = dec.decode(chunk); - assertEqual(longText.substr(offset, s.length), s); - offset += s.length; - } - } -}); diff --git a/net/iotest.ts b/net/iotest.ts deleted file mode 100644 index e3a42f58a..000000000 --- a/net/iotest.ts +++ /dev/null @@ -1,61 +0,0 @@ -// Ported to Deno from -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import { Reader, ReadResult } from "deno"; - -/** OneByteReader returns a Reader that implements - * each non-empty Read by reading one byte from r. - */ -export class OneByteReader implements Reader { - constructor(readonly r: Reader) {} - - async read(p: Uint8Array): Promise { - if (p.byteLength === 0) { - return { nread: 0, eof: false }; - } - if (!(p instanceof Uint8Array)) { - throw Error("expected Uint8Array"); - } - return this.r.read(p.subarray(0, 1)); - } -} - -/** HalfReader returns a Reader that implements Read - * by reading half as many requested bytes from r. - */ -export class HalfReader implements Reader { - constructor(readonly r: Reader) {} - - async read(p: Uint8Array): Promise { - if (!(p instanceof Uint8Array)) { - throw Error("expected Uint8Array"); - } - const half = Math.floor((p.byteLength + 1) / 2); - return this.r.read(p.subarray(0, half)); - } -} - -export class ErrTimeout extends Error { - constructor() { - super("timeout"); - this.name = "ErrTimeout"; - } -} - -/** TimeoutReader returns ErrTimeout on the second read - * with no data. Subsequent calls to read succeed. - */ -export class TimeoutReader implements Reader { - count = 0; - constructor(readonly r: Reader) {} - - async read(p: Uint8Array): Promise { - this.count++; - if (this.count === 2) { - throw new ErrTimeout(); - } - return this.r.read(p); - } -} diff --git a/net/ioutil.ts b/net/ioutil.ts deleted file mode 100644 index 68d6e5190..000000000 --- a/net/ioutil.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -import { BufReader } from "./bufio.ts"; - -/* Read big endian 16bit short from BufReader */ -export async function readShort(buf: BufReader): Promise { - const [high, low] = [await buf.readByte(), await buf.readByte()]; - return (high << 8) | low; -} - -/* Read big endian 32bit integer from BufReader */ -export async function readInt(buf: BufReader): Promise { - const [high, low] = [await readShort(buf), await readShort(buf)]; - return (high << 16) | low; -} - -const BIT32 = 0xffffffff; -/* Read big endian 64bit long from BufReader */ -export async function readLong(buf: BufReader): Promise { - const [high, low] = [await readInt(buf), await readInt(buf)]; - // ECMAScript doesn't support 64bit bit ops. - return high ? high * (BIT32 + 1) + low : low; -} - -/* Slice number into 64bit big endian byte array */ -export function sliceLongToBytes(d: number, dest = new Array(8)): number[] { - let mask = 0xff; - let low = (d << 32) >>> 32; - let high = (d - low) / (BIT32 + 1); - let shift = 24; - for (let i = 0; i < 4; i++) { - dest[i] = (high >>> shift) & mask; - dest[i + 4] = (low >>> shift) & mask; - shift -= 8; - } - return dest; -} diff --git a/net/ioutil_test.ts b/net/ioutil_test.ts deleted file mode 100644 index 422901e4a..000000000 --- a/net/ioutil_test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { Reader, ReadResult } from "deno"; -import { assertEqual, test } from "../testing/mod.ts"; -import { readInt, readLong, readShort, sliceLongToBytes } from "./ioutil.ts"; -import { BufReader } from "./bufio.ts"; - -class BinaryReader implements Reader { - index = 0; - - constructor(private bytes: Uint8Array = new Uint8Array(0)) {} - - async read(p: Uint8Array): Promise { - p.set(this.bytes.subarray(this.index, p.byteLength)); - this.index += p.byteLength; - return { nread: p.byteLength, eof: false }; - } -} - -test(async function testReadShort() { - const r = new BinaryReader(new Uint8Array([0x12, 0x34])); - const short = await readShort(new BufReader(r)); - assertEqual(short, 0x1234); -}); - -test(async function testReadInt() { - const r = new BinaryReader(new Uint8Array([0x12, 0x34, 0x56, 0x78])); - const int = await readInt(new BufReader(r)); - assertEqual(int, 0x12345678); -}); - -test(async function testReadLong() { - const r = new BinaryReader( - new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78]) - ); - const long = await readLong(new BufReader(r)); - assertEqual(long, 0x1234567812345678); -}); - -test(async function testReadLong2() { - const r = new BinaryReader( - new Uint8Array([0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]) - ); - const long = await readLong(new BufReader(r)); - assertEqual(long, 0x12345678); -}); - -test(async function testSliceLongToBytes() { - const arr = sliceLongToBytes(0x1234567890abcdef); - const actual = readLong(new BufReader(new BinaryReader(new Uint8Array(arr)))); - const expected = readLong( - new BufReader( - new BinaryReader( - new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]) - ) - ) - ); - assertEqual(actual, expected); -}); - -test(async function testSliceLongToBytes2() { - const arr = sliceLongToBytes(0x12345678); - assertEqual(arr, [0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]); -}); diff --git a/net/sha1.ts b/net/sha1.ts deleted file mode 100644 index 036c3c552..000000000 --- a/net/sha1.ts +++ /dev/null @@ -1,382 +0,0 @@ -/* - * [js-sha1]{@link https://github.com/emn178/js-sha1} - * - * @version 0.6.0 - * @author Chen, Yi-Cyuan [emn178@gmail.com] - * @copyright Chen, Yi-Cyuan 2014-2017 - * @license MIT - */ -/*jslint bitwise: true */ - -const HEX_CHARS = "0123456789abcdef".split(""); -const EXTRA = [-2147483648, 8388608, 32768, 128]; -const SHIFT = [24, 16, 8, 0]; - -const blocks = []; - -export class Sha1 { - blocks; - block; - start; - bytes; - hBytes; - finalized; - hashed; - first; - - h0 = 0x67452301; - h1 = 0xefcdab89; - h2 = 0x98badcfe; - h3 = 0x10325476; - h4 = 0xc3d2e1f0; - lastByteIndex = 0; - - constructor(sharedMemory: boolean = false) { - if (sharedMemory) { - blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; - this.blocks = blocks; - } else { - this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - } - - this.h0 = 0x67452301; - this.h1 = 0xefcdab89; - this.h2 = 0x98badcfe; - this.h3 = 0x10325476; - this.h4 = 0xc3d2e1f0; - - this.block = this.start = this.bytes = this.hBytes = 0; - this.finalized = this.hashed = false; - this.first = true; - } - - update(data: string | ArrayBuffer) { - if (this.finalized) { - return; - } - let message; - let notString = typeof data !== "string"; - if (notString && data instanceof ArrayBuffer) { - message = new Uint8Array(data); - } else { - message = data; - } - let code, - index = 0, - i, - length = message.length || 0, - blocks = this.blocks; - - while (index < length) { - if (this.hashed) { - this.hashed = false; - blocks[0] = this.block; - blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; - } - - if (notString) { - for (i = this.start; index < length && i < 64; ++index) { - blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; - } - } else { - for (i = this.start; index < length && i < 64; ++index) { - code = message.charCodeAt(index); - if (code < 0x80) { - blocks[i >> 2] |= code << SHIFT[i++ & 3]; - } else if (code < 0x800) { - blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } else if (code < 0xd800 || code >= 0xe000) { - blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } else { - code = - 0x10000 + - (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); - blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } - } - } - - this.lastByteIndex = i; - this.bytes += i - this.start; - if (i >= 64) { - this.block = blocks[16]; - this.start = i - 64; - this.hash(); - this.hashed = true; - } else { - this.start = i; - } - } - if (this.bytes > 4294967295) { - this.hBytes += (this.bytes / 4294967296) << 0; - this.bytes = this.bytes % 4294967296; - } - return this; - } - - finalize() { - if (this.finalized) { - return; - } - this.finalized = true; - let blocks = this.blocks, - i = this.lastByteIndex; - blocks[16] = this.block; - blocks[i >> 2] |= EXTRA[i & 3]; - this.block = blocks[16]; - if (i >= 56) { - if (!this.hashed) { - this.hash(); - } - blocks[0] = this.block; - blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; - } - blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29); - blocks[15] = this.bytes << 3; - this.hash(); - } - - hash() { - let a = this.h0, - b = this.h1, - c = this.h2, - d = this.h3, - e = this.h4; - let f, - j, - t, - blocks = this.blocks; - - for (j = 16; j < 80; ++j) { - t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16]; - blocks[j] = (t << 1) | (t >>> 31); - } - - for (j = 0; j < 20; j += 5) { - f = (b & c) | (~b & d); - t = (a << 5) | (a >>> 27); - e = (t + f + e + 1518500249 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - - f = (a & b) | (~a & c); - t = (e << 5) | (e >>> 27); - d = (t + f + d + 1518500249 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - - f = (e & a) | (~e & b); - t = (d << 5) | (d >>> 27); - c = (t + f + c + 1518500249 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - - f = (d & e) | (~d & a); - t = (c << 5) | (c >>> 27); - b = (t + f + b + 1518500249 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - - f = (c & d) | (~c & e); - t = (b << 5) | (b >>> 27); - a = (t + f + a + 1518500249 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); - } - - for (; j < 40; j += 5) { - f = b ^ c ^ d; - t = (a << 5) | (a >>> 27); - e = (t + f + e + 1859775393 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - - f = a ^ b ^ c; - t = (e << 5) | (e >>> 27); - d = (t + f + d + 1859775393 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - - f = e ^ a ^ b; - t = (d << 5) | (d >>> 27); - c = (t + f + c + 1859775393 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - - f = d ^ e ^ a; - t = (c << 5) | (c >>> 27); - b = (t + f + b + 1859775393 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - - f = c ^ d ^ e; - t = (b << 5) | (b >>> 27); - a = (t + f + a + 1859775393 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); - } - - for (; j < 60; j += 5) { - f = (b & c) | (b & d) | (c & d); - t = (a << 5) | (a >>> 27); - e = (t + f + e - 1894007588 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - - f = (a & b) | (a & c) | (b & c); - t = (e << 5) | (e >>> 27); - d = (t + f + d - 1894007588 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - - f = (e & a) | (e & b) | (a & b); - t = (d << 5) | (d >>> 27); - c = (t + f + c - 1894007588 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - - f = (d & e) | (d & a) | (e & a); - t = (c << 5) | (c >>> 27); - b = (t + f + b - 1894007588 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - - f = (c & d) | (c & e) | (d & e); - t = (b << 5) | (b >>> 27); - a = (t + f + a - 1894007588 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); - } - - for (; j < 80; j += 5) { - f = b ^ c ^ d; - t = (a << 5) | (a >>> 27); - e = (t + f + e - 899497514 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - - f = a ^ b ^ c; - t = (e << 5) | (e >>> 27); - d = (t + f + d - 899497514 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - - f = e ^ a ^ b; - t = (d << 5) | (d >>> 27); - c = (t + f + c - 899497514 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - - f = d ^ e ^ a; - t = (c << 5) | (c >>> 27); - b = (t + f + b - 899497514 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - - f = c ^ d ^ e; - t = (b << 5) | (b >>> 27); - a = (t + f + a - 899497514 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); - } - - this.h0 = (this.h0 + a) << 0; - this.h1 = (this.h1 + b) << 0; - this.h2 = (this.h2 + c) << 0; - this.h3 = (this.h3 + d) << 0; - this.h4 = (this.h4 + e) << 0; - } - - hex() { - this.finalize(); - - let h0 = this.h0, - h1 = this.h1, - h2 = this.h2, - h3 = this.h3, - h4 = this.h4; - - return ( - HEX_CHARS[(h0 >> 28) & 0x0f] + - HEX_CHARS[(h0 >> 24) & 0x0f] + - HEX_CHARS[(h0 >> 20) & 0x0f] + - HEX_CHARS[(h0 >> 16) & 0x0f] + - HEX_CHARS[(h0 >> 12) & 0x0f] + - HEX_CHARS[(h0 >> 8) & 0x0f] + - HEX_CHARS[(h0 >> 4) & 0x0f] + - HEX_CHARS[h0 & 0x0f] + - HEX_CHARS[(h1 >> 28) & 0x0f] + - HEX_CHARS[(h1 >> 24) & 0x0f] + - HEX_CHARS[(h1 >> 20) & 0x0f] + - HEX_CHARS[(h1 >> 16) & 0x0f] + - HEX_CHARS[(h1 >> 12) & 0x0f] + - HEX_CHARS[(h1 >> 8) & 0x0f] + - HEX_CHARS[(h1 >> 4) & 0x0f] + - HEX_CHARS[h1 & 0x0f] + - HEX_CHARS[(h2 >> 28) & 0x0f] + - HEX_CHARS[(h2 >> 24) & 0x0f] + - HEX_CHARS[(h2 >> 20) & 0x0f] + - HEX_CHARS[(h2 >> 16) & 0x0f] + - HEX_CHARS[(h2 >> 12) & 0x0f] + - HEX_CHARS[(h2 >> 8) & 0x0f] + - HEX_CHARS[(h2 >> 4) & 0x0f] + - HEX_CHARS[h2 & 0x0f] + - HEX_CHARS[(h3 >> 28) & 0x0f] + - HEX_CHARS[(h3 >> 24) & 0x0f] + - HEX_CHARS[(h3 >> 20) & 0x0f] + - HEX_CHARS[(h3 >> 16) & 0x0f] + - HEX_CHARS[(h3 >> 12) & 0x0f] + - HEX_CHARS[(h3 >> 8) & 0x0f] + - HEX_CHARS[(h3 >> 4) & 0x0f] + - HEX_CHARS[h3 & 0x0f] + - HEX_CHARS[(h4 >> 28) & 0x0f] + - HEX_CHARS[(h4 >> 24) & 0x0f] + - HEX_CHARS[(h4 >> 20) & 0x0f] + - HEX_CHARS[(h4 >> 16) & 0x0f] + - HEX_CHARS[(h4 >> 12) & 0x0f] + - HEX_CHARS[(h4 >> 8) & 0x0f] + - HEX_CHARS[(h4 >> 4) & 0x0f] + - HEX_CHARS[h4 & 0x0f] - ); - } - - toString() { - return this.hex(); - } - - digest() { - this.finalize(); - - let h0 = this.h0, - h1 = this.h1, - h2 = this.h2, - h3 = this.h3, - h4 = this.h4; - - return [ - (h0 >> 24) & 0xff, - (h0 >> 16) & 0xff, - (h0 >> 8) & 0xff, - h0 & 0xff, - (h1 >> 24) & 0xff, - (h1 >> 16) & 0xff, - (h1 >> 8) & 0xff, - h1 & 0xff, - (h2 >> 24) & 0xff, - (h2 >> 16) & 0xff, - (h2 >> 8) & 0xff, - h2 & 0xff, - (h3 >> 24) & 0xff, - (h3 >> 16) & 0xff, - (h3 >> 8) & 0xff, - h3 & 0xff, - (h4 >> 24) & 0xff, - (h4 >> 16) & 0xff, - (h4 >> 8) & 0xff, - h4 & 0xff - ]; - } - - array() { - return this.digest(); - } - - arrayBuffer() { - this.finalize(); - - let buffer = new ArrayBuffer(20); - let dataView = new DataView(buffer); - dataView.setUint32(0, this.h0); - dataView.setUint32(4, this.h1); - dataView.setUint32(8, this.h2); - dataView.setUint32(12, this.h3); - dataView.setUint32(16, this.h4); - return buffer; - } -} diff --git a/net/sha1_test.ts b/net/sha1_test.ts deleted file mode 100644 index b385f18da..000000000 --- a/net/sha1_test.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { assertEqual, test } from "../testing/mod.ts"; -import { Sha1 } from "./sha1.ts"; - -test(function testSha1() { - const sha1 = new Sha1(); - sha1.update("abcde"); - assertEqual(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); -}); diff --git a/net/textproto.ts b/net/textproto.ts deleted file mode 100644 index 832299e1c..000000000 --- a/net/textproto.ts +++ /dev/null @@ -1,150 +0,0 @@ -// Based on https://github.com/golang/go/blob/891682/src/net/textproto/ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import { BufReader, BufState } from "./bufio.ts"; -import { charCode } from "./util.ts"; - -const asciiDecoder = new TextDecoder(); -function str(buf: Uint8Array): string { - if (buf == null) { - return ""; - } else { - return asciiDecoder.decode(buf); - } -} - -export class ProtocolError extends Error { - constructor(msg: string) { - super(msg); - this.name = "ProtocolError"; - } -} - -export class TextProtoReader { - constructor(readonly r: BufReader) {} - - /** readLine() reads a single line from the TextProtoReader, - * eliding the final \n or \r\n from the returned string. - */ - async readLine(): Promise<[string, BufState]> { - let [line, err] = await this.readLineSlice(); - return [str(line), err]; - } - - /** ReadMIMEHeader reads a MIME-style header from r. - * The header is a sequence of possibly continued Key: Value lines - * ending in a blank line. - * The returned map m maps CanonicalMIMEHeaderKey(key) to a - * sequence of values in the same order encountered in the input. - * - * For example, consider this input: - * - * My-Key: Value 1 - * Long-Key: Even - * Longer Value - * My-Key: Value 2 - * - * Given that input, ReadMIMEHeader returns the map: - * - * map[string][]string{ - * "My-Key": {"Value 1", "Value 2"}, - * "Long-Key": {"Even Longer Value"}, - * } - */ - async readMIMEHeader(): Promise<[Headers, BufState]> { - let m = new Headers(); - let line: Uint8Array; - - // The first line cannot start with a leading space. - let [buf, err] = await this.r.peek(1); - if (buf[0] == charCode(" ") || buf[0] == charCode("\t")) { - [line, err] = await this.readLineSlice(); - } - - [buf, err] = await this.r.peek(1); - if (err == null && (buf[0] == charCode(" ") || buf[0] == charCode("\t"))) { - throw new ProtocolError( - `malformed MIME header initial line: ${str(line)}` - ); - } - - while (true) { - let [kv, err] = await this.readLineSlice(); // readContinuedLineSlice - if (kv.byteLength == 0) { - return [m, err]; - } - - // Key ends at first colon; should not have trailing spaces - // but they appear in the wild, violating specs, so we remove - // them if present. - let i = kv.indexOf(charCode(":")); - if (i < 0) { - throw new ProtocolError(`malformed MIME header line: ${str(kv)}`); - } - let endKey = i; - while (endKey > 0 && kv[endKey - 1] == charCode(" ")) { - endKey--; - } - - //let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey)); - let key = str(kv.subarray(0, endKey)); - - // As per RFC 7230 field-name is a token, tokens consist of one or more chars. - // We could return a ProtocolError here, but better to be liberal in what we - // accept, so if we get an empty key, skip it. - if (key == "") { - continue; - } - - // Skip initial spaces in value. - i++; // skip colon - while ( - i < kv.byteLength && - (kv[i] == charCode(" ") || kv[i] == charCode("\t")) - ) { - i++; - } - let value = str(kv.subarray(i)); - - m.append(key, value); - - if (err != null) { - throw err; - } - } - } - - async readLineSlice(): Promise<[Uint8Array, BufState]> { - // this.closeDot(); - let line: Uint8Array; - while (true) { - let [l, more, err] = await this.r.readLine(); - if (err != null) { - // Go's len(typed nil) works fine, but not in JS - return [new Uint8Array(0), err]; - } - // Avoid the copy if the first call produced a full line. - if (line == null && !more) { - return [l, null]; - } - line = append(line, l); - if (!more) { - break; - } - } - return [line, null]; - } -} - -export function append(a: Uint8Array, b: Uint8Array): Uint8Array { - if (a == null) { - return b; - } else { - const output = new Uint8Array(a.length + b.length); - output.set(a, 0); - output.set(b, a.length); - return output; - } -} diff --git a/net/textproto_test.ts b/net/textproto_test.ts deleted file mode 100644 index e0ae0749c..000000000 --- a/net/textproto_test.ts +++ /dev/null @@ -1,98 +0,0 @@ -// Based on https://github.com/golang/go/blob/891682/src/net/textproto/ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import { BufReader } from "./bufio.ts"; -import { TextProtoReader, append } from "./textproto.ts"; -import { stringsReader } from "./util.ts"; -import { test, assert, assertEqual } from "../testing/mod.ts"; - -function reader(s: string): TextProtoReader { - return new TextProtoReader(new BufReader(stringsReader(s))); -} - -test(async function textprotoReader() { - let r = reader("line1\nline2\n"); - let [s, err] = await r.readLine(); - assertEqual(s, "line1"); - assert(err == null); - - [s, err] = await r.readLine(); - assertEqual(s, "line2"); - assert(err == null); - - [s, err] = await r.readLine(); - assertEqual(s, ""); - assert(err == "EOF"); -}); - -/* -test(async function textprotoReadMIMEHeader() { - let r = reader("my-key: Value 1 \r\nLong-key: Even \n Longer Value\r\nmy-Key: Value 2\r\n\n"); - let [m, err] = await r.readMIMEHeader(); - - console.log("Got headers", m.toString()); - want := MIMEHeader{ - "My-Key": {"Value 1", "Value 2"}, - "Long-Key": {"Even Longer Value"}, - } - if !reflect.DeepEqual(m, want) || err != nil { - t.Fatalf("ReadMIMEHeader: %v, %v; want %v", m, err, want) - } -}); -*/ - -test(async function textprotoReadMIMEHeaderSingle() { - let r = reader("Foo: bar\n\n"); - let [m, err] = await r.readMIMEHeader(); - assertEqual(m.get("Foo"), "bar"); - assert(!err); -}); - -// Test that we read slightly-bogus MIME headers seen in the wild, -// with spaces before colons, and spaces in keys. -test(async function textprotoReadMIMEHeaderNonCompliant() { - // Invalid HTTP response header as sent by an Axis security - // camera: (this is handled by IE, Firefox, Chrome, curl, etc.) - let r = reader( - "Foo: bar\r\n" + - "Content-Language: en\r\n" + - "SID : 0\r\n" + - // TODO Re-enable Currently fails with: - // "TypeError: audio mode is not a legal HTTP header name" - // "Audio Mode : None\r\n" + - "Privilege : 127\r\n\r\n" - ); - let [m, err] = await r.readMIMEHeader(); - console.log(m.toString()); - assert(!err); - /* - let want = MIMEHeader{ - "Foo": {"bar"}, - "Content-Language": {"en"}, - "Sid": {"0"}, - "Audio Mode": {"None"}, - "Privilege": {"127"}, - } - if !reflect.DeepEqual(m, want) || err != nil { - t.Fatalf("ReadMIMEHeader =\n%v, %v; want:\n%v", m, err, want) - } - */ -}); - -test(async function textprotoAppend() { - const enc = new TextEncoder(); - const dec = new TextDecoder(); - const u1 = enc.encode("Hello "); - const u2 = enc.encode("World"); - const joined = append(u1, u2); - assertEqual(dec.decode(joined), "Hello World"); -}); - -test(async function textprotoReadEmpty() { - let r = reader(""); - let [m, err] = await r.readMIMEHeader(); - // Should not crash! - assertEqual(err, "EOF"); -}); diff --git a/net/util.ts b/net/util.ts deleted file mode 100644 index 811940b4d..000000000 --- a/net/util.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Buffer, Reader } from "deno"; - -export function assert(cond: boolean, msg = "assert") { - if (!cond) { - throw Error(msg); - } -} - -// `off` is the offset into `dst` where it will at which to begin writing values -// from `src`. -// Returns the number of bytes copied. -export function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number { - const r = dst.byteLength - off; - if (src.byteLength > r) { - src = src.subarray(0, r); - } - dst.set(src, off); - return src.byteLength; -} - -export function charCode(s: string): number { - return s.charCodeAt(0); -} - -const encoder = new TextEncoder(); -export function stringsReader(s: string): Reader { - const ui8 = encoder.encode(s); - return new Buffer(ui8.buffer as ArrayBuffer); -} diff --git a/net/ws.ts b/net/ws.ts deleted file mode 100644 index 5ce96b3ca..000000000 --- a/net/ws.ts +++ /dev/null @@ -1,350 +0,0 @@ -// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -import { Buffer, Writer, Conn } from "deno"; -import { ServerRequest } from "./http.ts"; -import { BufReader, BufWriter } from "./bufio.ts"; -import { readLong, readShort, sliceLongToBytes } from "./ioutil.ts"; -import { Sha1 } from "./sha1.ts"; - -export const OpCodeContinue = 0x0; -export const OpCodeTextFrame = 0x1; -export const OpCodeBinaryFrame = 0x2; -export const OpCodeClose = 0x8; -export const OpcodePing = 0x9; -export const OpcodePong = 0xa; - -export type WebSocketEvent = - | string - | Uint8Array - | WebSocketCloseEvent - | WebSocketPingEvent - | WebSocketPongEvent; - -export type WebSocketCloseEvent = { - code: number; - reason?: string; -}; - -export function isWebSocketCloseEvent(a): a is WebSocketCloseEvent { - return a && typeof a["code"] === "number"; -} - -export type WebSocketPingEvent = ["ping", Uint8Array]; - -export function isWebSocketPingEvent(a): a is WebSocketPingEvent { - return Array.isArray(a) && a[0] === "ping" && a[1] instanceof Uint8Array; -} - -export type WebSocketPongEvent = ["pong", Uint8Array]; - -export function isWebSocketPongEvent(a): a is WebSocketPongEvent { - return Array.isArray(a) && a[0] === "pong" && a[1] instanceof Uint8Array; -} - -export class SocketClosedError extends Error {} - -export type WebSocketFrame = { - isLastFrame: boolean; - opcode: number; - mask?: Uint8Array; - payload: Uint8Array; -}; - -export type WebSocket = { - readonly isClosed: boolean; - receive(): AsyncIterableIterator; - send(data: string | Uint8Array): Promise; - ping(data?: string | Uint8Array): Promise; - close(code: number, reason?: string): Promise; -}; - -class WebSocketImpl implements WebSocket { - encoder = new TextEncoder(); - constructor(private conn: Conn, private mask?: Uint8Array) {} - - async *receive(): AsyncIterableIterator { - let frames: WebSocketFrame[] = []; - let payloadsLength = 0; - for await (const frame of receiveFrame(this.conn)) { - unmask(frame.payload, frame.mask); - switch (frame.opcode) { - case OpCodeTextFrame: - case OpCodeBinaryFrame: - case OpCodeContinue: - frames.push(frame); - payloadsLength += frame.payload.length; - if (frame.isLastFrame) { - const concat = new Uint8Array(payloadsLength); - let offs = 0; - for (const frame of frames) { - concat.set(frame.payload, offs); - offs += frame.payload.length; - } - if (frames[0].opcode === OpCodeTextFrame) { - // text - yield new Buffer(concat).toString(); - } else { - // binary - yield concat; - } - frames = []; - payloadsLength = 0; - } - break; - case OpCodeClose: - const code = (frame.payload[0] << 16) | frame.payload[1]; - const reason = new Buffer( - frame.payload.subarray(2, frame.payload.length) - ).toString(); - this._isClosed = true; - yield { code, reason }; - return; - case OpcodePing: - yield ["ping", frame.payload] as WebSocketPingEvent; - break; - case OpcodePong: - yield ["pong", frame.payload] as WebSocketPongEvent; - break; - } - } - } - - async send(data: string | Uint8Array): Promise { - if (this.isClosed) { - throw new SocketClosedError("socket has been closed"); - } - const opcode = - typeof data === "string" ? OpCodeTextFrame : OpCodeBinaryFrame; - const payload = typeof data === "string" ? this.encoder.encode(data) : data; - const isLastFrame = true; - await writeFrame( - { - isLastFrame, - opcode, - payload, - mask: this.mask - }, - this.conn - ); - } - - async ping(data: string | Uint8Array): Promise { - const payload = typeof data === "string" ? this.encoder.encode(data) : data; - await writeFrame( - { - isLastFrame: true, - opcode: OpCodeClose, - mask: this.mask, - payload - }, - this.conn - ); - } - - private _isClosed = false; - get isClosed() { - return this._isClosed; - } - - async close(code: number, reason?: string): Promise { - try { - const header = [code >>> 8, code & 0x00ff]; - let payload: Uint8Array; - if (reason) { - const reasonBytes = this.encoder.encode(reason); - payload = new Uint8Array(2 + reasonBytes.byteLength); - payload.set(header); - payload.set(reasonBytes, 2); - } else { - payload = new Uint8Array(header); - } - await writeFrame( - { - isLastFrame: true, - opcode: OpCodeClose, - mask: this.mask, - payload - }, - this.conn - ); - } catch (e) { - throw e; - } finally { - this.ensureSocketClosed(); - } - } - - private ensureSocketClosed(): Error { - if (this.isClosed) return; - try { - this.conn.close(); - } catch (e) { - console.error(e); - } finally { - this._isClosed = true; - } - } -} - -export async function* receiveFrame( - conn: Conn -): AsyncIterableIterator { - let receiving = true; - const reader = new BufReader(conn); - while (receiving) { - const frame = await readFrame(reader); - switch (frame.opcode) { - case OpCodeTextFrame: - case OpCodeBinaryFrame: - case OpCodeContinue: - yield frame; - break; - case OpCodeClose: - await writeFrame( - { - isLastFrame: true, - opcode: OpCodeClose, - payload: frame.payload - }, - conn - ); - conn.close(); - yield frame; - receiving = false; - break; - case OpcodePing: - await writeFrame( - { - isLastFrame: true, - opcode: OpcodePong, - payload: frame.payload - }, - conn - ); - yield frame; - break; - case OpcodePong: - yield frame; - break; - } - } -} - -export async function writeFrame(frame: WebSocketFrame, writer: Writer) { - let payloadLength = frame.payload.byteLength; - let header: Uint8Array; - const hasMask = (frame.mask ? 1 : 0) << 7; - if (payloadLength < 126) { - header = new Uint8Array([ - (0b1000 << 4) | frame.opcode, - hasMask | payloadLength - ]); - } else if (payloadLength < 0xffff) { - header = new Uint8Array([ - (0b1000 << 4) | frame.opcode, - hasMask | 0b01111110, - payloadLength >>> 8, - payloadLength & 0x00ff - ]); - } else { - header = new Uint8Array([ - (0b1000 << 4) | frame.opcode, - hasMask | 0b01111111, - ...sliceLongToBytes(payloadLength) - ]); - } - if (frame.mask) { - unmask(frame.payload, frame.mask); - } - const bytes = new Uint8Array(header.length + payloadLength); - bytes.set(header, 0); - bytes.set(frame.payload, header.length); - const w = new BufWriter(writer); - await w.write(bytes); - await w.flush(); -} - -export function unmask(payload: Uint8Array, mask: Uint8Array) { - if (mask) { - for (let i = 0; i < payload.length; i++) { - payload[i] ^= mask[i % 4]; - } - } -} - -export function acceptable(req: ServerRequest): boolean { - return ( - req.headers.get("upgrade") === "websocket" && - req.headers.has("sec-websocket-key") - ); -} - -export async function acceptWebSocket(req: ServerRequest): Promise { - if (acceptable(req)) { - const sock = new WebSocketImpl(req.conn); - const secKey = req.headers.get("sec-websocket-key"); - const secAccept = createSecAccept(secKey); - await req.respond({ - status: 101, - headers: new Headers({ - Upgrade: "websocket", - Connection: "Upgrade", - "Sec-WebSocket-Accept": secAccept - }) - }); - return sock; - } - throw new Error("request is not acceptable"); -} - -const kGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - -export function createSecAccept(nonce: string) { - const sha1 = new Sha1(); - sha1.update(nonce + kGUID); - const bytes = sha1.digest(); - const hash = bytes.reduce( - (data, byte) => data + String.fromCharCode(byte), - "" - ); - return btoa(hash); -} - -export async function readFrame(buf: BufReader): Promise { - let b = await buf.readByte(); - let isLastFrame = false; - switch (b >>> 4) { - case 0b1000: - isLastFrame = true; - break; - case 0b0000: - isLastFrame = false; - break; - default: - throw new Error("invalid signature"); - } - const opcode = b & 0x0f; - // has_mask & payload - b = await buf.readByte(); - const hasMask = b >>> 7; - let payloadLength = b & 0b01111111; - if (payloadLength === 126) { - payloadLength = await readShort(buf); - } else if (payloadLength === 127) { - payloadLength = await readLong(buf); - } - // mask - let mask; - if (hasMask) { - mask = new Uint8Array(4); - await buf.readFull(mask); - } - // payload - const payload = new Uint8Array(payloadLength); - await buf.readFull(payload); - return { - isLastFrame, - opcode, - mask, - payload - }; -} diff --git a/net/ws_test.ts b/net/ws_test.ts deleted file mode 100644 index 62e5a6089..000000000 --- a/net/ws_test.ts +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -import { Buffer } from "deno"; -import { BufReader } from "./bufio.ts"; -import { test, assert, assertEqual } from "../testing/mod.ts"; -import { - createSecAccept, - OpCodeBinaryFrame, - OpCodeContinue, - OpcodePing, - OpcodePong, - OpCodeTextFrame, - readFrame, - unmask -} from "./ws.ts"; -import { serve } from "./http.ts"; - -test(async function testReadUnmaskedTextFrame() { - // unmasked single text frame with payload "Hello" - const buf = new BufReader( - new Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) - ); - const frame = await readFrame(buf); - assertEqual(frame.opcode, OpCodeTextFrame); - assertEqual(frame.mask, undefined); - assertEqual(new Buffer(frame.payload).toString(), "Hello"); - assertEqual(frame.isLastFrame, true); -}); - -test(async function testReadMakedTextFrame() { - //a masked single text frame with payload "Hello" - const buf = new BufReader( - new Buffer( - new Uint8Array([ - 0x81, - 0x85, - 0x37, - 0xfa, - 0x21, - 0x3d, - 0x7f, - 0x9f, - 0x4d, - 0x51, - 0x58 - ]) - ) - ); - const frame = await readFrame(buf); - console.dir(frame); - assertEqual(frame.opcode, OpCodeTextFrame); - unmask(frame.payload, frame.mask); - assertEqual(new Buffer(frame.payload).toString(), "Hello"); - assertEqual(frame.isLastFrame, true); -}); - -test(async function testReadUnmaskedSplittedTextFrames() { - const buf1 = new BufReader( - new Buffer(new Uint8Array([0x01, 0x03, 0x48, 0x65, 0x6c])) - ); - const buf2 = new BufReader( - new Buffer(new Uint8Array([0x80, 0x02, 0x6c, 0x6f])) - ); - const [f1, f2] = await Promise.all([readFrame(buf1), readFrame(buf2)]); - assertEqual(f1.isLastFrame, false); - assertEqual(f1.mask, undefined); - assertEqual(f1.opcode, OpCodeTextFrame); - assertEqual(new Buffer(f1.payload).toString(), "Hel"); - - assertEqual(f2.isLastFrame, true); - assertEqual(f2.mask, undefined); - assertEqual(f2.opcode, OpCodeContinue); - assertEqual(new Buffer(f2.payload).toString(), "lo"); -}); - -test(async function testReadUnmaksedPingPongFrame() { - // unmasked ping with payload "Hello" - const buf = new BufReader( - new Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) - ); - const ping = await readFrame(buf); - assertEqual(ping.opcode, OpcodePing); - assertEqual(new Buffer(ping.payload).toString(), "Hello"); - - const buf2 = new BufReader( - new Buffer( - new Uint8Array([ - 0x8a, - 0x85, - 0x37, - 0xfa, - 0x21, - 0x3d, - 0x7f, - 0x9f, - 0x4d, - 0x51, - 0x58 - ]) - ) - ); - const pong = await readFrame(buf2); - assertEqual(pong.opcode, OpcodePong); - assert(pong.mask !== undefined); - unmask(pong.payload, pong.mask); - assertEqual(new Buffer(pong.payload).toString(), "Hello"); -}); - -test(async function testReadUnmaksedBigBinaryFrame() { - let a = [0x82, 0x7e, 0x01, 0x00]; - for (let i = 0; i < 256; i++) { - a.push(i); - } - const buf = new BufReader(new Buffer(new Uint8Array(a))); - const bin = await readFrame(buf); - assertEqual(bin.opcode, OpCodeBinaryFrame); - assertEqual(bin.isLastFrame, true); - assertEqual(bin.mask, undefined); - assertEqual(bin.payload.length, 256); -}); - -test(async function testReadUnmaskedBigBigBinaryFrame() { - let a = [0x82, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]; - for (let i = 0; i < 0xffff; i++) { - a.push(i); - } - const buf = new BufReader(new Buffer(new Uint8Array(a))); - const bin = await readFrame(buf); - assertEqual(bin.opcode, OpCodeBinaryFrame); - assertEqual(bin.isLastFrame, true); - assertEqual(bin.mask, undefined); - assertEqual(bin.payload.length, 0xffff + 1); -}); - -test(async function testCreateSecAccept() { - const nonce = "dGhlIHNhbXBsZSBub25jZQ=="; - const d = createSecAccept(nonce); - assertEqual(d, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); -}); diff --git a/test.ts b/test.ts index 8a3534457..994148178 100755 --- a/test.ts +++ b/test.ts @@ -5,11 +5,6 @@ import "colors/test.ts"; import "datetime/test.ts"; import "examples/test.ts"; import "flags/test.ts"; -import "logging/test.ts"; -import "media_types/test.ts"; -import "net/bufio_test.ts"; -import "net/http_test.ts"; -import "net/textproto_test.ts"; import "fs/mkdirp_test.ts"; import "fs/path/basename_test.ts"; import "fs/path/dirname_test.ts"; @@ -20,12 +15,18 @@ import "fs/path/parse_format_test.ts"; import "fs/path/relative_test.ts"; import "fs/path/resolve_test.ts"; import "fs/path/zero_length_strings_test.ts"; +import "io/bufio_test.ts"; +import "http/http_test.ts"; +import "log/test.ts"; +import "media_types/test.ts"; import "testing/test.ts"; +import "textproto/test.ts"; +import "ws/test.ts"; -import { runTests, completePromise } from "net/file_server_test.ts"; +import { runTests, completePromise } from "http/file_server_test.ts"; const fileServer = run({ - args: ["deno", "--allow-net", "net/file_server.ts", ".", "--cors"] + args: ["deno", "--allow-net", "http/file_server.ts", ".", "--cors"] }); runTests(new Promise(res => setTimeout(res, 5000))); diff --git a/textproto/mod.ts b/textproto/mod.ts new file mode 100644 index 000000000..ee7647296 --- /dev/null +++ b/textproto/mod.ts @@ -0,0 +1,150 @@ +// Based on https://github.com/golang/go/blob/891682/src/net/textproto/ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { BufReader, BufState } from "../io/bufio.ts"; +import { charCode } from "../io/util.ts"; + +const asciiDecoder = new TextDecoder(); +function str(buf: Uint8Array): string { + if (buf == null) { + return ""; + } else { + return asciiDecoder.decode(buf); + } +} + +export class ProtocolError extends Error { + constructor(msg: string) { + super(msg); + this.name = "ProtocolError"; + } +} + +export class TextProtoReader { + constructor(readonly r: BufReader) {} + + /** readLine() reads a single line from the TextProtoReader, + * eliding the final \n or \r\n from the returned string. + */ + async readLine(): Promise<[string, BufState]> { + let [line, err] = await this.readLineSlice(); + return [str(line), err]; + } + + /** ReadMIMEHeader reads a MIME-style header from r. + * The header is a sequence of possibly continued Key: Value lines + * ending in a blank line. + * The returned map m maps CanonicalMIMEHeaderKey(key) to a + * sequence of values in the same order encountered in the input. + * + * For example, consider this input: + * + * My-Key: Value 1 + * Long-Key: Even + * Longer Value + * My-Key: Value 2 + * + * Given that input, ReadMIMEHeader returns the map: + * + * map[string][]string{ + * "My-Key": {"Value 1", "Value 2"}, + * "Long-Key": {"Even Longer Value"}, + * } + */ + async readMIMEHeader(): Promise<[Headers, BufState]> { + let m = new Headers(); + let line: Uint8Array; + + // The first line cannot start with a leading space. + let [buf, err] = await this.r.peek(1); + if (buf[0] == charCode(" ") || buf[0] == charCode("\t")) { + [line, err] = await this.readLineSlice(); + } + + [buf, err] = await this.r.peek(1); + if (err == null && (buf[0] == charCode(" ") || buf[0] == charCode("\t"))) { + throw new ProtocolError( + `malformed MIME header initial line: ${str(line)}` + ); + } + + while (true) { + let [kv, err] = await this.readLineSlice(); // readContinuedLineSlice + if (kv.byteLength == 0) { + return [m, err]; + } + + // Key ends at first colon; should not have trailing spaces + // but they appear in the wild, violating specs, so we remove + // them if present. + let i = kv.indexOf(charCode(":")); + if (i < 0) { + throw new ProtocolError(`malformed MIME header line: ${str(kv)}`); + } + let endKey = i; + while (endKey > 0 && kv[endKey - 1] == charCode(" ")) { + endKey--; + } + + //let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey)); + let key = str(kv.subarray(0, endKey)); + + // As per RFC 7230 field-name is a token, tokens consist of one or more chars. + // We could return a ProtocolError here, but better to be liberal in what we + // accept, so if we get an empty key, skip it. + if (key == "") { + continue; + } + + // Skip initial spaces in value. + i++; // skip colon + while ( + i < kv.byteLength && + (kv[i] == charCode(" ") || kv[i] == charCode("\t")) + ) { + i++; + } + let value = str(kv.subarray(i)); + + m.append(key, value); + + if (err != null) { + throw err; + } + } + } + + async readLineSlice(): Promise<[Uint8Array, BufState]> { + // this.closeDot(); + let line: Uint8Array; + while (true) { + let [l, more, err] = await this.r.readLine(); + if (err != null) { + // Go's len(typed nil) works fine, but not in JS + return [new Uint8Array(0), err]; + } + // Avoid the copy if the first call produced a full line. + if (line == null && !more) { + return [l, null]; + } + line = append(line, l); + if (!more) { + break; + } + } + return [line, null]; + } +} + +export function append(a: Uint8Array, b: Uint8Array): Uint8Array { + if (a == null) { + return b; + } else { + const output = new Uint8Array(a.length + b.length); + output.set(a, 0); + output.set(b, a.length); + return output; + } +} diff --git a/textproto/test.ts b/textproto/test.ts new file mode 100644 index 000000000..0f8bee227 --- /dev/null +++ b/textproto/test.ts @@ -0,0 +1,98 @@ +// Based on https://github.com/golang/go/blob/891682/src/net/textproto/ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +import { BufReader } from "../io/bufio.ts"; +import { TextProtoReader, append } from "./mod.ts"; +import { stringsReader } from "../io/util.ts"; +import { test, assert, assertEqual } from "../testing/mod.ts"; + +function reader(s: string): TextProtoReader { + return new TextProtoReader(new BufReader(stringsReader(s))); +} + +test(async function textprotoReader() { + let r = reader("line1\nline2\n"); + let [s, err] = await r.readLine(); + assertEqual(s, "line1"); + assert(err == null); + + [s, err] = await r.readLine(); + assertEqual(s, "line2"); + assert(err == null); + + [s, err] = await r.readLine(); + assertEqual(s, ""); + assert(err == "EOF"); +}); + +/* +test(async function textprotoReadMIMEHeader() { + let r = reader("my-key: Value 1 \r\nLong-key: Even \n Longer Value\r\nmy-Key: Value 2\r\n\n"); + let [m, err] = await r.readMIMEHeader(); + + console.log("Got headers", m.toString()); + want := MIMEHeader{ + "My-Key": {"Value 1", "Value 2"}, + "Long-Key": {"Even Longer Value"}, + } + if !reflect.DeepEqual(m, want) || err != nil { + t.Fatalf("ReadMIMEHeader: %v, %v; want %v", m, err, want) + } +}); +*/ + +test(async function textprotoReadMIMEHeaderSingle() { + let r = reader("Foo: bar\n\n"); + let [m, err] = await r.readMIMEHeader(); + assertEqual(m.get("Foo"), "bar"); + assert(!err); +}); + +// Test that we read slightly-bogus MIME headers seen in the wild, +// with spaces before colons, and spaces in keys. +test(async function textprotoReadMIMEHeaderNonCompliant() { + // Invalid HTTP response header as sent by an Axis security + // camera: (this is handled by IE, Firefox, Chrome, curl, etc.) + let r = reader( + "Foo: bar\r\n" + + "Content-Language: en\r\n" + + "SID : 0\r\n" + + // TODO Re-enable Currently fails with: + // "TypeError: audio mode is not a legal HTTP header name" + // "Audio Mode : None\r\n" + + "Privilege : 127\r\n\r\n" + ); + let [m, err] = await r.readMIMEHeader(); + console.log(m.toString()); + assert(!err); + /* + let want = MIMEHeader{ + "Foo": {"bar"}, + "Content-Language": {"en"}, + "Sid": {"0"}, + "Audio Mode": {"None"}, + "Privilege": {"127"}, + } + if !reflect.DeepEqual(m, want) || err != nil { + t.Fatalf("ReadMIMEHeader =\n%v, %v; want:\n%v", m, err, want) + } + */ +}); + +test(async function textprotoAppend() { + const enc = new TextEncoder(); + const dec = new TextDecoder(); + const u1 = enc.encode("Hello "); + const u2 = enc.encode("World"); + const joined = append(u1, u2); + assertEqual(dec.decode(joined), "Hello World"); +}); + +test(async function textprotoReadEmpty() { + let r = reader(""); + let [m, err] = await r.readMIMEHeader(); + // Should not crash! + assertEqual(err, "EOF"); +}); diff --git a/ws/mod.ts b/ws/mod.ts new file mode 100644 index 000000000..b0b490978 --- /dev/null +++ b/ws/mod.ts @@ -0,0 +1,350 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { Buffer, Writer, Conn } from "deno"; +import { ServerRequest } from "../http/http.ts"; +import { BufReader, BufWriter } from "../io/bufio.ts"; +import { readLong, readShort, sliceLongToBytes } from "../io/ioutil.ts"; +import { Sha1 } from "./sha1.ts"; + +export const OpCodeContinue = 0x0; +export const OpCodeTextFrame = 0x1; +export const OpCodeBinaryFrame = 0x2; +export const OpCodeClose = 0x8; +export const OpcodePing = 0x9; +export const OpcodePong = 0xa; + +export type WebSocketEvent = + | string + | Uint8Array + | WebSocketCloseEvent + | WebSocketPingEvent + | WebSocketPongEvent; + +export type WebSocketCloseEvent = { + code: number; + reason?: string; +}; + +export function isWebSocketCloseEvent(a): a is WebSocketCloseEvent { + return a && typeof a["code"] === "number"; +} + +export type WebSocketPingEvent = ["ping", Uint8Array]; + +export function isWebSocketPingEvent(a): a is WebSocketPingEvent { + return Array.isArray(a) && a[0] === "ping" && a[1] instanceof Uint8Array; +} + +export type WebSocketPongEvent = ["pong", Uint8Array]; + +export function isWebSocketPongEvent(a): a is WebSocketPongEvent { + return Array.isArray(a) && a[0] === "pong" && a[1] instanceof Uint8Array; +} + +export class SocketClosedError extends Error {} + +export type WebSocketFrame = { + isLastFrame: boolean; + opcode: number; + mask?: Uint8Array; + payload: Uint8Array; +}; + +export type WebSocket = { + readonly isClosed: boolean; + receive(): AsyncIterableIterator; + send(data: string | Uint8Array): Promise; + ping(data?: string | Uint8Array): Promise; + close(code: number, reason?: string): Promise; +}; + +class WebSocketImpl implements WebSocket { + encoder = new TextEncoder(); + constructor(private conn: Conn, private mask?: Uint8Array) {} + + async *receive(): AsyncIterableIterator { + let frames: WebSocketFrame[] = []; + let payloadsLength = 0; + for await (const frame of receiveFrame(this.conn)) { + unmask(frame.payload, frame.mask); + switch (frame.opcode) { + case OpCodeTextFrame: + case OpCodeBinaryFrame: + case OpCodeContinue: + frames.push(frame); + payloadsLength += frame.payload.length; + if (frame.isLastFrame) { + const concat = new Uint8Array(payloadsLength); + let offs = 0; + for (const frame of frames) { + concat.set(frame.payload, offs); + offs += frame.payload.length; + } + if (frames[0].opcode === OpCodeTextFrame) { + // text + yield new Buffer(concat).toString(); + } else { + // binary + yield concat; + } + frames = []; + payloadsLength = 0; + } + break; + case OpCodeClose: + const code = (frame.payload[0] << 16) | frame.payload[1]; + const reason = new Buffer( + frame.payload.subarray(2, frame.payload.length) + ).toString(); + this._isClosed = true; + yield { code, reason }; + return; + case OpcodePing: + yield ["ping", frame.payload] as WebSocketPingEvent; + break; + case OpcodePong: + yield ["pong", frame.payload] as WebSocketPongEvent; + break; + } + } + } + + async send(data: string | Uint8Array): Promise { + if (this.isClosed) { + throw new SocketClosedError("socket has been closed"); + } + const opcode = + typeof data === "string" ? OpCodeTextFrame : OpCodeBinaryFrame; + const payload = typeof data === "string" ? this.encoder.encode(data) : data; + const isLastFrame = true; + await writeFrame( + { + isLastFrame, + opcode, + payload, + mask: this.mask + }, + this.conn + ); + } + + async ping(data: string | Uint8Array): Promise { + const payload = typeof data === "string" ? this.encoder.encode(data) : data; + await writeFrame( + { + isLastFrame: true, + opcode: OpCodeClose, + mask: this.mask, + payload + }, + this.conn + ); + } + + private _isClosed = false; + get isClosed() { + return this._isClosed; + } + + async close(code: number, reason?: string): Promise { + try { + const header = [code >>> 8, code & 0x00ff]; + let payload: Uint8Array; + if (reason) { + const reasonBytes = this.encoder.encode(reason); + payload = new Uint8Array(2 + reasonBytes.byteLength); + payload.set(header); + payload.set(reasonBytes, 2); + } else { + payload = new Uint8Array(header); + } + await writeFrame( + { + isLastFrame: true, + opcode: OpCodeClose, + mask: this.mask, + payload + }, + this.conn + ); + } catch (e) { + throw e; + } finally { + this.ensureSocketClosed(); + } + } + + private ensureSocketClosed(): Error { + if (this.isClosed) return; + try { + this.conn.close(); + } catch (e) { + console.error(e); + } finally { + this._isClosed = true; + } + } +} + +export async function* receiveFrame( + conn: Conn +): AsyncIterableIterator { + let receiving = true; + const reader = new BufReader(conn); + while (receiving) { + const frame = await readFrame(reader); + switch (frame.opcode) { + case OpCodeTextFrame: + case OpCodeBinaryFrame: + case OpCodeContinue: + yield frame; + break; + case OpCodeClose: + await writeFrame( + { + isLastFrame: true, + opcode: OpCodeClose, + payload: frame.payload + }, + conn + ); + conn.close(); + yield frame; + receiving = false; + break; + case OpcodePing: + await writeFrame( + { + isLastFrame: true, + opcode: OpcodePong, + payload: frame.payload + }, + conn + ); + yield frame; + break; + case OpcodePong: + yield frame; + break; + } + } +} + +export async function writeFrame(frame: WebSocketFrame, writer: Writer) { + let payloadLength = frame.payload.byteLength; + let header: Uint8Array; + const hasMask = (frame.mask ? 1 : 0) << 7; + if (payloadLength < 126) { + header = new Uint8Array([ + (0b1000 << 4) | frame.opcode, + hasMask | payloadLength + ]); + } else if (payloadLength < 0xffff) { + header = new Uint8Array([ + (0b1000 << 4) | frame.opcode, + hasMask | 0b01111110, + payloadLength >>> 8, + payloadLength & 0x00ff + ]); + } else { + header = new Uint8Array([ + (0b1000 << 4) | frame.opcode, + hasMask | 0b01111111, + ...sliceLongToBytes(payloadLength) + ]); + } + if (frame.mask) { + unmask(frame.payload, frame.mask); + } + const bytes = new Uint8Array(header.length + payloadLength); + bytes.set(header, 0); + bytes.set(frame.payload, header.length); + const w = new BufWriter(writer); + await w.write(bytes); + await w.flush(); +} + +export function unmask(payload: Uint8Array, mask: Uint8Array) { + if (mask) { + for (let i = 0; i < payload.length; i++) { + payload[i] ^= mask[i % 4]; + } + } +} + +export function acceptable(req: ServerRequest): boolean { + return ( + req.headers.get("upgrade") === "websocket" && + req.headers.has("sec-websocket-key") + ); +} + +export async function acceptWebSocket(req: ServerRequest): Promise { + if (acceptable(req)) { + const sock = new WebSocketImpl(req.conn); + const secKey = req.headers.get("sec-websocket-key"); + const secAccept = createSecAccept(secKey); + await req.respond({ + status: 101, + headers: new Headers({ + Upgrade: "websocket", + Connection: "Upgrade", + "Sec-WebSocket-Accept": secAccept + }) + }); + return sock; + } + throw new Error("request is not acceptable"); +} + +const kGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + +export function createSecAccept(nonce: string) { + const sha1 = new Sha1(); + sha1.update(nonce + kGUID); + const bytes = sha1.digest(); + const hash = bytes.reduce( + (data, byte) => data + String.fromCharCode(byte), + "" + ); + return btoa(hash); +} + +export async function readFrame(buf: BufReader): Promise { + let b = await buf.readByte(); + let isLastFrame = false; + switch (b >>> 4) { + case 0b1000: + isLastFrame = true; + break; + case 0b0000: + isLastFrame = false; + break; + default: + throw new Error("invalid signature"); + } + const opcode = b & 0x0f; + // has_mask & payload + b = await buf.readByte(); + const hasMask = b >>> 7; + let payloadLength = b & 0b01111111; + if (payloadLength === 126) { + payloadLength = await readShort(buf); + } else if (payloadLength === 127) { + payloadLength = await readLong(buf); + } + // mask + let mask; + if (hasMask) { + mask = new Uint8Array(4); + await buf.readFull(mask); + } + // payload + const payload = new Uint8Array(payloadLength); + await buf.readFull(payload); + return { + isLastFrame, + opcode, + mask, + payload + }; +} diff --git a/ws/sha1.ts b/ws/sha1.ts new file mode 100644 index 000000000..036c3c552 --- /dev/null +++ b/ws/sha1.ts @@ -0,0 +1,382 @@ +/* + * [js-sha1]{@link https://github.com/emn178/js-sha1} + * + * @version 0.6.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2014-2017 + * @license MIT + */ +/*jslint bitwise: true */ + +const HEX_CHARS = "0123456789abcdef".split(""); +const EXTRA = [-2147483648, 8388608, 32768, 128]; +const SHIFT = [24, 16, 8, 0]; + +const blocks = []; + +export class Sha1 { + blocks; + block; + start; + bytes; + hBytes; + finalized; + hashed; + first; + + h0 = 0x67452301; + h1 = 0xefcdab89; + h2 = 0x98badcfe; + h3 = 0x10325476; + h4 = 0xc3d2e1f0; + lastByteIndex = 0; + + constructor(sharedMemory: boolean = false) { + if (sharedMemory) { + blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + this.blocks = blocks; + } else { + this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } + + this.h0 = 0x67452301; + this.h1 = 0xefcdab89; + this.h2 = 0x98badcfe; + this.h3 = 0x10325476; + this.h4 = 0xc3d2e1f0; + + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; + } + + update(data: string | ArrayBuffer) { + if (this.finalized) { + return; + } + let message; + let notString = typeof data !== "string"; + if (notString && data instanceof ArrayBuffer) { + message = new Uint8Array(data); + } else { + message = data; + } + let code, + index = 0, + i, + length = message.length || 0, + blocks = this.blocks; + + while (index < length) { + if (this.hashed) { + this.hashed = false; + blocks[0] = this.block; + blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + } + + if (notString) { + for (i = this.start; index < length && i < 64; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else { + code = + 0x10000 + + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + } + } + + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } else { + this.start = i; + } + } + if (this.bytes > 4294967295) { + this.hBytes += (this.bytes / 4294967296) << 0; + this.bytes = this.bytes % 4294967296; + } + return this; + } + + finalize() { + if (this.finalized) { + return; + } + this.finalized = true; + let blocks = this.blocks, + i = this.lastByteIndex; + blocks[16] = this.block; + blocks[i >> 2] |= EXTRA[i & 3]; + this.block = blocks[16]; + if (i >= 56) { + if (!this.hashed) { + this.hash(); + } + blocks[0] = this.block; + blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + } + blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29); + blocks[15] = this.bytes << 3; + this.hash(); + } + + hash() { + let a = this.h0, + b = this.h1, + c = this.h2, + d = this.h3, + e = this.h4; + let f, + j, + t, + blocks = this.blocks; + + for (j = 16; j < 80; ++j) { + t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16]; + blocks[j] = (t << 1) | (t >>> 31); + } + + for (j = 0; j < 20; j += 5) { + f = (b & c) | (~b & d); + t = (a << 5) | (a >>> 27); + e = (t + f + e + 1518500249 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + + f = (a & b) | (~a & c); + t = (e << 5) | (e >>> 27); + d = (t + f + d + 1518500249 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + + f = (e & a) | (~e & b); + t = (d << 5) | (d >>> 27); + c = (t + f + c + 1518500249 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + + f = (d & e) | (~d & a); + t = (c << 5) | (c >>> 27); + b = (t + f + b + 1518500249 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + + f = (c & d) | (~c & e); + t = (b << 5) | (b >>> 27); + a = (t + f + a + 1518500249 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + + for (; j < 40; j += 5) { + f = b ^ c ^ d; + t = (a << 5) | (a >>> 27); + e = (t + f + e + 1859775393 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + + f = a ^ b ^ c; + t = (e << 5) | (e >>> 27); + d = (t + f + d + 1859775393 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + + f = e ^ a ^ b; + t = (d << 5) | (d >>> 27); + c = (t + f + c + 1859775393 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + + f = d ^ e ^ a; + t = (c << 5) | (c >>> 27); + b = (t + f + b + 1859775393 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + + f = c ^ d ^ e; + t = (b << 5) | (b >>> 27); + a = (t + f + a + 1859775393 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + + for (; j < 60; j += 5) { + f = (b & c) | (b & d) | (c & d); + t = (a << 5) | (a >>> 27); + e = (t + f + e - 1894007588 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + + f = (a & b) | (a & c) | (b & c); + t = (e << 5) | (e >>> 27); + d = (t + f + d - 1894007588 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + + f = (e & a) | (e & b) | (a & b); + t = (d << 5) | (d >>> 27); + c = (t + f + c - 1894007588 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + + f = (d & e) | (d & a) | (e & a); + t = (c << 5) | (c >>> 27); + b = (t + f + b - 1894007588 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + + f = (c & d) | (c & e) | (d & e); + t = (b << 5) | (b >>> 27); + a = (t + f + a - 1894007588 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + + for (; j < 80; j += 5) { + f = b ^ c ^ d; + t = (a << 5) | (a >>> 27); + e = (t + f + e - 899497514 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + + f = a ^ b ^ c; + t = (e << 5) | (e >>> 27); + d = (t + f + d - 899497514 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + + f = e ^ a ^ b; + t = (d << 5) | (d >>> 27); + c = (t + f + c - 899497514 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + + f = d ^ e ^ a; + t = (c << 5) | (c >>> 27); + b = (t + f + b - 899497514 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + + f = c ^ d ^ e; + t = (b << 5) | (b >>> 27); + a = (t + f + a - 899497514 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + + this.h0 = (this.h0 + a) << 0; + this.h1 = (this.h1 + b) << 0; + this.h2 = (this.h2 + c) << 0; + this.h3 = (this.h3 + d) << 0; + this.h4 = (this.h4 + e) << 0; + } + + hex() { + this.finalize(); + + let h0 = this.h0, + h1 = this.h1, + h2 = this.h2, + h3 = this.h3, + h4 = this.h4; + + return ( + HEX_CHARS[(h0 >> 28) & 0x0f] + + HEX_CHARS[(h0 >> 24) & 0x0f] + + HEX_CHARS[(h0 >> 20) & 0x0f] + + HEX_CHARS[(h0 >> 16) & 0x0f] + + HEX_CHARS[(h0 >> 12) & 0x0f] + + HEX_CHARS[(h0 >> 8) & 0x0f] + + HEX_CHARS[(h0 >> 4) & 0x0f] + + HEX_CHARS[h0 & 0x0f] + + HEX_CHARS[(h1 >> 28) & 0x0f] + + HEX_CHARS[(h1 >> 24) & 0x0f] + + HEX_CHARS[(h1 >> 20) & 0x0f] + + HEX_CHARS[(h1 >> 16) & 0x0f] + + HEX_CHARS[(h1 >> 12) & 0x0f] + + HEX_CHARS[(h1 >> 8) & 0x0f] + + HEX_CHARS[(h1 >> 4) & 0x0f] + + HEX_CHARS[h1 & 0x0f] + + HEX_CHARS[(h2 >> 28) & 0x0f] + + HEX_CHARS[(h2 >> 24) & 0x0f] + + HEX_CHARS[(h2 >> 20) & 0x0f] + + HEX_CHARS[(h2 >> 16) & 0x0f] + + HEX_CHARS[(h2 >> 12) & 0x0f] + + HEX_CHARS[(h2 >> 8) & 0x0f] + + HEX_CHARS[(h2 >> 4) & 0x0f] + + HEX_CHARS[h2 & 0x0f] + + HEX_CHARS[(h3 >> 28) & 0x0f] + + HEX_CHARS[(h3 >> 24) & 0x0f] + + HEX_CHARS[(h3 >> 20) & 0x0f] + + HEX_CHARS[(h3 >> 16) & 0x0f] + + HEX_CHARS[(h3 >> 12) & 0x0f] + + HEX_CHARS[(h3 >> 8) & 0x0f] + + HEX_CHARS[(h3 >> 4) & 0x0f] + + HEX_CHARS[h3 & 0x0f] + + HEX_CHARS[(h4 >> 28) & 0x0f] + + HEX_CHARS[(h4 >> 24) & 0x0f] + + HEX_CHARS[(h4 >> 20) & 0x0f] + + HEX_CHARS[(h4 >> 16) & 0x0f] + + HEX_CHARS[(h4 >> 12) & 0x0f] + + HEX_CHARS[(h4 >> 8) & 0x0f] + + HEX_CHARS[(h4 >> 4) & 0x0f] + + HEX_CHARS[h4 & 0x0f] + ); + } + + toString() { + return this.hex(); + } + + digest() { + this.finalize(); + + let h0 = this.h0, + h1 = this.h1, + h2 = this.h2, + h3 = this.h3, + h4 = this.h4; + + return [ + (h0 >> 24) & 0xff, + (h0 >> 16) & 0xff, + (h0 >> 8) & 0xff, + h0 & 0xff, + (h1 >> 24) & 0xff, + (h1 >> 16) & 0xff, + (h1 >> 8) & 0xff, + h1 & 0xff, + (h2 >> 24) & 0xff, + (h2 >> 16) & 0xff, + (h2 >> 8) & 0xff, + h2 & 0xff, + (h3 >> 24) & 0xff, + (h3 >> 16) & 0xff, + (h3 >> 8) & 0xff, + h3 & 0xff, + (h4 >> 24) & 0xff, + (h4 >> 16) & 0xff, + (h4 >> 8) & 0xff, + h4 & 0xff + ]; + } + + array() { + return this.digest(); + } + + arrayBuffer() { + this.finalize(); + + let buffer = new ArrayBuffer(20); + let dataView = new DataView(buffer); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + return buffer; + } +} diff --git a/ws/sha1_test.ts b/ws/sha1_test.ts new file mode 100644 index 000000000..b385f18da --- /dev/null +++ b/ws/sha1_test.ts @@ -0,0 +1,8 @@ +import { assertEqual, test } from "../testing/mod.ts"; +import { Sha1 } from "./sha1.ts"; + +test(function testSha1() { + const sha1 = new Sha1(); + sha1.update("abcde"); + assertEqual(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); +}); diff --git a/ws/test.ts b/ws/test.ts new file mode 100644 index 000000000..bf800f7e3 --- /dev/null +++ b/ws/test.ts @@ -0,0 +1,138 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { Buffer } from "deno"; +import { BufReader } from "../io/bufio.ts"; +import { test, assert, assertEqual } from "../testing/mod.ts"; +import { + createSecAccept, + OpCodeBinaryFrame, + OpCodeContinue, + OpcodePing, + OpcodePong, + OpCodeTextFrame, + readFrame, + unmask +} from "./mod.ts"; +import { serve } from "../http/http.ts"; + +test(async function testReadUnmaskedTextFrame() { + // unmasked single text frame with payload "Hello" + const buf = new BufReader( + new Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) + ); + const frame = await readFrame(buf); + assertEqual(frame.opcode, OpCodeTextFrame); + assertEqual(frame.mask, undefined); + assertEqual(new Buffer(frame.payload).toString(), "Hello"); + assertEqual(frame.isLastFrame, true); +}); + +test(async function testReadMakedTextFrame() { + //a masked single text frame with payload "Hello" + const buf = new BufReader( + new Buffer( + new Uint8Array([ + 0x81, + 0x85, + 0x37, + 0xfa, + 0x21, + 0x3d, + 0x7f, + 0x9f, + 0x4d, + 0x51, + 0x58 + ]) + ) + ); + const frame = await readFrame(buf); + console.dir(frame); + assertEqual(frame.opcode, OpCodeTextFrame); + unmask(frame.payload, frame.mask); + assertEqual(new Buffer(frame.payload).toString(), "Hello"); + assertEqual(frame.isLastFrame, true); +}); + +test(async function testReadUnmaskedSplittedTextFrames() { + const buf1 = new BufReader( + new Buffer(new Uint8Array([0x01, 0x03, 0x48, 0x65, 0x6c])) + ); + const buf2 = new BufReader( + new Buffer(new Uint8Array([0x80, 0x02, 0x6c, 0x6f])) + ); + const [f1, f2] = await Promise.all([readFrame(buf1), readFrame(buf2)]); + assertEqual(f1.isLastFrame, false); + assertEqual(f1.mask, undefined); + assertEqual(f1.opcode, OpCodeTextFrame); + assertEqual(new Buffer(f1.payload).toString(), "Hel"); + + assertEqual(f2.isLastFrame, true); + assertEqual(f2.mask, undefined); + assertEqual(f2.opcode, OpCodeContinue); + assertEqual(new Buffer(f2.payload).toString(), "lo"); +}); + +test(async function testReadUnmaksedPingPongFrame() { + // unmasked ping with payload "Hello" + const buf = new BufReader( + new Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) + ); + const ping = await readFrame(buf); + assertEqual(ping.opcode, OpcodePing); + assertEqual(new Buffer(ping.payload).toString(), "Hello"); + + const buf2 = new BufReader( + new Buffer( + new Uint8Array([ + 0x8a, + 0x85, + 0x37, + 0xfa, + 0x21, + 0x3d, + 0x7f, + 0x9f, + 0x4d, + 0x51, + 0x58 + ]) + ) + ); + const pong = await readFrame(buf2); + assertEqual(pong.opcode, OpcodePong); + assert(pong.mask !== undefined); + unmask(pong.payload, pong.mask); + assertEqual(new Buffer(pong.payload).toString(), "Hello"); +}); + +test(async function testReadUnmaksedBigBinaryFrame() { + let a = [0x82, 0x7e, 0x01, 0x00]; + for (let i = 0; i < 256; i++) { + a.push(i); + } + const buf = new BufReader(new Buffer(new Uint8Array(a))); + const bin = await readFrame(buf); + assertEqual(bin.opcode, OpCodeBinaryFrame); + assertEqual(bin.isLastFrame, true); + assertEqual(bin.mask, undefined); + assertEqual(bin.payload.length, 256); +}); + +test(async function testReadUnmaskedBigBigBinaryFrame() { + let a = [0x82, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]; + for (let i = 0; i < 0xffff; i++) { + a.push(i); + } + const buf = new BufReader(new Buffer(new Uint8Array(a))); + const bin = await readFrame(buf); + assertEqual(bin.opcode, OpCodeBinaryFrame); + assertEqual(bin.isLastFrame, true); + assertEqual(bin.mask, undefined); + assertEqual(bin.payload.length, 0xffff + 1); +}); + +test(async function testCreateSecAccept() { + const nonce = "dGhlIHNhbXBsZSBub25jZQ=="; + const d = createSecAccept(nonce); + assertEqual(d, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); +}); -- cgit v1.2.3 From 429fcbf77a850df7067cf91a879c2d0bac5836df Mon Sep 17 00:00:00 2001 From: hkdnet Date: Mon, 14 Jan 2019 02:40:57 +0900 Subject: Remove an unnecessary code block (denoland/deno_std#107) Original: https://github.com/denoland/deno_std/commit/9f1de43cc47b0bee4d7d04a1b3ebc238333575bc --- media_types/README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/media_types/README.md b/media_types/README.md index dbc895f7b..0cdc1c8be 100644 --- a/media_types/README.md +++ b/media_types/README.md @@ -87,7 +87,3 @@ types.get("ts"); // "application/javascript" Adapted from [mime-type](https://github.com/jshttp/mime-types). MIT License. - -``` - -``` -- cgit v1.2.3 From 4a7945098807172efc71f319001e6245079c0f14 Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Mon, 14 Jan 2019 10:55:23 +1000 Subject: Improve re-exports in http (denoland/deno_std#111) Original: https://github.com/denoland/deno_std/commit/b99d7d3e0f61216db7b5a5ad2bc254f8ac97ff4d --- http/mod.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/http/mod.ts b/http/mod.ts index 217bd68b3..a89f04417 100644 --- a/http/mod.ts +++ b/http/mod.ts @@ -1,8 +1,7 @@ -import { +export { serve, listenAndServe, Response, setContentLength, ServerRequest } from "./http.ts"; -export { serve, listenAndServe, Response, setContentLength, ServerRequest }; -- cgit v1.2.3 From 096e0b36e64074f704a692e6c18b5b694fd5d475 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=BF=B7=E6=B8=A1?= Date: Mon, 14 Jan 2019 13:34:46 +0800 Subject: fix wrong links for flags (denoland/deno_std#112) Original: https://github.com/denoland/deno_std/commit/1d64eba63df97ec70910560140bd1a1b87763fa7 --- flags/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flags/README.md b/flags/README.md index 9d09a2210..7b63006d6 100644 --- a/flags/README.md +++ b/flags/README.md @@ -6,7 +6,7 @@ Command line arguments parser for Deno based on minimist ```ts import { args } from "deno"; -import { parse } from "https://deno.land/x/flags/index.ts"; +import { parse } from "https://deno.land/x/flags/mod.ts"; console.dir(parse(args)); ``` -- cgit v1.2.3 From 61b401c63a4a7bd069672842f94d1b4c09a73b60 Mon Sep 17 00:00:00 2001 From: Yungoo Kong Date: Mon, 14 Jan 2019 15:46:00 +0900 Subject: Fix wrong links (denoland/deno_std#106) Original: https://github.com/denoland/deno_std/commit/39cfdb48a88527306e630b57eaa08ef42e38fb20 --- README.md | 4 ++-- log/README.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 13a1bd0e8..3d2f1901b 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Command line arguments parser. -- **[logging](./logging/)** +- **[log](./log/)** Command line logging @@ -22,7 +22,7 @@ Make directory branches. -- **[net](./net/)** +- **[http](./http/)** A framework for creating HTTP/HTTPS servers inspired by GoLang. diff --git a/log/README.md b/log/README.md index 1d88cb070..8ea5056c0 100644 --- a/log/README.md +++ b/log/README.md @@ -1,7 +1,7 @@ # Basic usage ```ts -import * as log from "https://deno.land/x/std/logging/index.ts"; +import * as log from "https://deno.land/x/std/log/mod.ts"; // simple console logger log.debug("Hello world"); -- cgit v1.2.3 From f1ac2b9540174e150e7fc0d201cd661961f05143 Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Tue, 15 Jan 2019 22:01:58 +1000 Subject: Fix media_types running under Deno with ESM (denoland/deno_std#113) And bump CI to v0.2.7 Original: https://github.com/denoland/deno_std/commit/77b3391a21fc823f891f85c854c2bc58f9ad298f --- azure-pipelines.yml | 2 +- media_types/deps.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 600f74227..1bb173ad2 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,5 +1,5 @@ variables: - DENO_VERSION: 'v0.2.6' + DENO_VERSION: 'v0.2.7' jobs: diff --git a/media_types/deps.ts b/media_types/deps.ts index e305f6831..bc08f3a48 100644 --- a/media_types/deps.ts +++ b/media_types/deps.ts @@ -11,5 +11,5 @@ interface DB { }; } -import * as _db from "./db_1.37.0.json"; +import _db from "./db_1.37.0.json"; export const db: DB = _db; -- cgit v1.2.3 From 0c74c8ebc40c61803d096bb8e590111f5d2733f9 Mon Sep 17 00:00:00 2001 From: "Kwang-in (Dennis) Jung" Date: Wed, 16 Jan 2019 01:09:55 +0900 Subject: Improve http/README (denoland/deno_std#114) Original: https://github.com/denoland/deno_std/commit/6c5bdc58bad12626152c5903e52c2457a5f81883 --- format.ts | 2 +- http/README.md | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/format.ts b/format.ts index f1fa19e23..2e7b9a606 100755 --- a/format.ts +++ b/format.ts @@ -30,7 +30,7 @@ async function main() { args: [ "bash", "-c", - "prettier --write *.ts */*.ts */**/*.ts *.md */**/*.md" + "prettier --write *.ts */*.ts */**/*.ts *.md */*.md */**/*.md" ] }); const s = await prettier.status(); diff --git a/http/README.md b/http/README.md index e81e42a41..c598cdef4 100644 --- a/http/README.md +++ b/http/README.md @@ -1,6 +1,8 @@ -# net +# http -Usage: +A framework for creating HTTP/HTTPS server. + +## Example ```typescript import { serve } from "https://deno.land/x/http/mod.ts"; -- cgit v1.2.3 From 80d30f0bdcaee346b64b09b6a4ed429ada958a89 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Tue, 15 Jan 2019 12:28:09 -0500 Subject: Improve readme (denoland/deno_std#117) Original: https://github.com/denoland/deno_std/commit/6a41189a98e29b0c233f12610220490b6deed608 --- README.md | 53 +++++++++++++++++++++-------------------------------- 1 file changed, 21 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 3d2f1901b..f0f3a90fc 100644 --- a/README.md +++ b/README.md @@ -2,52 +2,41 @@ [![Build Status](https://dev.azure.com/denoland/deno_std/_apis/build/status/denoland.deno_std?branchName=master)](https://dev.azure.com/denoland/deno_std/_build/latest?definitionId=2?branchName=master) -- **[colors](./colors/)** +These modules do not have external dependencies and they are reviewed by the +Deno core team. The intention is to have a standard set of high quality code +that all Deno projects can use fearlessly. - Modules that generate ANSI color codes for the console. +Contributions are welcome! -- **[flags](./flags/)** +## How to use - Command line arguments parser. +These modules are tagged in accordance with Deno releases. So, for example, the +v0.2.6 tag is guaranteed to work with deno v0.2.6. +You can link to v0.2.6 using the URL `https://deno.land/x/std@v0.2.6/` -- **[log](./log/)** - - Command line logging - -- **[media_types](./media_types/)** - - A library for resolving media types (MIME types) and extensions. - -- **[mkdirp](./fs/)** - - Make directory branches. - -- **[http](./http/)** - - A framework for creating HTTP/HTTPS servers inspired by GoLang. - -- **[path](./fs/path)** - - File path manipulation. - -- **[testing](./testing/)** - - Testing +It's strongly recommended that you link to tagged releases rather than the +master branch. The project is still young and we expect disruptive renames in +the future. ## Style Guide +### Use TypeScript + ### Use the term "module" instead of "library" or "package" For clarity and consistency avoid the terms "library" and "package". Instead use "module" to refer to a single JS or TS file and also to refer to a directory of TS/JS code. -### Use the filename "mod.ts" as the default entry point to a directory of code +### Do not use the filename `index.ts` nor `index.js` + +Deno does not treat "index.js" or "index.ts" in a special way. By using these +filenames, it suggests that they can be left out of the module specifier when +they cannot. This is confusing. -`index.ts` comes with the wrong connotations - and `main.ts` should be reserved -for executable programs. The filename `mod.ts` follows Rust’s convention, is -shorter than `index.ts`, and doesn’t come with any preconceived notions about -how it might work. +If a directory of code needs a default entry point, use the filename `mod.ts`. +The filename `mod.ts` follows Rust’s convention, is shorter than `index.ts`, and +doesn’t come with any preconceived notions about how it might work. ### Within `deno_std`, do not depend on external code -- cgit v1.2.3 From 8dd76af9ab7caa6f92b8a89a7adc61504dc7d277 Mon Sep 17 00:00:00 2001 From: James Garbutt <43081j@users.noreply.github.com> Date: Tue, 15 Jan 2019 21:16:52 +0000 Subject: colors: add test cases (denoland/deno_std#120) Original: https://github.com/denoland/deno_std/commit/388bc47ea7569b97c1a729343970c3cdb376c668 --- colors/test.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/colors/test.ts b/colors/test.ts index 1acc30072..266868090 100644 --- a/colors/test.ts +++ b/colors/test.ts @@ -7,5 +7,19 @@ test(function singleColor() { }); test(function doubleColor() { - assertEqual(color.red.bgBlue("Hello world"), "Hello world"); + assertEqual(color.red.bgBlue("Hello world"), + "Hello world"); +}); + +test(function newLinesContinueColors() { + assertEqual(color.red("Hello\nworld"), + "Hello\nworld"); + assertEqual(color.red("Hello\r\nworld"), + "Hello\r\nworld"); + assertEqual(color.red("Hello\n\nworld"), + "Hello\n\nworld"); +}); + +test(function replacesCloseCharacters() { + assertEqual(color.red("Hello"), "Hello"); }); -- cgit v1.2.3 From 7cb7b24537cd3771f8d2a02bdae9bffc9c7fcbb8 Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Wed, 16 Jan 2019 13:57:40 +1100 Subject: Improve assert (denoland/deno_std#124) Original: https://github.com/denoland/deno_std/commit/9a3eb207dcd1d032a3c3f7e60f8ee9c5e793f022 --- testing/README.md | 91 ++++++++++++++++++++++++++++++++++++++++------ testing/mod.ts | 88 +++++++++++++++++++++++++++++++++++++++++++-- testing/test.ts | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 273 insertions(+), 12 deletions(-) diff --git a/testing/README.md b/testing/README.md index 70968e3c7..49a6526fe 100644 --- a/testing/README.md +++ b/testing/README.md @@ -1,14 +1,41 @@ # Testing +This module provides a few basic utilities to make testing easier and +consistent in Deno. + ## Usage +The module exports a `test` function which is the test harness in Deno. It +accepts either a function (including async functions) or an object which +contains a `name` property and a `fn` property. When running tests and +outputting the results, the name of the past function is used, or if the +object is passed, the `name` property is used to identify the test. + +The module also exports `assert`, `assertEqual`, and `equal`. + +`equal` is a deep comparision function, where `actual` and `expected` are +compared deeply, and if they vary, `equal` returns `false`. + +The export `assert` is a function, but it is also decorated with other useful +functions: + +- `assert()` - Expects a boolean value, throws if the value is `false`. +- `assert.equal()` - Uses the `equal` comparison and throws if the `actual` and + `expected` are not equal. +- `assert.strictEqual()` - Compares `actual` and `expected` strictly, therefore + for non-primitives the values must reference the same instance. +- `assert.throws()` - Expects the passed `fn` to throw. If `fn` does not throw, + this function does. Also compares any errors thrown to an optional expected + `Error` class and checks that the error `.message` includes an optional + string. + +`assertEqual()` is the same as `assert.equal()` but maintained for backwards +compatibility. + +Basic usage: + ```ts -import { - test, - assert, - equal, - assertEqual -} from "https://deno.land/x/testing/mod.ts"; +import { test, assert, equal } from "https://deno.land/x/testing/mod.ts"; test({ name: "testing example", @@ -17,8 +44,8 @@ test({ assert(!equal("hello", "world")); assert(equal({ hello: "world" }, { hello: "world" })); assert(!equal({ world: "hello" }, { hello: "world" })); - assertEqual("world", "world"); - assertEqual({ hello: "world" }, { hello: "world" }); + assert.equal("world", "world"); + assert.equal({ hello: "world" }, { hello: "world" }); } }); ``` @@ -31,7 +58,51 @@ test(function example() { assert(!equal("hello", "world")); assert(equal({ hello: "world" }, { hello: "world" })); assert(!equal({ world: "hello" }, { hello: "world" })); - assertEqual("world", "world"); - assertEqual({ hello: "world" }, { hello: "world" }); + assert.equal("world", "world"); + assert.equal({ hello: "world" }, { hello: "world" }); +}); +``` + +Using `assert.strictEqual()`: + +```ts +test(function isStrictlyEqual() { + const a = {}; + const b = a; + assert.strictEqual(a, b); +}); + +// This test fails +test(function isNotStrictlyEqual() { + const a = {}; + const b = {}; + assert.strictEqual(a, b); +}); +``` + +Using `assert.throws()`: + +```ts +test(function doesThrow() { + assert.throws(() => { + throw new TypeError("hello world!"); + }); + assert.throws(() => { + throw new TypeError("hello world!"); + }, TypeError); + assert.throws( + () => { + throw new TypeError("hello world!"); + }, + TypeError, + "hello" + ); +}); + +// This test will not pass +test(function fails() { + assert.throws(() => { + console.log("Hello world"); + }); }); ``` diff --git a/testing/mod.ts b/testing/mod.ts index 96fe3f11f..1de5f55bc 100644 --- a/testing/mod.ts +++ b/testing/mod.ts @@ -29,11 +29,95 @@ export function assertEqual(actual: unknown, expected: unknown, msg?: string) { } } -export function assert(expr: boolean, msg = "") { +interface Constructor { + new (...args: any[]): any; +} + +interface Assert { + /** Make an assertion, if not true, then throw. */ + (expr: boolean, msg?: string): void; + + /** Make an assertion that `actual` and `expected` are equal, deeply. If not + * deeply equal, then throw. + */ + equal(actual: unknown, expected: unknown, msg?: string): void; + + /** Make an assertion that `actual` and `expected` are strictly equal. If + * not then throw. + */ + strictEqual(actual: unknown, expected: unknown, msg?: string): void; + + /** Executes a function, expecting it to throw. If it does not, then it + * throws. An error class and a string that should be included in the + * error message can also be asserted. + */ + throws(fn: () => void, errorClass?: Constructor, msgIncludes?: string): void; +} + +export const assert = function assert(expr: boolean, msg = "") { if (!expr) { throw new Error(msg); } -} +} as Assert; + +assert.equal = assertEqual; +assert.strictEqual = function strictEqual(actual, expected, msg = "") { + if (actual !== expected) { + let actualString: string; + let expectedString: string; + try { + actualString = String(actual); + } catch (e) { + actualString = "[Cannot display]"; + } + try { + expectedString = String(expected); + } catch (e) { + expectedString = "[Cannot display]"; + } + console.error( + "strictEqual failed. actual =", + actualString, + "expected =", + expectedString + ); + if (!msg) { + msg = `actual: ${actualString} expected: ${expectedString}`; + } + throw new Error(msg); + } +}; +assert.throws = function throws( + fn, + ErrorClass: Constructor, + msgIncludes = "", + msg = "" +) { + let doesThrow = false; + try { + fn(); + } catch (e) { + if (ErrorClass && !(Object.getPrototypeOf(e) === ErrorClass.prototype)) { + msg = `Expected error to be instance of "${ErrorClass.name}"${ + msg ? `: ${msg}` : "." + }`; + throw new Error(msg); + } + if (msgIncludes) { + if (!e.message.includes(msgIncludes)) { + msg = `Expected error message to include "${msgIncludes}", but got "${ + e.message + }"${msg ? `: ${msg}` : "."}`; + throw new Error(msg); + } + } + doesThrow = true; + } + if (!doesThrow) { + msg = `Expected function to throw${msg ? `: ${msg}` : "."}`; + throw new Error(msg); + } +}; export function equal(c: unknown, d: unknown): boolean { const seen = new Map(); diff --git a/testing/test.ts b/testing/test.ts index 7012a6e47..34b2762b4 100644 --- a/testing/test.ts +++ b/testing/test.ts @@ -28,6 +28,7 @@ test(function testingAssertEqual() { const a = Object.create(null); a.b = "foo"; assertEqual(a, a); + assert(assert.equal === assertEqual); }); test(function testingAssertEqualActualUncoercable() { @@ -55,3 +56,108 @@ test(function testingAssertEqualExpectedUncoercable() { } assert(didThrow); }); + +test(function testingAssertStrictEqual() { + const a = {}; + const b = a; + assert.strictEqual(a, b); +}); + +test(function testingAssertNotStrictEqual() { + let didThrow = false; + const a = {}; + const b = {}; + try { + assert.strictEqual(a, b); + } catch (e) { + assert(e.message === "actual: [object Object] expected: [object Object]"); + didThrow = true; + } + assert(didThrow); +}); + +test(function testingDoesThrow() { + let count = 0; + assert.throws(() => { + count++; + throw new Error(); + }); + assert(count === 1); +}); + +test(function testingDoesNotThrow() { + let count = 0; + let didThrow = false; + try { + assert.throws(() => { + count++; + console.log("Hello world"); + }); + } catch (e) { + assert(e.message === "Expected function to throw."); + didThrow = true; + } + assert(count === 1); + assert(didThrow); +}); + +test(function testingThrowsErrorType() { + let count = 0; + assert.throws(() => { + count++; + throw new TypeError(); + }, TypeError); + assert(count === 1); +}); + +test(function testingThrowsNotErrorType() { + let count = 0; + let didThrow = false; + try { + assert.throws(() => { + count++; + throw new TypeError(); + }, RangeError); + } catch (e) { + assert(e.message === `Expected error to be instance of "RangeError".`); + didThrow = true; + } + assert(count === 1); + assert(didThrow); +}); + +test(function testingThrowsMsgIncludes() { + let count = 0; + assert.throws( + () => { + count++; + throw new TypeError("Hello world!"); + }, + TypeError, + "world" + ); + assert(count === 1); +}); + +test(function testingThrowsMsgNotIncludes() { + let count = 0; + let didThrow = false; + try { + assert.throws( + () => { + count++; + throw new TypeError("Hello world!"); + }, + TypeError, + "foobar" + ); + } catch (e) { + assert( + e.message === + `Expected error message to include "foobar", but got "Hello world!".` + ); + didThrow = true; + } + assert(count === 1); + assert(didThrow); +}); -- cgit v1.2.3 From 811128864c4db40409c5c5538b56466e4f4e704c Mon Sep 17 00:00:00 2001 From: James Garbutt <43081j@users.noreply.github.com> Date: Wed, 16 Jan 2019 15:25:52 +0000 Subject: datetime: correct hh:mm formats and add test cases (denoland/deno_std#121) Original: https://github.com/denoland/deno_std/commit/cc40d3e984993afd5e6cdc4acab71676a278e7af --- datetime/mod.ts | 6 +++--- datetime/test.ts | 50 +++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/datetime/mod.ts b/datetime/mod.ts index c5e6bf0c4..5a967925d 100644 --- a/datetime/mod.ts +++ b/datetime/mod.ts @@ -57,13 +57,13 @@ export function parseDateTime( const datePattern = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/; [, y, m, d, ho, mi] = datePattern.exec(datetimeStr); } else if (format === "hh:mm mm-dd-yyyy") { - const datePattern = /^(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2})$/; + const datePattern = /^(\d{2}):(\d{2}) (\d{2})-(\d{2})-(\d{4})$/; [, ho, mi, m, d, y] = datePattern.exec(datetimeStr); } else if (format === "hh:mm dd-mm-yyyy") { - const datePattern = /^(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2})$/; + const datePattern = /^(\d{2}):(\d{2}) (\d{2})-(\d{2})-(\d{4})$/; [, ho, mi, d, m, y] = datePattern.exec(datetimeStr); } else if (format === "hh:mm yyyy-mm-dd") { - const datePattern = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/; + const datePattern = /^(\d{2}):(\d{2}) (\d{4})-(\d{2})-(\d{2})$/; [, ho, mi, y, m, d] = datePattern.exec(datetimeStr); } else { throw new Error("Invalid datetime format!"); diff --git a/datetime/test.ts b/datetime/test.ts index c0e0f89b1..5bc7eda21 100644 --- a/datetime/test.ts +++ b/datetime/test.ts @@ -1,4 +1,4 @@ -import { test, assertEqual } from "../testing/mod.ts"; +import { test, assertEqual, assert } from "../testing/mod.ts"; import * as datetime from "mod.ts"; test(function parseDateTime() { @@ -6,13 +6,61 @@ test(function parseDateTime() { datetime.parseDateTime("01-03-2019 16:34", "mm-dd-yyyy hh:mm"), new Date(2019, 1, 3, 16, 34) ); + assertEqual( + datetime.parseDateTime("03-01-2019 16:34", "dd-mm-yyyy hh:mm"), + new Date(2019, 1, 3, 16, 34) + ); + assertEqual( + datetime.parseDateTime("2019-01-03 16:34", "yyyy-mm-dd hh:mm"), + new Date(2019, 1, 3, 16, 34) + ); + assertEqual( + datetime.parseDateTime("16:34 01-03-2019", "hh:mm mm-dd-yyyy"), + new Date(2019, 1, 3, 16, 34) + ); + assertEqual( + datetime.parseDateTime("16:34 03-01-2019", "hh:mm dd-mm-yyyy"), + new Date(2019, 1, 3, 16, 34) + ); + assertEqual( + datetime.parseDateTime("16:34 2019-01-03", "hh:mm yyyy-mm-dd"), + new Date(2019, 1, 3, 16, 34) + ); +}); + +test(function invalidParseDateTimeFormatThrows() { + try { + (datetime as any).parseDateTime("2019-01-01 00:00", "x-y-z"); + assert(false, 'no exception was thrown'); + } catch (e) { + assertEqual(e.message, "Invalid datetime format!"); + } }); + test(function parseDate() { assertEqual( datetime.parseDate("01-03-2019", "mm-dd-yyyy"), new Date(2019, 1, 3) ); + assertEqual( + datetime.parseDate("03-01-2019", "dd-mm-yyyy"), + new Date(2019, 1, 3) + ); + assertEqual( + datetime.parseDate("2019-01-03", "yyyy-mm-dd"), + new Date(2019, 1, 3) + ); }); + +test(function invalidParseDateFormatThrows() { + try { + (datetime as any).parseDate("2019-01-01", "x-y-z"); + assert(false, 'no exception was thrown'); + } catch (e) { + assertEqual(e.message, "Invalid date format!"); + } +}); + test(function currentDayOfYear() { assertEqual( datetime.currentDayOfYear(), -- cgit v1.2.3 From b2e54bad61b37f3a186dd72237c694ada77ab94f Mon Sep 17 00:00:00 2001 From: Andy Hayden Date: Thu, 17 Jan 2019 10:08:59 -0800 Subject: Remove race-condition in file_server tests (denoland/deno_std#125) Original: https://github.com/denoland/deno_std/commit/e28c9a407951f10d952993ff6a7b248ca11243e1 --- examples/test.ts | 3 ++- http/file_server_test.ts | 65 +++++++++++++++++++++++++++++------------------- http/http.ts | 2 +- io/bufio.ts | 3 ++- io/util.ts | 6 ----- test.ts | 17 +++---------- 6 files changed, 47 insertions(+), 49 deletions(-) diff --git a/examples/test.ts b/examples/test.ts index f42db1bba..8d16e1703 100644 --- a/examples/test.ts +++ b/examples/test.ts @@ -13,7 +13,8 @@ test(function t2() { /** A more complicated test that runs a subprocess. */ test(async function catSmoke() { const p = run({ - args: ["deno", "examples/cat.ts", "README.md"] + args: ["deno", "examples/cat.ts", "README.md"], + stdout: "piped" }); const s = await p.status(); assertEqual(s.code, 0); diff --git a/http/file_server_test.ts b/http/file_server_test.ts index bd00d749b..f8b2429b0 100644 --- a/http/file_server_test.ts +++ b/http/file_server_test.ts @@ -1,23 +1,29 @@ -import { readFile } from "deno"; +import { readFile, run } from "deno"; import { test, assert, assertEqual } from "../testing/mod.ts"; +import { BufReader } from "../io/bufio.ts"; +import { TextProtoReader } from "../textproto/mod.ts"; -// Promise to completeResolve when all tests completes -let completeResolve; -export const completePromise = new Promise(res => (completeResolve = res)); -let completedTestCount = 0; - -function maybeCompleteTests() { - completedTestCount++; - // Change this when adding more tests - if (completedTestCount === 3) { - completeResolve(); - } +let fileServer; +async function startFileServer() { + fileServer = run({ + args: ["deno", "--allow-net", "http/file_server.ts", ".", "--cors"], + stdout: "piped" + }); + // Once fileServer is ready it will write to its stdout. + const r = new TextProtoReader(new BufReader(fileServer.stdout)); + const [s, err] = await r.readLine(); + assert(err == null); + assert(s.includes("server listening")); +} +function killFileServer() { + fileServer.close(); + fileServer.stdout.close(); } -export function runTests(serverReadyPromise: Promise) { - test(async function serveFile() { - await serverReadyPromise; +test(async function serveFile() { + await startFileServer(); + try { const res = await fetch("http://localhost:4500/azure-pipelines.yml"); assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-headers")); @@ -27,25 +33,32 @@ export function runTests(serverReadyPromise: Promise) { await readFile("./azure-pipelines.yml") ); assertEqual(downloadedFile, localFile); - maybeCompleteTests(); - }); + } finally { + killFileServer(); + } +}); - test(async function serveDirectory() { - await serverReadyPromise; +test(async function serveDirectory() { + await startFileServer(); + try { const res = await fetch("http://localhost:4500/"); assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-headers")); const page = await res.text(); assert(page.includes("azure-pipelines.yml")); - maybeCompleteTests(); - }); + } finally { + killFileServer(); + } +}); - test(async function serveFallback() { - await serverReadyPromise; +test(async function serveFallback() { + await startFileServer(); + try { const res = await fetch("http://localhost:4500/badfile.txt"); assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-headers")); assertEqual(res.status, 404); - maybeCompleteTests(); - }); -} + } finally { + killFileServer(); + } +}); diff --git a/http/http.ts b/http/http.ts index da7bc0169..fe25a5f6e 100644 --- a/http/http.ts +++ b/http/http.ts @@ -2,7 +2,7 @@ import { listen, Conn, toAsyncIterator, Reader, copy } from "deno"; import { BufReader, BufState, BufWriter } from "../io/bufio.ts"; import { TextProtoReader } from "../textproto/mod.ts"; import { STATUS_TEXT } from "./http_status.ts"; -import { assert } from "../io/util.ts"; +import { assert } from "../testing/mod.ts"; interface Deferred { promise: Promise<{}>; diff --git a/io/bufio.ts b/io/bufio.ts index 0dd2b94b4..05e6b0a0c 100644 --- a/io/bufio.ts +++ b/io/bufio.ts @@ -4,7 +4,8 @@ // license that can be found in the LICENSE file. import { Reader, ReadResult, Writer } from "deno"; -import { assert, charCode, copyBytes } from "./util.ts"; +import { charCode, copyBytes } from "./util.ts"; +import { assert } from "../testing/mod.ts"; const DEFAULT_BUF_SIZE = 4096; const MIN_BUF_SIZE = 16; diff --git a/io/util.ts b/io/util.ts index 811940b4d..3266e5018 100644 --- a/io/util.ts +++ b/io/util.ts @@ -1,11 +1,5 @@ import { Buffer, Reader } from "deno"; -export function assert(cond: boolean, msg = "assert") { - if (!cond) { - throw Error(msg); - } -} - // `off` is the offset into `dst` where it will at which to begin writing values // from `src`. // Returns the number of bytes copied. diff --git a/test.ts b/test.ts index 994148178..a128ce0a1 100755 --- a/test.ts +++ b/test.ts @@ -1,6 +1,4 @@ #!/usr/bin/env deno --allow-run --allow-net --allow-write -import { run } from "deno"; - import "colors/test.ts"; import "datetime/test.ts"; import "examples/test.ts"; @@ -16,21 +14,12 @@ import "fs/path/relative_test.ts"; import "fs/path/resolve_test.ts"; import "fs/path/zero_length_strings_test.ts"; import "io/bufio_test.ts"; +import "io/ioutil_test.ts"; import "http/http_test.ts"; +import "http/file_server_test.ts"; import "log/test.ts"; import "media_types/test.ts"; import "testing/test.ts"; import "textproto/test.ts"; +import "ws/sha1_test.ts"; import "ws/test.ts"; - -import { runTests, completePromise } from "http/file_server_test.ts"; - -const fileServer = run({ - args: ["deno", "--allow-net", "http/file_server.ts", ".", "--cors"] -}); - -runTests(new Promise(res => setTimeout(res, 5000))); -(async () => { - await completePromise; - fileServer.close(); -})(); -- cgit v1.2.3 From 15f372c5490e85cff66f9b2cca2a8868655f4ddb Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 17 Jan 2019 13:14:48 -0500 Subject: Remove mkdirp - deno.mkdir is already recursive (denoland/deno_std#118) Original: https://github.com/denoland/deno_std/commit/4283c26b8930ca80e5babca3337b5431f16334d0 --- fs/mkdirp.ts | 43 ------------------------------------------- fs/mkdirp_test.ts | 30 ------------------------------ test.ts | 1 - 3 files changed, 74 deletions(-) delete mode 100644 fs/mkdirp.ts delete mode 100644 fs/mkdirp_test.ts diff --git a/fs/mkdirp.ts b/fs/mkdirp.ts deleted file mode 100644 index 627166043..000000000 --- a/fs/mkdirp.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * # deno-mkdirp - * - * `mkdir -p` 4 `deno`. - * - * ## Import - * - * ```ts - * import { mkdirp } from "https://deno.land/x/std/fs/mkdirp.ts"; - * ``` - * - * ## API - * - * Same as [`deno.mkdir`](https://deno.land/typedoc/index.html#mkdir). - * - * ### `mkdirp(path: string, mode?: number) : Promise` - * - * Creates directories if they do not already exist and makes parent directories as needed. - */ -import { ErrorKind, FileInfo, lstat, mkdir, platform } from "deno"; - -const PATH_SEPARATOR: string = platform.os === "win" ? "\\" : "/"; - -export async function mkdirp(path: string, mode?: number): Promise { - for ( - let parts: string[] = path.split(/\/|\\/), - parts_len: number = parts.length, - level: string, - info: FileInfo, - i: number = 0; - i < parts_len; - i++ - ) { - level = parts.slice(0, i + 1).join(PATH_SEPARATOR); - try { - info = await lstat(level); - if (!info.isDirectory()) throw Error(`${level} is not a directory`); - } catch (err) { - if (err.kind !== ErrorKind.NotFound) throw err; - await mkdir(level, mode); - } - } -} diff --git a/fs/mkdirp_test.ts b/fs/mkdirp_test.ts deleted file mode 100644 index a3a4fac03..000000000 --- a/fs/mkdirp_test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { cwd, lstat, makeTempDirSync, removeAll, FileInfo } from "deno"; -import { test, assert } from "../testing/mod.ts"; -import { mkdirp } from "./mkdirp.ts"; - -let root: string = `${cwd()}/${Date.now()}`; //makeTempDirSync(); - -test(async function createsNestedDirs(): Promise { - const leaf: string = `${root}/levelx/levely`; - await mkdirp(leaf); - const info: FileInfo = await lstat(leaf); - assert(info.isDirectory()); - await removeAll(root); -}); - -test(async function handlesAnyPathSeparator(): Promise { - const leaf: string = `${root}\\levelx\\levely`; - await mkdirp(leaf); - const info: FileInfo = await lstat(leaf.replace(/\\/g, "/")); - assert(info.isDirectory()); - await removeAll(root); -}); - -test(async function failsNonDir(): Promise { - try { - await mkdirp("./test.ts/fest.fs"); - } catch (err) { - // TODO: assert caught DenoError of kind NOT_A_DIRECTORY or similar - assert(err); - } -}); diff --git a/test.ts b/test.ts index a128ce0a1..33a6f8d9b 100755 --- a/test.ts +++ b/test.ts @@ -3,7 +3,6 @@ import "colors/test.ts"; import "datetime/test.ts"; import "examples/test.ts"; import "flags/test.ts"; -import "fs/mkdirp_test.ts"; import "fs/path/basename_test.ts"; import "fs/path/dirname_test.ts"; import "fs/path/extname_test.ts"; -- cgit v1.2.3 From a489edc355e391117fc065dafe01bdf17c930b26 Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Sat, 19 Jan 2019 21:09:35 +1100 Subject: Rework color API (denoland/deno_std#134) Original: https://github.com/denoland/deno_std/commit/fa5b3dfc9c08ba4d12a5f466c5f30aca4524e1c9 --- colors/README.md | 11 ++-- colors/example.ts | 4 +- colors/mod.ts | 160 +++++++++++++++++++++++++++++++++++++++++++----------- colors/styles.ts | 66 ---------------------- colors/test.ts | 24 ++++---- 5 files changed, 147 insertions(+), 118 deletions(-) delete mode 100644 colors/styles.ts diff --git a/colors/README.md b/colors/README.md index 3148b7cab..3c371197f 100644 --- a/colors/README.md +++ b/colors/README.md @@ -1,18 +1,19 @@ # colors Is a basic console color module intended for [Deno](https://deno.land/). It is -inspired by [chalk](https://www.npmjs.com/package/chalk) and +inspired by [chalk](https://www.npmjs.com/package/chalk), +[kleur](https://www.npmjs.com/package/kleur), and [colors](https://www.npmjs.com/package/colors) on npm. ## Usage -The main modules exports a single function name `color` which is a function that -provides chaining to stack colors. Basic usage looks like this: +The main modules exports several functions which can color the output to the +console: ```ts -import { color } from "https://deno.land/x/std/colors/mod.ts"; +import { bgBlue, red, bold } from "https://deno.land/x/std/colors/mod.ts"; -console.log(color.bgBlue.red.bold("Hello world!")); +console.log(bgBlue(red(bold("Hello world!")))); ``` ## TODO diff --git a/colors/example.ts b/colors/example.ts index e98a32ec9..02bc93432 100644 --- a/colors/example.ts +++ b/colors/example.ts @@ -1,3 +1,3 @@ -import { color } from "./mod.ts"; +import { bgBlue, red, bold, italic } from "./mod.ts"; -console.log(color.bgBlue.red.bold("Hello world!")); +console.log(bgBlue(italic(red(bold("Hello world!"))))); diff --git a/colors/mod.ts b/colors/mod.ts index 8316060db..e271c54cf 100644 --- a/colors/mod.ts +++ b/colors/mod.ts @@ -1,33 +1,131 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -import { styles } from "./styles.ts"; - -type Styles = { readonly [S in keyof typeof styles]: Color }; - -type Color = Styles & { - (str: string): string; -}; - -const styleStack: string[] = []; - -export const color = function color(str: string): string { - styleStack.reverse(); - while (styleStack.length) { - const style = styleStack.pop(); - const code = styles[style]; - str = `${code.open}${str.replace(code.closeRe, code.open)}${ - code.close - }`.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } - return str; -} as Color; - -for (const style of Object.keys(styles)) { - Object.defineProperty(color, style, { - get() { - styleStack.push(style); - return color; - }, - enumerable: true, - configurable: false - }); + +interface Code { + open: string; + close: string; + regexp: RegExp; +} + +let enabled = true; + +export function setEnabled(value: boolean) { + enabled = value; +} + +export function getEnabled(): boolean { + return enabled; +} + +function code(open: number, close: number): Code { + return { + open: `\x1b[${open}m`, + close: `\x1b[${close}m`, + regexp: new RegExp(`\\x1b\\[${close}m`, "g") + }; +} + +function run(str: string, code: Code) { + return enabled + ? `${code.open}${str.replace(code.regexp, code.open)}${code.close}` + : str; +} + +export function reset(str: string): string { + return run(str, code(0, 0)); +} + +export function bold(str: string): string { + return run(str, code(1, 22)); +} + +export function dim(str: string): string { + return run(str, code(2, 22)); +} + +export function italic(str: string): string { + return run(str, code(3, 23)); +} + +export function underline(str: string): string { + return run(str, code(4, 24)); +} + +export function inverse(str: string): string { + return run(str, code(7, 27)); +} + +export function hidden(str: string): string { + return run(str, code(8, 28)); +} + +export function strikethrough(str: string): string { + return run(str, code(9, 29)); +} + +export function black(str: string): string { + return run(str, code(30, 39)); +} + +export function red(str: string): string { + return run(str, code(31, 39)); +} + +export function green(str: string): string { + return run(str, code(32, 39)); +} + +export function yellow(str: string): string { + return run(str, code(33, 39)); +} + +export function blue(str: string): string { + return run(str, code(34, 39)); +} + +export function magenta(str: string): string { + return run(str, code(35, 39)); +} + +export function cyan(str: string): string { + return run(str, code(36, 39)); +} + +export function white(str: string): string { + return run(str, code(37, 39)); +} + +export function gray(str: string): string { + return run(str, code(90, 39)); +} + +export function bgBlack(str: string): string { + return run(str, code(40, 49)); +} + +export function bgRed(str: string): string { + return run(str, code(41, 49)); +} + +export function bgGreen(str: string): string { + return run(str, code(42, 49)); +} + +export function bgYellow(str: string): string { + return run(str, code(43, 49)); +} + +export function bgBlue(str: string): string { + return run(str, code(44, 49)); +} + +export function bgMagenta(str: string): string { + return run(str, code(45, 49)); +} + +export function bgCyan(str: string): string { + return run(str, code(46, 49)); +} + +export function bgWhite(str: string): string { + return run(str, code(47, 49)); } diff --git a/colors/styles.ts b/colors/styles.ts deleted file mode 100644 index c9fd0eb3d..000000000 --- a/colors/styles.ts +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -const matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -function escapeStringRegexp(str: string): string { - return str.replace(matchOperatorsRe, "\\$&"); -} - -const codes = { - reset: [0, 0], - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], - - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39], - - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] -}; - -type Styles = { - [S in keyof T]: { open: string; close: string; closeRe: RegExp } -}; - -export const styles: Styles = {} as any; - -for (const [style, [open, close]] of Object.entries(codes)) { - styles[style] = { - open: `\u001b[${open}m`, - close: `\u001b[${close}m`, - closeRe: new RegExp(escapeStringRegexp(`\u001b[${close}m`), "g") - }; -} diff --git a/colors/test.ts b/colors/test.ts index 266868090..f12f0cbb1 100644 --- a/colors/test.ts +++ b/colors/test.ts @@ -1,25 +1,21 @@ -import { assertEqual, test } from "../testing/mod.ts"; -import { color } from "./mod.ts"; +import { assert, test } from "../testing/mod.ts"; +import { red, bgBlue, setEnabled, getEnabled } from "./mod.ts"; import "./example.ts"; test(function singleColor() { - assertEqual(color.red("Hello world"), "Hello world"); + assert.equal(red("Hello world"), "Hello world"); }); test(function doubleColor() { - assertEqual(color.red.bgBlue("Hello world"), - "Hello world"); + assert.equal(bgBlue(red("Hello world")), "Hello world"); }); -test(function newLinesContinueColors() { - assertEqual(color.red("Hello\nworld"), - "Hello\nworld"); - assertEqual(color.red("Hello\r\nworld"), - "Hello\r\nworld"); - assertEqual(color.red("Hello\n\nworld"), - "Hello\n\nworld"); +test(function replacesCloseCharacters() { + assert.equal(red("Hello"), "Hello"); }); -test(function replacesCloseCharacters() { - assertEqual(color.red("Hello"), "Hello"); +test(function enablingColors() { + assert.equal(getEnabled(), true); + setEnabled(false); + assert.equal(bgBlue(red("Hello world")), "Hello world"); }); -- cgit v1.2.3 From 4cc5839154d73f85f16593f6333375387cf56259 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Sat, 19 Jan 2019 19:46:46 +0100 Subject: Implement formatters for log (denoland/deno_std#127) Original: https://github.com/denoland/deno_std/commit/c304ee503a2f2bef8cee2cb03d07785ad060b7bc --- log/handlers.ts | 51 +++++++++++++++++++++++++++++-------- log/mod.ts | 4 +++ log/test.ts | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 117 insertions(+), 16 deletions(-) diff --git a/log/handlers.ts b/log/handlers.ts index a0163e6cd..bb684bdef 100644 --- a/log/handlers.ts +++ b/log/handlers.ts @@ -2,24 +2,49 @@ import { open, File, Writer } from "deno"; import { getLevelByName } from "./levels.ts"; import { LogRecord } from "./logger.ts"; +const DEFAULT_FORMATTER = "{levelName} {msg}"; +type FormatterFunction = (logRecord: LogRecord) => string; + +interface HandlerOptions { + formatter?: string | FormatterFunction; +} + export class BaseHandler { level: number; levelName: string; + formatter: string | FormatterFunction; - constructor(levelName: string) { + constructor(levelName: string, options: HandlerOptions = {}) { this.level = getLevelByName(levelName); this.levelName = levelName; + + this.formatter = options.formatter || DEFAULT_FORMATTER; } handle(logRecord: LogRecord) { if (this.level > logRecord.level) return; - // TODO: implement formatter - const msg = `${logRecord.levelName} ${logRecord.msg}`; - + const msg = this.format(logRecord); return this.log(msg); } + format(logRecord: LogRecord): string { + if (this.formatter instanceof Function) { + return this.formatter(logRecord); + } + + return this.formatter.replace(/{(\S+)}/g, (match, p1) => { + const value = logRecord[p1]; + + // do not interpolate missing values + if (!value) { + return match; + } + + return value; + }); + } + log(msg: string) {} async setup() {} async destroy() {} @@ -33,21 +58,27 @@ export class ConsoleHandler extends BaseHandler { export abstract class WriterHandler extends BaseHandler { protected _writer: Writer; + private _encoder = new TextEncoder(); log(msg: string) { - const encoder = new TextEncoder(); - // promise is intentionally not awaited - this._writer.write(encoder.encode(msg + "\n")); + this._writer.write(this._encoder.encode(msg + "\n")); } } +interface FileHandlerOptions extends HandlerOptions { + filename: string; +} + export class FileHandler extends WriterHandler { private _file: File; private _filename: string; - constructor(levelName: string, filename: string) { - super(levelName); - this._filename = filename; + constructor( + levelName: string, + options: FileHandlerOptions, + ) { + super(levelName, options); + this._filename = options.filename; } async setup() { diff --git a/log/mod.ts b/log/mod.ts index e8c762ac6..f332711b3 100644 --- a/log/mod.ts +++ b/log/mod.ts @@ -76,6 +76,10 @@ export function getLogger(name?: string) { return state.loggers.get(name); } +export function getHandler(name: string) { + return state.handlers.get(name); +} + export async function setup(config: LogConfig) { state.config = config; diff --git a/log/test.ts b/log/test.ts index fdc994eb7..4b623207f 100644 --- a/log/test.ts +++ b/log/test.ts @@ -3,16 +3,18 @@ import { assertEqual, test } from "../testing/mod.ts"; import * as log from "./mod.ts"; import { FileHandler } from "./handlers.ts"; -// TODO: establish something more sophisticated -let testOutput = ""; +// constructor(levelName: string, options: HandlerOptions = {}) { +// this.level = getLevelByName(levelName); +// this.levelName = levelName; + +// this.formatter = options.formatter || DEFAULT_FORMATTER; +// } class TestHandler extends log.handlers.BaseHandler { - constructor(levelName: string) { - super(levelName); - } + testOutput = ""; log(msg: string) { - testOutput += `${msg}\n`; + this.testOutput += `${msg}\n`; } } @@ -26,3 +28,67 @@ test(function testDefaultlogMethods() { const logger = log.getLogger(""); console.log(logger); }); + +test(async function testDefaultFormatter() { + await log.setup({ + handlers: { + test: new TestHandler("DEBUG"), + }, + + loggers: { + test: { + level: "DEBUG", + handlers: ["test"], + }, + }, + }); + + const logger = log.getLogger("test"); + const handler = log.getHandler("test"); + logger.debug("Hello, world!"); + assertEqual(handler.testOutput, "DEBUG Hello, world!\n"); +}); + +test(async function testFormatterAsString() { + await log.setup({ + handlers: { + test: new TestHandler("DEBUG", { + formatter: "test {levelName} {msg}", + }), + }, + + loggers: { + test: { + level: "DEBUG", + handlers: ["test"], + }, + }, + }); + + const logger = log.getLogger("test"); + const handler = log.getHandler("test"); + logger.debug("Hello, world!"); + assertEqual(handler.testOutput, "test DEBUG Hello, world!\n"); +}); + +test(async function testFormatterAsFunction() { + await log.setup({ + handlers: { + test: new TestHandler("DEBUG", { + formatter: logRecord => `fn formmatter ${logRecord.levelName} ${logRecord.msg}`, + }), + }, + + loggers: { + test: { + level: "DEBUG", + handlers: ["test"], + }, + }, + }); + + const logger = log.getLogger("test"); + const handler = log.getHandler("test"); + logger.error("Hello, world!"); + assertEqual(handler.testOutput, "fn formmatter ERROR Hello, world!\n"); +}); \ No newline at end of file -- cgit v1.2.3 From 88ecb4d167a551222db5bb405146f9b9fcc6ae1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E6=9D=89?= Date: Sun, 20 Jan 2019 10:38:48 +0800 Subject: Bump deno version to v0.2.8 (denoland/deno_std#138) Original: https://github.com/denoland/deno_std/commit/8f64a4a1f03e9f8a2a6d7a322f407baf1868ea06 --- azure-pipelines.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 1bb173ad2..e288bced1 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,5 +1,5 @@ variables: - DENO_VERSION: 'v0.2.7' + DENO_VERSION: 'v0.2.8' jobs: -- cgit v1.2.3 From 52fdf581a8dae226da7a7d5eae4498071a98eed2 Mon Sep 17 00:00:00 2001 From: Max Graey Date: Mon, 21 Jan 2019 17:31:57 +0200 Subject: Refactorings & improvments for ws module (denoland/deno_std#141) Original: https://github.com/denoland/deno_std/commit/0d2429cdf29fa5c6ae19affc475c1946e3c99774 --- ws/mod.ts | 54 +++++++++++++++++++++++++++++------------------------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/ws/mod.ts b/ws/mod.ts index b0b490978..ace5db33d 100644 --- a/ws/mod.ts +++ b/ws/mod.ts @@ -40,6 +40,16 @@ export function isWebSocketPongEvent(a): a is WebSocketPongEvent { return Array.isArray(a) && a[0] === "pong" && a[1] instanceof Uint8Array; } +// TODO move this to common/util module +export function append(a: Uint8Array, b: Uint8Array) { + if (a == null || !a.length) return b; + if (b == null || !b.length) return a; + const output = new Uint8Array(a.length + b.length); + output.set(a, 0); + output.set(b, a.length); + return output; +} + export class SocketClosedError extends Error {} export type WebSocketFrame = { @@ -189,10 +199,12 @@ export async function* receiveFrame( conn: Conn ): AsyncIterableIterator { let receiving = true; + let isLastFrame = true; const reader = new BufReader(conn); while (receiving) { const frame = await readFrame(reader); - switch (frame.opcode) { + const { opcode, payload } = frame; + switch (opcode) { case OpCodeTextFrame: case OpCodeBinaryFrame: case OpCodeContinue: @@ -201,9 +213,9 @@ export async function* receiveFrame( case OpCodeClose: await writeFrame( { - isLastFrame: true, - opcode: OpCodeClose, - payload: frame.payload + opcode, + payload, + isLastFrame }, conn ); @@ -214,9 +226,9 @@ export async function* receiveFrame( case OpcodePing: await writeFrame( { - isLastFrame: true, - opcode: OpcodePong, - payload: frame.payload + payload, + isLastFrame, + opcode: OpcodePong }, conn ); @@ -232,41 +244,37 @@ export async function* receiveFrame( export async function writeFrame(frame: WebSocketFrame, writer: Writer) { let payloadLength = frame.payload.byteLength; let header: Uint8Array; - const hasMask = (frame.mask ? 1 : 0) << 7; + const hasMask = frame.mask ? 0x80 : 0; if (payloadLength < 126) { header = new Uint8Array([ - (0b1000 << 4) | frame.opcode, + 0x80 | frame.opcode, hasMask | payloadLength ]); } else if (payloadLength < 0xffff) { header = new Uint8Array([ - (0b1000 << 4) | frame.opcode, + 0x80 | frame.opcode, hasMask | 0b01111110, payloadLength >>> 8, payloadLength & 0x00ff ]); } else { header = new Uint8Array([ - (0b1000 << 4) | frame.opcode, + 0x80 | frame.opcode, hasMask | 0b01111111, ...sliceLongToBytes(payloadLength) ]); } - if (frame.mask) { - unmask(frame.payload, frame.mask); - } - const bytes = new Uint8Array(header.length + payloadLength); - bytes.set(header, 0); - bytes.set(frame.payload, header.length); + unmask(frame.payload, frame.mask); + const bytes = append(header, frame.payload); const w = new BufWriter(writer); await w.write(bytes); await w.flush(); } -export function unmask(payload: Uint8Array, mask: Uint8Array) { +export function unmask(payload: Uint8Array, mask?: Uint8Array) { if (mask) { - for (let i = 0; i < payload.length; i++) { - payload[i] ^= mask[i % 4]; + for (let i = 0, len = payload.length; i < len; i++) { + payload[i] ^= mask![i & 3]; } } } @@ -302,11 +310,7 @@ export function createSecAccept(nonce: string) { const sha1 = new Sha1(); sha1.update(nonce + kGUID); const bytes = sha1.digest(); - const hash = bytes.reduce( - (data, byte) => data + String.fromCharCode(byte), - "" - ); - return btoa(hash); + return btoa(String.fromCharCode.apply(String, bytes)); } export async function readFrame(buf: BufReader): Promise { -- cgit v1.2.3 From d710f9427af35363fb7f9b82d09eae5bd8342a63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E6=9D=89?= Date: Mon, 21 Jan 2019 23:35:07 +0800 Subject: fix format (denoland/deno_std#140) Original: https://github.com/denoland/deno_std/commit/61a3911be7e01273e13bf35a3a16285f413f0b70 --- datetime/test.ts | 4 ++-- format.ts | 6 +----- log/handlers.ts | 7 ++----- log/test.ts | 31 ++++++++++++++++--------------- 4 files changed, 21 insertions(+), 27 deletions(-) diff --git a/datetime/test.ts b/datetime/test.ts index 5bc7eda21..ce8193dfb 100644 --- a/datetime/test.ts +++ b/datetime/test.ts @@ -31,7 +31,7 @@ test(function parseDateTime() { test(function invalidParseDateTimeFormatThrows() { try { (datetime as any).parseDateTime("2019-01-01 00:00", "x-y-z"); - assert(false, 'no exception was thrown'); + assert(false, "no exception was thrown"); } catch (e) { assertEqual(e.message, "Invalid datetime format!"); } @@ -55,7 +55,7 @@ test(function parseDate() { test(function invalidParseDateFormatThrows() { try { (datetime as any).parseDate("2019-01-01", "x-y-z"); - assert(false, 'no exception was thrown'); + assert(false, "no exception was thrown"); } catch (e) { assertEqual(e.message, "Invalid date format!"); } diff --git a/format.ts b/format.ts index 2e7b9a606..cee84a299 100755 --- a/format.ts +++ b/format.ts @@ -27,11 +27,7 @@ async function main() { await checkVersion(); const prettier = run({ - args: [ - "bash", - "-c", - "prettier --write *.ts */*.ts */**/*.ts *.md */*.md */**/*.md" - ] + args: ["bash", "-c", "prettier --write '**/*.ts' '**/*.md'"] }); const s = await prettier.status(); exit(s.code); diff --git a/log/handlers.ts b/log/handlers.ts index bb684bdef..c39102c8e 100644 --- a/log/handlers.ts +++ b/log/handlers.ts @@ -32,7 +32,7 @@ export class BaseHandler { if (this.formatter instanceof Function) { return this.formatter(logRecord); } - + return this.formatter.replace(/{(\S+)}/g, (match, p1) => { const value = logRecord[p1]; @@ -73,10 +73,7 @@ export class FileHandler extends WriterHandler { private _file: File; private _filename: string; - constructor( - levelName: string, - options: FileHandlerOptions, - ) { + constructor(levelName: string, options: FileHandlerOptions) { super(levelName, options); this._filename = options.filename; } diff --git a/log/test.ts b/log/test.ts index 4b623207f..2f3431348 100644 --- a/log/test.ts +++ b/log/test.ts @@ -32,15 +32,15 @@ test(function testDefaultlogMethods() { test(async function testDefaultFormatter() { await log.setup({ handlers: { - test: new TestHandler("DEBUG"), + test: new TestHandler("DEBUG") }, loggers: { test: { level: "DEBUG", - handlers: ["test"], - }, - }, + handlers: ["test"] + } + } }); const logger = log.getLogger("test"); @@ -53,16 +53,16 @@ test(async function testFormatterAsString() { await log.setup({ handlers: { test: new TestHandler("DEBUG", { - formatter: "test {levelName} {msg}", - }), + formatter: "test {levelName} {msg}" + }) }, loggers: { test: { level: "DEBUG", - handlers: ["test"], - }, - }, + handlers: ["test"] + } + } }); const logger = log.getLogger("test"); @@ -75,20 +75,21 @@ test(async function testFormatterAsFunction() { await log.setup({ handlers: { test: new TestHandler("DEBUG", { - formatter: logRecord => `fn formmatter ${logRecord.levelName} ${logRecord.msg}`, - }), + formatter: logRecord => + `fn formmatter ${logRecord.levelName} ${logRecord.msg}` + }) }, loggers: { test: { level: "DEBUG", - handlers: ["test"], - }, - }, + handlers: ["test"] + } + } }); const logger = log.getLogger("test"); const handler = log.getHandler("test"); logger.error("Hello, world!"); assertEqual(handler.testOutput, "fn formmatter ERROR Hello, world!\n"); -}); \ No newline at end of file +}); -- cgit v1.2.3 From 41829f3e2bd0b1c3af8b508dfafb1b5a17fe59b6 Mon Sep 17 00:00:00 2001 From: Max Graey Date: Tue, 22 Jan 2019 05:56:35 +0200 Subject: fix possible range issues for copyBytes in io/util (denoland/deno_std#146) Original: https://github.com/denoland/deno_std/commit/2081f03a0748dac0cf0ab7e6e2d7e427841aca22 --- io/util.ts | 1 + io/util_test.ts | 36 ++++++++++++++++++++++++++++++++++++ test.ts | 1 + 3 files changed, 38 insertions(+) create mode 100644 io/util_test.ts diff --git a/io/util.ts b/io/util.ts index 3266e5018..185732b36 100644 --- a/io/util.ts +++ b/io/util.ts @@ -4,6 +4,7 @@ import { Buffer, Reader } from "deno"; // from `src`. // Returns the number of bytes copied. export function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number { + off = Math.max(0, Math.min(off, dst.byteLength)); const r = dst.byteLength - off; if (src.byteLength > r) { src = src.subarray(0, r); diff --git a/io/util_test.ts b/io/util_test.ts new file mode 100644 index 000000000..7318d887c --- /dev/null +++ b/io/util_test.ts @@ -0,0 +1,36 @@ +import { test, assert } from "../testing/mod.ts"; +import { copyBytes } from "./util.ts"; + +test(function testCopyBytes() { + let dst = new Uint8Array(4); + + dst.fill(0); + let src = Uint8Array.of(1, 2); + let len = copyBytes(dst, src, 0); + assert(len === 2); + assert.equal(dst, Uint8Array.of(1, 2, 0, 0)); + + dst.fill(0); + src = Uint8Array.of(1, 2); + len = copyBytes(dst, src, 1); + assert(len === 2); + assert.equal(dst, Uint8Array.of(0, 1, 2, 0)); + + dst.fill(0); + src = Uint8Array.of(1, 2, 3, 4, 5); + len = copyBytes(dst, src); + assert(len === 4); + assert.equal(dst, Uint8Array.of(1, 2, 3, 4)); + + dst.fill(0); + src = Uint8Array.of(1, 2); + len = copyBytes(dst, src, 100); + assert(len === 0); + assert.equal(dst, Uint8Array.of(0, 0, 0, 0)); + + dst.fill(0); + src = Uint8Array.of(3, 4); + len = copyBytes(dst, src, -2); + assert(len === 2); + assert.equal(dst, Uint8Array.of(3, 4, 0, 0)); +}); diff --git a/test.ts b/test.ts index 33a6f8d9b..b9fcd74e0 100755 --- a/test.ts +++ b/test.ts @@ -14,6 +14,7 @@ import "fs/path/resolve_test.ts"; import "fs/path/zero_length_strings_test.ts"; import "io/bufio_test.ts"; import "io/ioutil_test.ts"; +import "io/util_test.ts"; import "http/http_test.ts"; import "http/file_server_test.ts"; import "log/test.ts"; -- cgit v1.2.3 From 8d474a7911d6b36aec222f08ef18d88baabe2dad Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Tue, 22 Jan 2019 16:09:51 +1000 Subject: Make testing more matainable Original: https://github.com/denoland/deno_std/commit/2f0ca2242f6db66acc5f8939e99615483b1d496c --- testing/mod.ts | 189 +++++++++++++++++++++++++++++---------------------------- 1 file changed, 97 insertions(+), 92 deletions(-) diff --git a/testing/mod.ts b/testing/mod.ts index 1de5f55bc..0ac2c4ea4 100644 --- a/testing/mod.ts +++ b/testing/mod.ts @@ -2,123 +2,128 @@ // Do not add imports in this file in order to be compatible with Node. -export function assertEqual(actual: unknown, expected: unknown, msg?: string) { - if (!equal(actual, expected)) { - let actualString: string; - let expectedString: string; - try { - actualString = String(actual); - } catch (e) { - actualString = "[Cannot display]"; - } - try { - expectedString = String(expected); - } catch (e) { - expectedString = "[Cannot display]"; - } - console.error( - "assertEqual failed. actual =", - actualString, - "expected =", - expectedString - ); - if (!msg) { - msg = `actual: ${actualString} expected: ${expectedString}`; - } - throw new Error(msg); - } -} - interface Constructor { new (...args: any[]): any; } -interface Assert { - /** Make an assertion, if not true, then throw. */ - (expr: boolean, msg?: string): void; +const assertions = { + /** Make an assertion, if not `true`, then throw. */ + assert(expr: boolean, msg = ""): void { + if (!expr) { + throw new Error(msg); + } + }, /** Make an assertion that `actual` and `expected` are equal, deeply. If not * deeply equal, then throw. */ - equal(actual: unknown, expected: unknown, msg?: string): void; + equal(actual: unknown, expected: unknown, msg?: string): void { + if (!equal(actual, expected)) { + let actualString: string; + let expectedString: string; + try { + actualString = String(actual); + } catch (e) { + actualString = "[Cannot display]"; + } + try { + expectedString = String(expected); + } catch (e) { + expectedString = "[Cannot display]"; + } + console.error( + "assertEqual failed. actual =", + actualString, + "expected =", + expectedString + ); + if (!msg) { + msg = `actual: ${actualString} expected: ${expectedString}`; + } + throw new Error(msg); + } + }, /** Make an assertion that `actual` and `expected` are strictly equal. If * not then throw. */ - strictEqual(actual: unknown, expected: unknown, msg?: string): void; + strictEqual(actual: unknown, expected: unknown, msg = ""): void { + if (actual !== expected) { + let actualString: string; + let expectedString: string; + try { + actualString = String(actual); + } catch (e) { + actualString = "[Cannot display]"; + } + try { + expectedString = String(expected); + } catch (e) { + expectedString = "[Cannot display]"; + } + console.error( + "strictEqual failed. actual =", + actualString, + "expected =", + expectedString + ); + if (!msg) { + msg = `actual: ${actualString} expected: ${expectedString}`; + } + throw new Error(msg); + } + }, /** Executes a function, expecting it to throw. If it does not, then it * throws. An error class and a string that should be included in the * error message can also be asserted. */ - throws(fn: () => void, errorClass?: Constructor, msgIncludes?: string): void; -} - -export const assert = function assert(expr: boolean, msg = "") { - if (!expr) { - throw new Error(msg); - } -} as Assert; - -assert.equal = assertEqual; -assert.strictEqual = function strictEqual(actual, expected, msg = "") { - if (actual !== expected) { - let actualString: string; - let expectedString: string; + throws( + fn: () => void, + ErrorClass?: Constructor, + msgIncludes = "", + msg = "" + ): void { + let doesThrow = false; try { - actualString = String(actual); + fn(); } catch (e) { - actualString = "[Cannot display]"; - } - try { - expectedString = String(expected); - } catch (e) { - expectedString = "[Cannot display]"; - } - console.error( - "strictEqual failed. actual =", - actualString, - "expected =", - expectedString - ); - if (!msg) { - msg = `actual: ${actualString} expected: ${expectedString}`; - } - throw new Error(msg); - } -}; -assert.throws = function throws( - fn, - ErrorClass: Constructor, - msgIncludes = "", - msg = "" -) { - let doesThrow = false; - try { - fn(); - } catch (e) { - if (ErrorClass && !(Object.getPrototypeOf(e) === ErrorClass.prototype)) { - msg = `Expected error to be instance of "${ErrorClass.name}"${ - msg ? `: ${msg}` : "." - }`; - throw new Error(msg); - } - if (msgIncludes) { - if (!e.message.includes(msgIncludes)) { - msg = `Expected error message to include "${msgIncludes}", but got "${ - e.message - }"${msg ? `: ${msg}` : "."}`; + if (ErrorClass && !(Object.getPrototypeOf(e) === ErrorClass.prototype)) { + msg = `Expected error to be instance of "${ErrorClass.name}"${ + msg ? `: ${msg}` : "." + }`; throw new Error(msg); } + if (msgIncludes) { + if (!e.message.includes(msgIncludes)) { + msg = `Expected error message to include "${msgIncludes}", but got "${ + e.message + }"${msg ? `: ${msg}` : "."}`; + throw new Error(msg); + } + } + doesThrow = true; + } + if (!doesThrow) { + msg = `Expected function to throw${msg ? `: ${msg}` : "."}`; + throw new Error(msg); } - doesThrow = true; - } - if (!doesThrow) { - msg = `Expected function to throw${msg ? `: ${msg}` : "."}`; - throw new Error(msg); } }; +type Assert = typeof assertions.assert & typeof assertions; + +// Decorate assertions.assert with all the assertions +Object.assign(assertions.assert, assertions); + +export const assert = assertions.assert as Assert; + +/** + * An alias to assert.equal + * @deprecated + */ +export const assertEqual = assert.equal; + export function equal(c: unknown, d: unknown): boolean { const seen = new Map(); return (function compare(a: unknown, b: unknown) { -- cgit v1.2.3 From b13b2cd883d438a177bacd3d43a3adf170104991 Mon Sep 17 00:00:00 2001 From: Kitson Kelly Date: Tue, 22 Jan 2019 16:15:25 +1000 Subject: Add assert.throwsAsync() Original: https://github.com/denoland/deno_std/commit/83bb7e99b6ff00011d4ac63a265644f657282c06 --- testing/README.md | 35 ++++++++++++++++ testing/mod.ts | 32 +++++++++++++++ testing/test.ts | 120 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 183 insertions(+), 4 deletions(-) diff --git a/testing/README.md b/testing/README.md index 49a6526fe..70613e0e1 100644 --- a/testing/README.md +++ b/testing/README.md @@ -28,6 +28,11 @@ functions: this function does. Also compares any errors thrown to an optional expected `Error` class and checks that the error `.message` includes an optional string. +- `assert.throwsAsync()` - Expects the passed `fn` to be async and throw (or + return a `Promise` that rejects). If the `fn` does not throw or reject, this + function will throw asynchronously. Also compares any errors thrown to an + optional expected `Error` class and checks that the error `.message` includes + an optional string. `assertEqual()` is the same as `assert.equal()` but maintained for backwards compatibility. @@ -106,3 +111,33 @@ test(function fails() { }); }); ``` + +Using `assert.throwsAsync()`: + +```ts +test(async function doesThrow() { + assert.throwsAsync(async () => { + throw new TypeError("hello world!"); + }); + assert.throwsAsync(async () => { + throw new TypeError("hello world!"); + }, TypeError); + assert.throwsAsync( + async () => { + throw new TypeError("hello world!"); + }, + TypeError, + "hello" + ); + assert.throwsAsync(async () => { + return Promise.reject(new Error()); + }); +}); + +// This test will not pass +test(async function fails() { + assert.throwsAsync(async () => { + console.log("Hello world"); + }); +}); +``` diff --git a/testing/mod.ts b/testing/mod.ts index 0ac2c4ea4..42f3939c5 100644 --- a/testing/mod.ts +++ b/testing/mod.ts @@ -108,6 +108,38 @@ const assertions = { msg = `Expected function to throw${msg ? `: ${msg}` : "."}`; throw new Error(msg); } + }, + + async throwsAsync( + fn: () => Promise, + ErrorClass?: Constructor, + msgIncludes = "", + msg = "" + ): Promise { + let doesThrow = false; + try { + await fn(); + } catch (e) { + if (ErrorClass && !(Object.getPrototypeOf(e) === ErrorClass.prototype)) { + msg = `Expected error to be instance of "${ErrorClass.name}"${ + msg ? `: ${msg}` : "." + }`; + throw new Error(msg); + } + if (msgIncludes) { + if (!e.message.includes(msgIncludes)) { + msg = `Expected error message to include "${msgIncludes}", but got "${ + e.message + }"${msg ? `: ${msg}` : "."}`; + throw new Error(msg); + } + } + doesThrow = true; + } + if (!doesThrow) { + msg = `Expected function to throw${msg ? `: ${msg}` : "."}`; + throw new Error(msg); + } } }; diff --git a/testing/test.ts b/testing/test.ts index 34b2762b4..1765fd6b6 100644 --- a/testing/test.ts +++ b/testing/test.ts @@ -27,15 +27,15 @@ test(function testingEqual() { test(function testingAssertEqual() { const a = Object.create(null); a.b = "foo"; - assertEqual(a, a); - assert(assert.equal === assertEqual); + assert.equal(a, a); + assert(assertEqual === assert.equal); }); test(function testingAssertEqualActualUncoercable() { let didThrow = false; const a = Object.create(null); try { - assertEqual(a, "bar"); + assert.equal(a, "bar"); } catch (e) { didThrow = true; console.log(e.message); @@ -48,7 +48,7 @@ test(function testingAssertEqualExpectedUncoercable() { let didThrow = false; const a = Object.create(null); try { - assertEqual("bar", a); + assert.equal("bar", a); } catch (e) { didThrow = true; console.log(e.message); @@ -161,3 +161,115 @@ test(function testingThrowsMsgNotIncludes() { assert(count === 1); assert(didThrow); }); + +test(async function testingDoesThrowAsync() { + let count = 0; + await assert.throwsAsync(async () => { + count++; + throw new Error(); + }); + assert(count === 1); +}); + +test(async function testingDoesReject() { + let count = 0; + await assert.throwsAsync(() => { + count++; + return Promise.reject(new Error()); + }); + assert(count === 1); +}); + +test(async function testingDoesNotThrowAsync() { + let count = 0; + let didThrow = false; + try { + await assert.throwsAsync(async () => { + count++; + console.log("Hello world"); + }); + } catch (e) { + assert(e.message === "Expected function to throw."); + didThrow = true; + } + assert(count === 1); + assert(didThrow); +}); + +test(async function testingDoesNotRejectAsync() { + let count = 0; + let didThrow = false; + try { + await assert.throwsAsync(() => { + count++; + console.log("Hello world"); + return Promise.resolve(); + }); + } catch (e) { + assert(e.message === "Expected function to throw."); + didThrow = true; + } + assert(count === 1); + assert(didThrow); +}); + +test(async function testingThrowsAsyncErrorType() { + let count = 0; + await assert.throwsAsync(async () => { + count++; + throw new TypeError(); + }, TypeError); + assert(count === 1); +}); + +test(async function testingThrowsAsyncNotErrorType() { + let count = 0; + let didThrow = false; + try { + await assert.throwsAsync(async () => { + count++; + throw new TypeError(); + }, RangeError); + } catch (e) { + assert(e.message === `Expected error to be instance of "RangeError".`); + didThrow = true; + } + assert(count === 1); + assert(didThrow); +}); + +test(async function testingThrowsAsyncMsgIncludes() { + let count = 0; + await assert.throwsAsync( + async () => { + count++; + throw new TypeError("Hello world!"); + }, + TypeError, + "world" + ); + assert(count === 1); +}); + +test(async function testingThrowsMsgNotIncludes() { + let count = 0; + let didThrow = false; + try { + await assert.throwsAsync( + async () => { + count++; + throw new TypeError("Hello world!"); + }, + TypeError, + "foobar" + ); + } catch (e) { + assert( + e.message === + `Expected error message to include "foobar", but got "Hello world!".` + ); + didThrow = true; + } + assert(count === 1); + assert(didThrow); +}); -- cgit v1.2.3 From d8c99059eca0c24a6985857cee37ae9f1f0cab64 Mon Sep 17 00:00:00 2001 From: Mark Tiedemann Date: Wed, 23 Jan 2019 22:41:44 +0100 Subject: Use sh installer instead of python one (denoland/deno_std#148) Original: https://github.com/denoland/deno_std/commit/d1a9605e53a275672941a49021dbfc095c292ffa --- azure-pipelines.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index e288bced1..97580b026 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -7,7 +7,7 @@ jobs: pool: vmImage: 'Ubuntu-16.04' steps: - - script: curl -L https://deno.land/x/install/install.py | python - $(DENO_VERSION) + - script: curl -L https://deno.land/x/install/install.sh | sh -s $(DENO_VERSION) - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' - script: deno test.ts --allow-run --allow-net --allow-write @@ -15,7 +15,7 @@ jobs: pool: vmImage: 'macOS-10.13' steps: - - script: curl -L https://deno.land/x/install/install.py | python - $(DENO_VERSION) + - script: curl -L https://deno.land/x/install/install.sh | sh -s $(DENO_VERSION) - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' - script: deno test.ts --allow-run --allow-net --allow-write @@ -23,6 +23,6 @@ jobs: pool: vmImage: 'vs2017-win2016' steps: - - powershell: iwr https://deno.land/x/install/install.ps1 -Outfile 'install.ps1'; ./install.ps1 $(DENO_VERSION) + - powershell: iwr https://deno.land/x/install/install.ps1 -out install.ps1; .\install.ps1 $(DENO_VERSION) - script: echo '##vso[task.prependpath]C:\Users\VssAdministrator\.deno\bin\' - script: 'C:\Users\VssAdministrator\.deno\bin\deno.exe test.ts --allow-run --allow-net --allow-write' -- cgit v1.2.3 From 306a5f701ee9fa3acfe62f6957bb4d35a09689ec Mon Sep 17 00:00:00 2001 From: Max Graey Date: Thu, 24 Jan 2019 17:55:24 +0200 Subject: Improve & refactor SHA-1 inside ws package (denoland/deno_std#137) Original: https://github.com/denoland/deno_std/commit/0a10ee9f93e9a243851de75d57cdded3f7e1aa8a --- ws/sha1.ts | 222 +++++++++++++++++++++++++++----------------------------- ws/sha1_test.ts | 15 +++- 2 files changed, 120 insertions(+), 117 deletions(-) diff --git a/ws/sha1.ts b/ws/sha1.ts index 036c3c552..916bbd9b3 100644 --- a/ws/sha1.ts +++ b/ws/sha1.ts @@ -9,77 +9,78 @@ /*jslint bitwise: true */ const HEX_CHARS = "0123456789abcdef".split(""); -const EXTRA = [-2147483648, 8388608, 32768, 128]; -const SHIFT = [24, 16, 8, 0]; +const EXTRA = Uint32Array.of(-2147483648, 8388608, 32768, 128); +const SHIFT = Uint32Array.of(24, 16, 8, 0); -const blocks = []; +const blocks = new Uint32Array(80); export class Sha1 { - blocks; - block; - start; - bytes; - hBytes; - finalized; - hashed; - first; - - h0 = 0x67452301; - h1 = 0xefcdab89; - h2 = 0x98badcfe; - h3 = 0x10325476; - h4 = 0xc3d2e1f0; - lastByteIndex = 0; - - constructor(sharedMemory: boolean = false) { + private _blocks: Uint32Array; + private _block: number; + private _start: number; + private _bytes: number; + private _hBytes: number; + private _finalized: boolean; + private _hashed: boolean; + + private _h0 = 0x67452301; + private _h1 = 0xefcdab89; + private _h2 = 0x98badcfe; + private _h3 = 0x10325476; + private _h4 = 0xc3d2e1f0; + private _lastByteIndex = 0; + + constructor(sharedMemory = false) { if (sharedMemory) { - blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; - this.blocks = blocks; + this._blocks = blocks.fill(0, 0, 17); } else { - this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + this._blocks = new Uint32Array(80); } - this.h0 = 0x67452301; - this.h1 = 0xefcdab89; - this.h2 = 0x98badcfe; - this.h3 = 0x10325476; - this.h4 = 0xc3d2e1f0; + this._h0 = 0x67452301; + this._h1 = 0xefcdab89; + this._h2 = 0x98badcfe; + this._h3 = 0x10325476; + this._h4 = 0xc3d2e1f0; - this.block = this.start = this.bytes = this.hBytes = 0; - this.finalized = this.hashed = false; - this.first = true; + this._block = this._start = this._bytes = this._hBytes = 0; + this._finalized = this._hashed = false; } - update(data: string | ArrayBuffer) { - if (this.finalized) { + update(data: string | ArrayBuffer | ArrayBufferView) { + if (this._finalized) { return; } + let notString = true; let message; - let notString = typeof data !== "string"; - if (notString && data instanceof ArrayBuffer) { + if (data instanceof ArrayBuffer) { message = new Uint8Array(data); + } else if (ArrayBuffer.isView(data)) { + message = new Uint8Array(data.buffer); } else { - message = data; + notString = false; + message = String(data); } let code, index = 0, i, + start = this._start, length = message.length || 0, - blocks = this.blocks; + blocks = this._blocks; while (index < length) { - if (this.hashed) { - this.hashed = false; - blocks[0] = this.block; - blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + if (this._hashed) { + this._hashed = false; + blocks[0] = this._block; + blocks.fill(0, 1, 17); } if (notString) { - for (i = this.start; index < length && i < 64; ++index) { + for (i = start; index < length && i < 64; ++index) { blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; } } else { - for (i = this.start; index < length && i < 64; ++index) { + for (i = start; index < length && i < 64; ++index) { code = message.charCodeAt(index); if (code < 0x80) { blocks[i >> 2] |= code << SHIFT[i++ & 3]; @@ -102,56 +103,55 @@ export class Sha1 { } } - this.lastByteIndex = i; - this.bytes += i - this.start; + this._lastByteIndex = i; + this._bytes += i - start; if (i >= 64) { - this.block = blocks[16]; - this.start = i - 64; + this._block = blocks[16]; + this._start = i - 64; this.hash(); - this.hashed = true; + this._hashed = true; } else { - this.start = i; + this._start = i; } } - if (this.bytes > 4294967295) { - this.hBytes += (this.bytes / 4294967296) << 0; - this.bytes = this.bytes % 4294967296; + if (this._bytes > 4294967295) { + this._hBytes += (this._bytes / 4294967296) >>> 0; + this._bytes = this._bytes >>> 0; } - return this; } finalize() { - if (this.finalized) { + if (this._finalized) { return; } - this.finalized = true; - let blocks = this.blocks, - i = this.lastByteIndex; - blocks[16] = this.block; + this._finalized = true; + let blocks = this._blocks, + i = this._lastByteIndex; + blocks[16] = this._block; blocks[i >> 2] |= EXTRA[i & 3]; - this.block = blocks[16]; + this._block = blocks[16]; if (i >= 56) { - if (!this.hashed) { + if (!this._hashed) { this.hash(); } - blocks[0] = this.block; - blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + blocks[0] = this._block; + blocks.fill(0, 1, 17); } - blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29); - blocks[15] = this.bytes << 3; + blocks[14] = (this._hBytes << 3) | (this._bytes >>> 29); + blocks[15] = this._bytes << 3; this.hash(); } hash() { - let a = this.h0, - b = this.h1, - c = this.h2, - d = this.h3, - e = this.h4; + let a = this._h0, + b = this._h1, + c = this._h2, + d = this._h3, + e = this._h4; let f, j, t, - blocks = this.blocks; + blocks = this._blocks; for (j = 16; j < 80; ++j) { t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16]; @@ -161,126 +161,126 @@ export class Sha1 { for (j = 0; j < 20; j += 5) { f = (b & c) | (~b & d); t = (a << 5) | (a >>> 27); - e = (t + f + e + 1518500249 + blocks[j]) << 0; + e = (t + f + e + 1518500249 + blocks[j]) >>> 0; b = (b << 30) | (b >>> 2); f = (a & b) | (~a & c); t = (e << 5) | (e >>> 27); - d = (t + f + d + 1518500249 + blocks[j + 1]) << 0; + d = (t + f + d + 1518500249 + blocks[j + 1]) >>> 0; a = (a << 30) | (a >>> 2); f = (e & a) | (~e & b); t = (d << 5) | (d >>> 27); - c = (t + f + c + 1518500249 + blocks[j + 2]) << 0; + c = (t + f + c + 1518500249 + blocks[j + 2]) >>> 0; e = (e << 30) | (e >>> 2); f = (d & e) | (~d & a); t = (c << 5) | (c >>> 27); - b = (t + f + b + 1518500249 + blocks[j + 3]) << 0; + b = (t + f + b + 1518500249 + blocks[j + 3]) >>> 0; d = (d << 30) | (d >>> 2); f = (c & d) | (~c & e); t = (b << 5) | (b >>> 27); - a = (t + f + a + 1518500249 + blocks[j + 4]) << 0; + a = (t + f + a + 1518500249 + blocks[j + 4]) >>> 0; c = (c << 30) | (c >>> 2); } for (; j < 40; j += 5) { f = b ^ c ^ d; t = (a << 5) | (a >>> 27); - e = (t + f + e + 1859775393 + blocks[j]) << 0; + e = (t + f + e + 1859775393 + blocks[j]) >>> 0; b = (b << 30) | (b >>> 2); f = a ^ b ^ c; t = (e << 5) | (e >>> 27); - d = (t + f + d + 1859775393 + blocks[j + 1]) << 0; + d = (t + f + d + 1859775393 + blocks[j + 1]) >>> 0; a = (a << 30) | (a >>> 2); f = e ^ a ^ b; t = (d << 5) | (d >>> 27); - c = (t + f + c + 1859775393 + blocks[j + 2]) << 0; + c = (t + f + c + 1859775393 + blocks[j + 2]) >>> 0; e = (e << 30) | (e >>> 2); f = d ^ e ^ a; t = (c << 5) | (c >>> 27); - b = (t + f + b + 1859775393 + blocks[j + 3]) << 0; + b = (t + f + b + 1859775393 + blocks[j + 3]) >>> 0; d = (d << 30) | (d >>> 2); f = c ^ d ^ e; t = (b << 5) | (b >>> 27); - a = (t + f + a + 1859775393 + blocks[j + 4]) << 0; + a = (t + f + a + 1859775393 + blocks[j + 4]) >>> 0; c = (c << 30) | (c >>> 2); } for (; j < 60; j += 5) { f = (b & c) | (b & d) | (c & d); t = (a << 5) | (a >>> 27); - e = (t + f + e - 1894007588 + blocks[j]) << 0; + e = (t + f + e - 1894007588 + blocks[j]) >>> 0; b = (b << 30) | (b >>> 2); f = (a & b) | (a & c) | (b & c); t = (e << 5) | (e >>> 27); - d = (t + f + d - 1894007588 + blocks[j + 1]) << 0; + d = (t + f + d - 1894007588 + blocks[j + 1]) >>> 0; a = (a << 30) | (a >>> 2); f = (e & a) | (e & b) | (a & b); t = (d << 5) | (d >>> 27); - c = (t + f + c - 1894007588 + blocks[j + 2]) << 0; + c = (t + f + c - 1894007588 + blocks[j + 2]) >>> 0; e = (e << 30) | (e >>> 2); f = (d & e) | (d & a) | (e & a); t = (c << 5) | (c >>> 27); - b = (t + f + b - 1894007588 + blocks[j + 3]) << 0; + b = (t + f + b - 1894007588 + blocks[j + 3]) >>> 0; d = (d << 30) | (d >>> 2); f = (c & d) | (c & e) | (d & e); t = (b << 5) | (b >>> 27); - a = (t + f + a - 1894007588 + blocks[j + 4]) << 0; + a = (t + f + a - 1894007588 + blocks[j + 4]) >>> 0; c = (c << 30) | (c >>> 2); } for (; j < 80; j += 5) { f = b ^ c ^ d; t = (a << 5) | (a >>> 27); - e = (t + f + e - 899497514 + blocks[j]) << 0; + e = (t + f + e - 899497514 + blocks[j]) >>> 0; b = (b << 30) | (b >>> 2); f = a ^ b ^ c; t = (e << 5) | (e >>> 27); - d = (t + f + d - 899497514 + blocks[j + 1]) << 0; + d = (t + f + d - 899497514 + blocks[j + 1]) >>> 0; a = (a << 30) | (a >>> 2); f = e ^ a ^ b; t = (d << 5) | (d >>> 27); - c = (t + f + c - 899497514 + blocks[j + 2]) << 0; + c = (t + f + c - 899497514 + blocks[j + 2]) >>> 0; e = (e << 30) | (e >>> 2); f = d ^ e ^ a; t = (c << 5) | (c >>> 27); - b = (t + f + b - 899497514 + blocks[j + 3]) << 0; + b = (t + f + b - 899497514 + blocks[j + 3]) >>> 0; d = (d << 30) | (d >>> 2); f = c ^ d ^ e; t = (b << 5) | (b >>> 27); - a = (t + f + a - 899497514 + blocks[j + 4]) << 0; + a = (t + f + a - 899497514 + blocks[j + 4]) >>> 0; c = (c << 30) | (c >>> 2); } - this.h0 = (this.h0 + a) << 0; - this.h1 = (this.h1 + b) << 0; - this.h2 = (this.h2 + c) << 0; - this.h3 = (this.h3 + d) << 0; - this.h4 = (this.h4 + e) << 0; + this._h0 = (this._h0 + a) >>> 0; + this._h1 = (this._h1 + b) >>> 0; + this._h2 = (this._h2 + c) >>> 0; + this._h3 = (this._h3 + d) >>> 0; + this._h4 = (this._h4 + e) >>> 0; } hex() { this.finalize(); - let h0 = this.h0, - h1 = this.h1, - h2 = this.h2, - h3 = this.h3, - h4 = this.h4; + let h0 = this._h0, + h1 = this._h1, + h2 = this._h2, + h3 = this._h3, + h4 = this._h4; return ( HEX_CHARS[(h0 >> 28) & 0x0f] + @@ -333,11 +333,11 @@ export class Sha1 { digest() { this.finalize(); - let h0 = this.h0, - h1 = this.h1, - h2 = this.h2, - h3 = this.h3, - h4 = this.h4; + let h0 = this._h0, + h1 = this._h1, + h2 = this._h2, + h3 = this._h3, + h4 = this._h4; return [ (h0 >> 24) & 0xff, @@ -369,14 +369,8 @@ export class Sha1 { arrayBuffer() { this.finalize(); - - let buffer = new ArrayBuffer(20); - let dataView = new DataView(buffer); - dataView.setUint32(0, this.h0); - dataView.setUint32(4, this.h1); - dataView.setUint32(8, this.h2); - dataView.setUint32(12, this.h3); - dataView.setUint32(16, this.h4); - return buffer; + return Uint32Array.of( + this._h0, this._h1, this._h2, this._h3, this._h4 + ).buffer; } } diff --git a/ws/sha1_test.ts b/ws/sha1_test.ts index b385f18da..0b1e2c858 100644 --- a/ws/sha1_test.ts +++ b/ws/sha1_test.ts @@ -1,8 +1,17 @@ -import { assertEqual, test } from "../testing/mod.ts"; +import { assert, test } from "../testing/mod.ts"; import { Sha1 } from "./sha1.ts"; test(function testSha1() { - const sha1 = new Sha1(); + let sha1 = new Sha1(); sha1.update("abcde"); - assertEqual(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); + assert.equal(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); + + const data = Uint8Array.of(0x61, 0x62, 0x63, 0x64, 0x65); + sha1 = new Sha1(); + sha1.update(data); + assert.equal(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); + + sha1 = new Sha1(); + sha1.update(data.buffer); + assert.equal(sha1.toString(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334"); }); -- cgit v1.2.3 From 441bc0982b1ff9c363a1e767d0a9ef7a35e6518c Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Fri, 18 Jan 2019 19:49:09 -0500 Subject: Style guide: metaprogramming, private filenames Original: https://github.com/denoland/deno_std/commit/e87cd44033e1ccce17d57c07e674ee573009633a --- README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/README.md b/README.md index f0f3a90fc..03bcae0fa 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,19 @@ export function foo(): string { } ``` +### Meta-programming is discouraged. Including the use of Proxy. + +Be explicit even when it means more code. + +There are some situations where it may make sense to use such techniques, but in +the vast majority of cases it does not. + +### If a filename starts with underscore, do not link to it: `_foo.ts` + +Sometimes there maybe situations where an internal module is necessary but its +API is not meant to be stable or linked to. In this case prefix it with an +underscore. By convention, only files in its own directory should import it. + ### When referencing Deno online, use the #denoland tag. The name "deno" unfortunately is not especially unique on the internet. In order -- cgit v1.2.3 From 73d5d7c680d3973b8ca8c9eaf535918790757ee9 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 24 Jan 2019 13:14:03 -0500 Subject: format Original: https://github.com/denoland/deno_std/commit/f911eca8d124d8b992b4b8171ad38a4d674469e3 --- ws/mod.ts | 5 +---- ws/sha1.ts | 7 +++---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/ws/mod.ts b/ws/mod.ts index ace5db33d..47c6271e0 100644 --- a/ws/mod.ts +++ b/ws/mod.ts @@ -246,10 +246,7 @@ export async function writeFrame(frame: WebSocketFrame, writer: Writer) { let header: Uint8Array; const hasMask = frame.mask ? 0x80 : 0; if (payloadLength < 126) { - header = new Uint8Array([ - 0x80 | frame.opcode, - hasMask | payloadLength - ]); + header = new Uint8Array([0x80 | frame.opcode, hasMask | payloadLength]); } else if (payloadLength < 0xffff) { header = new Uint8Array([ 0x80 | frame.opcode, diff --git a/ws/sha1.ts b/ws/sha1.ts index 916bbd9b3..38101fb22 100644 --- a/ws/sha1.ts +++ b/ws/sha1.ts @@ -64,7 +64,7 @@ export class Sha1 { let code, index = 0, i, - start = this._start, + start = this._start, length = message.length || 0, blocks = this._blocks; @@ -369,8 +369,7 @@ export class Sha1 { arrayBuffer() { this.finalize(); - return Uint32Array.of( - this._h0, this._h1, this._h2, this._h3, this._h4 - ).buffer; + return Uint32Array.of(this._h0, this._h1, this._h2, this._h3, this._h4) + .buffer; } } -- cgit v1.2.3 From deedb5e84e7878f70f652059dabace3ec64e2eda Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 24 Jan 2019 13:23:45 -0500 Subject: Disable cat.ts test because it's broken on Windows. Original: https://github.com/denoland/deno_std/commit/8ad47e358426b71d3e2508c0d4ab00f241ebd4eb --- examples/test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/test.ts b/examples/test.ts index 8d16e1703..58013c70b 100644 --- a/examples/test.ts +++ b/examples/test.ts @@ -11,6 +11,7 @@ test(function t2() { }); /** A more complicated test that runs a subprocess. */ +/* TODO re-enable this test. Seems to be broken on Windows. test(async function catSmoke() { const p = run({ args: ["deno", "examples/cat.ts", "README.md"], @@ -19,3 +20,4 @@ test(async function catSmoke() { const s = await p.status(); assertEqual(s.code, 0); }); +*/ -- cgit v1.2.3 From 57b6fdb2eb743260a771489b98eb9e691ccad236 Mon Sep 17 00:00:00 2001 From: Max Graey Date: Thu, 24 Jan 2019 21:06:24 +0200 Subject: Clean up path module (denoland/deno_std#149) Original: https://github.com/denoland/deno_std/commit/47e6fc775aaf1c4970e4098822aa40c3203286ae --- fs/path/constants.ts | 3 +- fs/path/interface.ts | 24 +------ fs/path/mod.ts | 191 +++++++++++++++++++++++++-------------------------- 3 files changed, 95 insertions(+), 123 deletions(-) diff --git a/fs/path/constants.ts b/fs/path/constants.ts index b440be9cc..ce121f9ac 100644 --- a/fs/path/constants.ts +++ b/fs/path/constants.ts @@ -3,8 +3,6 @@ import { platform } from "deno"; -const isWindows = platform.os === "win"; - // Alphabet chars. export const CHAR_UPPERCASE_A = 65; /* A */ export const CHAR_LOWERCASE_A = 97; /* a */ @@ -50,4 +48,5 @@ export const CHAR_EQUAL = 61; /* = */ export const CHAR_0 = 48; /* 0 */ export const CHAR_9 = 57; /* 9 */ +export const isWindows = platform.os === "win"; export const EOL = isWindows ? "\r\n" : "\n"; diff --git a/fs/path/interface.ts b/fs/path/interface.ts index 84a3030ff..a140a4ca5 100644 --- a/fs/path/interface.ts +++ b/fs/path/interface.ts @@ -23,25 +23,5 @@ export interface ParsedPath { */ name: string; } -export interface FormatInputPathObject { - /** - * The root of the path such as '/' or 'c:\' - */ - root?: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir?: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base?: string; - /** - * The file extension (if any) such as '.html' - */ - ext?: string; - /** - * The file name without extension (if any) such as 'index' - */ - name?: string; -} + +export type FormatInputPathObject = Partial diff --git a/fs/path/mod.ts b/fs/path/mod.ts index 4201c52ad..114c904a2 100644 --- a/fs/path/mod.ts +++ b/fs/path/mod.ts @@ -1,7 +1,10 @@ // Copyright the Browserify authors. MIT License. // Ported from https://github.com/browserify/path-browserify/ +import { cwd, env } from "deno"; +import { FormatInputPathObject, ParsedPath } from "./interface.ts"; import { + isWindows, CHAR_UPPERCASE_A, CHAR_LOWERCASE_A, CHAR_UPPERCASE_Z, @@ -12,10 +15,8 @@ import { CHAR_COLON, CHAR_QUESTION_MARK } from "./constants.ts"; -import { cwd, env, platform } from "deno"; -import { FormatInputPathObject, ParsedPath } from "./interface.ts"; -function assertPath(path: string) { +function assertPath(path: string): void { if (typeof path !== "string") { throw new TypeError( `Path must be a string. Received ${JSON.stringify(path)}` @@ -23,18 +24,18 @@ function assertPath(path: string) { } } -function isPathSeparator(code: number) { - return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +function isPosixPathSeparator(code: number): boolean { + return code === CHAR_FORWARD_SLASH; } -function isPosixPathSeparator(code: number) { - return code === CHAR_FORWARD_SLASH; +function isPathSeparator(code: number): boolean { + return isPosixPathSeparator(code) || code === CHAR_BACKWARD_SLASH; } -function isWindowsDeviceRoot(code: number) { +function isWindowsDeviceRoot(code: number): boolean { return ( - (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || - (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z) + (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z) || + (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ); } @@ -44,14 +45,14 @@ function normalizeString( allowAboveRoot: boolean, separator: string, isPathSeparator: (code: number) => boolean -) { +): string { let res = ""; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let code: number; - for (let i = 0; i <= path.length; ++i) { - if (i < path.length) code = path.charCodeAt(i); + for (let i = 0, len = path.length; i <= len; ++i) { + if (i < len) code = path.charCodeAt(i); else if (isPathSeparator(code)) break; else code = CHAR_FORWARD_SLASH; @@ -106,30 +107,26 @@ function normalizeString( return res; } -function _format(sep: string, pathObject: FormatInputPathObject) { - const dir = pathObject.dir || pathObject.root; - const base = +function _format(sep: string, pathObject: FormatInputPathObject): string { + const dir: string | null = pathObject.dir || pathObject.root; + const base: string = pathObject.base || (pathObject.name || "") + (pathObject.ext || ""); - if (!dir) { - return base; - } - if (dir === pathObject.root) { - return dir + base; - } + if (!dir) return base; + if (dir === pathObject.root) return dir + base; return dir + sep + base; } export const win32 = { // path.resolve([from ...], to) - resolve: function resolve(...pathSegments: string[]) { + resolve(...pathSegments: string[]): string { let resolvedDevice = ""; let resolvedTail = ""; let resolvedAbsolute = false; - for (let i = arguments.length - 1; i >= -1; i--) { + for (let i = pathSegments.length - 1; i >= -1; i--) { let path: string; if (i >= 0) { - path = arguments[i]; + path = pathSegments[i]; } else if (!resolvedDevice) { path = cwd(); } else { @@ -152,12 +149,11 @@ export const win32 = { assertPath(path); + const len = path.length; + // Skip empty entries - if (path.length === 0) { - continue; - } + if (len === 0) continue; - let len = path.length; let rootEnd = 0; let device = ""; let isAbsolute = false; @@ -249,9 +245,7 @@ export const win32 = { resolvedAbsolute = isAbsolute; } - if (resolvedDevice.length > 0 && resolvedAbsolute) { - break; - } + if (resolvedAbsolute && resolvedDevice.length > 0) break; } // At this point the path should be resolved to a full absolute path, @@ -271,7 +265,7 @@ export const win32 = { ); }, - normalize: function normalize(path: string) { + normalize(path: string): string { assertPath(path); const len = path.length; if (len === 0) return "."; @@ -384,7 +378,7 @@ export const win32 = { } }, - isAbsolute: function isAbsolute(path: string) { + isAbsolute(path: string): boolean { assertPath(path); const len = path.length; if (len === 0) return false; @@ -402,17 +396,18 @@ export const win32 = { return false; }, - join: function join(...paths: string[]) { - if (arguments.length === 0) return "."; + join(...paths: string[]): string { + const pathsCount = paths.length; + if (pathsCount === 0) return "."; let joined: string; let firstPart: string; - for (let i = 0; i < arguments.length; ++i) { - let arg = arguments[i]; - assertPath(arg); - if (arg.length > 0) { - if (joined === undefined) joined = firstPart = arg; - else joined += `\\${arg}`; + for (let i = 0; i < pathsCount; ++i) { + let path = paths[i]; + assertPath(path); + if (path.length > 0) { + if (joined === undefined) joined = firstPart = path; + else joined += `\\${path}`; } } @@ -466,7 +461,7 @@ export const win32 = { // from = 'C:\\orandea\\test\\aaa' // to = 'C:\\orandea\\impl\\bbb' // The output of the function should be: '..\\..\\impl\\bbb' - relative: function relative(from: string, to: string) { + relative(from: string, to: string): string { assertPath(from); assertPath(to); @@ -484,11 +479,11 @@ export const win32 = { // Trim any leading backslashes let fromStart = 0; - for (; fromStart < from.length; ++fromStart) { + let fromEnd = from.length; + for (; fromStart < fromEnd; ++fromStart) { if (from.charCodeAt(fromStart) !== CHAR_BACKWARD_SLASH) break; } // Trim trailing backslashes (applicable to UNC paths only) - let fromEnd = from.length; for (; fromEnd - 1 > fromStart; --fromEnd) { if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break; } @@ -496,11 +491,11 @@ export const win32 = { // Trim any leading backslashes let toStart = 0; - for (; toStart < to.length; ++toStart) { + let toEnd = to.length; + for (; toStart < toEnd; ++toStart) { if (to.charCodeAt(toStart) !== CHAR_BACKWARD_SLASH) break; } // Trim trailing backslashes (applicable to UNC paths only) - let toEnd = to.length; for (; toEnd - 1 > toStart; --toEnd) { if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break; } @@ -570,13 +565,10 @@ export const win32 = { } }, - toNamespacedPath: function toNamespacedPath(path: string) { + toNamespacedPath(path: string): string { // Note: this will *probably* throw somewhere. if (typeof path !== "string") return path; - - if (path.length === 0) { - return ""; - } + if (path.length === 0) return ""; const resolvedPath = win32.resolve(path); @@ -607,7 +599,7 @@ export const win32 = { return path; }, - dirname: function dirname(path: string) { + dirname(path: string): string { assertPath(path); const len = path.length; if (len === 0) return "."; @@ -695,10 +687,12 @@ export const win32 = { return path.slice(0, end); }, - basename: function basename(path: string, ext = "") { + basename(path: string, ext = ""): string { if (ext !== undefined && typeof ext !== "string") throw new TypeError('"ext" argument must be a string'); + assertPath(path); + let start = 0; let end = -1; let matchedSlash = true; @@ -777,7 +771,7 @@ export const win32 = { } }, - extname: function extname(path: string) { + extname(path: string): string { assertPath(path); let start = 0; let startDot = -1; @@ -841,7 +835,7 @@ export const win32 = { return path.slice(startDot, end); }, - format: function format(pathObject: FormatInputPathObject) { + format(pathObject: FormatInputPathObject): string { if (pathObject === null || typeof pathObject !== "object") { throw new TypeError( `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` @@ -850,13 +844,14 @@ export const win32 = { return _format("\\", pathObject); }, - parse: function parse(path: string) { + parse(path: string): ParsedPath { assertPath(path); let ret = { root: "", dir: "", base: "", ext: "", name: "" } as ParsedPath; - if (path.length === 0) return ret; - let len = path.length; + const len = path.length; + if (len === 0) return ret; + let rootEnd = 0; let code = path.charCodeAt(0); @@ -985,15 +980,15 @@ export const win32 = { } else { ret.name = path.slice(startPart, startDot); ret.base = path.slice(startPart, end); - ret.ext = path.slice(startDot, end); + ret.ext = path.slice(startDot, end); } // If the directory is the root, use the entire root as the `dir` including // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the // trailing slash (`C:\abc\def` -> `C:\abc`). - if (startPart > 0 && startPart !== rootEnd) + if (startPart > 0 && startPart !== rootEnd) { ret.dir = path.slice(0, startPart - 1); - else ret.dir = ret.root; + } else ret.dir = ret.root; return ret; }, @@ -1006,16 +1001,15 @@ export const win32 = { export const posix = { // path.resolve([from ...], to) - resolve: function resolve(...pathSegments: string[]) { + resolve(...pathSegments: string[]): string { let resolvedPath = ""; let resolvedAbsolute = false; - for (let i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) { let path: string; - if (i >= 0) path = arguments[i]; - else { - path = cwd(); - } + + if (i >= 0) path = pathSegments[i]; + else path = cwd(); assertPath(path); @@ -1042,14 +1036,11 @@ export const posix = { if (resolvedAbsolute) { if (resolvedPath.length > 0) return `/${resolvedPath}`; else return "/"; - } else if (resolvedPath.length > 0) { - return resolvedPath; - } else { - return "."; - } + } else if (resolvedPath.length > 0) return resolvedPath; + else return "."; }, - normalize: function normalize(path: string) { + normalize(path: string): string { assertPath(path); if (path.length === 0) return "."; @@ -1068,27 +1059,27 @@ export const posix = { return path; }, - isAbsolute: function isAbsolute(path: string) { + isAbsolute(path: string): boolean { assertPath(path); return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; }, - join: function join(...paths: string[]) { - if (arguments.length === 0) return "."; - let joined: string; - for (let i = 0; i < arguments.length; ++i) { - let arg = arguments[i]; - assertPath(arg); - if (arg.length > 0) { - if (joined === undefined) joined = arg; - else joined += `/${arg}`; + join(...paths: string[]): string { + if (paths.length === 0) return "."; + let joined: string | undefined; + for (let i = 0, len = paths.length; i < len; ++i) { + let path = paths[i]; + assertPath(path); + if (path.length > 0) { + if (!joined) joined = path; + else joined += `/${path}`; } } - if (joined === undefined) return "."; + if (!joined) return "."; return posix.normalize(joined); }, - relative: function relative(from: string, to: string) { + relative(from: string, to: string): string { assertPath(from); assertPath(to); @@ -1101,18 +1092,18 @@ export const posix = { // Trim any leading backslashes let fromStart = 1; - for (; fromStart < from.length; ++fromStart) { + let fromEnd = from.length; + for (; fromStart < fromEnd; ++fromStart) { if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) break; } - let fromEnd = from.length; let fromLen = fromEnd - fromStart; // Trim any leading backslashes let toStart = 1; - for (; toStart < to.length; ++toStart) { + const toEnd = to.length; + for (; toStart < toEnd; ++toStart) { if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) break; } - let toEnd = to.length; let toLen = toEnd - toStart; // Compare paths to find the longest common path from root @@ -1170,12 +1161,12 @@ export const posix = { } }, - toNamespacedPath: function toNamespacedPath(path: string) { + toNamespacedPath(path: string): string { // Non-op on posix systems return path; }, - dirname: function dirname(path: string) { + dirname(path: string): string { assertPath(path); if (path.length === 0) return "."; const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; @@ -1198,7 +1189,7 @@ export const posix = { return path.slice(0, end); }, - basename: function basename(path: string, ext = "") { + basename(path: string, ext = ""): string { if (ext !== undefined && typeof ext !== "string") throw new TypeError('"ext" argument must be a string'); assertPath(path); @@ -1271,7 +1262,7 @@ export const posix = { } }, - extname: function extname(path: string) { + extname(path: string): string { assertPath(path); let startDot = -1; let startPart = 0; @@ -1321,7 +1312,7 @@ export const posix = { return path.slice(startDot, end); }, - format: function format(pathObject: FormatInputPathObject) { + format(pathObject: FormatInputPathObject): string { if (pathObject === null || typeof pathObject !== "object") { throw new TypeError( `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` @@ -1330,7 +1321,7 @@ export const posix = { return _format("/", pathObject); }, - parse: function parse(path: string) { + parse(path: string): ParsedPath { assertPath(path); let ret = { root: "", dir: "", base: "", ext: "", name: "" } as ParsedPath; @@ -1391,9 +1382,11 @@ export const posix = { (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) ) { if (end !== -1) { - if (startPart === 0 && isAbsolute) + if (startPart === 0 && isAbsolute) { ret.base = ret.name = path.slice(1, end); - else ret.base = ret.name = path.slice(startPart, end); + } else { + ret.base = ret.name = path.slice(startPart, end); + } } } else { if (startPart === 0 && isAbsolute) { @@ -1421,7 +1414,7 @@ export const posix = { posix.win32 = win32.win32 = win32; posix.posix = win32.posix = posix; -const module = platform.os === "win" ? win32 : posix; +const module = isWindows ? win32 : posix; export const resolve = module.resolve; export const normalize = module.normalize; -- cgit v1.2.3 From 6a0e32dc35dd27807f4b95556ddb8c1fe26fae89 Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 24 Jan 2019 16:25:13 -0500 Subject: testing: Don't automatically run on import (denoland/deno_std#129) Original: https://github.com/denoland/deno_std/commit/ec1675a8cad2b9044ac8cf205920c0f230127133 --- test.ts | 2 ++ testing/main.ts | 3 +++ testing/mod.ts | 4 +--- 3 files changed, 6 insertions(+), 3 deletions(-) create mode 100644 testing/main.ts diff --git a/test.ts b/test.ts index b9fcd74e0..6850fc5af 100755 --- a/test.ts +++ b/test.ts @@ -23,3 +23,5 @@ import "testing/test.ts"; import "textproto/test.ts"; import "ws/sha1_test.ts"; import "ws/test.ts"; + +import "testing/main.ts"; diff --git a/testing/main.ts b/testing/main.ts new file mode 100644 index 000000000..d7e703697 --- /dev/null +++ b/testing/main.ts @@ -0,0 +1,3 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { runTests } from "mod.ts"; +runTests(); diff --git a/testing/mod.ts b/testing/mod.ts index 42f3939c5..762d37c48 100644 --- a/testing/mod.ts +++ b/testing/mod.ts @@ -238,7 +238,7 @@ function green_ok() { return FG_GREEN + "ok" + RESET; } -async function runTests() { +export async function runTests() { let passed = 0; let failed = 0; @@ -283,5 +283,3 @@ async function runTests() { }, 0); } } - -setTimeout(runTests, 0); -- cgit v1.2.3 From be65b2b0f69c32d0ac357976665c702adca02e37 Mon Sep 17 00:00:00 2001 From: James Garbutt <43081j@users.noreply.github.com> Date: Sat, 26 Jan 2019 11:51:19 +0000 Subject: testing: add fail() (denoland/deno_std#123) Original: https://github.com/denoland/deno_std/commit/c1c18c9469663ec54177d2b25f9778227b7dc813 --- testing/mod.ts | 7 +++++++ testing/test.ts | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/testing/mod.ts b/testing/mod.ts index 762d37c48..06089a80a 100644 --- a/testing/mod.ts +++ b/testing/mod.ts @@ -74,6 +74,13 @@ const assertions = { } }, + /** + * Forcefully throws a failed assertion + */ + fail(msg?: string): void { + assert(false, `Failed assertion${msg ? `: ${msg}` : "."}`); + }, + /** Executes a function, expecting it to throw. If it does not, then it * throws. An error class and a string that should be included in the * error message can also be asserted. diff --git a/testing/test.ts b/testing/test.ts index 1765fd6b6..347a31b56 100644 --- a/testing/test.ts +++ b/testing/test.ts @@ -31,6 +31,13 @@ test(function testingAssertEqual() { assert(assertEqual === assert.equal); }); +test(function testingAssertFail() { + let didThrow = false; + + assert.throws(assert.fail, Error, "Failed assertion."); + assert.throws(() => { assert.fail("foo"); }, Error, "Failed assertion: foo"); +}); + test(function testingAssertEqualActualUncoercable() { let didThrow = false; const a = Object.create(null); -- cgit v1.2.3 From 9c7d1244ede99166119e1707e52c324e1b9eb4ab Mon Sep 17 00:00:00 2001 From: Dmitry Sharshakov Date: Sat, 26 Jan 2019 21:17:34 +0300 Subject: Make .editorconfig root (denoland/deno_std#157) Original: https://github.com/denoland/deno_std/commit/7edda96a2dc882b19299c3cc30ddbd04c35d413d --- .editorconfig | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.editorconfig b/.editorconfig index 9582f9aae..d25df65a1 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,3 +1,5 @@ +root = true + [*.ts] end_of_line = lf insert_final_newline = true -- cgit v1.2.3 From 490c2eb5069c513f19429cdfa902796eb2819c2a Mon Sep 17 00:00:00 2001 From: Max Graey Date: Sat, 26 Jan 2019 21:09:53 +0200 Subject: add charset & trim_trailing_whitespace (denoland/deno_std#158) Original: https://github.com/denoland/deno_std/commit/37e3239fc09f3046a6bd17c060b83d02d42f922f --- .editorconfig | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.editorconfig b/.editorconfig index d25df65a1..2bdd36acf 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,11 +1,14 @@ root = true [*.ts] +charset = utf-8 end_of_line = lf insert_final_newline = true +trim_trailing_whitespace = true indent_style = space indent_size = 2 [*.yml] indent_style = space +trim_trailing_whitespace = true indent_size = 2 -- cgit v1.2.3 From 75dab82adbf64cb021b0133771a782c285991a4b Mon Sep 17 00:00:00 2001 From: Yoshiya Hinosawa Date: Sun, 27 Jan 2019 13:19:56 +0900 Subject: Port prettier (denoland/deno_std#156) Original: https://github.com/denoland/deno_std/commit/b792fe8c7234287ce133e15d63cae5295256fd19 --- azure-pipelines.yml | 3 + flags/tests/parse.ts | 0 format.ts | 145 +- fs/path/interface.ts | 2 +- fs/path/mod.ts | 2 +- prettier/parser_markdown.js | 11 + prettier/parser_typescript.js | 11 + prettier/prettier.ts | 9 + prettier/standalone.js | 30688 ++++++++++++++++++++++++++++++++++++++++ testing/test.ts | 8 +- 10 files changed, 30853 insertions(+), 26 deletions(-) mode change 100644 => 100755 flags/tests/parse.ts create mode 100644 prettier/parser_markdown.js create mode 100644 prettier/parser_typescript.js create mode 100644 prettier/prettier.ts create mode 100644 prettier/standalone.js diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 97580b026..963cf170a 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -10,6 +10,7 @@ jobs: - script: curl -L https://deno.land/x/install/install.sh | sh -s $(DENO_VERSION) - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' - script: deno test.ts --allow-run --allow-net --allow-write + - script: deno format.ts --allow-run --allow-write --check - job: 'Mac' pool: @@ -18,6 +19,7 @@ jobs: - script: curl -L https://deno.land/x/install/install.sh | sh -s $(DENO_VERSION) - script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/' - script: deno test.ts --allow-run --allow-net --allow-write + - script: deno format.ts --allow-run --allow-write --check - job: 'Windows' pool: @@ -26,3 +28,4 @@ jobs: - powershell: iwr https://deno.land/x/install/install.ps1 -out install.ps1; .\install.ps1 $(DENO_VERSION) - script: echo '##vso[task.prependpath]C:\Users\VssAdministrator\.deno\bin\' - script: 'C:\Users\VssAdministrator\.deno\bin\deno.exe test.ts --allow-run --allow-net --allow-write' + - script: 'C:\Users\VssAdministrator\.deno\bin\deno.exe format.ts --allow-run --allow-write --check' diff --git a/flags/tests/parse.ts b/flags/tests/parse.ts old mode 100644 new mode 100755 diff --git a/format.ts b/format.ts index cee84a299..681e67774 100755 --- a/format.ts +++ b/format.ts @@ -1,36 +1,135 @@ -#!/usr/bin/env deno --allow-run +#!/usr/bin/env deno --allow-run --allow-write // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +/** + * This script formats the source files in the repository. + * + * Usage: deno format.ts [--check] + * + * Options: + * --check Checks if the source files are formatted. + */ +import { args, platform, readAll, exit, run, readFile, writeFile } from "deno"; +import { parse } from "./flags/mod.ts"; +import { prettier, prettierPlugins } from "./prettier/prettier.ts"; -import { readAll, exit, run } from "deno"; +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); -async function checkVersion() { - const prettierVersion = run({ - args: ["bash", "-c", "prettier --version"], - stdout: "piped" +// Runs commands in cross-platform way +function xrun(opts) { + return run({ + ...opts, + args: platform.os === "win" ? ["cmd.exe", "/c", ...opts.args] : opts.args }); - const b = await readAll(prettierVersion.stdout); - const s = await prettierVersion.status(); - if (s.code != 0) { - console.log("error calling prettier --version error"); - exit(s.code); +} + +// Gets the source files in the repository +async function getSourceFiles() { + return decoder + .decode( + await readAll( + xrun({ + args: ["git", "ls-files"], + stdout: "piped" + }).stdout + ) + ) + .trim() + .split(/\r?\n/); +} + +/** + * Checks if the file has been formatted with prettier. + */ +async function checkFile( + filename: string, + parser: "typescript" | "markdown" +): Promise { + const text = decoder.decode(await readFile(filename)); + const formatted = prettier.check(text, { + parser, + plugins: prettierPlugins + }); + + if (!formatted) { + // TODO: print some diff info here to show why this failed + console.error(`${filename} ... Not formatted`); + } + + return formatted; +} + +/** + * Formats the given file. + */ +async function formatFile( + filename: string, + parser: "typescript" | "markdown" +): Promise { + const text = decoder.decode(await readFile(filename)); + const formatted = prettier.format(text, { + parser, + plugins: prettierPlugins + }); + + if (text !== formatted) { + console.log(`Formatting ${filename}`); + await writeFile(filename, encoder.encode(formatted)); } - const version = new TextDecoder().decode(b).trim(); - const requiredVersion = "1.15"; - if (!version.startsWith(requiredVersion)) { - console.log(`Required prettier version: ${requiredVersion}`); - console.log(`Installed prettier version: ${version}`); +} + +/** + * Checks if the all files have been formatted with prettier. + */ +async function checkSourceFiles() { + const checks = []; + + (await getSourceFiles()).forEach(file => { + if (/\.ts$/.test(file)) { + checks.push(checkFile(file, "typescript")); + } else if (/\.md$/.test(file)) { + checks.push(checkFile(file, "markdown")); + } + }); + + const results = await Promise.all(checks); + + if (results.every(result => result)) { + exit(0); + } else { exit(1); } } -async function main() { - await checkVersion(); +/** + * Formats the all files with prettier. + */ +async function formatSourceFiles() { + const formats = []; - const prettier = run({ - args: ["bash", "-c", "prettier --write '**/*.ts' '**/*.md'"] + (await getSourceFiles()).forEach(file => { + if (/\.ts$/.test(file)) { + formats.push(formatFile(file, "typescript")); + } else if (/\.md$/.test(file)) { + formats.push(formatFile(file, "markdown")); + } }); - const s = await prettier.status(); - exit(s.code); + + await Promise.all(formats); + exit(0); +} + +async function main(opts) { + try { + if (opts.check) { + await checkSourceFiles(); + } else { + await formatSourceFiles(); + } + } catch (e) { + console.log(e); + exit(1); + } } -main(); +main(parse(args)); diff --git a/fs/path/interface.ts b/fs/path/interface.ts index a140a4ca5..b31c89ea7 100644 --- a/fs/path/interface.ts +++ b/fs/path/interface.ts @@ -24,4 +24,4 @@ export interface ParsedPath { name: string; } -export type FormatInputPathObject = Partial +export type FormatInputPathObject = Partial; diff --git a/fs/path/mod.ts b/fs/path/mod.ts index 114c904a2..7adb230d2 100644 --- a/fs/path/mod.ts +++ b/fs/path/mod.ts @@ -980,7 +980,7 @@ export const win32 = { } else { ret.name = path.slice(startPart, startDot); ret.base = path.slice(startPart, end); - ret.ext = path.slice(startDot, end); + ret.ext = path.slice(startDot, end); } // If the directory is the root, use the entire root as the `dir` including diff --git a/prettier/parser_markdown.js b/prettier/parser_markdown.js new file mode 100644 index 000000000..5f28312f3 --- /dev/null +++ b/prettier/parser_markdown.js @@ -0,0 +1,11 @@ +// This file is copied from prettier@1.16.1 +/** + * Copyright © James Long and contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(r.prettierPlugins=r.prettierPlugins||{},r.prettierPlugins.markdown=e())}(globalThis,function(){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(r){return typeof r}:function(r){return r&&"function"==typeof Symbol&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r})(e)}function e(r,e){return t(r)||function(r,e){var t=[],u=!0,n=!1,a=void 0;try{for(var o,i=r[Symbol.iterator]();!(u=(o=i.next()).done)&&(t.push(o.value),!e||t.length!==e);u=!0);}catch(r){n=!0,a=r}finally{try{u||null==i.return||i.return()}finally{if(n)throw a}}return t}(r,e)||u()}function t(r){if(Array.isArray(r))return r}function u(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}var n=function(){for(var r={},e=0;ee)return{line:t+1,column:e-(r[t-1]||0)+1,offset:e};return{}}}(e),toOffset:function(r){return function(e){var t=e&&e.line,u=e&&e.column;if(!isNaN(t)&&!isNaN(u)&&t-1 in r)return(r[t-2]||0)+u-1||0;return-1}}(e)}};var h=function(r,e){return function(t){var u,n=0,a=t.indexOf("\\"),o=r[e],i=[];for(;-1!==a;)i.push(t.slice(n,a)),n=a+1,(u=t.charAt(n))&&-1!==o.indexOf(u)||i.push("\\"),a=t.indexOf("\\",n);return i.push(t.slice(n)),i.join("")}};var g={AEli:"Æ",AElig:"Æ",AM:"&",AMP:"&",Aacut:"Á",Aacute:"Á",Abreve:"Ă",Acir:"Â",Acirc:"Â",Acy:"А",Afr:"𝔄",Agrav:"À",Agrave:"À",Alpha:"Α",Amacr:"Ā",And:"⩓",Aogon:"Ą",Aopf:"𝔸",ApplyFunction:"⁡",Arin:"Å",Aring:"Å",Ascr:"𝒜",Assign:"≔",Atild:"Ã",Atilde:"Ã",Aum:"Ä",Auml:"Ä",Backslash:"∖",Barv:"⫧",Barwed:"⌆",Bcy:"Б",Because:"∵",Bernoullis:"ℬ",Beta:"Β",Bfr:"𝔅",Bopf:"𝔹",Breve:"˘",Bscr:"ℬ",Bumpeq:"≎",CHcy:"Ч",COP:"©",COPY:"©",Cacute:"Ć",Cap:"⋒",CapitalDifferentialD:"ⅅ",Cayleys:"ℭ",Ccaron:"Č",Ccedi:"Ç",Ccedil:"Ç",Ccirc:"Ĉ",Cconint:"∰",Cdot:"Ċ",Cedilla:"¸",CenterDot:"·",Cfr:"ℭ",Chi:"Χ",CircleDot:"⊙",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",Colon:"∷",Colone:"⩴",Congruent:"≡",Conint:"∯",ContourIntegral:"∮",Copf:"ℂ",Coproduct:"∐",CounterClockwiseContourIntegral:"∳",Cross:"⨯",Cscr:"𝒞",Cup:"⋓",CupCap:"≍",DD:"ⅅ",DDotrahd:"⤑",DJcy:"Ђ",DScy:"Ѕ",DZcy:"Џ",Dagger:"‡",Darr:"↡",Dashv:"⫤",Dcaron:"Ď",Dcy:"Д",Del:"∇",Delta:"Δ",Dfr:"𝔇",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",Diamond:"⋄",DifferentialD:"ⅆ",Dopf:"𝔻",Dot:"¨",DotDot:"⃜",DotEqual:"≐",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",Downarrow:"⇓",Dscr:"𝒟",Dstrok:"Đ",ENG:"Ŋ",ET:"Ð",ETH:"Ð",Eacut:"É",Eacute:"É",Ecaron:"Ě",Ecir:"Ê",Ecirc:"Ê",Ecy:"Э",Edot:"Ė",Efr:"𝔈",Egrav:"È",Egrave:"È",Element:"∈",Emacr:"Ē",EmptySmallSquare:"◻",EmptyVerySmallSquare:"▫",Eogon:"Ę",Eopf:"𝔼",Epsilon:"Ε",Equal:"⩵",EqualTilde:"≂",Equilibrium:"⇌",Escr:"ℰ",Esim:"⩳",Eta:"Η",Eum:"Ë",Euml:"Ë",Exists:"∃",ExponentialE:"ⅇ",Fcy:"Ф",Ffr:"𝔉",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",Fopf:"𝔽",ForAll:"∀",Fouriertrf:"ℱ",Fscr:"ℱ",GJcy:"Ѓ",G:">",GT:">",Gamma:"Γ",Gammad:"Ϝ",Gbreve:"Ğ",Gcedil:"Ģ",Gcirc:"Ĝ",Gcy:"Г",Gdot:"Ġ",Gfr:"𝔊",Gg:"⋙",Gopf:"𝔾",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",Gt:"≫",HARDcy:"Ъ",Hacek:"ˇ",Hat:"^",Hcirc:"Ĥ",Hfr:"ℌ",HilbertSpace:"ℋ",Hopf:"ℍ",HorizontalLine:"─",Hscr:"ℋ",Hstrok:"Ħ",HumpDownHump:"≎",HumpEqual:"≏",IEcy:"Е",IJlig:"IJ",IOcy:"Ё",Iacut:"Í",Iacute:"Í",Icir:"Î",Icirc:"Î",Icy:"И",Idot:"İ",Ifr:"ℑ",Igrav:"Ì",Igrave:"Ì",Im:"ℑ",Imacr:"Ī",ImaginaryI:"ⅈ",Implies:"⇒",Int:"∬",Integral:"∫",Intersection:"⋂",InvisibleComma:"⁣",InvisibleTimes:"⁢",Iogon:"Į",Iopf:"𝕀",Iota:"Ι",Iscr:"ℐ",Itilde:"Ĩ",Iukcy:"І",Ium:"Ï",Iuml:"Ï",Jcirc:"Ĵ",Jcy:"Й",Jfr:"𝔍",Jopf:"𝕁",Jscr:"𝒥",Jsercy:"Ј",Jukcy:"Є",KHcy:"Х",KJcy:"Ќ",Kappa:"Κ",Kcedil:"Ķ",Kcy:"К",Kfr:"𝔎",Kopf:"𝕂",Kscr:"𝒦",LJcy:"Љ",L:"<",LT:"<",Lacute:"Ĺ",Lambda:"Λ",Lang:"⟪",Laplacetrf:"ℒ",Larr:"↞",Lcaron:"Ľ",Lcedil:"Ļ",Lcy:"Л",LeftAngleBracket:"⟨",LeftArrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",LeftRightArrow:"↔",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",Leftarrow:"⇐",Leftrightarrow:"⇔",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",LessLess:"⪡",LessSlantEqual:"⩽",LessTilde:"≲",Lfr:"𝔏",Ll:"⋘",Lleftarrow:"⇚",Lmidot:"Ŀ",LongLeftArrow:"⟵",LongLeftRightArrow:"⟷",LongRightArrow:"⟶",Longleftarrow:"⟸",Longleftrightarrow:"⟺",Longrightarrow:"⟹",Lopf:"𝕃",LowerLeftArrow:"↙",LowerRightArrow:"↘",Lscr:"ℒ",Lsh:"↰",Lstrok:"Ł",Lt:"≪",Mcy:"М",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",MinusPlus:"∓",Mopf:"𝕄",Mscr:"ℳ",Mu:"Μ",NJcy:"Њ",Nacute:"Ń",Ncaron:"Ň",Ncedil:"Ņ",Ncy:"Н",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",Nfr:"𝔑",NoBreak:"⁠",NonBreakingSpace:" ",Nopf:"ℕ",Not:"⫬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",Nscr:"𝒩",Ntild:"Ñ",Ntilde:"Ñ",Nu:"Ν",OElig:"Œ",Oacut:"Ó",Oacute:"Ó",Ocir:"Ô",Ocirc:"Ô",Ocy:"О",Odblac:"Ő",Ofr:"𝔒",Ograv:"Ò",Ograve:"Ò",Omacr:"Ō",Omega:"Ω",Omicron:"Ο",Oopf:"𝕆",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",Or:"⩔",Oscr:"𝒪",Oslas:"Ø",Oslash:"Ø",Otild:"Õ",Otilde:"Õ",Otimes:"⨷",Oum:"Ö",Ouml:"Ö",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",PartialD:"∂",Pcy:"П",Pfr:"𝔓",Phi:"Φ",Pi:"Π",PlusMinus:"±",Poincareplane:"ℌ",Popf:"ℙ",Pr:"⪻",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",Prime:"″",Product:"∏",Proportion:"∷",Proportional:"∝",Pscr:"𝒫",Psi:"Ψ",QUO:'"',QUOT:'"',Qfr:"𝔔",Qopf:"ℚ",Qscr:"𝒬",RBarr:"⤐",RE:"®",REG:"®",Racute:"Ŕ",Rang:"⟫",Rarr:"↠",Rarrtl:"⤖",Rcaron:"Ř",Rcedil:"Ŗ",Rcy:"Р",Re:"ℜ",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",Rfr:"ℜ",Rho:"Ρ",RightAngleBracket:"⟩",RightArrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",Rightarrow:"⇒",Ropf:"ℝ",RoundImplies:"⥰",Rrightarrow:"⇛",Rscr:"ℛ",Rsh:"↱",RuleDelayed:"⧴",SHCHcy:"Щ",SHcy:"Ш",SOFTcy:"Ь",Sacute:"Ś",Sc:"⪼",Scaron:"Š",Scedil:"Ş",Scirc:"Ŝ",Scy:"С",Sfr:"𝔖",ShortDownArrow:"↓",ShortLeftArrow:"←",ShortRightArrow:"→",ShortUpArrow:"↑",Sigma:"Σ",SmallCircle:"∘",Sopf:"𝕊",Sqrt:"√",Square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",Sscr:"𝒮",Star:"⋆",Sub:"⋐",Subset:"⋐",SubsetEqual:"⊆",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",SuchThat:"∋",Sum:"∑",Sup:"⋑",Superset:"⊃",SupersetEqual:"⊇",Supset:"⋑",THOR:"Þ",THORN:"Þ",TRADE:"™",TSHcy:"Ћ",TScy:"Ц",Tab:"\t",Tau:"Τ",Tcaron:"Ť",Tcedil:"Ţ",Tcy:"Т",Tfr:"𝔗",Therefore:"∴",Theta:"Θ",ThickSpace:"  ",ThinSpace:" ",Tilde:"∼",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",Topf:"𝕋",TripleDot:"⃛",Tscr:"𝒯",Tstrok:"Ŧ",Uacut:"Ú",Uacute:"Ú",Uarr:"↟",Uarrocir:"⥉",Ubrcy:"Ў",Ubreve:"Ŭ",Ucir:"Û",Ucirc:"Û",Ucy:"У",Udblac:"Ű",Ufr:"𝔘",Ugrav:"Ù",Ugrave:"Ù",Umacr:"Ū",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",Uopf:"𝕌",UpArrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",UpEquilibrium:"⥮",UpTee:"⊥",UpTeeArrow:"↥",Uparrow:"⇑",Updownarrow:"⇕",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",Upsilon:"Υ",Uring:"Ů",Uscr:"𝒰",Utilde:"Ũ",Uum:"Ü",Uuml:"Ü",VDash:"⊫",Vbar:"⫫",Vcy:"В",Vdash:"⊩",Vdashl:"⫦",Vee:"⋁",Verbar:"‖",Vert:"‖",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",Vopf:"𝕍",Vscr:"𝒱",Vvdash:"⊪",Wcirc:"Ŵ",Wedge:"⋀",Wfr:"𝔚",Wopf:"𝕎",Wscr:"𝒲",Xfr:"𝔛",Xi:"Ξ",Xopf:"𝕏",Xscr:"𝒳",YAcy:"Я",YIcy:"Ї",YUcy:"Ю",Yacut:"Ý",Yacute:"Ý",Ycirc:"Ŷ",Ycy:"Ы",Yfr:"𝔜",Yopf:"𝕐",Yscr:"𝒴",Yuml:"Ÿ",ZHcy:"Ж",Zacute:"Ź",Zcaron:"Ž",Zcy:"З",Zdot:"Ż",ZeroWidthSpace:"​",Zeta:"Ζ",Zfr:"ℨ",Zopf:"ℤ",Zscr:"𝒵",aacut:"á",aacute:"á",abreve:"ă",ac:"∾",acE:"∾̳",acd:"∿",acir:"â",acirc:"â",acut:"´",acute:"´",acy:"а",aeli:"æ",aelig:"æ",af:"⁡",afr:"𝔞",agrav:"à",agrave:"à",alefsym:"ℵ",aleph:"ℵ",alpha:"α",amacr:"ā",amalg:"⨿",am:"&",amp:"&",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",aogon:"ą",aopf:"𝕒",ap:"≈",apE:"⩰",apacir:"⩯",ape:"≊",apid:"≋",apos:"'",approx:"≈",approxeq:"≊",arin:"å",aring:"å",ascr:"𝒶",ast:"*",asymp:"≈",asympeq:"≍",atild:"ã",atilde:"ã",aum:"ä",auml:"ä",awconint:"∳",awint:"⨑",bNot:"⫭",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",barvee:"⊽",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",bcy:"б",bdquo:"„",becaus:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",beta:"β",beth:"ℶ",between:"≬",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bnot:"⌐",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxDL:"╗",boxDR:"╔",boxDl:"╖",boxDr:"╓",boxH:"═",boxHD:"╦",boxHU:"╩",boxHd:"╤",boxHu:"╧",boxUL:"╝",boxUR:"╚",boxUl:"╜",boxUr:"╙",boxV:"║",boxVH:"╬",boxVL:"╣",boxVR:"╠",boxVh:"╫",boxVl:"╢",boxVr:"╟",boxbox:"⧉",boxdL:"╕",boxdR:"╒",boxdl:"┐",boxdr:"┌",boxh:"─",boxhD:"╥",boxhU:"╨",boxhd:"┬",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxuL:"╛",boxuR:"╘",boxul:"┘",boxur:"└",boxv:"│",boxvH:"╪",boxvL:"╡",boxvR:"╞",boxvh:"┼",boxvl:"┤",boxvr:"├",bprime:"‵",breve:"˘",brvba:"¦",brvbar:"¦",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",bumpeq:"≏",cacute:"ć",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",caps:"∩︀",caret:"⁁",caron:"ˇ",ccaps:"⩍",ccaron:"č",ccedi:"ç",ccedil:"ç",ccirc:"ĉ",ccups:"⩌",ccupssm:"⩐",cdot:"ċ",cedi:"¸",cedil:"¸",cemptyv:"⦲",cen:"¢",cent:"¢",centerdot:"·",cfr:"𝔠",chcy:"ч",check:"✓",checkmark:"✓",chi:"χ",cir:"○",cirE:"⧃",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledR:"®",circledS:"Ⓢ",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",clubs:"♣",clubsuit:"♣",colon:":",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",conint:"∮",copf:"𝕔",coprod:"∐",cop:"©",copy:"©",copysr:"℗",crarr:"↵",cross:"✗",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",cup:"∪",cupbrcap:"⩈",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curre:"¤",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",dArr:"⇓",dHar:"⥥",dagger:"†",daleth:"ℸ",darr:"↓",dash:"‐",dashv:"⊣",dbkarow:"⤏",dblac:"˝",dcaron:"ď",dcy:"д",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",ddotseq:"⩷",de:"°",deg:"°",delta:"δ",demptyv:"⦱",dfisht:"⥿",dfr:"𝔡",dharl:"⇃",dharr:"⇂",diam:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",digamma:"ϝ",disin:"⋲",div:"÷",divid:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",dopf:"𝕕",dot:"˙",doteq:"≐",doteqdot:"≑",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",downarrow:"↓",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",dscr:"𝒹",dscy:"ѕ",dsol:"⧶",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",dzcy:"џ",dzigrarr:"⟿",eDDot:"⩷",eDot:"≑",eacut:"é",eacute:"é",easter:"⩮",ecaron:"ě",ecir:"ê",ecirc:"ê",ecolon:"≕",ecy:"э",edot:"ė",ee:"ⅇ",efDot:"≒",efr:"𝔢",eg:"⪚",egrav:"è",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",emacr:"ē",empty:"∅",emptyset:"∅",emptyv:"∅",emsp13:" ",emsp14:" ",emsp:" ",eng:"ŋ",ensp:" ",eogon:"ę",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",equals:"=",equest:"≟",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erDot:"≓",erarr:"⥱",escr:"ℯ",esdot:"≐",esim:"≂",eta:"η",et:"ð",eth:"ð",eum:"ë",euml:"ë",euro:"€",excl:"!",exist:"∃",expectation:"ℰ",exponentiale:"ⅇ",fallingdotseq:"≒",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",ffr:"𝔣",filig:"fi",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",fopf:"𝕗",forall:"∀",fork:"⋔",forkv:"⫙",fpartint:"⨍",frac1:"¼",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac3:"¾",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",fscr:"𝒻",gE:"≧",gEl:"⪌",gacute:"ǵ",gamma:"γ",gammad:"ϝ",gap:"⪆",gbreve:"ğ",gcirc:"ĝ",gcy:"г",gdot:"ġ",ge:"≥",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",gfr:"𝔤",gg:"≫",ggg:"⋙",gimel:"ℷ",gjcy:"ѓ",gl:"≷",glE:"⪒",gla:"⪥",glj:"⪤",gnE:"≩",gnap:"⪊",gnapprox:"⪊",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",gopf:"𝕘",grave:"`",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",g:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",hArr:"⇔",hairsp:" ",half:"½",hamilt:"ℋ",hardcy:"ъ",harr:"↔",harrcir:"⥈",harrw:"↭",hbar:"ℏ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",hfr:"𝔥",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",hopf:"𝕙",horbar:"―",hscr:"𝒽",hslash:"ℏ",hstrok:"ħ",hybull:"⁃",hyphen:"‐",iacut:"í",iacute:"í",ic:"⁣",icir:"î",icirc:"î",icy:"и",iecy:"е",iexc:"¡",iexcl:"¡",iff:"⇔",ifr:"𝔦",igrav:"ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",ijlig:"ij",imacr:"ī",image:"ℑ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",int:"∫",intcal:"⊺",integers:"ℤ",intercal:"⊺",intlarhk:"⨗",intprod:"⨼",iocy:"ё",iogon:"į",iopf:"𝕚",iota:"ι",iprod:"⨼",iques:"¿",iquest:"¿",iscr:"𝒾",isin:"∈",isinE:"⋹",isindot:"⋵",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",itilde:"ĩ",iukcy:"і",ium:"ï",iuml:"ï",jcirc:"ĵ",jcy:"й",jfr:"𝔧",jmath:"ȷ",jopf:"𝕛",jscr:"𝒿",jsercy:"ј",jukcy:"є",kappa:"κ",kappav:"ϰ",kcedil:"ķ",kcy:"к",kfr:"𝔨",kgreen:"ĸ",khcy:"х",kjcy:"ќ",kopf:"𝕜",kscr:"𝓀",lAarr:"⇚",lArr:"⇐",lAtail:"⤛",lBarr:"⤎",lE:"≦",lEg:"⪋",lHar:"⥢",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",lambda:"λ",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",laqu:"«",laquo:"«",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",latail:"⤙",late:"⪭",lates:"⪭︀",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",lcaron:"ľ",lcedil:"ļ",lceil:"⌈",lcub:"{",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",le:"≤",leftarrow:"←",leftarrowtail:"↢",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",leftthreetimes:"⋋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",lessgtr:"≶",lesssim:"≲",lfisht:"⥼",lfloor:"⌊",lfr:"𝔩",lg:"≶",lgE:"⪑",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",ljcy:"љ",ll:"≪",llarr:"⇇",llcorner:"⌞",llhard:"⥫",lltri:"◺",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnE:"≨",lnap:"⪉",lnapprox:"⪉",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",longleftarrow:"⟵",longleftrightarrow:"⟷",longmapsto:"⟼",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",lscr:"𝓁",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",lstrok:"ł",l:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltrPar:"⦖",ltri:"◃",ltrie:"⊴",ltrif:"◂",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",mDDot:"∺",mac:"¯",macr:"¯",male:"♂",malt:"✠",maltese:"✠",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",mcy:"м",mdash:"—",measuredangle:"∡",mfr:"𝔪",mho:"℧",micr:"µ",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middo:"·",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",mopf:"𝕞",mp:"∓",mscr:"𝓂",mstpos:"∾",mu:"μ",multimap:"⊸",mumap:"⊸",nGg:"⋙̸",nGt:"≫⃒",nGtv:"≫̸",nLeftarrow:"⇍",nLeftrightarrow:"⇎",nLl:"⋘̸",nLt:"≪⃒",nLtv:"≪̸",nRightarrow:"⇏",nVDash:"⊯",nVdash:"⊮",nabla:"∇",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbs:" ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",ncaron:"ň",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",ncy:"н",ndash:"–",ne:"≠",neArr:"⇗",nearhk:"⤤",nearr:"↗",nearrow:"↗",nedot:"≐̸",nequiv:"≢",nesear:"⤨",nesim:"≂̸",nexist:"∄",nexists:"∄",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",ngsim:"≵",ngt:"≯",ngtr:"≯",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",njcy:"њ",nlArr:"⇍",nlE:"≦̸",nlarr:"↚",nldr:"‥",nle:"≰",nleftarrow:"↚",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nlsim:"≴",nlt:"≮",nltri:"⋪",nltrie:"⋬",nmid:"∤",nopf:"𝕟",no:"¬",not:"¬",notin:"∉",notinE:"⋹̸",notindot:"⋵̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",ntild:"ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",nu:"ν",num:"#",numero:"№",numsp:" ",nvDash:"⊭",nvHarr:"⤄",nvap:"≍⃒",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwArr:"⇖",nwarhk:"⤣",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",oS:"Ⓢ",oacut:"ó",oacute:"ó",oast:"⊛",ocir:"ô",ocirc:"ô",ocy:"о",odash:"⊝",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",oelig:"œ",ofcir:"⦿",ofr:"𝔬",ogon:"˛",ograv:"ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",omacr:"ō",omega:"ω",omicron:"ο",omid:"⦶",ominus:"⊖",oopf:"𝕠",opar:"⦷",operp:"⦹",oplus:"⊕",or:"∨",orarr:"↻",ord:"º",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oscr:"ℴ",oslas:"ø",oslash:"ø",osol:"⊘",otild:"õ",otilde:"õ",otimes:"⊗",otimesas:"⨶",oum:"ö",ouml:"ö",ovbar:"⌽",par:"¶",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",pfr:"𝔭",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",plusm:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",pointint:"⨕",popf:"𝕡",poun:"£",pound:"£",pr:"≺",prE:"⪳",prap:"⪷",prcue:"≼",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",prime:"′",primes:"ℙ",prnE:"⪵",prnap:"⪹",prnsim:"⋨",prod:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",propto:"∝",prsim:"≾",prurel:"⊰",pscr:"𝓅",psi:"ψ",puncsp:" ",qfr:"𝔮",qint:"⨌",qopf:"𝕢",qprime:"⁗",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",quo:'"',quot:'"',rAarr:"⇛",rArr:"⇒",rAtail:"⤜",rBarr:"⤏",rHar:"⥤",race:"∽̱",racute:"ŕ",radic:"√",raemptyv:"⦳",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raqu:"»",raquo:"»",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",rarrtl:"↣",rarrw:"↝",ratail:"⤚",ratio:"∶",rationals:"ℚ",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",rcaron:"ř",rcedil:"ŗ",rceil:"⌉",rcub:"}",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",re:"®",reg:"®",rfisht:"⥽",rfloor:"⌋",rfr:"𝔯",rhard:"⇁",rharu:"⇀",rharul:"⥬",rho:"ρ",rhov:"ϱ",rightarrow:"→",rightarrowtail:"↣",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",rightthreetimes:"⋌",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",rsaquo:"›",rscr:"𝓇",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",ruluhar:"⥨",rx:"℞",sacute:"ś",sbquo:"‚",sc:"≻",scE:"⪴",scap:"⪸",scaron:"š",sccue:"≽",sce:"⪰",scedil:"ş",scirc:"ŝ",scnE:"⪶",scnap:"⪺",scnsim:"⋩",scpolint:"⨓",scsim:"≿",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",seArr:"⇘",searhk:"⤥",searr:"↘",searrow:"↘",sec:"§",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",sfr:"𝔰",sfrown:"⌢",sharp:"♯",shchcy:"щ",shcy:"ш",shortmid:"∣",shortparallel:"∥",sh:"­",shy:"­",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",square:"□",squarf:"▪",squf:"▪",srarr:"→",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",sub:"⊂",subE:"⫅",subdot:"⪽",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",sum:"∑",sung:"♪",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supE:"⫆",supdot:"⪾",supdsub:"⫘",supe:"⊇",supedot:"⫄",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swArr:"⇙",swarhk:"⤦",swarr:"↙",swarrow:"↙",swnwar:"⤪",szli:"ß",szlig:"ß",target:"⌖",tau:"τ",tbrk:"⎴",tcaron:"ť",tcedil:"ţ",tcy:"т",tdot:"⃛",telrec:"⌕",tfr:"𝔱",there4:"∴",therefore:"∴",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",thinsp:" ",thkap:"≈",thksim:"∼",thor:"þ",thorn:"þ",tilde:"˜",time:"×",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",tscr:"𝓉",tscy:"ц",tshcy:"ћ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",uArr:"⇑",uHar:"⥣",uacut:"ú",uacute:"ú",uarr:"↑",ubrcy:"ў",ubreve:"ŭ",ucir:"û",ucirc:"û",ucy:"у",udarr:"⇅",udblac:"ű",udhar:"⥮",ufisht:"⥾",ufr:"𝔲",ugrav:"ù",ugrave:"ù",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",umacr:"ū",um:"¨",uml:"¨",uogon:"ų",uopf:"𝕦",uparrow:"↑",updownarrow:"↕",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",upsi:"υ",upsih:"ϒ",upsilon:"υ",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",uring:"ů",urtri:"◹",uscr:"𝓊",utdot:"⋰",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",uum:"ü",uuml:"ü",uwangle:"⦧",vArr:"⇕",vBar:"⫨",vBarv:"⫩",vDash:"⊨",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",vcy:"в",vdash:"⊢",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",verbar:"|",vert:"|",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",vopf:"𝕧",vprop:"∝",vrtri:"⊳",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",vzigzag:"⦚",wcirc:"ŵ",wedbar:"⩟",wedge:"∧",wedgeq:"≙",weierp:"℘",wfr:"𝔴",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",yacut:"ý",yacute:"ý",yacy:"я",ycirc:"ŷ",ycy:"ы",ye:"¥",yen:"¥",yfr:"𝔶",yicy:"ї",yopf:"𝕪",yscr:"𝓎",yucy:"ю",yum:"ÿ",yuml:"ÿ",zacute:"ź",zcaron:"ž",zcy:"з",zdot:"ż",zeetrf:"ℨ",zeta:"ζ",zfr:"𝔷",zhcy:"ж",zigrarr:"⇝",zopf:"𝕫",zscr:"𝓏",zwj:"‍",zwnj:"‌",Map:"⤅",in:"∈"},m=Object.freeze({AEli:"Æ",AElig:"Æ",AM:"&",AMP:"&",Aacut:"Á",Aacute:"Á",Abreve:"Ă",Acir:"Â",Acirc:"Â",Acy:"А",Afr:"𝔄",Agrav:"À",Agrave:"À",Alpha:"Α",Amacr:"Ā",And:"⩓",Aogon:"Ą",Aopf:"𝔸",ApplyFunction:"⁡",Arin:"Å",Aring:"Å",Ascr:"𝒜",Assign:"≔",Atild:"Ã",Atilde:"Ã",Aum:"Ä",Auml:"Ä",Backslash:"∖",Barv:"⫧",Barwed:"⌆",Bcy:"Б",Because:"∵",Bernoullis:"ℬ",Beta:"Β",Bfr:"𝔅",Bopf:"𝔹",Breve:"˘",Bscr:"ℬ",Bumpeq:"≎",CHcy:"Ч",COP:"©",COPY:"©",Cacute:"Ć",Cap:"⋒",CapitalDifferentialD:"ⅅ",Cayleys:"ℭ",Ccaron:"Č",Ccedi:"Ç",Ccedil:"Ç",Ccirc:"Ĉ",Cconint:"∰",Cdot:"Ċ",Cedilla:"¸",CenterDot:"·",Cfr:"ℭ",Chi:"Χ",CircleDot:"⊙",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",Colon:"∷",Colone:"⩴",Congruent:"≡",Conint:"∯",ContourIntegral:"∮",Copf:"ℂ",Coproduct:"∐",CounterClockwiseContourIntegral:"∳",Cross:"⨯",Cscr:"𝒞",Cup:"⋓",CupCap:"≍",DD:"ⅅ",DDotrahd:"⤑",DJcy:"Ђ",DScy:"Ѕ",DZcy:"Џ",Dagger:"‡",Darr:"↡",Dashv:"⫤",Dcaron:"Ď",Dcy:"Д",Del:"∇",Delta:"Δ",Dfr:"𝔇",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",Diamond:"⋄",DifferentialD:"ⅆ",Dopf:"𝔻",Dot:"¨",DotDot:"⃜",DotEqual:"≐",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",Downarrow:"⇓",Dscr:"𝒟",Dstrok:"Đ",ENG:"Ŋ",ET:"Ð",ETH:"Ð",Eacut:"É",Eacute:"É",Ecaron:"Ě",Ecir:"Ê",Ecirc:"Ê",Ecy:"Э",Edot:"Ė",Efr:"𝔈",Egrav:"È",Egrave:"È",Element:"∈",Emacr:"Ē",EmptySmallSquare:"◻",EmptyVerySmallSquare:"▫",Eogon:"Ę",Eopf:"𝔼",Epsilon:"Ε",Equal:"⩵",EqualTilde:"≂",Equilibrium:"⇌",Escr:"ℰ",Esim:"⩳",Eta:"Η",Eum:"Ë",Euml:"Ë",Exists:"∃",ExponentialE:"ⅇ",Fcy:"Ф",Ffr:"𝔉",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",Fopf:"𝔽",ForAll:"∀",Fouriertrf:"ℱ",Fscr:"ℱ",GJcy:"Ѓ",G:">",GT:">",Gamma:"Γ",Gammad:"Ϝ",Gbreve:"Ğ",Gcedil:"Ģ",Gcirc:"Ĝ",Gcy:"Г",Gdot:"Ġ",Gfr:"𝔊",Gg:"⋙",Gopf:"𝔾",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",Gt:"≫",HARDcy:"Ъ",Hacek:"ˇ",Hat:"^",Hcirc:"Ĥ",Hfr:"ℌ",HilbertSpace:"ℋ",Hopf:"ℍ",HorizontalLine:"─",Hscr:"ℋ",Hstrok:"Ħ",HumpDownHump:"≎",HumpEqual:"≏",IEcy:"Е",IJlig:"IJ",IOcy:"Ё",Iacut:"Í",Iacute:"Í",Icir:"Î",Icirc:"Î",Icy:"И",Idot:"İ",Ifr:"ℑ",Igrav:"Ì",Igrave:"Ì",Im:"ℑ",Imacr:"Ī",ImaginaryI:"ⅈ",Implies:"⇒",Int:"∬",Integral:"∫",Intersection:"⋂",InvisibleComma:"⁣",InvisibleTimes:"⁢",Iogon:"Į",Iopf:"𝕀",Iota:"Ι",Iscr:"ℐ",Itilde:"Ĩ",Iukcy:"І",Ium:"Ï",Iuml:"Ï",Jcirc:"Ĵ",Jcy:"Й",Jfr:"𝔍",Jopf:"𝕁",Jscr:"𝒥",Jsercy:"Ј",Jukcy:"Є",KHcy:"Х",KJcy:"Ќ",Kappa:"Κ",Kcedil:"Ķ",Kcy:"К",Kfr:"𝔎",Kopf:"𝕂",Kscr:"𝒦",LJcy:"Љ",L:"<",LT:"<",Lacute:"Ĺ",Lambda:"Λ",Lang:"⟪",Laplacetrf:"ℒ",Larr:"↞",Lcaron:"Ľ",Lcedil:"Ļ",Lcy:"Л",LeftAngleBracket:"⟨",LeftArrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",LeftRightArrow:"↔",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",Leftarrow:"⇐",Leftrightarrow:"⇔",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",LessLess:"⪡",LessSlantEqual:"⩽",LessTilde:"≲",Lfr:"𝔏",Ll:"⋘",Lleftarrow:"⇚",Lmidot:"Ŀ",LongLeftArrow:"⟵",LongLeftRightArrow:"⟷",LongRightArrow:"⟶",Longleftarrow:"⟸",Longleftrightarrow:"⟺",Longrightarrow:"⟹",Lopf:"𝕃",LowerLeftArrow:"↙",LowerRightArrow:"↘",Lscr:"ℒ",Lsh:"↰",Lstrok:"Ł",Lt:"≪",Mcy:"М",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",MinusPlus:"∓",Mopf:"𝕄",Mscr:"ℳ",Mu:"Μ",NJcy:"Њ",Nacute:"Ń",Ncaron:"Ň",Ncedil:"Ņ",Ncy:"Н",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",Nfr:"𝔑",NoBreak:"⁠",NonBreakingSpace:" ",Nopf:"ℕ",Not:"⫬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",Nscr:"𝒩",Ntild:"Ñ",Ntilde:"Ñ",Nu:"Ν",OElig:"Œ",Oacut:"Ó",Oacute:"Ó",Ocir:"Ô",Ocirc:"Ô",Ocy:"О",Odblac:"Ő",Ofr:"𝔒",Ograv:"Ò",Ograve:"Ò",Omacr:"Ō",Omega:"Ω",Omicron:"Ο",Oopf:"𝕆",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",Or:"⩔",Oscr:"𝒪",Oslas:"Ø",Oslash:"Ø",Otild:"Õ",Otilde:"Õ",Otimes:"⨷",Oum:"Ö",Ouml:"Ö",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",PartialD:"∂",Pcy:"П",Pfr:"𝔓",Phi:"Φ",Pi:"Π",PlusMinus:"±",Poincareplane:"ℌ",Popf:"ℙ",Pr:"⪻",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",Prime:"″",Product:"∏",Proportion:"∷",Proportional:"∝",Pscr:"𝒫",Psi:"Ψ",QUO:'"',QUOT:'"',Qfr:"𝔔",Qopf:"ℚ",Qscr:"𝒬",RBarr:"⤐",RE:"®",REG:"®",Racute:"Ŕ",Rang:"⟫",Rarr:"↠",Rarrtl:"⤖",Rcaron:"Ř",Rcedil:"Ŗ",Rcy:"Р",Re:"ℜ",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",Rfr:"ℜ",Rho:"Ρ",RightAngleBracket:"⟩",RightArrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",Rightarrow:"⇒",Ropf:"ℝ",RoundImplies:"⥰",Rrightarrow:"⇛",Rscr:"ℛ",Rsh:"↱",RuleDelayed:"⧴",SHCHcy:"Щ",SHcy:"Ш",SOFTcy:"Ь",Sacute:"Ś",Sc:"⪼",Scaron:"Š",Scedil:"Ş",Scirc:"Ŝ",Scy:"С",Sfr:"𝔖",ShortDownArrow:"↓",ShortLeftArrow:"←",ShortRightArrow:"→",ShortUpArrow:"↑",Sigma:"Σ",SmallCircle:"∘",Sopf:"𝕊",Sqrt:"√",Square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",Sscr:"𝒮",Star:"⋆",Sub:"⋐",Subset:"⋐",SubsetEqual:"⊆",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",SuchThat:"∋",Sum:"∑",Sup:"⋑",Superset:"⊃",SupersetEqual:"⊇",Supset:"⋑",THOR:"Þ",THORN:"Þ",TRADE:"™",TSHcy:"Ћ",TScy:"Ц",Tab:"\t",Tau:"Τ",Tcaron:"Ť",Tcedil:"Ţ",Tcy:"Т",Tfr:"𝔗",Therefore:"∴",Theta:"Θ",ThickSpace:"  ",ThinSpace:" ",Tilde:"∼",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",Topf:"𝕋",TripleDot:"⃛",Tscr:"𝒯",Tstrok:"Ŧ",Uacut:"Ú",Uacute:"Ú",Uarr:"↟",Uarrocir:"⥉",Ubrcy:"Ў",Ubreve:"Ŭ",Ucir:"Û",Ucirc:"Û",Ucy:"У",Udblac:"Ű",Ufr:"𝔘",Ugrav:"Ù",Ugrave:"Ù",Umacr:"Ū",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",Uopf:"𝕌",UpArrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",UpEquilibrium:"⥮",UpTee:"⊥",UpTeeArrow:"↥",Uparrow:"⇑",Updownarrow:"⇕",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",Upsilon:"Υ",Uring:"Ů",Uscr:"𝒰",Utilde:"Ũ",Uum:"Ü",Uuml:"Ü",VDash:"⊫",Vbar:"⫫",Vcy:"В",Vdash:"⊩",Vdashl:"⫦",Vee:"⋁",Verbar:"‖",Vert:"‖",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",Vopf:"𝕍",Vscr:"𝒱",Vvdash:"⊪",Wcirc:"Ŵ",Wedge:"⋀",Wfr:"𝔚",Wopf:"𝕎",Wscr:"𝒲",Xfr:"𝔛",Xi:"Ξ",Xopf:"𝕏",Xscr:"𝒳",YAcy:"Я",YIcy:"Ї",YUcy:"Ю",Yacut:"Ý",Yacute:"Ý",Ycirc:"Ŷ",Ycy:"Ы",Yfr:"𝔜",Yopf:"𝕐",Yscr:"𝒴",Yuml:"Ÿ",ZHcy:"Ж",Zacute:"Ź",Zcaron:"Ž",Zcy:"З",Zdot:"Ż",ZeroWidthSpace:"​",Zeta:"Ζ",Zfr:"ℨ",Zopf:"ℤ",Zscr:"𝒵",aacut:"á",aacute:"á",abreve:"ă",ac:"∾",acE:"∾̳",acd:"∿",acir:"â",acirc:"â",acut:"´",acute:"´",acy:"а",aeli:"æ",aelig:"æ",af:"⁡",afr:"𝔞",agrav:"à",agrave:"à",alefsym:"ℵ",aleph:"ℵ",alpha:"α",amacr:"ā",amalg:"⨿",am:"&",amp:"&",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",aogon:"ą",aopf:"𝕒",ap:"≈",apE:"⩰",apacir:"⩯",ape:"≊",apid:"≋",apos:"'",approx:"≈",approxeq:"≊",arin:"å",aring:"å",ascr:"𝒶",ast:"*",asymp:"≈",asympeq:"≍",atild:"ã",atilde:"ã",aum:"ä",auml:"ä",awconint:"∳",awint:"⨑",bNot:"⫭",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",barvee:"⊽",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",bcy:"б",bdquo:"„",becaus:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",beta:"β",beth:"ℶ",between:"≬",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bnot:"⌐",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxDL:"╗",boxDR:"╔",boxDl:"╖",boxDr:"╓",boxH:"═",boxHD:"╦",boxHU:"╩",boxHd:"╤",boxHu:"╧",boxUL:"╝",boxUR:"╚",boxUl:"╜",boxUr:"╙",boxV:"║",boxVH:"╬",boxVL:"╣",boxVR:"╠",boxVh:"╫",boxVl:"╢",boxVr:"╟",boxbox:"⧉",boxdL:"╕",boxdR:"╒",boxdl:"┐",boxdr:"┌",boxh:"─",boxhD:"╥",boxhU:"╨",boxhd:"┬",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxuL:"╛",boxuR:"╘",boxul:"┘",boxur:"└",boxv:"│",boxvH:"╪",boxvL:"╡",boxvR:"╞",boxvh:"┼",boxvl:"┤",boxvr:"├",bprime:"‵",breve:"˘",brvba:"¦",brvbar:"¦",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",bumpeq:"≏",cacute:"ć",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",caps:"∩︀",caret:"⁁",caron:"ˇ",ccaps:"⩍",ccaron:"č",ccedi:"ç",ccedil:"ç",ccirc:"ĉ",ccups:"⩌",ccupssm:"⩐",cdot:"ċ",cedi:"¸",cedil:"¸",cemptyv:"⦲",cen:"¢",cent:"¢",centerdot:"·",cfr:"𝔠",chcy:"ч",check:"✓",checkmark:"✓",chi:"χ",cir:"○",cirE:"⧃",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledR:"®",circledS:"Ⓢ",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",clubs:"♣",clubsuit:"♣",colon:":",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",conint:"∮",copf:"𝕔",coprod:"∐",cop:"©",copy:"©",copysr:"℗",crarr:"↵",cross:"✗",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",cup:"∪",cupbrcap:"⩈",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curre:"¤",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",dArr:"⇓",dHar:"⥥",dagger:"†",daleth:"ℸ",darr:"↓",dash:"‐",dashv:"⊣",dbkarow:"⤏",dblac:"˝",dcaron:"ď",dcy:"д",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",ddotseq:"⩷",de:"°",deg:"°",delta:"δ",demptyv:"⦱",dfisht:"⥿",dfr:"𝔡",dharl:"⇃",dharr:"⇂",diam:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",digamma:"ϝ",disin:"⋲",div:"÷",divid:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",dopf:"𝕕",dot:"˙",doteq:"≐",doteqdot:"≑",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",downarrow:"↓",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",dscr:"𝒹",dscy:"ѕ",dsol:"⧶",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",dzcy:"џ",dzigrarr:"⟿",eDDot:"⩷",eDot:"≑",eacut:"é",eacute:"é",easter:"⩮",ecaron:"ě",ecir:"ê",ecirc:"ê",ecolon:"≕",ecy:"э",edot:"ė",ee:"ⅇ",efDot:"≒",efr:"𝔢",eg:"⪚",egrav:"è",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",emacr:"ē",empty:"∅",emptyset:"∅",emptyv:"∅",emsp13:" ",emsp14:" ",emsp:" ",eng:"ŋ",ensp:" ",eogon:"ę",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",equals:"=",equest:"≟",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erDot:"≓",erarr:"⥱",escr:"ℯ",esdot:"≐",esim:"≂",eta:"η",et:"ð",eth:"ð",eum:"ë",euml:"ë",euro:"€",excl:"!",exist:"∃",expectation:"ℰ",exponentiale:"ⅇ",fallingdotseq:"≒",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",ffr:"𝔣",filig:"fi",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",fopf:"𝕗",forall:"∀",fork:"⋔",forkv:"⫙",fpartint:"⨍",frac1:"¼",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac3:"¾",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",fscr:"𝒻",gE:"≧",gEl:"⪌",gacute:"ǵ",gamma:"γ",gammad:"ϝ",gap:"⪆",gbreve:"ğ",gcirc:"ĝ",gcy:"г",gdot:"ġ",ge:"≥",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",gfr:"𝔤",gg:"≫",ggg:"⋙",gimel:"ℷ",gjcy:"ѓ",gl:"≷",glE:"⪒",gla:"⪥",glj:"⪤",gnE:"≩",gnap:"⪊",gnapprox:"⪊",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",gopf:"𝕘",grave:"`",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",g:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",hArr:"⇔",hairsp:" ",half:"½",hamilt:"ℋ",hardcy:"ъ",harr:"↔",harrcir:"⥈",harrw:"↭",hbar:"ℏ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",hfr:"𝔥",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",hopf:"𝕙",horbar:"―",hscr:"𝒽",hslash:"ℏ",hstrok:"ħ",hybull:"⁃",hyphen:"‐",iacut:"í",iacute:"í",ic:"⁣",icir:"î",icirc:"î",icy:"и",iecy:"е",iexc:"¡",iexcl:"¡",iff:"⇔",ifr:"𝔦",igrav:"ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",ijlig:"ij",imacr:"ī",image:"ℑ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",int:"∫",intcal:"⊺",integers:"ℤ",intercal:"⊺",intlarhk:"⨗",intprod:"⨼",iocy:"ё",iogon:"į",iopf:"𝕚",iota:"ι",iprod:"⨼",iques:"¿",iquest:"¿",iscr:"𝒾",isin:"∈",isinE:"⋹",isindot:"⋵",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",itilde:"ĩ",iukcy:"і",ium:"ï",iuml:"ï",jcirc:"ĵ",jcy:"й",jfr:"𝔧",jmath:"ȷ",jopf:"𝕛",jscr:"𝒿",jsercy:"ј",jukcy:"є",kappa:"κ",kappav:"ϰ",kcedil:"ķ",kcy:"к",kfr:"𝔨",kgreen:"ĸ",khcy:"х",kjcy:"ќ",kopf:"𝕜",kscr:"𝓀",lAarr:"⇚",lArr:"⇐",lAtail:"⤛",lBarr:"⤎",lE:"≦",lEg:"⪋",lHar:"⥢",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",lambda:"λ",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",laqu:"«",laquo:"«",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",latail:"⤙",late:"⪭",lates:"⪭︀",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",lcaron:"ľ",lcedil:"ļ",lceil:"⌈",lcub:"{",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",le:"≤",leftarrow:"←",leftarrowtail:"↢",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",leftthreetimes:"⋋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",lessgtr:"≶",lesssim:"≲",lfisht:"⥼",lfloor:"⌊",lfr:"𝔩",lg:"≶",lgE:"⪑",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",ljcy:"љ",ll:"≪",llarr:"⇇",llcorner:"⌞",llhard:"⥫",lltri:"◺",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnE:"≨",lnap:"⪉",lnapprox:"⪉",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",longleftarrow:"⟵",longleftrightarrow:"⟷",longmapsto:"⟼",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",lscr:"𝓁",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",lstrok:"ł",l:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltrPar:"⦖",ltri:"◃",ltrie:"⊴",ltrif:"◂",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",mDDot:"∺",mac:"¯",macr:"¯",male:"♂",malt:"✠",maltese:"✠",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",mcy:"м",mdash:"—",measuredangle:"∡",mfr:"𝔪",mho:"℧",micr:"µ",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middo:"·",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",mopf:"𝕞",mp:"∓",mscr:"𝓂",mstpos:"∾",mu:"μ",multimap:"⊸",mumap:"⊸",nGg:"⋙̸",nGt:"≫⃒",nGtv:"≫̸",nLeftarrow:"⇍",nLeftrightarrow:"⇎",nLl:"⋘̸",nLt:"≪⃒",nLtv:"≪̸",nRightarrow:"⇏",nVDash:"⊯",nVdash:"⊮",nabla:"∇",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbs:" ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",ncaron:"ň",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",ncy:"н",ndash:"–",ne:"≠",neArr:"⇗",nearhk:"⤤",nearr:"↗",nearrow:"↗",nedot:"≐̸",nequiv:"≢",nesear:"⤨",nesim:"≂̸",nexist:"∄",nexists:"∄",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",ngsim:"≵",ngt:"≯",ngtr:"≯",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",njcy:"њ",nlArr:"⇍",nlE:"≦̸",nlarr:"↚",nldr:"‥",nle:"≰",nleftarrow:"↚",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nlsim:"≴",nlt:"≮",nltri:"⋪",nltrie:"⋬",nmid:"∤",nopf:"𝕟",no:"¬",not:"¬",notin:"∉",notinE:"⋹̸",notindot:"⋵̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",ntild:"ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",nu:"ν",num:"#",numero:"№",numsp:" ",nvDash:"⊭",nvHarr:"⤄",nvap:"≍⃒",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwArr:"⇖",nwarhk:"⤣",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",oS:"Ⓢ",oacut:"ó",oacute:"ó",oast:"⊛",ocir:"ô",ocirc:"ô",ocy:"о",odash:"⊝",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",oelig:"œ",ofcir:"⦿",ofr:"𝔬",ogon:"˛",ograv:"ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",omacr:"ō",omega:"ω",omicron:"ο",omid:"⦶",ominus:"⊖",oopf:"𝕠",opar:"⦷",operp:"⦹",oplus:"⊕",or:"∨",orarr:"↻",ord:"º",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oscr:"ℴ",oslas:"ø",oslash:"ø",osol:"⊘",otild:"õ",otilde:"õ",otimes:"⊗",otimesas:"⨶",oum:"ö",ouml:"ö",ovbar:"⌽",par:"¶",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",pfr:"𝔭",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",plusm:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",pointint:"⨕",popf:"𝕡",poun:"£",pound:"£",pr:"≺",prE:"⪳",prap:"⪷",prcue:"≼",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",prime:"′",primes:"ℙ",prnE:"⪵",prnap:"⪹",prnsim:"⋨",prod:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",propto:"∝",prsim:"≾",prurel:"⊰",pscr:"𝓅",psi:"ψ",puncsp:" ",qfr:"𝔮",qint:"⨌",qopf:"𝕢",qprime:"⁗",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",quo:'"',quot:'"',rAarr:"⇛",rArr:"⇒",rAtail:"⤜",rBarr:"⤏",rHar:"⥤",race:"∽̱",racute:"ŕ",radic:"√",raemptyv:"⦳",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raqu:"»",raquo:"»",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",rarrtl:"↣",rarrw:"↝",ratail:"⤚",ratio:"∶",rationals:"ℚ",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",rcaron:"ř",rcedil:"ŗ",rceil:"⌉",rcub:"}",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",re:"®",reg:"®",rfisht:"⥽",rfloor:"⌋",rfr:"𝔯",rhard:"⇁",rharu:"⇀",rharul:"⥬",rho:"ρ",rhov:"ϱ",rightarrow:"→",rightarrowtail:"↣",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",rightthreetimes:"⋌",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",rsaquo:"›",rscr:"𝓇",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",ruluhar:"⥨",rx:"℞",sacute:"ś",sbquo:"‚",sc:"≻",scE:"⪴",scap:"⪸",scaron:"š",sccue:"≽",sce:"⪰",scedil:"ş",scirc:"ŝ",scnE:"⪶",scnap:"⪺",scnsim:"⋩",scpolint:"⨓",scsim:"≿",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",seArr:"⇘",searhk:"⤥",searr:"↘",searrow:"↘",sec:"§",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",sfr:"𝔰",sfrown:"⌢",sharp:"♯",shchcy:"щ",shcy:"ш",shortmid:"∣",shortparallel:"∥",sh:"­",shy:"­",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",square:"□",squarf:"▪",squf:"▪",srarr:"→",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",sub:"⊂",subE:"⫅",subdot:"⪽",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",sum:"∑",sung:"♪",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supE:"⫆",supdot:"⪾",supdsub:"⫘",supe:"⊇",supedot:"⫄",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swArr:"⇙",swarhk:"⤦",swarr:"↙",swarrow:"↙",swnwar:"⤪",szli:"ß",szlig:"ß",target:"⌖",tau:"τ",tbrk:"⎴",tcaron:"ť",tcedil:"ţ",tcy:"т",tdot:"⃛",telrec:"⌕",tfr:"𝔱",there4:"∴",therefore:"∴",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",thinsp:" ",thkap:"≈",thksim:"∼",thor:"þ",thorn:"þ",tilde:"˜",time:"×",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",tscr:"𝓉",tscy:"ц",tshcy:"ћ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",uArr:"⇑",uHar:"⥣",uacut:"ú",uacute:"ú",uarr:"↑",ubrcy:"ў",ubreve:"ŭ",ucir:"û",ucirc:"û",ucy:"у",udarr:"⇅",udblac:"ű",udhar:"⥮",ufisht:"⥾",ufr:"𝔲",ugrav:"ù",ugrave:"ù",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",umacr:"ū",um:"¨",uml:"¨",uogon:"ų",uopf:"𝕦",uparrow:"↑",updownarrow:"↕",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",upsi:"υ",upsih:"ϒ",upsilon:"υ",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",uring:"ů",urtri:"◹",uscr:"𝓊",utdot:"⋰",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",uum:"ü",uuml:"ü",uwangle:"⦧",vArr:"⇕",vBar:"⫨",vBarv:"⫩",vDash:"⊨",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",vcy:"в",vdash:"⊢",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",verbar:"|",vert:"|",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",vopf:"𝕧",vprop:"∝",vrtri:"⊳",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",vzigzag:"⦚",wcirc:"ŵ",wedbar:"⩟",wedge:"∧",wedgeq:"≙",weierp:"℘",wfr:"𝔴",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",yacut:"ý",yacute:"ý",yacy:"я",ycirc:"ŷ",ycy:"ы",ye:"¥",yen:"¥",yfr:"𝔶",yicy:"ї",yopf:"𝕪",yscr:"𝓎",yucy:"ю",yum:"ÿ",yuml:"ÿ",zacute:"ź",zcaron:"ž",zcy:"з",zdot:"ż",zeetrf:"ℨ",zeta:"ζ",zfr:"𝔷",zhcy:"ж",zigrarr:"⇝",zopf:"𝕫",zscr:"𝓏",zwj:"‍",zwnj:"‌",default:g}),b={AElig:"Æ",AMP:"&",Aacute:"Á",Acirc:"Â",Agrave:"À",Aring:"Å",Atilde:"Ã",Auml:"Ä",COPY:"©",Ccedil:"Ç",ETH:"Ð",Eacute:"É",Ecirc:"Ê",Egrave:"È",Euml:"Ë",GT:">",Iacute:"Í",Icirc:"Î",Igrave:"Ì",Iuml:"Ï",LT:"<",Ntilde:"Ñ",Oacute:"Ó",Ocirc:"Ô",Ograve:"Ò",Oslash:"Ø",Otilde:"Õ",Ouml:"Ö",QUOT:'"',REG:"®",THORN:"Þ",Uacute:"Ú",Ucirc:"Û",Ugrave:"Ù",Uuml:"Ü",Yacute:"Ý",aacute:"á",acirc:"â",acute:"´",aelig:"æ",agrave:"à",amp:"&",aring:"å",atilde:"ã",auml:"ä",brvbar:"¦",ccedil:"ç",cedil:"¸",cent:"¢",copy:"©",curren:"¤",deg:"°",divide:"÷",eacute:"é",ecirc:"ê",egrave:"è",eth:"ð",euml:"ë",frac12:"½",frac14:"¼",frac34:"¾",gt:">",iacute:"í",icirc:"î",iexcl:"¡",igrave:"ì",iquest:"¿",iuml:"ï",laquo:"«",lt:"<",macr:"¯",micro:"µ",middot:"·",nbsp:" ",not:"¬",ntilde:"ñ",oacute:"ó",ocirc:"ô",ograve:"ò",ordf:"ª",ordm:"º",oslash:"ø",otilde:"õ",ouml:"ö",para:"¶",plusmn:"±",pound:"£",quot:'"',raquo:"»",reg:"®",sect:"§",shy:"­",sup1:"¹",sup2:"²",sup3:"³",szlig:"ß",thorn:"þ",times:"×",uacute:"ú",ucirc:"û",ugrave:"ù",uml:"¨",uuml:"ü",yacute:"ý",yen:"¥",yuml:"ÿ"},v=Object.freeze({AElig:"Æ",AMP:"&",Aacute:"Á",Acirc:"Â",Agrave:"À",Aring:"Å",Atilde:"Ã",Auml:"Ä",COPY:"©",Ccedil:"Ç",ETH:"Ð",Eacute:"É",Ecirc:"Ê",Egrave:"È",Euml:"Ë",GT:">",Iacute:"Í",Icirc:"Î",Igrave:"Ì",Iuml:"Ï",LT:"<",Ntilde:"Ñ",Oacute:"Ó",Ocirc:"Ô",Ograve:"Ò",Oslash:"Ø",Otilde:"Õ",Ouml:"Ö",QUOT:'"',REG:"®",THORN:"Þ",Uacute:"Ú",Ucirc:"Û",Ugrave:"Ù",Uuml:"Ü",Yacute:"Ý",aacute:"á",acirc:"â",acute:"´",aelig:"æ",agrave:"à",amp:"&",aring:"å",atilde:"ã",auml:"ä",brvbar:"¦",ccedil:"ç",cedil:"¸",cent:"¢",copy:"©",curren:"¤",deg:"°",divide:"÷",eacute:"é",ecirc:"ê",egrave:"è",eth:"ð",euml:"ë",frac12:"½",frac14:"¼",frac34:"¾",gt:">",iacute:"í",icirc:"î",iexcl:"¡",igrave:"ì",iquest:"¿",iuml:"ï",laquo:"«",lt:"<",macr:"¯",micro:"µ",middot:"·",nbsp:" ",not:"¬",ntilde:"ñ",oacute:"ó",ocirc:"ô",ograve:"ò",ordf:"ª",ordm:"º",oslash:"ø",otilde:"õ",ouml:"ö",para:"¶",plusmn:"±",pound:"£",quot:'"',raquo:"»",reg:"®",sect:"§",shy:"­",sup1:"¹",sup2:"²",sup3:"³",szlig:"ß",thorn:"þ",times:"×",uacute:"ú",ucirc:"û",ugrave:"ù",uml:"¨",uuml:"ü",yacute:"ý",yen:"¥",yuml:"ÿ",default:b}),E={0:"�",128:"€",130:"‚",131:"ƒ",132:"„",133:"…",134:"†",135:"‡",136:"ˆ",137:"‰",138:"Š",139:"‹",140:"Œ",142:"Ž",145:"‘",146:"’",147:"“",148:"”",149:"•",150:"–",151:"—",152:"˜",153:"™",154:"š",155:"›",156:"œ",158:"ž",159:"Ÿ"},w=Object.freeze({default:E}),y=function(r){var e="string"==typeof r?r.charCodeAt(0):r;return e>=48&&e<=57};var A=function(r){var e="string"==typeof r?r.charCodeAt(0):r;return e>=97&&e<=102||e>=65&&e<=70||e>=48&&e<=57};var C=function(r){var e="string"==typeof r?r.charCodeAt(0):r;return e>=97&&e<=122||e>=65&&e<=90};var q=function(r){return C(r)||y(r)};var F=m&&g||m,k=v&&b||v,x=w&&E||w,L=function(r,e){var t,u,n={};e||(e={});for(u in Z)t=e[u],n[u]=null===t||void 0===t?Z[u]:t;(n.position.indent||n.position.start)&&(n.indent=n.position.indent||[],n.position=n.position.start);return function(r,e){var t,u,n,a,o,i,c,l,s,f,p,D,d,h,g,m,b,v,E=e.additional,w=e.nonTerminated,y=e.text,A=e.reference,C=e.warning,L=e.textContext,Z=e.referenceContext,ar=e.warningContext,or=e.position,ir=e.indent||[],sr=r.length,fr=0,pr=-1,Dr=or.column||1,dr=or.line||1,hr=M,gr=[];g=br(),c=C?function(r,e){var t=br();t.column+=e,t.offset+=e,C.call(ar,cr[r],t,r)}:T,fr--,sr++;for(;++fr=55296&&mr<=57343||mr>1114111?(c(nr,b),o=O):o in x?(c(ur,b),o=x[o]):(s=M,lr(o)&&c(ur,b),o>65535&&(s+=S((o-=65536)>>>10|55296),o=56320|1023&o),o=s+S(o))):d!==Y&&c(er,b)),o?(Er(),g=br(),fr=v-1,Dr+=v-D+1,gr.push(o),(m=br()).offset++,A&&A.call(Z,o,{start:g,end:m},r.slice(D-1,v)),g=m):(n=r.slice(D-1,v),hr+=n,Dr+=n.length,fr=v-1)}var mr;return gr.join(M);function br(){return{line:dr,column:Dr,offset:fr+(or.offset||0)}}function vr(e){return r.charAt(e)}function Er(){hr&&(gr.push(hr),y&&y.call(L,hr,{start:g,end:br()}),hr=M)}}(r,n)},B={}.hasOwnProperty,S=String.fromCharCode,T=Function.prototype,O="�",N="\f",R="&",U="#",P=";",I="\n",V="x",z="X",j=" ",G="<",H="=",M="",$="\t",Z={warning:null,reference:null,text:null,warningContext:null,referenceContext:null,textContext:null,position:{},additional:null,attribute:!1,nonTerminated:!0},Y="named",_="hexadecimal",J="decimal",Q={};Q[_]=16,Q[J]=10;var K={};K[Y]=q,K[J]=y,K[_]=A;var W=1,X=2,rr=3,er=4,tr=5,ur=6,nr=7,ar="Numeric character references",or=" must be terminated by a semicolon",ir=" cannot be empty",cr={};function lr(r){return r>=1&&r<=8||11===r||r>=13&&r<=31||r>=127&&r<=159||r>=64976&&r<=65007||65535==(65535&r)||65534==(65535&r)}cr[W]="Named character references"+or,cr[X]=ar+or,cr[rr]="Named character references"+ir,cr[er]=ar+ir,cr[tr]="Named character references must be known",cr[ur]=ar+" cannot be disallowed",cr[nr]=ar+" cannot be outside the permissible Unicode range";var sr=function(r){return u.raw=function(r,u,a){return L(r,n(a,{position:e(u),warning:t}))},u;function e(e){for(var t=r.offset,u=e.line,n=[];++u&&u in t;)n.push((t[u]||0)+1);return{start:e,indent:n}}function t(e,t,u){3!==u&&r.file.message(e,t)}function u(u,n,a){L(u,{position:e(n),warning:t,text:a,reference:a,textContext:r,referenceContext:r})}};var fr=function(r){return function(e,t){var u,n,a,o,i,c,l=this,s=l.offset,f=[],p=l[r+"Methods"],D=l[r+"Tokenizers"],d=t.line,h=t.column;if(!e)return f;v.now=m,v.file=l.file,g("");for(;e;){for(u=-1,n=p.length,i=!1;++u"],gr=hr.concat(["~","|"]),mr=gr.concat(["\n",'"',"$","%","&","'",",","/",":",";","<","=","?","@","^"]);function br(r){var e=r||{};return e.commonmark?mr:e.gfm?gr:hr}br.default=hr,br.gfm=gr,br.commonmark=mr;var vr=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","iframe","legend","li","link","main","menu","menuitem","meta","nav","noframes","ol","optgroup","option","p","param","pre","section","source","title","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Er=Object.freeze({default:vr}),wr={position:!0,gfm:!0,commonmark:!1,footnotes:!1,pedantic:!1,blocks:Er&&vr||Er},yr=function(e){var t,u,a=this.options;if(null==e)e={};else{if("object"!==r(e))throw new Error("Invalid value `"+e+"` for setting `options`");e=n(e)}for(t in wr){if(null==(u=e[t])&&(u=a[t]),"blocks"!==t&&"boolean"!=typeof u||"blocks"===t&&"object"!==r(u))throw new Error("Invalid value `"+u+"` for setting `options."+t+"`");e[t]=u}return this.options=e,this.escape=dr(e),this};var Ar=function(r,e,t,u){"function"==typeof e&&(u=t,t=e,e=null);function n(r,a,o){var i;return a=a||(o?0:null),e&&r.type!==e||(i=t(r,a,o||null)),r.children&&!1!==i?function(r,e){var t,a=u?-1:1,o=r.length,i=(u?o:-1)+a;for(;i>-1&&i=t)return Rr.substr(0,t);for(;t>Rr.length&&e>1;)1&e&&(Rr+=r),e>>=1,r+=r;return Rr=(Rr+=r).substr(0,t)};var Pr=function(r){var e=String(r),t=e.length;for(;e.charAt(--t)===Ir;);return e.slice(0,t+1)},Ir="\n";var Vr=function(r,e,t){var u,n,a,o=-1,i=e.length,c="",l="",s="",f="";for(;++o=Kr)){for(i="";gse)return;if(!a||!o.pedantic&&e.charAt(c+1)===le)return;i=e.length+1,n="";for(;++c=be&&(!u||u===pe)?(l+=o,!!t||r(l)({type:"thematicBreak"})):void 0;o+=u}},pe="\n",De="\t",de=" ",he="*",ge="_",me="-",be=3;var ve=function(r){var e,t=0,u=0,n=r.charAt(t),a={};for(;n in Ee;)e=Ee[n],u+=e,e>1&&(u=Math.floor(u/e)*e),a[u]=t,n=r.charAt(++t);return{indent:u,stops:a}},Ee={" ":1,"\t":4};var we=function(r,e){var t,u,n,a,o=r.split(Ae),i=o.length+1,c=1/0,l=[];o.unshift(Ur(ye,e)+"!");for(;i--;)if(u=ve(o[i]),l[i]=u.stops,0!==Wr(o[i]).length){if(!u.indent){c=1/0;break}u.indent>0&&u.indent=Oe)return;if(o=e.charAt(T),u=x?je:ze,!0===Ve[o])i=o,a=!1;else{for(a=!0,n="";T=Oe&&(k=!0),v&&R>=v.indent&&(k=!0),o=e.charAt(T),f=null,!k){if(!0===Ve[o])f=o,T++,R++;else{for(n="";T=v.indent||R>Oe):k=!0,s=!1,T=l;if(D=e.slice(l,c),p=l===T?D:e.slice(T,c),(f===Fe||f===ke||f===xe)&&B.thematicBreak.call(this,r,D,!0))break;if(d=h,h=!Wr(p).length,k&&v)v.value=v.value.concat(b,D),m=m.concat(b,D),b=[];else if(s)0!==b.length&&(v.value.push(""),v.trail=b.concat()),v={value:[D],indent:R,trail:[]},g.push(v),m=m.concat(b,D),b=[];else if(h){if(d)break;b.push(D)}else{if(d)break;if(Xr(S,B,this,[r,D,!0]))break;v.value=v.value.concat(b,D),m=m.concat(b,D),b=[]}T=c+1}C=r(m.join(Be)).reset({type:"list",ordered:a,start:N,loose:null,children:[]}),E=this.enterList(),w=this.enterBlock(),A=!1,T=-1,O=g.length;for(;++T=Je){s--;break}f+=a}u="",n="";for(;++s`\\u0000-\\u0020]+|'[^']*'|\"[^\"]*\"))?)*\\s*\\/?>",We="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",Xe={openCloseTag:new RegExp("^(?:"+Ke+"|"+We+")"),tag:new RegExp("^(?:"+Ke+"|"+We+"|\x3c!----\x3e|\x3c!--(?:-?[^>-])(?:-?[^-])*--\x3e|<[?].*?[?]>|]*>|)")},rt=Xe.openCloseTag,et=function(r,e,t){var u,n,a,o,i,c,l,s=this.options.blocks,f=e.length,p=0,D=[[/^<(script|pre|style)(?=(\s|>|$))/i,/<\/(script|pre|style)>/i,!0],[/^/,!0],[/^<\?/,/\?>/,!0],[/^/,!0],[/^/,!0],[new RegExp("^|$))","i"),/^$/,!0],[new RegExp(rt.source+"\\s*$"),/^$/,!1]];for(;pC){if(E1&&(f?(o+=s.slice(0,s.length-1),s=s.charAt(s.length-1)):(o+=s,s="")),b=r.now(),r(o)({type:"tableCell",children:this.tokenizeInline(d,b)},i)),r(s+f),s="",d=""}else if(s&&(d+=s,s=""),d+=f,f===Pt&&u!==c-2&&(d+=w.charAt(u+1),u++),f===It){for(g=1;w.charAt(u+1)===f;)d+=f,u++,g++;m?g>=m&&(m=0):m=g}h=!1,u++}else d?s+=f:r(f),u++;v||r(Ht+n)}return A},Pt="\\",It="`",Vt="-",zt="|",jt=":",Gt=" ",Ht="\n",Mt="\t",$t=1,Zt=2,Yt="left",_t="center",Jt="right",Qt=null;var Kt=function(r,e,t){var u,n,a,o,i,c=this.options,l=c.commonmark,s=c.gfm,f=this.blockTokenizers,p=this.interruptParagraph,D=e.indexOf(Wt),d=e.length;for(;D=eu){D=e.indexOf(Wt,D+1);continue}}if(n=e.slice(D+1),Xr(p,f,this,[r,n,!0]))break;if(f.list.call(this,r,n,!0)&&(this.inList||l||s&&!y(Wr.left(n).charAt(0))))break;if(u=D,-1!==(D=e.indexOf(Wt,D+1))&&""===Wr(e.slice(u,D))){D=u;break}}if(n=e.slice(0,D),""===Wr(n))return r(n),null;if(t)return!0;return i=r.now(),n=Pr(n),r(n)({type:"paragraph",children:this.tokenizeInline(n,i)})},Wt="\n",Xt="\t",ru=" ",eu=4;var tu=function(r,e){return r.indexOf("\\",e)};var uu=nu;function nu(r,e,t){var u,n;if("\\"===e.charAt(0)&&(u=e.charAt(1),-1!==this.escape.indexOf(u)))return!!t||(n="\n"===u?{type:"break"}:{type:"text",value:u},r("\\"+u)(n))}nu.locator=tu;var au=function(r,e){return r.indexOf("<",e)};var ou=Du;Du.locator=au,Du.notInLink=!0;var iu="<",cu=">",lu="@",su="/",fu="mailto:",pu=fu.length;function Du(r,e,t){var u,n,a,o,i,c,l,s,f,p,D;if(e.charAt(0)===iu){for(this,u="",n=e.length,a=0,o="",c=!1,l="",a++,u=iu;a/i;function Su(r,e,t){var u,n,a=e.length;if(!("<"!==e.charAt(0)||a<3)&&(u=e.charAt(1),(C(u)||"?"===u||"!"===u||"/"===u)&&(n=e.match(ku))))return!!t||(n=n[0],!this.inLink&&Lu.test(n)?this.inLink=!0:this.inLink&&Bu.test(n)&&(this.inLink=!1),r(n)({type:"html",value:n}))}var Tu=function(r,e){var t=r.indexOf("[",e),u=r.indexOf("![",e);if(-1===u)return t;return t",Gu="`",Hu={'"':'"',"'":"'"},Mu={};function $u(r,e,t){var u,n,a,o,i,c,l,s,f,p,D,d,h,g,m,b,v,E,w,y="",A=0,C=e.charAt(0),q=this.options.pedantic,F=this.options.commonmark,k=this.options.gfm;if("!"===C&&(f=!0,y=C,C=e.charAt(++A)),C===Uu&&(f||!this.inLink)){for(y+=C,m="",A++,d=e.length,g=0,(v=r.now()).column+=A,v.offset+=A;A=a&&(a=0):a=n}else if(C===Ru)A++,c+=e.charAt(A);else if(a&&!k||C!==Uu){if((!a||k)&&C===Pu){if(!g){if(!q)for(;Ae&&" "===r.charAt(t-1);)t--;return t};var xn=Bn;Bn.locator=kn;var Ln=2;function Bn(r,e,t){for(var u,n=e.length,a=-1,o="";++a1)for(var t=1;ta.length;o&&a.push(u);try{e=r.apply(null,a)}catch(r){if(o&&t)throw r;return u(r)}o||(e&&"function"==typeof e.then?e.then(n,u):e instanceof Error?u(e):n(e))};function u(){t||(t=!0,e.apply(null,arguments))}function n(r){u(null,r)}}(o,n).apply(null,t):u.apply(null,[null].concat(t))}}).apply(null,[null].concat(t))},e.use=function(t){if("function"!=typeof t)throw new Error("Expected `fn` to be a function, not "+t);return r.push(t),e},e},Ia=[].slice;var Va=Object.prototype.toString,za=function(r){return"[object String]"===Va.call(r)};var ja=function(r){return"[object Function]"===Object.prototype.toString.call(r)},Ga=Object.prototype.toString,Ha=function(r){var e;return"[object Object]"===Ga.call(r)&&(null===(e=Object.getPrototypeOf(r))||e===Object.getPrototypeOf({}))},Ma=function e(){var t=[];var u=Pa();var n={};var a=!1;var o=-1;i.data=function(r,e){if(za(r))return 2===arguments.length?(Ka("data",a),n[r]=e,i):Za.call(n,r)&&n[r]||null;if(r)return Ka("data",a),n=r,i;return n};i.freeze=c;i.attachers=t;i.use=function(e){var u;if(Ka("use",a),null===e||void 0===e);else if(ja(e))s.apply(null,arguments);else{if("object"!==r(e))throw new Error("Expected usable value, not `"+e+"`");"length"in e?l(e):o(e)}u&&(n.settings=Gn(n.settings||{},u));return i;function o(r){l(r.plugins),r.settings&&(u=Gn(u||{},r.settings))}function c(e){if(ja(e))s(e);else{if("object"!==r(e))throw new Error("Expected usable value, not `"+e+"`");"length"in e?s.apply(null,e):o(e)}}function l(e){var t,u;if(null===e||void 0===e);else{if(!("object"===r(e)&&"length"in e))throw new Error("Expected a list of plugins, not `"+e+"`");for(t=e.length,u=-1;++u<~]))"].join("|");return new RegExp(e,r.onlyFirst?void 0:"g")}}),oo=o(function(r){r.exports=function(r){return!Number.isNaN(r)&&(r>=4352&&(r<=4447||9001===r||9002===r||11904<=r&&r<=12871&&12351!==r||12880<=r&&r<=19903||19968<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65131||65281<=r&&r<=65376||65504<=r&&r<=65510||110592<=r&&r<=110593||127488<=r&&r<=127569||131072<=r&&r<=262141))}});o(function(r){var e=/\uD83C\uDFF4(?:\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\u200D\u2620\uFE0F)|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3]))|\uD83D\uDC69\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDD1-\uDDDD])/g;r.exports=function(r){if("string"!=typeof(r=r.replace(e," "))||0===r.length)return 0;r=function(r){return"string"==typeof r?r.replace(ao(),""):r}(r);for(var t=0,u=0;u=127&&n<=159||(n>=768&&n<=879||(n>65535&&u++,t+=oo(n)?2:1))}return t}});function io(r){return function(e,t,u){var n=u&&u.backwards;if(!1===t)return!1;for(var a=e.length,o=t;o>=0&&o"],["||","??"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]].forEach(function(r,e){r.forEach(function(r){co[r]=e})});var lo="[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312e\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u32fe\\u3300-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fea\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d]",so="[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]",fo="[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0af0\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166d-\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e49\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc9\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]",po=function(r){return r.length>0?r[r.length-1]:null},Do=["liquidNode","inlineCode","emphasis","strong","delete","link","linkReference","image","imageReference","footnote","footnoteReference","sentence","whitespace","word","break","inlineMath"],ho=Do.concat(["tableCell","paragraph","heading"]),go=new RegExp(so),mo=new RegExp(fo);var bo={mapAst:function(r,e){return function r(t,u,n){n=n||[];var a=Object.assign({},e(t,u,n));return a.children&&(a.children=a.children.map(function(e,t){return r(e,t,[a].concat(n))})),a}(r,null,null)},splitText:function(r,e){var t="non-cjk",u="cj-letter",n="cjk-punctuation",a=[];return("preserve"===e.proseWrap?r:r.replace(new RegExp("(".concat(lo,")\n(").concat(lo,")"),"g"),"$1$2")).split(/([ \t\n]+)/).forEach(function(r,e,i){e%2!=1?(0!==e&&e!==i.length-1||""!==r)&&r.split(new RegExp("(".concat(lo,")"))).forEach(function(r,e,a){(0!==e&&e!==a.length-1||""!==r)&&(e%2!=0?o(mo.test(r)?{type:"word",value:r,kind:n,hasLeadingPunctuation:!0,hasTrailingPunctuation:!0}:{type:"word",value:r,kind:go.test(r)?"k-letter":u,hasLeadingPunctuation:!1,hasTrailingPunctuation:!1}):""!==r&&o({type:"word",value:r,kind:t,hasLeadingPunctuation:mo.test(r[0]),hasTrailingPunctuation:mo.test(po(r))}))}):a.push({type:"whitespace",value:/\n/.test(r)?"\n":" "})}),a;function o(r){var e,o,i=po(a);i&&"word"===i.type&&(i.kind===t&&r.kind===u&&!i.hasTrailingPunctuation||i.kind===u&&r.kind===t&&!r.hasLeadingPunctuation?a.push({type:"whitespace",value:" "}):(e=t,o=n,i.kind===e&&r.kind===o||i.kind===o&&r.kind===e||[i.value,r.value].some(function(r){return/\u3000/.test(r)})||a.push({type:"whitespace",value:""}))),a.push(r)}},punctuationPattern:fo,getFencedCodeBlockValue:function(r,e){var t=e.slice(r.position.start.offset,r.position.end.offset),u=t.match(/^\s*/)[0].length,n=new RegExp("^\\s{0,".concat(u,"}")),a=t.split("\n"),o=t[u],i=t.slice(u).match(new RegExp("^[".concat(o,"]+")))[0],c=new RegExp("^\\s{0,3}".concat(i)).test(a[a.length-1].slice(l(a.length-1)));return a.slice(1,c?-1:void 0).map(function(r,e){return r.slice(l(e+1)).replace(n,"")}).join("\n");function l(e){return r.position.indent[e-1]-1}},getOrderedListItemInfo:function(r,t){var u=e(t.slice(r.position.start.offset,r.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/),4);return{numberText:u[1],marker:u[2],leadingSpaces:u[3]}},INLINE_NODE_TYPES:Do,INLINE_NODE_WRAPPER_TYPES:ho},vo=o(function(r){var e=/^import/,t=/^export/,u=function(r){return e.test(r)},n=function(r){return t.test(r)},a=function(r,e){var t=e.indexOf("\n\n"),a=e.slice(0,t);if(n(a)||u(a))return r(a)({type:n(a)?"export":"import",value:a})};a.locator=function(r){return n(r)||u(r)?-1:1},r.exports={esSyntax:function(){var r=this.Parser,e=r.prototype.blockTokenizers,t=r.prototype.blockMethods;e.esSyntax=a,t.splice(t.indexOf("paragraph"),0,"esSyntax")},BLOCKS_REGEX:"[a-z\\.]+(\\.){0,1}[a-z\\.]"}});function Eo(r,e){return r.indexOf("$",e)}var wo=/^\\\$/,yo=/^\$((?:\\\$|[^$])+)\$/,Ao=/^\$\$((?:\\\$|[^$])+)\$\$/,Co="\n",qo="\t",Fo=" ",ko="$",xo=2,Lo=4,Bo=function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(function(r){var e=this.Parser,t=e.prototype.blockTokenizers,u=e.prototype.blockMethods;t.math=function(r,e,t){for(var u,n,a,o,i,c,l,s,f,p,D=e.length+1,d=0,h="";d=Lo)){for(o="";d$/.test(r.value)||-1!==To.indexOf(n.type)?r:Object.assign({},r,{type:"jsx"})})}}function Uo(){var r=this.Parser.prototype;function e(r,e){var t=uo(e);if(t.frontMatter)return r(t.frontMatter.raw)(t.frontMatter)}r.blockMethods=["frontMatter"].concat(r.blockMethods),r.blockTokenizers.frontMatter=e,e.onlyAtStart=!0}function Po(){var r=this.Parser.prototype,e=r.inlineMethods;function t(r,e){var t=e.match(/^({%[\s\S]*?%}|{{[\s\S]*?}})/);if(t)return r(t[0])({type:"liquidNode",value:t[0]})}e.splice(e.indexOf("text"),0,"liquid"),r.inlineTokenizers.liquid=t,t.locator=function(r,e){return r.indexOf("{",e)}}var Io={astFormat:"mdast",hasPragma:no.hasPragma,locStart:function(r){return r.position.start.offset},locEnd:function(r){return r.position.end.offset},preprocess:function(r){return r.replace(/\n\s+$/,"\n")}},Vo=Object.assign({},Io,{parse:Oo({isMDX:!1})});return{parsers:{remark:Vo,markdown:Vo,mdx:Object.assign({},Io,{parse:Oo({isMDX:!0})})}}}); diff --git a/prettier/parser_typescript.js b/prettier/parser_typescript.js new file mode 100644 index 000000000..ffb2d3554 --- /dev/null +++ b/prettier/parser_typescript.js @@ -0,0 +1,11 @@ +// This file is copied from prettier@1.16.1 +/** + * Copyright © James Long and contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e.prettierPlugins=e.prettierPlugins||{},e.prettierPlugins.typescript=t())}(globalThis,function(){"use strict";var e=function(e,t){var r=new SyntaxError(e+" ("+t.start.line+":"+t.start.column+")");return r.loc=t,r};var t=function(e,t){if(e.startsWith("#!")){var r=e.indexOf("\n"),n={type:"Line",value:e.slice(2,r),range:[0,r],loc:{source:null,start:{line:1,column:0},end:{line:1,column:r}}};t.comments=[n].concat(t.comments)}},r="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(){throw new Error("Dynamic requires are not currently supported by rollup-plugin-commonjs")}function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function a(e,t){return e(t={exports:{}},t.exports),t.exports}var o=a(function(e){e.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");var t=e.match(/(?:\r?\n)/g)||[];if(0===t.length)return null;var r=t.filter(function(e){return"\r\n"===e}).length;return r>t.length-r?"\r\n":"\n"},e.exports.graceful=function(t){return e.exports(t)||"\n"}}),s={EOL:"\n"},c=Object.freeze({default:s}),u=c&&s||c,l=a(function(e,t){var r,n;function i(){return r=(e=o)&&e.__esModule?e:{default:e};var e}function a(){return n=u}Object.defineProperty(t,"__esModule",{value:!0}),t.extract=function(e){var t=e.match(l);return t?t[0].trimLeft():""},t.strip=function(e){var t=e.match(l);return t&&t[0]?e.substring(t[0].length):e},t.parse=function(e){return g(e).pragmas},t.parseWithComments=g,t.print=function(e){var t=e.comments,o=void 0===t?"":t,s=e.pragmas,c=void 0===s?{}:s,u=(0,(r||i()).default)(o)||(n||a()).EOL,l=Object.keys(c),_=l.map(function(e){return y(e,c[e])}).reduce(function(e,t){return e.concat(t)},[]).map(function(e){return" * "+e+u}).join("");if(!o){if(0===l.length)return"";if(1===l.length&&!Array.isArray(c[l[0]])){var d=c[l[0]];return"".concat("/**"," ").concat(y(l[0],d)[0]).concat(" */")}}var p=o.split(u).map(function(e){return"".concat(" *"," ").concat(e)}).join(u)+u;return"/**"+u+(o?p:"")+(o&&l.length?" *"+u:"")+_+" */"};var s=/\*\/$/,c=/^\/\*\*/,l=/^\s*(\/\*\*?(.|\r?\n)*?\*\/)/,_=/(^|\s+)\/\/([^\r\n]*)/g,d=/^(\r?\n)+/,p=/(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g,f=/(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g,m=/(\r?\n|^) *\* ?/g;function g(e){var t=(0,(r||i()).default)(e)||(n||a()).EOL;e=e.replace(c,"").replace(s,"").replace(m,"$1");for(var o="";o!==e;)o=e,e=e.replace(p,"".concat(t,"$1 $2").concat(t));e=e.replace(d,"").trimRight();for(var u,l=Object.create(null),g=e.replace(f,"").replace(d,"").trimRight();u=f.exec(e);){var y=u[2].replace(_,"");"string"==typeof l[u[1]]||Array.isArray(l[u[1]])?l[u[1]]=[].concat(l[u[1]],y):l[u[1]]=y}return{comments:g,pragmas:l}}function y(e,t){return[].concat(t).map(function(t){return"@".concat(e," ").concat(t).trim()})}});i(l);var _=function(e){var t=Object.keys(l.parse(l.extract(e)));return-1!==t.indexOf("prettier")||-1!==t.indexOf("format")},d=function(e){return e.length>0?e[e.length-1]:null};var p={locStart:function e(t,r){return!(r=r||{}).ignoreDecorators&&t.declaration&&t.declaration.decorators&&t.declaration.decorators.length>0?e(t.declaration.decorators[0]):!r.ignoreDecorators&&t.decorators&&t.decorators.length>0?e(t.decorators[0]):t.__location?t.__location.startOffset:t.range?t.range[0]:"number"==typeof t.start?t.start:t.loc?t.loc.start:null},locEnd:function e(t){var r=t.nodes&&d(t.nodes);if(r&&t.source&&!t.source.end&&(t=r),t.__location)return t.__location.endOffset;var n=t.range?t.range[1]:"number"==typeof t.end?t.end:null;return t.typeAnnotation?Math.max(n,e(t.typeAnnotation)):t.loc&&!n?t.loc.end:n}};function f(e){return(f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function m(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var g=a(function(e){e.exports=function(e){e=Object.assign({onlyFirst:!1},e);var t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(t,e.onlyFirst?void 0:"g")}}),y=a(function(e){e.exports=function(e){return!Number.isNaN(e)&&(e>=4352&&(e<=4447||9001===e||9002===e||11904<=e&&e<=12871&&12351!==e||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141))}});a(function(e){var t=/\uD83C\uDFF4(?:\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\u200D\u2620\uFE0F)|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3]))|\uD83D\uDC69\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDD1-\uDDDD])/g;e.exports=function(e){if("string"!=typeof(e=e.replace(t," "))||0===e.length)return 0;e=function(e){return"string"==typeof e?e.replace(g(),""):e}(e);for(var r=0,n=0;n=127&&i<=159||(i>=768&&i<=879||(i>65535&&n++,r+=y(i)?2:1))}return r}});function v(e){return function(t,r,n){var i=n&&n.backwards;if(!1===r)return!1;for(var a=t.length,o=r;o>=0&&o"],["||","??"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]].forEach(function(e,t){e.forEach(function(e){h[e]=t})});var b=function(e){return e.length>0?e[e.length-1]:null};var D=function(e,t){return function e(t,r){if(t&&"object"===f(t))if(Array.isArray(t)){var n=!0,i=!1,a=void 0;try{for(var o,s=t[Symbol.iterator]();!(n=(o=s.next()).done);n=!0){var c=o.value;e(c,r)}}catch(e){i=!0,a=e}finally{try{n||null==s.return||s.return()}finally{if(i)throw a}}}else if("string"==typeof t.type){for(var u=Object.keys(t),l=0;l1)for(var r=1;r>>=5)>0&&(t|=32),r+=re(t)}while(n>0);return r},ae=function(e,t,r){var n,i,a,o,s=e.length,c=0,u=0;do{if(t>=s)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(i=ne(e.charCodeAt(t++))))throw new Error("Invalid base64 digit: "+e.charAt(t-1));n=!!(32&i),c+=(i&=31)<>1,1==(1&a)?-o:o),r.rest=t},oe=a(function(e,t){t.getArg=function(e,t,r){if(t in e)return e[t];if(3===arguments.length)return r;throw new Error('"'+t+'" is a required argument.')};var r=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,n=/^data:.+\,.+$/;function i(e){var t=e.match(r);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}function a(e){var t="";return e.scheme&&(t+=e.scheme+":"),t+="//",e.auth&&(t+=e.auth+"@"),e.host&&(t+=e.host),e.port&&(t+=":"+e.port),e.path&&(t+=e.path),t}function o(e){var r=e,n=i(e);if(n){if(!n.path)return e;r=n.path}for(var o,s=t.isAbsolute(r),c=r.split(/\/+/),u=0,l=c.length-1;l>=0;l--)"."===(o=c[l])?c.splice(l,1):".."===o?u++:u>0&&(""===o?(c.splice(l+1,u),u=0):(c.splice(l,2),u--));return""===(r=c.join("/"))&&(r=s?"/":"."),n?(n.path=r,a(n)):r}function s(e,t){""===e&&(e="."),""===t&&(t=".");var r=i(t),s=i(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),a(r);if(r||t.match(n))return t;if(s&&!s.host&&!s.path)return s.host=t,a(s);var c="/"===t.charAt(0)?t:o(e.replace(/\/+$/,"")+"/"+t);return s?(s.path=c,a(s)):c}t.urlParse=i,t.urlGenerate=a,t.normalize=o,t.join=s,t.isAbsolute=function(e){return"/"===e.charAt(0)||r.test(e)},t.relative=function(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==t.indexOf(e+"/");){var n=e.lastIndexOf("/");if(n<0)return t;if((e=e.slice(0,n)).match(/^([^\/]+:\/)?\/*$/))return t;++r}return Array(r+1).join("../")+t.substr(e.length+1)};var c=!("__proto__"in Object.create(null));function u(e){return e}function l(e){if(!e)return!1;var t=e.length;if(t<9)return!1;if(95!==e.charCodeAt(t-1)||95!==e.charCodeAt(t-2)||111!==e.charCodeAt(t-3)||116!==e.charCodeAt(t-4)||111!==e.charCodeAt(t-5)||114!==e.charCodeAt(t-6)||112!==e.charCodeAt(t-7)||95!==e.charCodeAt(t-8)||95!==e.charCodeAt(t-9))return!1;for(var r=t-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function _(e,t){return e===t?0:null===e?1:null===t?-1:e>t?1:-1}t.toSetString=c?u:function(e){return l(e)?"$"+e:e},t.fromSetString=c?u:function(e){return l(e)?e.slice(1):e},t.compareByOriginalPositions=function(e,t,r){var n=_(e.source,t.source);return 0!==n?n:0!=(n=e.originalLine-t.originalLine)?n:0!=(n=e.originalColumn-t.originalColumn)||r?n:0!=(n=e.generatedColumn-t.generatedColumn)?n:0!=(n=e.generatedLine-t.generatedLine)?n:_(e.name,t.name)},t.compareByGeneratedPositionsDeflated=function(e,t,r){var n=e.generatedLine-t.generatedLine;return 0!==n?n:0!=(n=e.generatedColumn-t.generatedColumn)||r?n:0!==(n=_(e.source,t.source))?n:0!=(n=e.originalLine-t.originalLine)?n:0!=(n=e.originalColumn-t.originalColumn)?n:_(e.name,t.name)},t.compareByGeneratedPositionsInflated=function(e,t){var r=e.generatedLine-t.generatedLine;return 0!==r?r:0!=(r=e.generatedColumn-t.generatedColumn)?r:0!==(r=_(e.source,t.source))?r:0!=(r=e.originalLine-t.originalLine)?r:0!=(r=e.originalColumn-t.originalColumn)?r:_(e.name,t.name)},t.parseSourceMapInput=function(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))},t.computeSourceURL=function(e,t,r){if(t=t||"",e&&("/"!==e[e.length-1]&&"/"!==t[0]&&(e+="/"),t=e+t),r){var n=i(r);if(!n)throw new Error("sourceMapURL could not be parsed");if(n.path){var c=n.path.lastIndexOf("/");c>=0&&(n.path=n.path.substring(0,c+1))}t=s(a(n),t)}return o(t)}}),se=Object.prototype.hasOwnProperty,ce="undefined"!=typeof Map;function ue(){this._array=[],this._set=ce?new Map:Object.create(null)}ue.fromArray=function(e,t){for(var r=new ue,n=0,i=e.length;n=0)return t}else{var r=oe.toSetString(e);if(se.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},ue.prototype.at=function(e){if(e>=0&&en||i==n&&o>=a||oe.compareByGeneratedPositionsInflated(t,r)<=0?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},_e.prototype.toArray=function(){return this._sorted||(this._array.sort(oe.compareByGeneratedPositionsInflated),this._sorted=!0),this._array};var de=le.ArraySet,pe={MappingList:_e}.MappingList;function fe(e){e||(e={}),this._file=oe.getArg(e,"file",null),this._sourceRoot=oe.getArg(e,"sourceRoot",null),this._skipValidation=oe.getArg(e,"skipValidation",!1),this._sources=new de,this._names=new de,this._mappings=new pe,this._sourcesContents=null}fe.prototype._version=3,fe.fromSourceMap=function(e){var t=e.sourceRoot,r=new fe({file:e.file,sourceRoot:t});return e.eachMapping(function(e){var n={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(n.source=e.source,null!=t&&(n.source=oe.relative(t,n.source)),n.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(n.name=e.name)),r.addMapping(n)}),e.sources.forEach(function(n){var i=n;null!==t&&(i=oe.relative(t,n)),r._sources.has(i)||r._sources.add(i);var a=e.sourceContentFor(n);null!=a&&r.setSourceContent(n,a)}),r},fe.prototype.addMapping=function(e){var t=oe.getArg(e,"generated"),r=oe.getArg(e,"original",null),n=oe.getArg(e,"source",null),i=oe.getArg(e,"name",null);this._skipValidation||this._validateMapping(t,r,n,i),null!=n&&(n=String(n),this._sources.has(n)||this._sources.add(n)),null!=i&&(i=String(i),this._names.has(i)||this._names.add(i)),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:n,name:i})},fe.prototype.setSourceContent=function(e,t){var r=e;null!=this._sourceRoot&&(r=oe.relative(this._sourceRoot,r)),null!=t?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[oe.toSetString(r)]=t):this._sourcesContents&&(delete this._sourcesContents[oe.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},fe.prototype.applySourceMap=function(e,t,r){var n=t;if(null==t){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');n=e.file}var i=this._sourceRoot;null!=i&&(n=oe.relative(i,n));var a=new de,o=new de;this._mappings.unsortedForEach(function(t){if(t.source===n&&null!=t.originalLine){var s=e.originalPositionFor({line:t.originalLine,column:t.originalColumn});null!=s.source&&(t.source=s.source,null!=r&&(t.source=oe.join(r,t.source)),null!=i&&(t.source=oe.relative(i,t.source)),t.originalLine=s.line,t.originalColumn=s.column,null!=s.name&&(t.name=s.name))}var c=t.source;null==c||a.has(c)||a.add(c);var u=t.name;null==u||o.has(u)||o.add(u)},this),this._sources=a,this._names=o,e.sources.forEach(function(t){var n=e.sourceContentFor(t);null!=n&&(null!=r&&(t=oe.join(r,t)),null!=i&&(t=oe.relative(i,t)),this.setSourceContent(t,n))},this)},fe.prototype._validateMapping=function(e,t,r,n){if(t&&"number"!=typeof t.line&&"number"!=typeof t.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||t||r||n)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:t,name:n}))},fe.prototype._serializeMappings=function(){for(var e,t,r,n,i=0,a=1,o=0,s=0,c=0,u=0,l="",_=this._mappings.toArray(),d=0,p=_.length;d0){if(!oe.compareByGeneratedPositionsInflated(t,_[d-1]))continue;e+=","}e+=ie(t.generatedColumn-i),i=t.generatedColumn,null!=t.source&&(n=this._sources.indexOf(t.source),e+=ie(n-u),u=n,e+=ie(t.originalLine-1-s),s=t.originalLine-1,e+=ie(t.originalColumn-o),o=t.originalColumn,null!=t.name&&(r=this._names.indexOf(t.name),e+=ie(r-c),c=r)),l+=e}return l},fe.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;null!=t&&(e=oe.relative(t,e));var r=oe.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},fe.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},fe.prototype.toString=function(){return JSON.stringify(this.toJSON())};var me={SourceMapGenerator:fe},ge=a(function(e,t){t.GREATEST_LOWER_BOUND=1,t.LEAST_UPPER_BOUND=2,t.search=function(e,r,n,i){if(0===r.length)return-1;var a=function e(r,n,i,a,o,s){var c=Math.floor((n-r)/2)+r,u=o(i,a[c],!0);return 0===u?c:u>0?n-c>1?e(c,n,i,a,o,s):s==t.LEAST_UPPER_BOUND?n1?e(r,c,i,a,o,s):s==t.LEAST_UPPER_BOUND?c:r<0?-1:r}(-1,r.length,e,r,n,i||t.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&0===n(r[a],r[a-1],!0);)--a;return a}});function ye(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function ve(e,t,r,n){if(r=0){var a=this._originalMappings[i];if(void 0===e.column)for(var o=a.originalLine;a&&a.originalLine===o;)n.push({line:oe.getArg(a,"generatedLine",null),column:oe.getArg(a,"generatedColumn",null),lastColumn:oe.getArg(a,"lastGeneratedColumn",null)}),a=this._originalMappings[++i];else for(var s=a.originalColumn;a&&a.originalLine===t&&a.originalColumn==s;)n.push({line:oe.getArg(a,"generatedLine",null),column:oe.getArg(a,"generatedColumn",null),lastColumn:oe.getArg(a,"lastGeneratedColumn",null)}),a=this._originalMappings[++i]}return n};function xe(e,t){var r=e;"string"==typeof e&&(r=oe.parseSourceMapInput(e));var n=oe.getArg(r,"version"),i=oe.getArg(r,"sources"),a=oe.getArg(r,"names",[]),o=oe.getArg(r,"sourceRoot",null),s=oe.getArg(r,"sourcesContent",null),c=oe.getArg(r,"mappings"),u=oe.getArg(r,"file",null);if(n!=this._version)throw new Error("Unsupported version: "+n);o&&(o=oe.normalize(o)),i=i.map(String).map(oe.normalize).map(function(e){return o&&oe.isAbsolute(o)&&oe.isAbsolute(e)?oe.relative(o,e):e}),this._names=he.fromArray(a.map(String),!0),this._sources=he.fromArray(i,!0),this._absoluteSources=this._sources.toArray().map(function(e){return oe.computeSourceURL(o,e,t)}),this.sourceRoot=o,this.sourcesContent=s,this._mappings=c,this._sourceMapURL=t,this.file=u}function Se(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}xe.prototype=Object.create(De.prototype),xe.prototype.consumer=De,xe.prototype._findSourceIndex=function(e){var t,r=e;if(null!=this.sourceRoot&&(r=oe.relative(this.sourceRoot,r)),this._sources.has(r))return this._sources.indexOf(r);for(t=0;t1&&(r.source=_+i[1],_+=i[1],r.originalLine=u+i[2],u=r.originalLine,r.originalLine+=1,r.originalColumn=l+i[3],l=r.originalColumn,i.length>4&&(r.name=d+i[4],d+=i[4])),v.push(r),"number"==typeof r.originalLine&&y.push(r)}be(v,oe.compareByGeneratedPositionsDeflated),this.__generatedMappings=v,be(y,oe.compareByOriginalPositions),this.__originalMappings=y},xe.prototype._findMapping=function(e,t,r,n,i,a){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[n]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[n]);return ge.search(e,t,i,a)},xe.prototype.computeColumnSpans=function(){for(var e=0;e=0){var n=this._generatedMappings[r];if(n.generatedLine===t.generatedLine){var i=oe.getArg(n,"source",null);null!==i&&(i=this._sources.at(i),i=oe.computeSourceURL(this.sourceRoot,i,this._sourceMapURL));var a=oe.getArg(n,"name",null);return null!==a&&(a=this._names.at(a)),{source:i,line:oe.getArg(n,"originalLine",null),column:oe.getArg(n,"originalColumn",null),name:a}}}return{source:null,line:null,column:null,name:null}},xe.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},xe.prototype.sourceContentFor=function(e,t){if(!this.sourcesContent)return null;var r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];var n,i=e;if(null!=this.sourceRoot&&(i=oe.relative(this.sourceRoot,i)),null!=this.sourceRoot&&(n=oe.urlParse(this.sourceRoot))){var a=i.replace(/^file:\/\//,"");if("file"==n.scheme&&this._sources.has(a))return this.sourcesContent[this._sources.indexOf(a)];if((!n.path||"/"==n.path)&&this._sources.has("/"+i))return this.sourcesContent[this._sources.indexOf("/"+i)]}if(t)return null;throw new Error('"'+i+'" is not in the SourceMap.')},xe.prototype.generatedPositionFor=function(e){var t=oe.getArg(e,"source");if((t=this._findSourceIndex(t))<0)return{line:null,column:null,lastColumn:null};var r={source:t,originalLine:oe.getArg(e,"line"),originalColumn:oe.getArg(e,"column")},n=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",oe.compareByOriginalPositions,oe.getArg(e,"bias",De.GREATEST_LOWER_BOUND));if(n>=0){var i=this._originalMappings[n];if(i.source===r.source)return{line:oe.getArg(i,"generatedLine",null),column:oe.getArg(i,"generatedColumn",null),lastColumn:oe.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}};function Te(e,t){var r=e;"string"==typeof e&&(r=oe.parseSourceMapInput(e));var n=oe.getArg(r,"version"),i=oe.getArg(r,"sections");if(n!=this._version)throw new Error("Unsupported version: "+n);this._sources=new he,this._names=new he;var a={line:-1,column:0};this._sections=i.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var r=oe.getArg(e,"offset"),n=oe.getArg(r,"line"),i=oe.getArg(r,"column");if(n=0;t--)this.prepend(e[t]);else{if(!e[Ee]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},Ne.prototype.walk=function(e){for(var t,r=0,n=this.children.length;r0){for(t=[],r=0;r>18&63]+Ae[i>>12&63]+Ae[i>>6&63]+Ae[63&i]);return a.join("")}function Me(e){var t;we||Oe();for(var r=e.length,n=r%3,i="",a=[],o=0,s=r-n;os?s:o+16383));return 1===n?(t=e[r-1],i+=Ae[t>>2],i+=Ae[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=Ae[t>>10],i+=Ae[t>>4&63],i+=Ae[t<<2&63],i+="="),a.push(i),a.join("")}function Le(e,t,r,n,i){var a,o,s=8*i-n-1,c=(1<>1,l=-7,_=r?i-1:0,d=r?-1:1,p=e[t+_];for(_+=d,a=p&(1<<-l)-1,p>>=-l,l+=s;l>0;a=256*a+e[t+_],_+=d,l-=8);for(o=a&(1<<-l)-1,a>>=-l,l+=n;l>0;o=256*o+e[t+_],_+=d,l-=8);if(0===a)a=1-u;else{if(a===c)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),a-=u}return(p?-1:1)*o*Math.pow(2,a-n)}function Re(e,t,r,n,i,a){var o,s,c,u=8*a-i-1,l=(1<>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,f=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+_>=1?d/c:d*Math.pow(2,1-_))*c>=2&&(o++,c/=2),o+_>=l?(s=0,o=l):o+_>=1?(s=(t*c-1)*Math.pow(2,i),o+=_):(s=t*Math.pow(2,_-1)*Math.pow(2,i),o=0));i>=8;e[r+p]=255&s,p+=f,s/=256,i-=8);for(o=o<0;e[r+p]=255&o,p+=f,o/=256,u-=8);e[r+p-f]|=128*m}var Be={}.toString,je=Array.isArray||function(e){return"[object Array]"==Be.call(e)};function Je(){return Ke.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function ze(e,t){if(Je()=Je())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Je().toString(16)+" bytes");return 0|e}function Ge(e){return!(null==e||!e._isBuffer)}function Ye(e,t){if(Ge(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Dt(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return xt(e).length;default:if(n)return Dt(e).length;t=(""+t).toLowerCase(),n=!0}}function Xe(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function Qe(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=Ke.from(t,n)),Ge(t))return 0===t.length?-1:$e(e,t,r,n,i);if("number"==typeof t)return t&=255,Ke.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):$e(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function $e(e,t,r,n,i){var a,o=1,s=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;o=2,s/=2,c/=2,r/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){var l=-1;for(a=r;as&&(r=s-c),a=r;a>=0;a--){for(var _=!0,d=0;di&&(n=i):n=i;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var o=0;o>8,i=r%256,a.push(i),a.push(n);return a}(t,e.length-r),e,r,n)}function at(e,t,r){return 0===t&&r===e.length?Me(e):Me(e.slice(t,r))}function ot(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:u>223?3:u>191?2:1;if(i+_<=r)switch(_){case 1:u<128&&(l=u);break;case 2:128==(192&(a=e[i+1]))&&(c=(31&u)<<6|63&a)>127&&(l=c);break;case 3:a=e[i+1],o=e[i+2],128==(192&a)&&128==(192&o)&&(c=(15&u)<<12|(63&a)<<6|63&o)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:a=e[i+1],o=e[i+2],s=e[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&(c=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&c<1114112&&(l=c)}null===l?(l=65533,_=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=_}return function(e){var t=e.length;if(t<=st)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return lt(this,t,r);case"utf8":case"utf-8":return ot(this,t,r);case"ascii":return ct(this,t,r);case"latin1":case"binary":return ut(this,t,r);case"base64":return at(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _t(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},Ke.prototype.equals=function(e){if(!Ge(e))throw new TypeError("Argument must be a Buffer");return this===e||0===Ke.compare(this,e)},Ke.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),""},Ke.prototype.compare=function(e,t,r,n,i){if(!Ge(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;for(var a=i-n,o=r-t,s=Math.min(a,o),c=this.slice(n,i),u=e.slice(t,r),l=0;li)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return Ze(this,e,t,r);case"utf8":case"utf-8":return et(this,e,t,r);case"ascii":return tt(this,e,t,r);case"latin1":case"binary":return rt(this,e,t,r);case"base64":return nt(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return it(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},Ke.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var st=4096;function ct(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",a=t;ar)throw new RangeError("Trying to access beyond buffer length")}function pt(e,t,r,n,i,a){if(!Ge(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function ft(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,a=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function mt(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,a=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function gt(e,t,r,n,i,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function yt(e,t,r,n,i){return i||gt(e,0,r,4),Re(e,t,r,n,23,4),r+4}function vt(e,t,r,n,i){return i||gt(e,0,r,8),Re(e,t,r,n,52,8),r+8}Ke.prototype.slice=function(e,t){var r,n=this.length;if(e=~~e,t=void 0===t?n:~~t,e<0?(e+=n)<0&&(e=0):e>n&&(e=n),t<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(i*=256);)n+=this[e+--t]*i;return n},Ke.prototype.readUInt8=function(e,t){return t||dt(e,1,this.length),this[e]},Ke.prototype.readUInt16LE=function(e,t){return t||dt(e,2,this.length),this[e]|this[e+1]<<8},Ke.prototype.readUInt16BE=function(e,t){return t||dt(e,2,this.length),this[e]<<8|this[e+1]},Ke.prototype.readUInt32LE=function(e,t){return t||dt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Ke.prototype.readUInt32BE=function(e,t){return t||dt(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Ke.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||dt(e,t,this.length);for(var n=this[e],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*t)),n},Ke.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||dt(e,t,this.length);for(var n=t,i=1,a=this[e+--n];n>0&&(i*=256);)a+=this[e+--n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*t)),a},Ke.prototype.readInt8=function(e,t){return t||dt(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Ke.prototype.readInt16LE=function(e,t){t||dt(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},Ke.prototype.readInt16BE=function(e,t){t||dt(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},Ke.prototype.readInt32LE=function(e,t){return t||dt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Ke.prototype.readInt32BE=function(e,t){return t||dt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Ke.prototype.readFloatLE=function(e,t){return t||dt(e,4,this.length),Le(this,e,!0,23,4)},Ke.prototype.readFloatBE=function(e,t){return t||dt(e,4,this.length),Le(this,e,!1,23,4)},Ke.prototype.readDoubleLE=function(e,t){return t||dt(e,8,this.length),Le(this,e,!0,52,8)},Ke.prototype.readDoubleBE=function(e,t){return t||dt(e,8,this.length),Le(this,e,!1,52,8)},Ke.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||pt(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+i]=e/a&255;return t+r},Ke.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||pt(this,e,t,1,255,0),Ke.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Ke.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||pt(this,e,t,2,65535,0),Ke.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):ft(this,e,t,!0),t+2},Ke.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||pt(this,e,t,2,65535,0),Ke.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):ft(this,e,t,!1),t+2},Ke.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||pt(this,e,t,4,4294967295,0),Ke.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):mt(this,e,t,!0),t+4},Ke.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||pt(this,e,t,4,4294967295,0),Ke.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):mt(this,e,t,!1),t+4},Ke.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);pt(this,e,t,r,i-1,-i)}var a=0,o=1,s=0;for(this[t]=255&e;++a>0)-s&255;return t+r},Ke.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);pt(this,e,t,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[t+a]=255&e;--a>=0&&(o*=256);)e<0&&0===s&&0!==this[t+a+1]&&(s=1),this[t+a]=(e/o>>0)-s&255;return t+r},Ke.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||pt(this,e,t,1,127,-128),Ke.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Ke.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||pt(this,e,t,2,32767,-32768),Ke.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):ft(this,e,t,!0),t+2},Ke.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||pt(this,e,t,2,32767,-32768),Ke.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):ft(this,e,t,!1),t+2},Ke.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||pt(this,e,t,4,2147483647,-2147483648),Ke.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):mt(this,e,t,!0),t+4},Ke.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||pt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Ke.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):mt(this,e,t,!1),t+4},Ke.prototype.writeFloatLE=function(e,t,r){return yt(this,e,t,!0,r)},Ke.prototype.writeFloatBE=function(e,t,r){return yt(this,e,t,!1,r)},Ke.prototype.writeDoubleLE=function(e,t,r){return vt(this,e,t,!0,r)},Ke.prototype.writeDoubleBE=function(e,t,r){return vt(this,e,t,!1,r)},Ke.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(a<1e3||!Ke.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function xt(e){return function(e){var t,r,n,i,a,o;we||Oe();var s=e.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===e[s-2]?2:"="===e[s-1]?1:0,o=new Pe(3*s/4-a),n=a>0?s-4:s;var c=0;for(t=0,r=0;t>16&255,o[c++]=i>>8&255,o[c++]=255&i;return 2===a?(i=Fe[e.charCodeAt(t)]<<2|Fe[e.charCodeAt(t+1)]>>4,o[c++]=255&i):1===a&&(i=Fe[e.charCodeAt(t)]<<10|Fe[e.charCodeAt(t+1)]<<4|Fe[e.charCodeAt(t+2)]>>2,o[c++]=i>>8&255,o[c++]=255&i),o}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(ht,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function St(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function Tt(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}var Ct=Object.prototype.toString,kt="function"==typeof Ke.alloc&&"function"==typeof Ke.allocUnsafe&&"function"==typeof Ke.from;var Et,Nt=function(e,t,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return n=e,"ArrayBuffer"===Ct.call(n).slice(8,-1)?function(e,t,r){t>>>=0;var n=e.byteLength-t;if(n<0)throw new RangeError("'offset' is out of bounds");if(void 0===r)r=n;else if((r>>>=0)>n)throw new RangeError("'length' is out of bounds");return kt?Ke.from(e.slice(t,t+r)):new Ke(new Uint8Array(e.slice(t,t+r)))}(e,t,r):"string"==typeof e?function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!Ke.isEncoding(t))throw new TypeError('"encoding" must be a valid string encoding');return kt?Ke.from(e,t):new Ke(e,t)}(e,t):kt?Ke.from(e):new Ke(e);var n},At={},Ft=(Object.freeze({default:At}),Y&&G||Y),Pt=$&&Q||$,wt=Ft;try{(Et=Pt).existsSync&&Et.readFileSync||(Et=null)}catch(e){}var Ot="auto",It={},Mt=/^data:application\/json[^,]+base64,/,Lt=[],Rt=[];function Bt(){return"browser"===Ot||"node"!==Ot&&("undefined"!=typeof window&&"function"==typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type))}function jt(e){return function(t){for(var r=0;r0&&i[i.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]0;for(var r=0,n=e;r>1);switch(n(r(e[c]),t)){case-1:a=c+1;break;case 0:return c;case 1:s=c-1}}return~a}function y(e,t,r,n,i){if(e&&e.length>0){var a=e.length;if(a>0){var o=void 0===n||n<0?0:n,s=void 0===i||o+i>a-1?a-1:o+i,c=void 0;for(arguments.length<=2?(c=e[o],o++):c=r;o<=s;)c=t(c,e[o],o),o++;return c}}return r}e.emptyArray=[],e.createMap=r,e.createMapFromEntries=function(e){for(var t=r(),n=0,i=e;n=0;r--){var n=e[r];if(t(n,r))return n}},e.findIndex=function(e,t,r){for(var n=r||0;n=0;n--)if(t(e[n],n))return n;return-1},e.findMap=function(e,t){for(var r=0;r0&&v.assertGreaterThanOrEqual(r(t[a],t[a-1]),0);t:for(var o=i;io&&v.assertGreaterThanOrEqual(r(e[i],e[i-1]),0),r(t[a],e[i])){case-1:n.push(t[a]);continue e;case 0:continue e;case 1:continue t}}return n},e.sum=function(e,t){for(var r=0,n=0,i=e;nt?1:0}function M(e,t){return w(e,t)}e.hasProperty=b,e.getProperty=function(e,t){return h.call(e,t)?e[t]:void 0},e.getOwnKeys=function(e){var t=[];for(var r in e)h.call(e,r)&&t.push(r);return t},e.getOwnValues=function(e){var t=[];for(var r in e)h.call(e,r)&&t.push(e[r]);return t},e.arrayFrom=D,e.assign=function(e){for(var t=[],r=1;r=t},e.assert=function e(r,n,i,a){r||(i&&(n+="\r\nVerbose Debug Information: "+("string"==typeof i?i:i())),t(n?"False expression: "+n:"False expression.",a||e))},e.assertEqual=function(e,r,n,i){e!==r&&t("Expected "+e+" === "+r+". "+(n?i?n+" "+i:n:""))},e.assertLessThan=function(e,r,n){e>=r&&t("Expected "+e+" < "+r+". "+(n||""))},e.assertLessThanOrEqual=function(e,r){e>r&&t("Expected "+e+" <= "+r)},e.assertGreaterThanOrEqual=function(e,r){e= "+r)},e.fail=t,e.assertDefined=r,e.assertEachDefined=function(e,t){for(var n=0,i=e;n0?1:0}function i(e){var t=new Intl.Collator(e,{usage:"sort",sensitivity:"variant"}).compare;return function(e,r){return n(e,r,t)}}function a(e){return void 0!==e?o():function(e,r){return n(e,r,t)};function t(e,t){return e.localeCompare(t)}}function o(){return function(t,r){return n(t,r,e)};function e(e,r){return t(e.toUpperCase(),r.toUpperCase())||t(e,r)}function t(e,t){return et?1:0}}}();function j(e,t,r){for(var n=new Array(t.length+1),i=new Array(t.length+1),a=r+1,o=0;o<=t.length;o++)n[o]=o;for(o=1;o<=e.length;o++){var s=e.charCodeAt(o-1),c=o>r?o-r:1,u=t.length>r+o?r+o:t.length;i[0]=o;for(var l=o,_=1;_r)return;var p=n;n=i,i=p}var f=n[t.length];return f>r?void 0:f}function J(e,t){var r=e.length-t.length;return r>=0&&e.indexOf(t,r)===r}function z(e,t){return e.length>t.length&&J(e,t)}function K(e,t){for(var r=t;r=r.length+n.length&&q(t,r)&&J(t,n)}e.getUILocale=function(){return R},e.setUILocale=function(e){R!==e&&(R=e,L=void 0)},e.compareStringsCaseSensitiveUI=function(e,t){return(L||(L=B(R)))(e,t)},e.compareProperties=function(e,t,r,n){return e===t?0:void 0===e?-1:void 0===t?1:n(e[r],t[r])},e.compareBooleans=function(e,t){return O(e?1:0,t?1:0)},e.getSpellingSuggestion=function(e,t,r){for(var n,i=Math.min(2,Math.floor(.34*e.length)),a=Math.floor(.4*e.length)+1,o=!1,s=e.toLowerCase(),c=0,u=t;ci&&(i=c.prefix.length,n=s)}return n},e.startsWith=q,e.removePrefix=function(e,t){return q(e,t)?e.substr(t.length):e},e.tryRemovePrefix=function(e,t,r){return void 0===r&&(r=N),q(r(e),r(t))?e.substring(t.length):void 0},e.and=function(e,t){return function(r){return e(r)&&t(r)}},e.or=function(e,t){return function(r){return e(r)||t(r)}},e.assertType=function(e){},e.singleElementArray=function(e){return void 0===e?void 0:[e]},e.enumerateInsertsAndDeletes=function(e,t,r,n,i,a){a=a||E;for(var o=0,s=0,c=e.length,u=t.length;o=0,"Invalid argument: major"),e.Debug.assert(i>=0,"Invalid argument: minor"),e.Debug.assert(a>=0,"Invalid argument: patch"),e.Debug.assert(!s||r.test(s),"Invalid argument: prerelease"),e.Debug.assert(!c||n.test(c),"Invalid argument: build"),this.major=t,this.minor=i,this.patch=a,this.prerelease=s?s.split("."):e.emptyArray,this.build=c?c.split("."):e.emptyArray}return t.tryParse=function(e){var r=o(e);if(r)return new t(r.major,r.minor,r.patch,r.prerelease,r.build)},t.prototype.compareTo=function(t){return this===t?0:void 0===t?1:e.compareValues(this.major,t.major)||e.compareValues(this.minor,t.minor)||e.compareValues(this.patch,t.patch)||function(t,r){if(t===r)return 0;if(0===t.length)return 0===r.length?0:1;if(0===r.length)return-1;for(var n=Math.min(t.length,r.length),a=0;a|>=|=)?\s*([a-z0-9-+.*]+)$/i;function p(e){for(var t=[],r=0,n=e.trim().split(c);r=",n.version)),y(i.major)||r.push(y(i.minor)?v("<",i.version.increment("major")):y(i.patch)?v("<",i.version.increment("minor")):v("<=",i.version)),!0)}function g(e,t,r){var n=f(t);if(!n)return!1;var i=n.version,o=n.major,s=n.minor,c=n.patch;if(y(o))"<"!==e&&">"!==e||r.push(v("<",a.zero));else switch(e){case"~":r.push(v(">=",i)),r.push(v("<",i.increment(y(s)?"major":"minor")));break;case"^":r.push(v(">=",i)),r.push(v("<",i.increment(i.major>0||y(s)?"major":i.minor>0||y(c)?"minor":"patch")));break;case"<":case">=":r.push(v(e,i));break;case"<=":case">":r.push(y(s)?v("<="===e?"<":">=",i.increment("major")):y(c)?v("<="===e?"<":">=",i.increment("minor")):v(e,i));break;case"=":case void 0:y(s)||y(c)?(r.push(v(">=",i)),r.push(v("<",i.increment(y(s)?"major":"minor")))):r.push(v("=",i));break;default:return!1}return!0}function y(e){return"*"===e||"x"===e||"X"===e}function v(e,t){return{operator:e,operand:t}}function h(e,t){for(var r=0,n=t;r":return i>0;case">=":return i>=0;case"=":return 0===i;default:return e.Debug.assertNever(r)}}function D(t){return e.map(t,x).join(" ")}function x(e){return""+e.operator+e.operand}}(c||(c={})),function(e){!function(e){e[e.Unknown=0]="Unknown",e[e.EndOfFileToken=1]="EndOfFileToken",e[e.SingleLineCommentTrivia=2]="SingleLineCommentTrivia",e[e.MultiLineCommentTrivia=3]="MultiLineCommentTrivia",e[e.NewLineTrivia=4]="NewLineTrivia",e[e.WhitespaceTrivia=5]="WhitespaceTrivia",e[e.ShebangTrivia=6]="ShebangTrivia",e[e.ConflictMarkerTrivia=7]="ConflictMarkerTrivia",e[e.NumericLiteral=8]="NumericLiteral",e[e.BigIntLiteral=9]="BigIntLiteral",e[e.StringLiteral=10]="StringLiteral",e[e.JsxText=11]="JsxText",e[e.JsxTextAllWhiteSpaces=12]="JsxTextAllWhiteSpaces",e[e.RegularExpressionLiteral=13]="RegularExpressionLiteral",e[e.NoSubstitutionTemplateLiteral=14]="NoSubstitutionTemplateLiteral",e[e.TemplateHead=15]="TemplateHead",e[e.TemplateMiddle=16]="TemplateMiddle",e[e.TemplateTail=17]="TemplateTail",e[e.OpenBraceToken=18]="OpenBraceToken",e[e.CloseBraceToken=19]="CloseBraceToken",e[e.OpenParenToken=20]="OpenParenToken",e[e.CloseParenToken=21]="CloseParenToken",e[e.OpenBracketToken=22]="OpenBracketToken",e[e.CloseBracketToken=23]="CloseBracketToken",e[e.DotToken=24]="DotToken",e[e.DotDotDotToken=25]="DotDotDotToken",e[e.SemicolonToken=26]="SemicolonToken",e[e.CommaToken=27]="CommaToken",e[e.LessThanToken=28]="LessThanToken",e[e.LessThanSlashToken=29]="LessThanSlashToken",e[e.GreaterThanToken=30]="GreaterThanToken",e[e.LessThanEqualsToken=31]="LessThanEqualsToken",e[e.GreaterThanEqualsToken=32]="GreaterThanEqualsToken",e[e.EqualsEqualsToken=33]="EqualsEqualsToken",e[e.ExclamationEqualsToken=34]="ExclamationEqualsToken",e[e.EqualsEqualsEqualsToken=35]="EqualsEqualsEqualsToken",e[e.ExclamationEqualsEqualsToken=36]="ExclamationEqualsEqualsToken",e[e.EqualsGreaterThanToken=37]="EqualsGreaterThanToken",e[e.PlusToken=38]="PlusToken",e[e.MinusToken=39]="MinusToken",e[e.AsteriskToken=40]="AsteriskToken",e[e.AsteriskAsteriskToken=41]="AsteriskAsteriskToken",e[e.SlashToken=42]="SlashToken",e[e.PercentToken=43]="PercentToken",e[e.PlusPlusToken=44]="PlusPlusToken",e[e.MinusMinusToken=45]="MinusMinusToken",e[e.LessThanLessThanToken=46]="LessThanLessThanToken",e[e.GreaterThanGreaterThanToken=47]="GreaterThanGreaterThanToken",e[e.GreaterThanGreaterThanGreaterThanToken=48]="GreaterThanGreaterThanGreaterThanToken",e[e.AmpersandToken=49]="AmpersandToken",e[e.BarToken=50]="BarToken",e[e.CaretToken=51]="CaretToken",e[e.ExclamationToken=52]="ExclamationToken",e[e.TildeToken=53]="TildeToken",e[e.AmpersandAmpersandToken=54]="AmpersandAmpersandToken",e[e.BarBarToken=55]="BarBarToken",e[e.QuestionToken=56]="QuestionToken",e[e.ColonToken=57]="ColonToken",e[e.AtToken=58]="AtToken",e[e.EqualsToken=59]="EqualsToken",e[e.PlusEqualsToken=60]="PlusEqualsToken",e[e.MinusEqualsToken=61]="MinusEqualsToken",e[e.AsteriskEqualsToken=62]="AsteriskEqualsToken",e[e.AsteriskAsteriskEqualsToken=63]="AsteriskAsteriskEqualsToken",e[e.SlashEqualsToken=64]="SlashEqualsToken",e[e.PercentEqualsToken=65]="PercentEqualsToken",e[e.LessThanLessThanEqualsToken=66]="LessThanLessThanEqualsToken",e[e.GreaterThanGreaterThanEqualsToken=67]="GreaterThanGreaterThanEqualsToken",e[e.GreaterThanGreaterThanGreaterThanEqualsToken=68]="GreaterThanGreaterThanGreaterThanEqualsToken",e[e.AmpersandEqualsToken=69]="AmpersandEqualsToken",e[e.BarEqualsToken=70]="BarEqualsToken",e[e.CaretEqualsToken=71]="CaretEqualsToken",e[e.Identifier=72]="Identifier",e[e.BreakKeyword=73]="BreakKeyword",e[e.CaseKeyword=74]="CaseKeyword",e[e.CatchKeyword=75]="CatchKeyword",e[e.ClassKeyword=76]="ClassKeyword",e[e.ConstKeyword=77]="ConstKeyword",e[e.ContinueKeyword=78]="ContinueKeyword",e[e.DebuggerKeyword=79]="DebuggerKeyword",e[e.DefaultKeyword=80]="DefaultKeyword",e[e.DeleteKeyword=81]="DeleteKeyword",e[e.DoKeyword=82]="DoKeyword",e[e.ElseKeyword=83]="ElseKeyword",e[e.EnumKeyword=84]="EnumKeyword",e[e.ExportKeyword=85]="ExportKeyword",e[e.ExtendsKeyword=86]="ExtendsKeyword",e[e.FalseKeyword=87]="FalseKeyword",e[e.FinallyKeyword=88]="FinallyKeyword",e[e.ForKeyword=89]="ForKeyword",e[e.FunctionKeyword=90]="FunctionKeyword",e[e.IfKeyword=91]="IfKeyword",e[e.ImportKeyword=92]="ImportKeyword",e[e.InKeyword=93]="InKeyword",e[e.InstanceOfKeyword=94]="InstanceOfKeyword",e[e.NewKeyword=95]="NewKeyword",e[e.NullKeyword=96]="NullKeyword",e[e.ReturnKeyword=97]="ReturnKeyword",e[e.SuperKeyword=98]="SuperKeyword",e[e.SwitchKeyword=99]="SwitchKeyword",e[e.ThisKeyword=100]="ThisKeyword",e[e.ThrowKeyword=101]="ThrowKeyword",e[e.TrueKeyword=102]="TrueKeyword",e[e.TryKeyword=103]="TryKeyword",e[e.TypeOfKeyword=104]="TypeOfKeyword",e[e.VarKeyword=105]="VarKeyword",e[e.VoidKeyword=106]="VoidKeyword",e[e.WhileKeyword=107]="WhileKeyword",e[e.WithKeyword=108]="WithKeyword",e[e.ImplementsKeyword=109]="ImplementsKeyword",e[e.InterfaceKeyword=110]="InterfaceKeyword",e[e.LetKeyword=111]="LetKeyword",e[e.PackageKeyword=112]="PackageKeyword",e[e.PrivateKeyword=113]="PrivateKeyword",e[e.ProtectedKeyword=114]="ProtectedKeyword",e[e.PublicKeyword=115]="PublicKeyword",e[e.StaticKeyword=116]="StaticKeyword",e[e.YieldKeyword=117]="YieldKeyword",e[e.AbstractKeyword=118]="AbstractKeyword",e[e.AsKeyword=119]="AsKeyword",e[e.AnyKeyword=120]="AnyKeyword",e[e.AsyncKeyword=121]="AsyncKeyword",e[e.AwaitKeyword=122]="AwaitKeyword",e[e.BooleanKeyword=123]="BooleanKeyword",e[e.ConstructorKeyword=124]="ConstructorKeyword",e[e.DeclareKeyword=125]="DeclareKeyword",e[e.GetKeyword=126]="GetKeyword",e[e.InferKeyword=127]="InferKeyword",e[e.IsKeyword=128]="IsKeyword",e[e.KeyOfKeyword=129]="KeyOfKeyword",e[e.ModuleKeyword=130]="ModuleKeyword",e[e.NamespaceKeyword=131]="NamespaceKeyword",e[e.NeverKeyword=132]="NeverKeyword",e[e.ReadonlyKeyword=133]="ReadonlyKeyword",e[e.RequireKeyword=134]="RequireKeyword",e[e.NumberKeyword=135]="NumberKeyword",e[e.ObjectKeyword=136]="ObjectKeyword",e[e.SetKeyword=137]="SetKeyword",e[e.StringKeyword=138]="StringKeyword",e[e.SymbolKeyword=139]="SymbolKeyword",e[e.TypeKeyword=140]="TypeKeyword",e[e.UndefinedKeyword=141]="UndefinedKeyword",e[e.UniqueKeyword=142]="UniqueKeyword",e[e.UnknownKeyword=143]="UnknownKeyword",e[e.FromKeyword=144]="FromKeyword",e[e.GlobalKeyword=145]="GlobalKeyword",e[e.BigIntKeyword=146]="BigIntKeyword",e[e.OfKeyword=147]="OfKeyword",e[e.QualifiedName=148]="QualifiedName",e[e.ComputedPropertyName=149]="ComputedPropertyName",e[e.TypeParameter=150]="TypeParameter",e[e.Parameter=151]="Parameter",e[e.Decorator=152]="Decorator",e[e.PropertySignature=153]="PropertySignature",e[e.PropertyDeclaration=154]="PropertyDeclaration",e[e.MethodSignature=155]="MethodSignature",e[e.MethodDeclaration=156]="MethodDeclaration",e[e.Constructor=157]="Constructor",e[e.GetAccessor=158]="GetAccessor",e[e.SetAccessor=159]="SetAccessor",e[e.CallSignature=160]="CallSignature",e[e.ConstructSignature=161]="ConstructSignature",e[e.IndexSignature=162]="IndexSignature",e[e.TypePredicate=163]="TypePredicate",e[e.TypeReference=164]="TypeReference",e[e.FunctionType=165]="FunctionType",e[e.ConstructorType=166]="ConstructorType",e[e.TypeQuery=167]="TypeQuery",e[e.TypeLiteral=168]="TypeLiteral",e[e.ArrayType=169]="ArrayType",e[e.TupleType=170]="TupleType",e[e.OptionalType=171]="OptionalType",e[e.RestType=172]="RestType",e[e.UnionType=173]="UnionType",e[e.IntersectionType=174]="IntersectionType",e[e.ConditionalType=175]="ConditionalType",e[e.InferType=176]="InferType",e[e.ParenthesizedType=177]="ParenthesizedType",e[e.ThisType=178]="ThisType",e[e.TypeOperator=179]="TypeOperator",e[e.IndexedAccessType=180]="IndexedAccessType",e[e.MappedType=181]="MappedType",e[e.LiteralType=182]="LiteralType",e[e.ImportType=183]="ImportType",e[e.ObjectBindingPattern=184]="ObjectBindingPattern",e[e.ArrayBindingPattern=185]="ArrayBindingPattern",e[e.BindingElement=186]="BindingElement",e[e.ArrayLiteralExpression=187]="ArrayLiteralExpression",e[e.ObjectLiteralExpression=188]="ObjectLiteralExpression",e[e.PropertyAccessExpression=189]="PropertyAccessExpression",e[e.ElementAccessExpression=190]="ElementAccessExpression",e[e.CallExpression=191]="CallExpression",e[e.NewExpression=192]="NewExpression",e[e.TaggedTemplateExpression=193]="TaggedTemplateExpression",e[e.TypeAssertionExpression=194]="TypeAssertionExpression",e[e.ParenthesizedExpression=195]="ParenthesizedExpression",e[e.FunctionExpression=196]="FunctionExpression",e[e.ArrowFunction=197]="ArrowFunction",e[e.DeleteExpression=198]="DeleteExpression",e[e.TypeOfExpression=199]="TypeOfExpression",e[e.VoidExpression=200]="VoidExpression",e[e.AwaitExpression=201]="AwaitExpression",e[e.PrefixUnaryExpression=202]="PrefixUnaryExpression",e[e.PostfixUnaryExpression=203]="PostfixUnaryExpression",e[e.BinaryExpression=204]="BinaryExpression",e[e.ConditionalExpression=205]="ConditionalExpression",e[e.TemplateExpression=206]="TemplateExpression",e[e.YieldExpression=207]="YieldExpression",e[e.SpreadElement=208]="SpreadElement",e[e.ClassExpression=209]="ClassExpression",e[e.OmittedExpression=210]="OmittedExpression",e[e.ExpressionWithTypeArguments=211]="ExpressionWithTypeArguments",e[e.AsExpression=212]="AsExpression",e[e.NonNullExpression=213]="NonNullExpression",e[e.MetaProperty=214]="MetaProperty",e[e.SyntheticExpression=215]="SyntheticExpression",e[e.TemplateSpan=216]="TemplateSpan",e[e.SemicolonClassElement=217]="SemicolonClassElement",e[e.Block=218]="Block",e[e.VariableStatement=219]="VariableStatement",e[e.EmptyStatement=220]="EmptyStatement",e[e.ExpressionStatement=221]="ExpressionStatement",e[e.IfStatement=222]="IfStatement",e[e.DoStatement=223]="DoStatement",e[e.WhileStatement=224]="WhileStatement",e[e.ForStatement=225]="ForStatement",e[e.ForInStatement=226]="ForInStatement",e[e.ForOfStatement=227]="ForOfStatement",e[e.ContinueStatement=228]="ContinueStatement",e[e.BreakStatement=229]="BreakStatement",e[e.ReturnStatement=230]="ReturnStatement",e[e.WithStatement=231]="WithStatement",e[e.SwitchStatement=232]="SwitchStatement",e[e.LabeledStatement=233]="LabeledStatement",e[e.ThrowStatement=234]="ThrowStatement",e[e.TryStatement=235]="TryStatement",e[e.DebuggerStatement=236]="DebuggerStatement",e[e.VariableDeclaration=237]="VariableDeclaration",e[e.VariableDeclarationList=238]="VariableDeclarationList",e[e.FunctionDeclaration=239]="FunctionDeclaration",e[e.ClassDeclaration=240]="ClassDeclaration",e[e.InterfaceDeclaration=241]="InterfaceDeclaration",e[e.TypeAliasDeclaration=242]="TypeAliasDeclaration",e[e.EnumDeclaration=243]="EnumDeclaration",e[e.ModuleDeclaration=244]="ModuleDeclaration",e[e.ModuleBlock=245]="ModuleBlock",e[e.CaseBlock=246]="CaseBlock",e[e.NamespaceExportDeclaration=247]="NamespaceExportDeclaration",e[e.ImportEqualsDeclaration=248]="ImportEqualsDeclaration",e[e.ImportDeclaration=249]="ImportDeclaration",e[e.ImportClause=250]="ImportClause",e[e.NamespaceImport=251]="NamespaceImport",e[e.NamedImports=252]="NamedImports",e[e.ImportSpecifier=253]="ImportSpecifier",e[e.ExportAssignment=254]="ExportAssignment",e[e.ExportDeclaration=255]="ExportDeclaration",e[e.NamedExports=256]="NamedExports",e[e.ExportSpecifier=257]="ExportSpecifier",e[e.MissingDeclaration=258]="MissingDeclaration",e[e.ExternalModuleReference=259]="ExternalModuleReference",e[e.JsxElement=260]="JsxElement",e[e.JsxSelfClosingElement=261]="JsxSelfClosingElement",e[e.JsxOpeningElement=262]="JsxOpeningElement",e[e.JsxClosingElement=263]="JsxClosingElement",e[e.JsxFragment=264]="JsxFragment",e[e.JsxOpeningFragment=265]="JsxOpeningFragment",e[e.JsxClosingFragment=266]="JsxClosingFragment",e[e.JsxAttribute=267]="JsxAttribute",e[e.JsxAttributes=268]="JsxAttributes",e[e.JsxSpreadAttribute=269]="JsxSpreadAttribute",e[e.JsxExpression=270]="JsxExpression",e[e.CaseClause=271]="CaseClause",e[e.DefaultClause=272]="DefaultClause",e[e.HeritageClause=273]="HeritageClause",e[e.CatchClause=274]="CatchClause",e[e.PropertyAssignment=275]="PropertyAssignment",e[e.ShorthandPropertyAssignment=276]="ShorthandPropertyAssignment",e[e.SpreadAssignment=277]="SpreadAssignment",e[e.EnumMember=278]="EnumMember",e[e.SourceFile=279]="SourceFile",e[e.Bundle=280]="Bundle",e[e.UnparsedSource=281]="UnparsedSource",e[e.InputFiles=282]="InputFiles",e[e.JSDocTypeExpression=283]="JSDocTypeExpression",e[e.JSDocAllType=284]="JSDocAllType",e[e.JSDocUnknownType=285]="JSDocUnknownType",e[e.JSDocNullableType=286]="JSDocNullableType",e[e.JSDocNonNullableType=287]="JSDocNonNullableType",e[e.JSDocOptionalType=288]="JSDocOptionalType",e[e.JSDocFunctionType=289]="JSDocFunctionType",e[e.JSDocVariadicType=290]="JSDocVariadicType",e[e.JSDocComment=291]="JSDocComment",e[e.JSDocTypeLiteral=292]="JSDocTypeLiteral",e[e.JSDocSignature=293]="JSDocSignature",e[e.JSDocTag=294]="JSDocTag",e[e.JSDocAugmentsTag=295]="JSDocAugmentsTag",e[e.JSDocClassTag=296]="JSDocClassTag",e[e.JSDocCallbackTag=297]="JSDocCallbackTag",e[e.JSDocEnumTag=298]="JSDocEnumTag",e[e.JSDocParameterTag=299]="JSDocParameterTag",e[e.JSDocReturnTag=300]="JSDocReturnTag",e[e.JSDocThisTag=301]="JSDocThisTag",e[e.JSDocTypeTag=302]="JSDocTypeTag",e[e.JSDocTemplateTag=303]="JSDocTemplateTag",e[e.JSDocTypedefTag=304]="JSDocTypedefTag",e[e.JSDocPropertyTag=305]="JSDocPropertyTag",e[e.SyntaxList=306]="SyntaxList",e[e.NotEmittedStatement=307]="NotEmittedStatement",e[e.PartiallyEmittedExpression=308]="PartiallyEmittedExpression",e[e.CommaListExpression=309]="CommaListExpression",e[e.MergeDeclarationMarker=310]="MergeDeclarationMarker",e[e.EndOfDeclarationMarker=311]="EndOfDeclarationMarker",e[e.Count=312]="Count",e[e.FirstAssignment=59]="FirstAssignment",e[e.LastAssignment=71]="LastAssignment",e[e.FirstCompoundAssignment=60]="FirstCompoundAssignment",e[e.LastCompoundAssignment=71]="LastCompoundAssignment",e[e.FirstReservedWord=73]="FirstReservedWord",e[e.LastReservedWord=108]="LastReservedWord",e[e.FirstKeyword=73]="FirstKeyword",e[e.LastKeyword=147]="LastKeyword",e[e.FirstFutureReservedWord=109]="FirstFutureReservedWord",e[e.LastFutureReservedWord=117]="LastFutureReservedWord",e[e.FirstTypeNode=163]="FirstTypeNode",e[e.LastTypeNode=183]="LastTypeNode",e[e.FirstPunctuation=18]="FirstPunctuation",e[e.LastPunctuation=71]="LastPunctuation",e[e.FirstToken=0]="FirstToken",e[e.LastToken=147]="LastToken",e[e.FirstTriviaToken=2]="FirstTriviaToken",e[e.LastTriviaToken=7]="LastTriviaToken",e[e.FirstLiteralToken=8]="FirstLiteralToken",e[e.LastLiteralToken=14]="LastLiteralToken",e[e.FirstTemplateToken=14]="FirstTemplateToken",e[e.LastTemplateToken=17]="LastTemplateToken",e[e.FirstBinaryOperator=28]="FirstBinaryOperator",e[e.LastBinaryOperator=71]="LastBinaryOperator",e[e.FirstNode=148]="FirstNode",e[e.FirstJSDocNode=283]="FirstJSDocNode",e[e.LastJSDocNode=305]="LastJSDocNode",e[e.FirstJSDocTagNode=294]="FirstJSDocTagNode",e[e.LastJSDocTagNode=305]="LastJSDocTagNode",e[e.FirstContextualKeyword=118]="FirstContextualKeyword",e[e.LastContextualKeyword=147]="LastContextualKeyword"}(e.SyntaxKind||(e.SyntaxKind={})),function(e){e[e.None=0]="None",e[e.Let=1]="Let",e[e.Const=2]="Const",e[e.NestedNamespace=4]="NestedNamespace",e[e.Synthesized=8]="Synthesized",e[e.Namespace=16]="Namespace",e[e.ExportContext=32]="ExportContext",e[e.ContainsThis=64]="ContainsThis",e[e.HasImplicitReturn=128]="HasImplicitReturn",e[e.HasExplicitReturn=256]="HasExplicitReturn",e[e.GlobalAugmentation=512]="GlobalAugmentation",e[e.HasAsyncFunctions=1024]="HasAsyncFunctions",e[e.DisallowInContext=2048]="DisallowInContext",e[e.YieldContext=4096]="YieldContext",e[e.DecoratorContext=8192]="DecoratorContext",e[e.AwaitContext=16384]="AwaitContext",e[e.ThisNodeHasError=32768]="ThisNodeHasError",e[e.JavaScriptFile=65536]="JavaScriptFile",e[e.ThisNodeOrAnySubNodesHasError=131072]="ThisNodeOrAnySubNodesHasError",e[e.HasAggregatedChildData=262144]="HasAggregatedChildData",e[e.PossiblyContainsDynamicImport=524288]="PossiblyContainsDynamicImport",e[e.PossiblyContainsImportMeta=1048576]="PossiblyContainsImportMeta",e[e.JSDoc=2097152]="JSDoc",e[e.Ambient=4194304]="Ambient",e[e.InWithStatement=8388608]="InWithStatement",e[e.JsonFile=16777216]="JsonFile",e[e.BlockScoped=3]="BlockScoped",e[e.ReachabilityCheckFlags=384]="ReachabilityCheckFlags",e[e.ReachabilityAndEmitFlags=1408]="ReachabilityAndEmitFlags",e[e.ContextFlags=12679168]="ContextFlags",e[e.TypeExcludesFlags=20480]="TypeExcludesFlags",e[e.PermanentlySetIncrementalFlags=1572864]="PermanentlySetIncrementalFlags"}(e.NodeFlags||(e.NodeFlags={})),function(e){e[e.None=0]="None",e[e.Export=1]="Export",e[e.Ambient=2]="Ambient",e[e.Public=4]="Public",e[e.Private=8]="Private",e[e.Protected=16]="Protected",e[e.Static=32]="Static",e[e.Readonly=64]="Readonly",e[e.Abstract=128]="Abstract",e[e.Async=256]="Async",e[e.Default=512]="Default",e[e.Const=2048]="Const",e[e.HasComputedFlags=536870912]="HasComputedFlags",e[e.AccessibilityModifier=28]="AccessibilityModifier",e[e.ParameterPropertyModifier=92]="ParameterPropertyModifier",e[e.NonPublicAccessibilityModifier=24]="NonPublicAccessibilityModifier",e[e.TypeScriptModifier=2270]="TypeScriptModifier",e[e.ExportDefault=513]="ExportDefault",e[e.All=3071]="All"}(e.ModifierFlags||(e.ModifierFlags={})),function(e){e[e.None=0]="None",e[e.IntrinsicNamedElement=1]="IntrinsicNamedElement",e[e.IntrinsicIndexedElement=2]="IntrinsicIndexedElement",e[e.IntrinsicElement=3]="IntrinsicElement"}(e.JsxFlags||(e.JsxFlags={})),function(e){e[e.Succeeded=1]="Succeeded",e[e.Failed=2]="Failed",e[e.FailedAndReported=3]="FailedAndReported"}(e.RelationComparisonResult||(e.RelationComparisonResult={})),function(e){e[e.None=0]="None",e[e.Auto=1]="Auto",e[e.Loop=2]="Loop",e[e.Unique=3]="Unique",e[e.Node=4]="Node",e[e.KindMask=7]="KindMask",e[e.ReservedInNestedScopes=8]="ReservedInNestedScopes",e[e.Optimistic=16]="Optimistic",e[e.FileLevel=32]="FileLevel"}(e.GeneratedIdentifierFlags||(e.GeneratedIdentifierFlags={})),function(e){e[e.None=0]="None",e[e.PrecedingLineBreak=1]="PrecedingLineBreak",e[e.PrecedingJSDocComment=2]="PrecedingJSDocComment",e[e.Unterminated=4]="Unterminated",e[e.ExtendedUnicodeEscape=8]="ExtendedUnicodeEscape",e[e.Scientific=16]="Scientific",e[e.Octal=32]="Octal",e[e.HexSpecifier=64]="HexSpecifier",e[e.BinarySpecifier=128]="BinarySpecifier",e[e.OctalSpecifier=256]="OctalSpecifier",e[e.ContainsSeparator=512]="ContainsSeparator",e[e.BinaryOrOctalSpecifier=384]="BinaryOrOctalSpecifier",e[e.NumericLiteralFlags=1008]="NumericLiteralFlags"}(e.TokenFlags||(e.TokenFlags={})),function(e){e[e.Unreachable=1]="Unreachable",e[e.Start=2]="Start",e[e.BranchLabel=4]="BranchLabel",e[e.LoopLabel=8]="LoopLabel",e[e.Assignment=16]="Assignment",e[e.TrueCondition=32]="TrueCondition",e[e.FalseCondition=64]="FalseCondition",e[e.SwitchClause=128]="SwitchClause",e[e.ArrayMutation=256]="ArrayMutation",e[e.Referenced=512]="Referenced",e[e.Shared=1024]="Shared",e[e.PreFinally=2048]="PreFinally",e[e.AfterFinally=4096]="AfterFinally",e[e.Label=12]="Label",e[e.Condition=96]="Condition"}(e.FlowFlags||(e.FlowFlags={}));var t,r=function(){return function(){}}();e.OperationCanceledException=r,function(e){e[e.Not=0]="Not",e[e.SafeModules=1]="SafeModules",e[e.Completely=2]="Completely"}(e.StructureIsReused||(e.StructureIsReused={})),function(e){e[e.Success=0]="Success",e[e.DiagnosticsPresent_OutputsSkipped=1]="DiagnosticsPresent_OutputsSkipped",e[e.DiagnosticsPresent_OutputsGenerated=2]="DiagnosticsPresent_OutputsGenerated"}(e.ExitStatus||(e.ExitStatus={})),function(e){e[e.None=0]="None",e[e.Literal=1]="Literal",e[e.Subtype=2]="Subtype"}(e.UnionReduction||(e.UnionReduction={})),function(e){e[e.None=0]="None",e[e.NoTruncation=1]="NoTruncation",e[e.WriteArrayAsGenericType=2]="WriteArrayAsGenericType",e[e.GenerateNamesForShadowedTypeParams=4]="GenerateNamesForShadowedTypeParams",e[e.UseStructuralFallback=8]="UseStructuralFallback",e[e.ForbidIndexedAccessSymbolReferences=16]="ForbidIndexedAccessSymbolReferences",e[e.WriteTypeArgumentsOfSignature=32]="WriteTypeArgumentsOfSignature",e[e.UseFullyQualifiedType=64]="UseFullyQualifiedType",e[e.UseOnlyExternalAliasing=128]="UseOnlyExternalAliasing",e[e.SuppressAnyReturnType=256]="SuppressAnyReturnType",e[e.WriteTypeParametersInQualifiedName=512]="WriteTypeParametersInQualifiedName",e[e.MultilineObjectLiterals=1024]="MultilineObjectLiterals",e[e.WriteClassExpressionAsTypeLiteral=2048]="WriteClassExpressionAsTypeLiteral",e[e.UseTypeOfFunction=4096]="UseTypeOfFunction",e[e.OmitParameterModifiers=8192]="OmitParameterModifiers",e[e.UseAliasDefinedOutsideCurrentScope=16384]="UseAliasDefinedOutsideCurrentScope",e[e.AllowThisInObjectLiteral=32768]="AllowThisInObjectLiteral",e[e.AllowQualifedNameInPlaceOfIdentifier=65536]="AllowQualifedNameInPlaceOfIdentifier",e[e.AllowAnonymousIdentifier=131072]="AllowAnonymousIdentifier",e[e.AllowEmptyUnionOrIntersection=262144]="AllowEmptyUnionOrIntersection",e[e.AllowEmptyTuple=524288]="AllowEmptyTuple",e[e.AllowUniqueESSymbolType=1048576]="AllowUniqueESSymbolType",e[e.AllowEmptyIndexInfoType=2097152]="AllowEmptyIndexInfoType",e[e.AllowNodeModulesRelativePaths=67108864]="AllowNodeModulesRelativePaths",e[e.DoNotIncludeSymbolChain=134217728]="DoNotIncludeSymbolChain",e[e.IgnoreErrors=70221824]="IgnoreErrors",e[e.InObjectTypeLiteral=4194304]="InObjectTypeLiteral",e[e.InTypeAlias=8388608]="InTypeAlias",e[e.InInitialEntityName=16777216]="InInitialEntityName",e[e.InReverseMappedType=33554432]="InReverseMappedType"}(e.NodeBuilderFlags||(e.NodeBuilderFlags={})),function(e){e[e.None=0]="None",e[e.NoTruncation=1]="NoTruncation",e[e.WriteArrayAsGenericType=2]="WriteArrayAsGenericType",e[e.UseStructuralFallback=8]="UseStructuralFallback",e[e.WriteTypeArgumentsOfSignature=32]="WriteTypeArgumentsOfSignature",e[e.UseFullyQualifiedType=64]="UseFullyQualifiedType",e[e.SuppressAnyReturnType=256]="SuppressAnyReturnType",e[e.MultilineObjectLiterals=1024]="MultilineObjectLiterals",e[e.WriteClassExpressionAsTypeLiteral=2048]="WriteClassExpressionAsTypeLiteral",e[e.UseTypeOfFunction=4096]="UseTypeOfFunction",e[e.OmitParameterModifiers=8192]="OmitParameterModifiers",e[e.UseAliasDefinedOutsideCurrentScope=16384]="UseAliasDefinedOutsideCurrentScope",e[e.AllowUniqueESSymbolType=1048576]="AllowUniqueESSymbolType",e[e.AddUndefined=131072]="AddUndefined",e[e.WriteArrowStyleSignature=262144]="WriteArrowStyleSignature",e[e.InArrayType=524288]="InArrayType",e[e.InElementType=2097152]="InElementType",e[e.InFirstTypeArgument=4194304]="InFirstTypeArgument",e[e.InTypeAlias=8388608]="InTypeAlias",e[e.WriteOwnNameForAnyLike=0]="WriteOwnNameForAnyLike",e[e.NodeBuilderFlagsMask=9469291]="NodeBuilderFlagsMask"}(e.TypeFormatFlags||(e.TypeFormatFlags={})),function(e){e[e.None=0]="None",e[e.WriteTypeParametersOrArguments=1]="WriteTypeParametersOrArguments",e[e.UseOnlyExternalAliasing=2]="UseOnlyExternalAliasing",e[e.AllowAnyNodeKind=4]="AllowAnyNodeKind",e[e.UseAliasDefinedOutsideCurrentScope=8]="UseAliasDefinedOutsideCurrentScope",e[e.DoNotIncludeSymbolChain=16]="DoNotIncludeSymbolChain"}(e.SymbolFormatFlags||(e.SymbolFormatFlags={})),function(e){e[e.Accessible=0]="Accessible",e[e.NotAccessible=1]="NotAccessible",e[e.CannotBeNamed=2]="CannotBeNamed"}(e.SymbolAccessibility||(e.SymbolAccessibility={})),function(e){e[e.UnionOrIntersection=0]="UnionOrIntersection",e[e.Spread=1]="Spread"}(e.SyntheticSymbolKind||(e.SyntheticSymbolKind={})),function(e){e[e.This=0]="This",e[e.Identifier=1]="Identifier"}(e.TypePredicateKind||(e.TypePredicateKind={})),function(e){e[e.Unknown=0]="Unknown",e[e.TypeWithConstructSignatureAndValue=1]="TypeWithConstructSignatureAndValue",e[e.VoidNullableOrNeverType=2]="VoidNullableOrNeverType",e[e.NumberLikeType=3]="NumberLikeType",e[e.BigIntLikeType=4]="BigIntLikeType",e[e.StringLikeType=5]="StringLikeType",e[e.BooleanType=6]="BooleanType",e[e.ArrayLikeType=7]="ArrayLikeType",e[e.ESSymbolType=8]="ESSymbolType",e[e.Promise=9]="Promise",e[e.TypeWithCallSignature=10]="TypeWithCallSignature",e[e.ObjectType=11]="ObjectType"}(e.TypeReferenceSerializationKind||(e.TypeReferenceSerializationKind={})),function(e){e[e.None=0]="None",e[e.FunctionScopedVariable=1]="FunctionScopedVariable",e[e.BlockScopedVariable=2]="BlockScopedVariable",e[e.Property=4]="Property",e[e.EnumMember=8]="EnumMember",e[e.Function=16]="Function",e[e.Class=32]="Class",e[e.Interface=64]="Interface",e[e.ConstEnum=128]="ConstEnum",e[e.RegularEnum=256]="RegularEnum",e[e.ValueModule=512]="ValueModule",e[e.NamespaceModule=1024]="NamespaceModule",e[e.TypeLiteral=2048]="TypeLiteral",e[e.ObjectLiteral=4096]="ObjectLiteral",e[e.Method=8192]="Method",e[e.Constructor=16384]="Constructor",e[e.GetAccessor=32768]="GetAccessor",e[e.SetAccessor=65536]="SetAccessor",e[e.Signature=131072]="Signature",e[e.TypeParameter=262144]="TypeParameter",e[e.TypeAlias=524288]="TypeAlias",e[e.ExportValue=1048576]="ExportValue",e[e.Alias=2097152]="Alias",e[e.Prototype=4194304]="Prototype",e[e.ExportStar=8388608]="ExportStar",e[e.Optional=16777216]="Optional",e[e.Transient=33554432]="Transient",e[e.Assignment=67108864]="Assignment",e[e.ModuleExports=134217728]="ModuleExports",e[e.All=67108863]="All",e[e.Enum=384]="Enum",e[e.Variable=3]="Variable",e[e.Value=67220415]="Value",e[e.Type=67897832]="Type",e[e.Namespace=1920]="Namespace",e[e.Module=1536]="Module",e[e.Accessor=98304]="Accessor",e[e.FunctionScopedVariableExcludes=67220414]="FunctionScopedVariableExcludes",e[e.BlockScopedVariableExcludes=67220415]="BlockScopedVariableExcludes",e[e.ParameterExcludes=67220415]="ParameterExcludes",e[e.PropertyExcludes=0]="PropertyExcludes",e[e.EnumMemberExcludes=68008959]="EnumMemberExcludes",e[e.FunctionExcludes=67219887]="FunctionExcludes",e[e.ClassExcludes=68008383]="ClassExcludes",e[e.InterfaceExcludes=67897736]="InterfaceExcludes",e[e.RegularEnumExcludes=68008191]="RegularEnumExcludes",e[e.ConstEnumExcludes=68008831]="ConstEnumExcludes",e[e.ValueModuleExcludes=110735]="ValueModuleExcludes",e[e.NamespaceModuleExcludes=0]="NamespaceModuleExcludes",e[e.MethodExcludes=67212223]="MethodExcludes",e[e.GetAccessorExcludes=67154879]="GetAccessorExcludes",e[e.SetAccessorExcludes=67187647]="SetAccessorExcludes",e[e.TypeParameterExcludes=67635688]="TypeParameterExcludes",e[e.TypeAliasExcludes=67897832]="TypeAliasExcludes",e[e.AliasExcludes=2097152]="AliasExcludes",e[e.ModuleMember=2623475]="ModuleMember",e[e.ExportHasLocal=944]="ExportHasLocal",e[e.BlockScoped=418]="BlockScoped",e[e.PropertyOrAccessor=98308]="PropertyOrAccessor",e[e.ClassMember=106500]="ClassMember",e[e.Classifiable=2885600]="Classifiable",e[e.LateBindingContainer=6240]="LateBindingContainer"}(e.SymbolFlags||(e.SymbolFlags={})),function(e){e[e.Numeric=0]="Numeric",e[e.Literal=1]="Literal"}(e.EnumKind||(e.EnumKind={})),function(e){e[e.Instantiated=1]="Instantiated",e[e.SyntheticProperty=2]="SyntheticProperty",e[e.SyntheticMethod=4]="SyntheticMethod",e[e.Readonly=8]="Readonly",e[e.Partial=16]="Partial",e[e.HasNonUniformType=32]="HasNonUniformType",e[e.ContainsPublic=64]="ContainsPublic",e[e.ContainsProtected=128]="ContainsProtected",e[e.ContainsPrivate=256]="ContainsPrivate",e[e.ContainsStatic=512]="ContainsStatic",e[e.Late=1024]="Late",e[e.ReverseMapped=2048]="ReverseMapped",e[e.OptionalParameter=4096]="OptionalParameter",e[e.RestParameter=8192]="RestParameter",e[e.Synthetic=6]="Synthetic"}(e.CheckFlags||(e.CheckFlags={})),function(e){e.Call="__call",e.Constructor="__constructor",e.New="__new",e.Index="__index",e.ExportStar="__export",e.Global="__global",e.Missing="__missing",e.Type="__type",e.Object="__object",e.JSXAttributes="__jsxAttributes",e.Class="__class",e.Function="__function",e.Computed="__computed",e.Resolving="__resolving__",e.ExportEquals="export=",e.Default="default",e.This="this"}(e.InternalSymbolName||(e.InternalSymbolName={})),function(e){e[e.TypeChecked=1]="TypeChecked",e[e.LexicalThis=2]="LexicalThis",e[e.CaptureThis=4]="CaptureThis",e[e.CaptureNewTarget=8]="CaptureNewTarget",e[e.SuperInstance=256]="SuperInstance",e[e.SuperStatic=512]="SuperStatic",e[e.ContextChecked=1024]="ContextChecked",e[e.AsyncMethodWithSuper=2048]="AsyncMethodWithSuper",e[e.AsyncMethodWithSuperBinding=4096]="AsyncMethodWithSuperBinding",e[e.CaptureArguments=8192]="CaptureArguments",e[e.EnumValuesComputed=16384]="EnumValuesComputed",e[e.LexicalModuleMergesWithClass=32768]="LexicalModuleMergesWithClass",e[e.LoopWithCapturedBlockScopedBinding=65536]="LoopWithCapturedBlockScopedBinding",e[e.ContainsCapturedBlockScopeBinding=131072]="ContainsCapturedBlockScopeBinding",e[e.CapturedBlockScopedBinding=262144]="CapturedBlockScopedBinding",e[e.BlockScopedBindingInLoop=524288]="BlockScopedBindingInLoop",e[e.ClassWithBodyScopedClassBinding=1048576]="ClassWithBodyScopedClassBinding",e[e.BodyScopedClassBinding=2097152]="BodyScopedClassBinding",e[e.NeedsLoopOutParameter=4194304]="NeedsLoopOutParameter",e[e.AssignmentsMarked=8388608]="AssignmentsMarked",e[e.ClassWithConstructorReference=16777216]="ClassWithConstructorReference",e[e.ConstructorReferenceInClass=33554432]="ConstructorReferenceInClass"}(e.NodeCheckFlags||(e.NodeCheckFlags={})),function(e){e[e.Any=1]="Any",e[e.Unknown=2]="Unknown",e[e.String=4]="String",e[e.Number=8]="Number",e[e.Boolean=16]="Boolean",e[e.Enum=32]="Enum",e[e.BigInt=64]="BigInt",e[e.StringLiteral=128]="StringLiteral",e[e.NumberLiteral=256]="NumberLiteral",e[e.BooleanLiteral=512]="BooleanLiteral",e[e.EnumLiteral=1024]="EnumLiteral",e[e.BigIntLiteral=2048]="BigIntLiteral",e[e.ESSymbol=4096]="ESSymbol",e[e.UniqueESSymbol=8192]="UniqueESSymbol",e[e.Void=16384]="Void",e[e.Undefined=32768]="Undefined",e[e.Null=65536]="Null",e[e.Never=131072]="Never",e[e.TypeParameter=262144]="TypeParameter",e[e.Object=524288]="Object",e[e.Union=1048576]="Union",e[e.Intersection=2097152]="Intersection",e[e.Index=4194304]="Index",e[e.IndexedAccess=8388608]="IndexedAccess",e[e.Conditional=16777216]="Conditional",e[e.Substitution=33554432]="Substitution",e[e.NonPrimitive=67108864]="NonPrimitive",e[e.ContainsWideningType=134217728]="ContainsWideningType",e[e.ContainsObjectLiteral=268435456]="ContainsObjectLiteral",e[e.ContainsAnyFunctionType=536870912]="ContainsAnyFunctionType",e[e.AnyOrUnknown=3]="AnyOrUnknown",e[e.Nullable=98304]="Nullable",e[e.Literal=2944]="Literal",e[e.Unit=109440]="Unit",e[e.StringOrNumberLiteral=384]="StringOrNumberLiteral",e[e.StringOrNumberLiteralOrUnique=8576]="StringOrNumberLiteralOrUnique",e[e.DefinitelyFalsy=117632]="DefinitelyFalsy",e[e.PossiblyFalsy=117724]="PossiblyFalsy",e[e.Intrinsic=67359327]="Intrinsic",e[e.Primitive=131068]="Primitive",e[e.StringLike=132]="StringLike",e[e.NumberLike=296]="NumberLike",e[e.BigIntLike=2112]="BigIntLike",e[e.BooleanLike=528]="BooleanLike",e[e.EnumLike=1056]="EnumLike",e[e.ESSymbolLike=12288]="ESSymbolLike",e[e.VoidLike=49152]="VoidLike",e[e.DisjointDomains=67238908]="DisjointDomains",e[e.UnionOrIntersection=3145728]="UnionOrIntersection",e[e.StructuredType=3670016]="StructuredType",e[e.TypeVariable=8650752]="TypeVariable",e[e.InstantiableNonPrimitive=58982400]="InstantiableNonPrimitive",e[e.InstantiablePrimitive=4194304]="InstantiablePrimitive",e[e.Instantiable=63176704]="Instantiable",e[e.StructuredOrInstantiable=66846720]="StructuredOrInstantiable",e[e.Narrowable=133970943]="Narrowable",e[e.NotUnionOrUnit=67637251]="NotUnionOrUnit",e[e.NotPrimitiveUnion=66994211]="NotPrimitiveUnion",e[e.RequiresWidening=402653184]="RequiresWidening",e[e.PropagatingFlags=939524096]="PropagatingFlags",e[e.NonWideningType=134217728]="NonWideningType",e[e.Wildcard=268435456]="Wildcard",e[e.EmptyObject=536870912]="EmptyObject",e[e.ConstructionFlags=939524096]="ConstructionFlags",e[e.GenericMappedType=134217728]="GenericMappedType"}(e.TypeFlags||(e.TypeFlags={})),function(e){e[e.Class=1]="Class",e[e.Interface=2]="Interface",e[e.Reference=4]="Reference",e[e.Tuple=8]="Tuple",e[e.Anonymous=16]="Anonymous",e[e.Mapped=32]="Mapped",e[e.Instantiated=64]="Instantiated",e[e.ObjectLiteral=128]="ObjectLiteral",e[e.EvolvingArray=256]="EvolvingArray",e[e.ObjectLiteralPatternWithComputedProperties=512]="ObjectLiteralPatternWithComputedProperties",e[e.ContainsSpread=1024]="ContainsSpread",e[e.ReverseMapped=2048]="ReverseMapped",e[e.JsxAttributes=4096]="JsxAttributes",e[e.MarkerType=8192]="MarkerType",e[e.JSLiteral=16384]="JSLiteral",e[e.FreshLiteral=32768]="FreshLiteral",e[e.ClassOrInterface=3]="ClassOrInterface"}(e.ObjectFlags||(e.ObjectFlags={})),function(e){e[e.Invariant=0]="Invariant",e[e.Covariant=1]="Covariant",e[e.Contravariant=2]="Contravariant",e[e.Bivariant=3]="Bivariant",e[e.Independent=4]="Independent"}(e.Variance||(e.Variance={})),function(e){e[e.Component=0]="Component",e[e.Function=1]="Function",e[e.Mixed=2]="Mixed"}(e.JsxReferenceKind||(e.JsxReferenceKind={})),function(e){e[e.Call=0]="Call",e[e.Construct=1]="Construct"}(e.SignatureKind||(e.SignatureKind={})),function(e){e[e.String=0]="String",e[e.Number=1]="Number"}(e.IndexKind||(e.IndexKind={})),function(e){e[e.NakedTypeVariable=1]="NakedTypeVariable",e[e.HomomorphicMappedType=2]="HomomorphicMappedType",e[e.MappedTypeConstraint=4]="MappedTypeConstraint",e[e.ReturnType=8]="ReturnType",e[e.LiteralKeyof=16]="LiteralKeyof",e[e.NoConstraints=32]="NoConstraints",e[e.AlwaysStrict=64]="AlwaysStrict",e[e.PriorityImpliesCombination=28]="PriorityImpliesCombination"}(e.InferencePriority||(e.InferencePriority={})),function(e){e[e.None=0]="None",e[e.NoDefault=1]="NoDefault",e[e.AnyDefault=2]="AnyDefault"}(e.InferenceFlags||(e.InferenceFlags={})),function(e){e[e.False=0]="False",e[e.Maybe=1]="Maybe",e[e.True=-1]="True"}(e.Ternary||(e.Ternary={})),function(e){e[e.None=0]="None",e[e.ExportsProperty=1]="ExportsProperty",e[e.ModuleExports=2]="ModuleExports",e[e.PrototypeProperty=3]="PrototypeProperty",e[e.ThisProperty=4]="ThisProperty",e[e.Property=5]="Property",e[e.Prototype=6]="Prototype",e[e.ObjectDefinePropertyValue=7]="ObjectDefinePropertyValue",e[e.ObjectDefinePropertyExports=8]="ObjectDefinePropertyExports",e[e.ObjectDefinePrototypeProperty=9]="ObjectDefinePrototypeProperty"}(e.AssignmentDeclarationKind||(e.AssignmentDeclarationKind={})),function(e){e[e.Warning=0]="Warning",e[e.Error=1]="Error",e[e.Suggestion=2]="Suggestion",e[e.Message=3]="Message"}(t=e.DiagnosticCategory||(e.DiagnosticCategory={})),e.diagnosticCategoryName=function(e,r){void 0===r&&(r=!0);var n=t[e.category];return r?n.toLowerCase():n},function(e){e[e.Classic=1]="Classic",e[e.NodeJs=2]="NodeJs"}(e.ModuleResolutionKind||(e.ModuleResolutionKind={})),function(e){e[e.None=0]="None",e[e.CommonJS=1]="CommonJS",e[e.AMD=2]="AMD",e[e.UMD=3]="UMD",e[e.System=4]="System",e[e.ES2015=5]="ES2015",e[e.ESNext=6]="ESNext"}(e.ModuleKind||(e.ModuleKind={})),function(e){e[e.None=0]="None",e[e.Preserve=1]="Preserve",e[e.React=2]="React",e[e.ReactNative=3]="ReactNative"}(e.JsxEmit||(e.JsxEmit={})),function(e){e[e.CarriageReturnLineFeed=0]="CarriageReturnLineFeed",e[e.LineFeed=1]="LineFeed"}(e.NewLineKind||(e.NewLineKind={})),function(e){e[e.Unknown=0]="Unknown",e[e.JS=1]="JS",e[e.JSX=2]="JSX",e[e.TS=3]="TS",e[e.TSX=4]="TSX",e[e.External=5]="External",e[e.JSON=6]="JSON",e[e.Deferred=7]="Deferred"}(e.ScriptKind||(e.ScriptKind={})),function(e){e[e.ES3=0]="ES3",e[e.ES5=1]="ES5",e[e.ES2015=2]="ES2015",e[e.ES2016=3]="ES2016",e[e.ES2017=4]="ES2017",e[e.ES2018=5]="ES2018",e[e.ESNext=6]="ESNext",e[e.JSON=100]="JSON",e[e.Latest=6]="Latest"}(e.ScriptTarget||(e.ScriptTarget={})),function(e){e[e.Standard=0]="Standard",e[e.JSX=1]="JSX"}(e.LanguageVariant||(e.LanguageVariant={})),function(e){e[e.None=0]="None",e[e.Recursive=1]="Recursive"}(e.WatchDirectoryFlags||(e.WatchDirectoryFlags={})),function(e){e[e.nullCharacter=0]="nullCharacter",e[e.maxAsciiCharacter=127]="maxAsciiCharacter",e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.lineSeparator=8232]="lineSeparator",e[e.paragraphSeparator=8233]="paragraphSeparator",e[e.nextLine=133]="nextLine",e[e.space=32]="space",e[e.nonBreakingSpace=160]="nonBreakingSpace",e[e.enQuad=8192]="enQuad",e[e.emQuad=8193]="emQuad",e[e.enSpace=8194]="enSpace",e[e.emSpace=8195]="emSpace",e[e.threePerEmSpace=8196]="threePerEmSpace",e[e.fourPerEmSpace=8197]="fourPerEmSpace",e[e.sixPerEmSpace=8198]="sixPerEmSpace",e[e.figureSpace=8199]="figureSpace",e[e.punctuationSpace=8200]="punctuationSpace",e[e.thinSpace=8201]="thinSpace",e[e.hairSpace=8202]="hairSpace",e[e.zeroWidthSpace=8203]="zeroWidthSpace",e[e.narrowNoBreakSpace=8239]="narrowNoBreakSpace",e[e.ideographicSpace=12288]="ideographicSpace",e[e.mathematicalSpace=8287]="mathematicalSpace",e[e.ogham=5760]="ogham",e[e._=95]="_",e[e.$=36]="$",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.ampersand=38]="ampersand",e[e.asterisk=42]="asterisk",e[e.at=64]="at",e[e.backslash=92]="backslash",e[e.backtick=96]="backtick",e[e.bar=124]="bar",e[e.caret=94]="caret",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.closeParen=41]="closeParen",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.equals=61]="equals",e[e.exclamation=33]="exclamation",e[e.greaterThan=62]="greaterThan",e[e.hash=35]="hash",e[e.lessThan=60]="lessThan",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.openParen=40]="openParen",e[e.percent=37]="percent",e[e.plus=43]="plus",e[e.question=63]="question",e[e.semicolon=59]="semicolon",e[e.singleQuote=39]="singleQuote",e[e.slash=47]="slash",e[e.tilde=126]="tilde",e[e.backspace=8]="backspace",e[e.formFeed=12]="formFeed",e[e.byteOrderMark=65279]="byteOrderMark",e[e.tab=9]="tab",e[e.verticalTab=11]="verticalTab"}(e.CharacterCodes||(e.CharacterCodes={})),function(e){e.Ts=".ts",e.Tsx=".tsx",e.Dts=".d.ts",e.Js=".js",e.Jsx=".jsx",e.Json=".json"}(e.Extension||(e.Extension={})),function(e){e[e.None=0]="None",e[e.TypeScript=1]="TypeScript",e[e.ContainsTypeScript=2]="ContainsTypeScript",e[e.ContainsJsx=4]="ContainsJsx",e[e.ContainsESNext=8]="ContainsESNext",e[e.ContainsES2017=16]="ContainsES2017",e[e.ContainsES2016=32]="ContainsES2016",e[e.ES2015=64]="ES2015",e[e.ContainsES2015=128]="ContainsES2015",e[e.Generator=256]="Generator",e[e.ContainsGenerator=512]="ContainsGenerator",e[e.DestructuringAssignment=1024]="DestructuringAssignment",e[e.ContainsDestructuringAssignment=2048]="ContainsDestructuringAssignment",e[e.ContainsTypeScriptClassSyntax=4096]="ContainsTypeScriptClassSyntax",e[e.ContainsLexicalThis=8192]="ContainsLexicalThis",e[e.ContainsCapturedLexicalThis=16384]="ContainsCapturedLexicalThis",e[e.ContainsLexicalThisInComputedPropertyName=32768]="ContainsLexicalThisInComputedPropertyName",e[e.ContainsDefaultValueAssignments=65536]="ContainsDefaultValueAssignments",e[e.ContainsRestOrSpread=131072]="ContainsRestOrSpread",e[e.ContainsObjectRestOrSpread=262144]="ContainsObjectRestOrSpread",e[e.ContainsComputedPropertyName=524288]="ContainsComputedPropertyName",e[e.ContainsBlockScopedBinding=1048576]="ContainsBlockScopedBinding",e[e.ContainsBindingPattern=2097152]="ContainsBindingPattern",e[e.ContainsYield=4194304]="ContainsYield",e[e.ContainsHoistedDeclarationOrCompletion=8388608]="ContainsHoistedDeclarationOrCompletion",e[e.ContainsDynamicImport=16777216]="ContainsDynamicImport",e[e.Super=33554432]="Super",e[e.ContainsSuper=67108864]="ContainsSuper",e[e.HasComputedFlags=536870912]="HasComputedFlags",e[e.AssertTypeScript=3]="AssertTypeScript",e[e.AssertJsx=4]="AssertJsx",e[e.AssertESNext=8]="AssertESNext",e[e.AssertES2017=16]="AssertES2017",e[e.AssertES2016=32]="AssertES2016",e[e.AssertES2015=192]="AssertES2015",e[e.AssertGenerator=768]="AssertGenerator",e[e.AssertDestructuringAssignment=3072]="AssertDestructuringAssignment",e[e.OuterExpressionExcludes=536872257]="OuterExpressionExcludes",e[e.PropertyAccessExcludes=570426689]="PropertyAccessExcludes",e[e.NodeExcludes=637535553]="NodeExcludes",e[e.ArrowFunctionExcludes=653604161]="ArrowFunctionExcludes",e[e.FunctionExcludes=653620545]="FunctionExcludes",e[e.ConstructorExcludes=653616449]="ConstructorExcludes",e[e.MethodOrAccessorExcludes=653616449]="MethodOrAccessorExcludes",e[e.ClassExcludes=638121281]="ClassExcludes",e[e.ModuleExcludes=647001409]="ModuleExcludes",e[e.TypeExcludes=-3]="TypeExcludes",e[e.ObjectLiteralExcludes=638358849]="ObjectLiteralExcludes",e[e.ArrayLiteralOrCallOrNewExcludes=637666625]="ArrayLiteralOrCallOrNewExcludes",e[e.VariableDeclarationListExcludes=639894849]="VariableDeclarationListExcludes",e[e.ParameterExcludes=637535553]="ParameterExcludes",e[e.CatchClauseExcludes=637797697]="CatchClauseExcludes",e[e.BindingPatternExcludes=637666625]="BindingPatternExcludes",e[e.ES2015FunctionSyntaxMask=81920]="ES2015FunctionSyntaxMask"}(e.TransformFlags||(e.TransformFlags={})),function(e){e[e.None=0]="None",e[e.SingleLine=1]="SingleLine",e[e.AdviseOnEmitNode=2]="AdviseOnEmitNode",e[e.NoSubstitution=4]="NoSubstitution",e[e.CapturesThis=8]="CapturesThis",e[e.NoLeadingSourceMap=16]="NoLeadingSourceMap",e[e.NoTrailingSourceMap=32]="NoTrailingSourceMap",e[e.NoSourceMap=48]="NoSourceMap",e[e.NoNestedSourceMaps=64]="NoNestedSourceMaps",e[e.NoTokenLeadingSourceMaps=128]="NoTokenLeadingSourceMaps",e[e.NoTokenTrailingSourceMaps=256]="NoTokenTrailingSourceMaps",e[e.NoTokenSourceMaps=384]="NoTokenSourceMaps",e[e.NoLeadingComments=512]="NoLeadingComments",e[e.NoTrailingComments=1024]="NoTrailingComments",e[e.NoComments=1536]="NoComments",e[e.NoNestedComments=2048]="NoNestedComments",e[e.HelperName=4096]="HelperName",e[e.ExportName=8192]="ExportName",e[e.LocalName=16384]="LocalName",e[e.InternalName=32768]="InternalName",e[e.Indented=65536]="Indented",e[e.NoIndentation=131072]="NoIndentation",e[e.AsyncFunctionBody=262144]="AsyncFunctionBody",e[e.ReuseTempVariableScope=524288]="ReuseTempVariableScope",e[e.CustomPrologue=1048576]="CustomPrologue",e[e.NoHoisting=2097152]="NoHoisting",e[e.HasEndOfDeclarationMarker=4194304]="HasEndOfDeclarationMarker",e[e.Iterator=8388608]="Iterator",e[e.NoAsciiEscaping=16777216]="NoAsciiEscaping",e[e.TypeScriptClassWrapper=33554432]="TypeScriptClassWrapper",e[e.NeverApplyImportHelper=67108864]="NeverApplyImportHelper"}(e.EmitFlags||(e.EmitFlags={})),function(e){e[e.Extends=1]="Extends",e[e.Assign=2]="Assign",e[e.Rest=4]="Rest",e[e.Decorate=8]="Decorate",e[e.Metadata=16]="Metadata",e[e.Param=32]="Param",e[e.Awaiter=64]="Awaiter",e[e.Generator=128]="Generator",e[e.Values=256]="Values",e[e.Read=512]="Read",e[e.Spread=1024]="Spread",e[e.Await=2048]="Await",e[e.AsyncGenerator=4096]="AsyncGenerator",e[e.AsyncDelegator=8192]="AsyncDelegator",e[e.AsyncValues=16384]="AsyncValues",e[e.ExportStar=32768]="ExportStar",e[e.MakeTemplateObject=65536]="MakeTemplateObject",e[e.FirstEmitHelper=1]="FirstEmitHelper",e[e.LastEmitHelper=65536]="LastEmitHelper",e[e.ForOfIncludes=256]="ForOfIncludes",e[e.ForAwaitOfIncludes=16384]="ForAwaitOfIncludes",e[e.AsyncGeneratorIncludes=6144]="AsyncGeneratorIncludes",e[e.AsyncDelegatorIncludes=26624]="AsyncDelegatorIncludes",e[e.SpreadIncludes=1536]="SpreadIncludes"}(e.ExternalEmitHelpers||(e.ExternalEmitHelpers={})),function(e){e[e.SourceFile=0]="SourceFile",e[e.Expression=1]="Expression",e[e.IdentifierName=2]="IdentifierName",e[e.MappedTypeParameter=3]="MappedTypeParameter",e[e.Unspecified=4]="Unspecified",e[e.EmbeddedStatement=5]="EmbeddedStatement"}(e.EmitHint||(e.EmitHint={})),function(e){e[e.None=0]="None",e[e.SingleLine=0]="SingleLine",e[e.MultiLine=1]="MultiLine",e[e.PreserveLines=2]="PreserveLines",e[e.LinesMask=3]="LinesMask",e[e.NotDelimited=0]="NotDelimited",e[e.BarDelimited=4]="BarDelimited",e[e.AmpersandDelimited=8]="AmpersandDelimited",e[e.CommaDelimited=16]="CommaDelimited",e[e.AsteriskDelimited=32]="AsteriskDelimited",e[e.DelimitersMask=60]="DelimitersMask",e[e.AllowTrailingComma=64]="AllowTrailingComma",e[e.Indented=128]="Indented",e[e.SpaceBetweenBraces=256]="SpaceBetweenBraces",e[e.SpaceBetweenSiblings=512]="SpaceBetweenSiblings",e[e.Braces=1024]="Braces",e[e.Parenthesis=2048]="Parenthesis",e[e.AngleBrackets=4096]="AngleBrackets",e[e.SquareBrackets=8192]="SquareBrackets",e[e.BracketsMask=15360]="BracketsMask",e[e.OptionalIfUndefined=16384]="OptionalIfUndefined",e[e.OptionalIfEmpty=32768]="OptionalIfEmpty",e[e.Optional=49152]="Optional",e[e.PreferNewLine=65536]="PreferNewLine",e[e.NoTrailingNewLine=131072]="NoTrailingNewLine",e[e.NoInterveningComments=262144]="NoInterveningComments",e[e.NoSpaceIfEmpty=524288]="NoSpaceIfEmpty",e[e.SingleElement=1048576]="SingleElement",e[e.Modifiers=262656]="Modifiers",e[e.HeritageClauses=512]="HeritageClauses",e[e.SingleLineTypeLiteralMembers=768]="SingleLineTypeLiteralMembers",e[e.MultiLineTypeLiteralMembers=32897]="MultiLineTypeLiteralMembers",e[e.TupleTypeElements=528]="TupleTypeElements",e[e.UnionTypeConstituents=516]="UnionTypeConstituents",e[e.IntersectionTypeConstituents=520]="IntersectionTypeConstituents",e[e.ObjectBindingPatternElements=525136]="ObjectBindingPatternElements",e[e.ArrayBindingPatternElements=524880]="ArrayBindingPatternElements",e[e.ObjectLiteralExpressionProperties=526226]="ObjectLiteralExpressionProperties",e[e.ArrayLiteralExpressionElements=8914]="ArrayLiteralExpressionElements",e[e.CommaListElements=528]="CommaListElements",e[e.CallExpressionArguments=2576]="CallExpressionArguments",e[e.NewExpressionArguments=18960]="NewExpressionArguments",e[e.TemplateExpressionSpans=262144]="TemplateExpressionSpans",e[e.SingleLineBlockStatements=768]="SingleLineBlockStatements",e[e.MultiLineBlockStatements=129]="MultiLineBlockStatements",e[e.VariableDeclarationList=528]="VariableDeclarationList",e[e.SingleLineFunctionBodyStatements=768]="SingleLineFunctionBodyStatements",e[e.MultiLineFunctionBodyStatements=1]="MultiLineFunctionBodyStatements",e[e.ClassHeritageClauses=0]="ClassHeritageClauses",e[e.ClassMembers=129]="ClassMembers",e[e.InterfaceMembers=129]="InterfaceMembers",e[e.EnumMembers=145]="EnumMembers",e[e.CaseBlockClauses=129]="CaseBlockClauses",e[e.NamedImportsOrExportsElements=525136]="NamedImportsOrExportsElements",e[e.JsxElementOrFragmentChildren=262144]="JsxElementOrFragmentChildren",e[e.JsxElementAttributes=262656]="JsxElementAttributes",e[e.CaseOrDefaultClauseStatements=163969]="CaseOrDefaultClauseStatements",e[e.HeritageClauseTypes=528]="HeritageClauseTypes",e[e.SourceFileStatements=131073]="SourceFileStatements",e[e.Decorators=49153]="Decorators",e[e.TypeArguments=53776]="TypeArguments",e[e.TypeParameters=53776]="TypeParameters",e[e.Parameters=2576]="Parameters",e[e.IndexSignatureParameters=8848]="IndexSignatureParameters",e[e.JSDocComment=33]="JSDocComment"}(e.ListFormat||(e.ListFormat={})),function(e){e[e.None=0]="None",e[e.TripleSlashXML=1]="TripleSlashXML",e[e.SingleLine=2]="SingleLine",e[e.MultiLine=4]="MultiLine",e[e.All=7]="All",e[e.Default=7]="Default"}(e.PragmaKindFlags||(e.PragmaKindFlags={})),e.commentPragmas={reference:{args:[{name:"types",optional:!0,captureSpan:!0},{name:"lib",optional:!0,captureSpan:!0},{name:"path",optional:!0,captureSpan:!0},{name:"no-default-lib",optional:!0}],kind:1},"amd-dependency":{args:[{name:"path"},{name:"name",optional:!0}],kind:1},"amd-module":{args:[{name:"name"}],kind:1},"ts-check":{kind:2},"ts-nocheck":{kind:2},jsx:{args:[{name:"factory"}],kind:4}}}(c||(c={})),function(e){var t,r;function n(e){var t;return(t={})[r.Low]=e.Low,t[r.Medium]=e.Medium,t[r.High]=e.High,t}e.setStackTraceLimit=function(){Error.stackTraceLimit<100&&(Error.stackTraceLimit=100)},function(e){e[e.Created=0]="Created",e[e.Changed=1]="Changed",e[e.Deleted=2]="Deleted"}(t=e.FileWatcherEventKind||(e.FileWatcherEventKind={})),function(e){e[e.High=2e3]="High",e[e.Medium=500]="Medium",e[e.Low=250]="Low"}(r=e.PollingInterval||(e.PollingInterval={})),e.missingFileModifiedTime=new Date(0);var a={Low:32,Medium:64,High:256},o=n(a);function s(t){if(t.getEnvironmentVariable){var s=function(e,t){var r=c(e);if(r)return n("Low"),n("Medium"),n("High"),!0;return!1;function n(e){t[e]=r[e]||t[e]}}("TSC_WATCH_POLLINGINTERVAL",r);o=u("TSC_WATCH_POLLINGCHUNKSIZE",a)||o,e.unchangedPollThresholds=u("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS",a)||e.unchangedPollThresholds}function c(e){var r;return n("Low"),n("Medium"),n("High"),r;function n(n){var i=function(e,r){return t.getEnvironmentVariable(e+"_"+r.toUpperCase())}(e,n);i&&((r||(r={}))[n]=Number(i))}}function u(e,t){var r=c(e);return(s||r)&&n(r?i({},t,r):t)}}function c(t){var n=[],i=[],a=l(r.Low),s=l(r.Medium),c=l(r.High);return function(t,r,i){var a={fileName:t,callback:r,unchangedPolls:0,mtime:h(t)};return n.push(a),m(a,i),{close:function(){a.isClosed=!0,e.unorderedRemoveItem(n,a)}}};function l(e){var t=[];return t.pollingInterval=e,t.pollIndex=0,t.pollScheduled=!1,t}function _(t){t.pollIndex=p(t,t.pollingInterval,t.pollIndex,o[t.pollingInterval]),t.length?v(t.pollingInterval):(e.Debug.assert(0===t.pollIndex),t.pollScheduled=!1)}function d(e){p(i,r.Low,0,i.length),_(e),!e.pollScheduled&&i.length&&v(r.Low)}function p(t,n,a,o){for(var s=t.length,c=a,l=0;l0;p(),s--){var _=t[a];if(_)if(_.isClosed)t[a]=void 0;else{l++;var d=u(_,h(_.fileName));_.isClosed?t[a]=void 0:d?(_.unchangedPolls=0,t!==i&&(t[a]=void 0,g(_))):_.unchangedPolls!==e.unchangedPollThresholds[n]?_.unchangedPolls++:t===i?(_.unchangedPolls=1,t[a]=void 0,m(_,r.Low)):n!==r.High&&(_.unchangedPolls++,t[a]=void 0,m(_,n===r.Low?r.Medium:r.High)),t[a]&&(c type."),In_ambient_enum_declarations_member_initializer_must_be_constant_expression:t(1066,e.DiagnosticCategory.Error,"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066","In ambient enum declarations member initializer must be constant expression."),Unexpected_token_A_constructor_method_accessor_or_property_was_expected:t(1068,e.DiagnosticCategory.Error,"Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068","Unexpected token. A constructor, method, accessor, or property was expected."),Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces:t(1069,e.DiagnosticCategory.Error,"Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069","Unexpected token. A type parameter name was expected without curly braces."),_0_modifier_cannot_appear_on_a_type_member:t(1070,e.DiagnosticCategory.Error,"_0_modifier_cannot_appear_on_a_type_member_1070","'{0}' modifier cannot appear on a type member."),_0_modifier_cannot_appear_on_an_index_signature:t(1071,e.DiagnosticCategory.Error,"_0_modifier_cannot_appear_on_an_index_signature_1071","'{0}' modifier cannot appear on an index signature."),A_0_modifier_cannot_be_used_with_an_import_declaration:t(1079,e.DiagnosticCategory.Error,"A_0_modifier_cannot_be_used_with_an_import_declaration_1079","A '{0}' modifier cannot be used with an import declaration."),Invalid_reference_directive_syntax:t(1084,e.DiagnosticCategory.Error,"Invalid_reference_directive_syntax_1084","Invalid 'reference' directive syntax."),Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0:t(1085,e.DiagnosticCategory.Error,"Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085","Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."),An_accessor_cannot_be_declared_in_an_ambient_context:t(1086,e.DiagnosticCategory.Error,"An_accessor_cannot_be_declared_in_an_ambient_context_1086","An accessor cannot be declared in an ambient context."),_0_modifier_cannot_appear_on_a_constructor_declaration:t(1089,e.DiagnosticCategory.Error,"_0_modifier_cannot_appear_on_a_constructor_declaration_1089","'{0}' modifier cannot appear on a constructor declaration."),_0_modifier_cannot_appear_on_a_parameter:t(1090,e.DiagnosticCategory.Error,"_0_modifier_cannot_appear_on_a_parameter_1090","'{0}' modifier cannot appear on a parameter."),Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement:t(1091,e.DiagnosticCategory.Error,"Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091","Only a single variable declaration is allowed in a 'for...in' statement."),Type_parameters_cannot_appear_on_a_constructor_declaration:t(1092,e.DiagnosticCategory.Error,"Type_parameters_cannot_appear_on_a_constructor_declaration_1092","Type parameters cannot appear on a constructor declaration."),Type_annotation_cannot_appear_on_a_constructor_declaration:t(1093,e.DiagnosticCategory.Error,"Type_annotation_cannot_appear_on_a_constructor_declaration_1093","Type annotation cannot appear on a constructor declaration."),An_accessor_cannot_have_type_parameters:t(1094,e.DiagnosticCategory.Error,"An_accessor_cannot_have_type_parameters_1094","An accessor cannot have type parameters."),A_set_accessor_cannot_have_a_return_type_annotation:t(1095,e.DiagnosticCategory.Error,"A_set_accessor_cannot_have_a_return_type_annotation_1095","A 'set' accessor cannot have a return type annotation."),An_index_signature_must_have_exactly_one_parameter:t(1096,e.DiagnosticCategory.Error,"An_index_signature_must_have_exactly_one_parameter_1096","An index signature must have exactly one parameter."),_0_list_cannot_be_empty:t(1097,e.DiagnosticCategory.Error,"_0_list_cannot_be_empty_1097","'{0}' list cannot be empty."),Type_parameter_list_cannot_be_empty:t(1098,e.DiagnosticCategory.Error,"Type_parameter_list_cannot_be_empty_1098","Type parameter list cannot be empty."),Type_argument_list_cannot_be_empty:t(1099,e.DiagnosticCategory.Error,"Type_argument_list_cannot_be_empty_1099","Type argument list cannot be empty."),Invalid_use_of_0_in_strict_mode:t(1100,e.DiagnosticCategory.Error,"Invalid_use_of_0_in_strict_mode_1100","Invalid use of '{0}' in strict mode."),with_statements_are_not_allowed_in_strict_mode:t(1101,e.DiagnosticCategory.Error,"with_statements_are_not_allowed_in_strict_mode_1101","'with' statements are not allowed in strict mode."),delete_cannot_be_called_on_an_identifier_in_strict_mode:t(1102,e.DiagnosticCategory.Error,"delete_cannot_be_called_on_an_identifier_in_strict_mode_1102","'delete' cannot be called on an identifier in strict mode."),A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator:t(1103,e.DiagnosticCategory.Error,"A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103","A 'for-await-of' statement is only allowed within an async function or async generator."),A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement:t(1104,e.DiagnosticCategory.Error,"A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104","A 'continue' statement can only be used within an enclosing iteration statement."),A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement:t(1105,e.DiagnosticCategory.Error,"A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105","A 'break' statement can only be used within an enclosing iteration or switch statement."),Jump_target_cannot_cross_function_boundary:t(1107,e.DiagnosticCategory.Error,"Jump_target_cannot_cross_function_boundary_1107","Jump target cannot cross function boundary."),A_return_statement_can_only_be_used_within_a_function_body:t(1108,e.DiagnosticCategory.Error,"A_return_statement_can_only_be_used_within_a_function_body_1108","A 'return' statement can only be used within a function body."),Expression_expected:t(1109,e.DiagnosticCategory.Error,"Expression_expected_1109","Expression expected."),Type_expected:t(1110,e.DiagnosticCategory.Error,"Type_expected_1110","Type expected."),A_default_clause_cannot_appear_more_than_once_in_a_switch_statement:t(1113,e.DiagnosticCategory.Error,"A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113","A 'default' clause cannot appear more than once in a 'switch' statement."),Duplicate_label_0:t(1114,e.DiagnosticCategory.Error,"Duplicate_label_0_1114","Duplicate label '{0}'."),A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement:t(1115,e.DiagnosticCategory.Error,"A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115","A 'continue' statement can only jump to a label of an enclosing iteration statement."),A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement:t(1116,e.DiagnosticCategory.Error,"A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116","A 'break' statement can only jump to a label of an enclosing statement."),An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode:t(1117,e.DiagnosticCategory.Error,"An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117","An object literal cannot have multiple properties with the same name in strict mode."),An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name:t(1118,e.DiagnosticCategory.Error,"An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118","An object literal cannot have multiple get/set accessors with the same name."),An_object_literal_cannot_have_property_and_accessor_with_the_same_name:t(1119,e.DiagnosticCategory.Error,"An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119","An object literal cannot have property and accessor with the same name."),An_export_assignment_cannot_have_modifiers:t(1120,e.DiagnosticCategory.Error,"An_export_assignment_cannot_have_modifiers_1120","An export assignment cannot have modifiers."),Octal_literals_are_not_allowed_in_strict_mode:t(1121,e.DiagnosticCategory.Error,"Octal_literals_are_not_allowed_in_strict_mode_1121","Octal literals are not allowed in strict mode."),Variable_declaration_list_cannot_be_empty:t(1123,e.DiagnosticCategory.Error,"Variable_declaration_list_cannot_be_empty_1123","Variable declaration list cannot be empty."),Digit_expected:t(1124,e.DiagnosticCategory.Error,"Digit_expected_1124","Digit expected."),Hexadecimal_digit_expected:t(1125,e.DiagnosticCategory.Error,"Hexadecimal_digit_expected_1125","Hexadecimal digit expected."),Unexpected_end_of_text:t(1126,e.DiagnosticCategory.Error,"Unexpected_end_of_text_1126","Unexpected end of text."),Invalid_character:t(1127,e.DiagnosticCategory.Error,"Invalid_character_1127","Invalid character."),Declaration_or_statement_expected:t(1128,e.DiagnosticCategory.Error,"Declaration_or_statement_expected_1128","Declaration or statement expected."),Statement_expected:t(1129,e.DiagnosticCategory.Error,"Statement_expected_1129","Statement expected."),case_or_default_expected:t(1130,e.DiagnosticCategory.Error,"case_or_default_expected_1130","'case' or 'default' expected."),Property_or_signature_expected:t(1131,e.DiagnosticCategory.Error,"Property_or_signature_expected_1131","Property or signature expected."),Enum_member_expected:t(1132,e.DiagnosticCategory.Error,"Enum_member_expected_1132","Enum member expected."),Variable_declaration_expected:t(1134,e.DiagnosticCategory.Error,"Variable_declaration_expected_1134","Variable declaration expected."),Argument_expression_expected:t(1135,e.DiagnosticCategory.Error,"Argument_expression_expected_1135","Argument expression expected."),Property_assignment_expected:t(1136,e.DiagnosticCategory.Error,"Property_assignment_expected_1136","Property assignment expected."),Expression_or_comma_expected:t(1137,e.DiagnosticCategory.Error,"Expression_or_comma_expected_1137","Expression or comma expected."),Parameter_declaration_expected:t(1138,e.DiagnosticCategory.Error,"Parameter_declaration_expected_1138","Parameter declaration expected."),Type_parameter_declaration_expected:t(1139,e.DiagnosticCategory.Error,"Type_parameter_declaration_expected_1139","Type parameter declaration expected."),Type_argument_expected:t(1140,e.DiagnosticCategory.Error,"Type_argument_expected_1140","Type argument expected."),String_literal_expected:t(1141,e.DiagnosticCategory.Error,"String_literal_expected_1141","String literal expected."),Line_break_not_permitted_here:t(1142,e.DiagnosticCategory.Error,"Line_break_not_permitted_here_1142","Line break not permitted here."),or_expected:t(1144,e.DiagnosticCategory.Error,"or_expected_1144","'{' or ';' expected."),Declaration_expected:t(1146,e.DiagnosticCategory.Error,"Declaration_expected_1146","Declaration expected."),Import_declarations_in_a_namespace_cannot_reference_a_module:t(1147,e.DiagnosticCategory.Error,"Import_declarations_in_a_namespace_cannot_reference_a_module_1147","Import declarations in a namespace cannot reference a module."),Cannot_use_imports_exports_or_module_augmentations_when_module_is_none:t(1148,e.DiagnosticCategory.Error,"Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148","Cannot use imports, exports, or module augmentations when '--module' is 'none'."),File_name_0_differs_from_already_included_file_name_1_only_in_casing:t(1149,e.DiagnosticCategory.Error,"File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149","File name '{0}' differs from already included file name '{1}' only in casing."),new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead:t(1150,e.DiagnosticCategory.Error,"new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150","'new T[]' cannot be used to create an array. Use 'new Array()' instead."),const_declarations_must_be_initialized:t(1155,e.DiagnosticCategory.Error,"const_declarations_must_be_initialized_1155","'const' declarations must be initialized."),const_declarations_can_only_be_declared_inside_a_block:t(1156,e.DiagnosticCategory.Error,"const_declarations_can_only_be_declared_inside_a_block_1156","'const' declarations can only be declared inside a block."),let_declarations_can_only_be_declared_inside_a_block:t(1157,e.DiagnosticCategory.Error,"let_declarations_can_only_be_declared_inside_a_block_1157","'let' declarations can only be declared inside a block."),Unterminated_template_literal:t(1160,e.DiagnosticCategory.Error,"Unterminated_template_literal_1160","Unterminated template literal."),Unterminated_regular_expression_literal:t(1161,e.DiagnosticCategory.Error,"Unterminated_regular_expression_literal_1161","Unterminated regular expression literal."),An_object_member_cannot_be_declared_optional:t(1162,e.DiagnosticCategory.Error,"An_object_member_cannot_be_declared_optional_1162","An object member cannot be declared optional."),A_yield_expression_is_only_allowed_in_a_generator_body:t(1163,e.DiagnosticCategory.Error,"A_yield_expression_is_only_allowed_in_a_generator_body_1163","A 'yield' expression is only allowed in a generator body."),Computed_property_names_are_not_allowed_in_enums:t(1164,e.DiagnosticCategory.Error,"Computed_property_names_are_not_allowed_in_enums_1164","Computed property names are not allowed in enums."),A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type:t(1165,e.DiagnosticCategory.Error,"A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_t_1165","A computed property name in an ambient context must refer to an expression whose type is a literal type or a 'unique symbol' type."),A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type:t(1166,e.DiagnosticCategory.Error,"A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166","A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."),A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type:t(1168,e.DiagnosticCategory.Error,"A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_ty_1168","A computed property name in a method overload must refer to an expression whose type is a literal type or a 'unique symbol' type."),A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type:t(1169,e.DiagnosticCategory.Error,"A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_1169","A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."),A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type:t(1170,e.DiagnosticCategory.Error,"A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type__1170","A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."),A_comma_expression_is_not_allowed_in_a_computed_property_name:t(1171,e.DiagnosticCategory.Error,"A_comma_expression_is_not_allowed_in_a_computed_property_name_1171","A comma expression is not allowed in a computed property name."),extends_clause_already_seen:t(1172,e.DiagnosticCategory.Error,"extends_clause_already_seen_1172","'extends' clause already seen."),extends_clause_must_precede_implements_clause:t(1173,e.DiagnosticCategory.Error,"extends_clause_must_precede_implements_clause_1173","'extends' clause must precede 'implements' clause."),Classes_can_only_extend_a_single_class:t(1174,e.DiagnosticCategory.Error,"Classes_can_only_extend_a_single_class_1174","Classes can only extend a single class."),implements_clause_already_seen:t(1175,e.DiagnosticCategory.Error,"implements_clause_already_seen_1175","'implements' clause already seen."),Interface_declaration_cannot_have_implements_clause:t(1176,e.DiagnosticCategory.Error,"Interface_declaration_cannot_have_implements_clause_1176","Interface declaration cannot have 'implements' clause."),Binary_digit_expected:t(1177,e.DiagnosticCategory.Error,"Binary_digit_expected_1177","Binary digit expected."),Octal_digit_expected:t(1178,e.DiagnosticCategory.Error,"Octal_digit_expected_1178","Octal digit expected."),Unexpected_token_expected:t(1179,e.DiagnosticCategory.Error,"Unexpected_token_expected_1179","Unexpected token. '{' expected."),Property_destructuring_pattern_expected:t(1180,e.DiagnosticCategory.Error,"Property_destructuring_pattern_expected_1180","Property destructuring pattern expected."),Array_element_destructuring_pattern_expected:t(1181,e.DiagnosticCategory.Error,"Array_element_destructuring_pattern_expected_1181","Array element destructuring pattern expected."),A_destructuring_declaration_must_have_an_initializer:t(1182,e.DiagnosticCategory.Error,"A_destructuring_declaration_must_have_an_initializer_1182","A destructuring declaration must have an initializer."),An_implementation_cannot_be_declared_in_ambient_contexts:t(1183,e.DiagnosticCategory.Error,"An_implementation_cannot_be_declared_in_ambient_contexts_1183","An implementation cannot be declared in ambient contexts."),Modifiers_cannot_appear_here:t(1184,e.DiagnosticCategory.Error,"Modifiers_cannot_appear_here_1184","Modifiers cannot appear here."),Merge_conflict_marker_encountered:t(1185,e.DiagnosticCategory.Error,"Merge_conflict_marker_encountered_1185","Merge conflict marker encountered."),A_rest_element_cannot_have_an_initializer:t(1186,e.DiagnosticCategory.Error,"A_rest_element_cannot_have_an_initializer_1186","A rest element cannot have an initializer."),A_parameter_property_may_not_be_declared_using_a_binding_pattern:t(1187,e.DiagnosticCategory.Error,"A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187","A parameter property may not be declared using a binding pattern."),Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement:t(1188,e.DiagnosticCategory.Error,"Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188","Only a single variable declaration is allowed in a 'for...of' statement."),The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer:t(1189,e.DiagnosticCategory.Error,"The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189","The variable declaration of a 'for...in' statement cannot have an initializer."),The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer:t(1190,e.DiagnosticCategory.Error,"The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190","The variable declaration of a 'for...of' statement cannot have an initializer."),An_import_declaration_cannot_have_modifiers:t(1191,e.DiagnosticCategory.Error,"An_import_declaration_cannot_have_modifiers_1191","An import declaration cannot have modifiers."),Module_0_has_no_default_export:t(1192,e.DiagnosticCategory.Error,"Module_0_has_no_default_export_1192","Module '{0}' has no default export."),An_export_declaration_cannot_have_modifiers:t(1193,e.DiagnosticCategory.Error,"An_export_declaration_cannot_have_modifiers_1193","An export declaration cannot have modifiers."),Export_declarations_are_not_permitted_in_a_namespace:t(1194,e.DiagnosticCategory.Error,"Export_declarations_are_not_permitted_in_a_namespace_1194","Export declarations are not permitted in a namespace."),Catch_clause_variable_cannot_have_a_type_annotation:t(1196,e.DiagnosticCategory.Error,"Catch_clause_variable_cannot_have_a_type_annotation_1196","Catch clause variable cannot have a type annotation."),Catch_clause_variable_cannot_have_an_initializer:t(1197,e.DiagnosticCategory.Error,"Catch_clause_variable_cannot_have_an_initializer_1197","Catch clause variable cannot have an initializer."),An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive:t(1198,e.DiagnosticCategory.Error,"An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198","An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."),Unterminated_Unicode_escape_sequence:t(1199,e.DiagnosticCategory.Error,"Unterminated_Unicode_escape_sequence_1199","Unterminated Unicode escape sequence."),Line_terminator_not_permitted_before_arrow:t(1200,e.DiagnosticCategory.Error,"Line_terminator_not_permitted_before_arrow_1200","Line terminator not permitted before arrow."),Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead:t(1202,e.DiagnosticCategory.Error,"Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202","Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead."),Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead:t(1203,e.DiagnosticCategory.Error,"Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203","Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead."),Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided:t(1205,e.DiagnosticCategory.Error,"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205","Cannot re-export a type when the '--isolatedModules' flag is provided."),Decorators_are_not_valid_here:t(1206,e.DiagnosticCategory.Error,"Decorators_are_not_valid_here_1206","Decorators are not valid here."),Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name:t(1207,e.DiagnosticCategory.Error,"Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207","Decorators cannot be applied to multiple get/set accessors of the same name."),Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided:t(1208,e.DiagnosticCategory.Error,"Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208","Cannot compile namespaces when the '--isolatedModules' flag is provided."),Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided:t(1209,e.DiagnosticCategory.Error,"Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209","Ambient const enums are not allowed when the '--isolatedModules' flag is provided."),Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode:t(1210,e.DiagnosticCategory.Error,"Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210","Invalid use of '{0}'. Class definitions are automatically in strict mode."),A_class_declaration_without_the_default_modifier_must_have_a_name:t(1211,e.DiagnosticCategory.Error,"A_class_declaration_without_the_default_modifier_must_have_a_name_1211","A class declaration without the 'default' modifier must have a name."),Identifier_expected_0_is_a_reserved_word_in_strict_mode:t(1212,e.DiagnosticCategory.Error,"Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212","Identifier expected. '{0}' is a reserved word in strict mode."),Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode:t(1213,e.DiagnosticCategory.Error,"Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213","Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."),Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode:t(1214,e.DiagnosticCategory.Error,"Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214","Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."),Invalid_use_of_0_Modules_are_automatically_in_strict_mode:t(1215,e.DiagnosticCategory.Error,"Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215","Invalid use of '{0}'. Modules are automatically in strict mode."),Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules:t(1216,e.DiagnosticCategory.Error,"Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216","Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."),Export_assignment_is_not_supported_when_module_flag_is_system:t(1218,e.DiagnosticCategory.Error,"Export_assignment_is_not_supported_when_module_flag_is_system_1218","Export assignment is not supported when '--module' flag is 'system'."),Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning:t(1219,e.DiagnosticCategory.Error,"Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219","Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."),Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher:t(1220,e.DiagnosticCategory.Error,"Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220","Generators are only available when targeting ECMAScript 2015 or higher."),Generators_are_not_allowed_in_an_ambient_context:t(1221,e.DiagnosticCategory.Error,"Generators_are_not_allowed_in_an_ambient_context_1221","Generators are not allowed in an ambient context."),An_overload_signature_cannot_be_declared_as_a_generator:t(1222,e.DiagnosticCategory.Error,"An_overload_signature_cannot_be_declared_as_a_generator_1222","An overload signature cannot be declared as a generator."),_0_tag_already_specified:t(1223,e.DiagnosticCategory.Error,"_0_tag_already_specified_1223","'{0}' tag already specified."),Signature_0_must_be_a_type_predicate:t(1224,e.DiagnosticCategory.Error,"Signature_0_must_be_a_type_predicate_1224","Signature '{0}' must be a type predicate."),Cannot_find_parameter_0:t(1225,e.DiagnosticCategory.Error,"Cannot_find_parameter_0_1225","Cannot find parameter '{0}'."),Type_predicate_0_is_not_assignable_to_1:t(1226,e.DiagnosticCategory.Error,"Type_predicate_0_is_not_assignable_to_1_1226","Type predicate '{0}' is not assignable to '{1}'."),Parameter_0_is_not_in_the_same_position_as_parameter_1:t(1227,e.DiagnosticCategory.Error,"Parameter_0_is_not_in_the_same_position_as_parameter_1_1227","Parameter '{0}' is not in the same position as parameter '{1}'."),A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods:t(1228,e.DiagnosticCategory.Error,"A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228","A type predicate is only allowed in return type position for functions and methods."),A_type_predicate_cannot_reference_a_rest_parameter:t(1229,e.DiagnosticCategory.Error,"A_type_predicate_cannot_reference_a_rest_parameter_1229","A type predicate cannot reference a rest parameter."),A_type_predicate_cannot_reference_element_0_in_a_binding_pattern:t(1230,e.DiagnosticCategory.Error,"A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230","A type predicate cannot reference element '{0}' in a binding pattern."),An_export_assignment_can_only_be_used_in_a_module:t(1231,e.DiagnosticCategory.Error,"An_export_assignment_can_only_be_used_in_a_module_1231","An export assignment can only be used in a module."),An_import_declaration_can_only_be_used_in_a_namespace_or_module:t(1232,e.DiagnosticCategory.Error,"An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232","An import declaration can only be used in a namespace or module."),An_export_declaration_can_only_be_used_in_a_module:t(1233,e.DiagnosticCategory.Error,"An_export_declaration_can_only_be_used_in_a_module_1233","An export declaration can only be used in a module."),An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file:t(1234,e.DiagnosticCategory.Error,"An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234","An ambient module declaration is only allowed at the top level in a file."),A_namespace_declaration_is_only_allowed_in_a_namespace_or_module:t(1235,e.DiagnosticCategory.Error,"A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235","A namespace declaration is only allowed in a namespace or module."),The_return_type_of_a_property_decorator_function_must_be_either_void_or_any:t(1236,e.DiagnosticCategory.Error,"The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236","The return type of a property decorator function must be either 'void' or 'any'."),The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any:t(1237,e.DiagnosticCategory.Error,"The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237","The return type of a parameter decorator function must be either 'void' or 'any'."),Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression:t(1238,e.DiagnosticCategory.Error,"Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238","Unable to resolve signature of class decorator when called as an expression."),Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression:t(1239,e.DiagnosticCategory.Error,"Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239","Unable to resolve signature of parameter decorator when called as an expression."),Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression:t(1240,e.DiagnosticCategory.Error,"Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240","Unable to resolve signature of property decorator when called as an expression."),Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression:t(1241,e.DiagnosticCategory.Error,"Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241","Unable to resolve signature of method decorator when called as an expression."),abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration:t(1242,e.DiagnosticCategory.Error,"abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242","'abstract' modifier can only appear on a class, method, or property declaration."),_0_modifier_cannot_be_used_with_1_modifier:t(1243,e.DiagnosticCategory.Error,"_0_modifier_cannot_be_used_with_1_modifier_1243","'{0}' modifier cannot be used with '{1}' modifier."),Abstract_methods_can_only_appear_within_an_abstract_class:t(1244,e.DiagnosticCategory.Error,"Abstract_methods_can_only_appear_within_an_abstract_class_1244","Abstract methods can only appear within an abstract class."),Method_0_cannot_have_an_implementation_because_it_is_marked_abstract:t(1245,e.DiagnosticCategory.Error,"Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245","Method '{0}' cannot have an implementation because it is marked abstract."),An_interface_property_cannot_have_an_initializer:t(1246,e.DiagnosticCategory.Error,"An_interface_property_cannot_have_an_initializer_1246","An interface property cannot have an initializer."),A_type_literal_property_cannot_have_an_initializer:t(1247,e.DiagnosticCategory.Error,"A_type_literal_property_cannot_have_an_initializer_1247","A type literal property cannot have an initializer."),A_class_member_cannot_have_the_0_keyword:t(1248,e.DiagnosticCategory.Error,"A_class_member_cannot_have_the_0_keyword_1248","A class member cannot have the '{0}' keyword."),A_decorator_can_only_decorate_a_method_implementation_not_an_overload:t(1249,e.DiagnosticCategory.Error,"A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249","A decorator can only decorate a method implementation, not an overload."),Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5:t(1250,e.DiagnosticCategory.Error,"Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250","Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."),Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode:t(1251,e.DiagnosticCategory.Error,"Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251","Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."),Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode:t(1252,e.DiagnosticCategory.Error,"Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252","Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."),_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag:t(1253,e.DiagnosticCategory.Error,"_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253","'{0}' tag cannot be used independently as a top level JSDoc tag."),A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference:t(1254,e.DiagnosticCategory.Error,"A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_refere_1254","A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference."),A_definite_assignment_assertion_is_not_permitted_in_this_context:t(1255,e.DiagnosticCategory.Error,"A_definite_assignment_assertion_is_not_permitted_in_this_context_1255","A definite assignment assertion '!' is not permitted in this context."),A_rest_element_must_be_last_in_a_tuple_type:t(1256,e.DiagnosticCategory.Error,"A_rest_element_must_be_last_in_a_tuple_type_1256","A rest element must be last in a tuple type."),A_required_element_cannot_follow_an_optional_element:t(1257,e.DiagnosticCategory.Error,"A_required_element_cannot_follow_an_optional_element_1257","A required element cannot follow an optional element."),with_statements_are_not_allowed_in_an_async_function_block:t(1300,e.DiagnosticCategory.Error,"with_statements_are_not_allowed_in_an_async_function_block_1300","'with' statements are not allowed in an async function block."),await_expression_is_only_allowed_within_an_async_function:t(1308,e.DiagnosticCategory.Error,"await_expression_is_only_allowed_within_an_async_function_1308","'await' expression is only allowed within an async function."),can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment:t(1312,e.DiagnosticCategory.Error,"can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312","'=' can only be used in an object literal property inside a destructuring assignment."),The_body_of_an_if_statement_cannot_be_the_empty_statement:t(1313,e.DiagnosticCategory.Error,"The_body_of_an_if_statement_cannot_be_the_empty_statement_1313","The body of an 'if' statement cannot be the empty statement."),Global_module_exports_may_only_appear_in_module_files:t(1314,e.DiagnosticCategory.Error,"Global_module_exports_may_only_appear_in_module_files_1314","Global module exports may only appear in module files."),Global_module_exports_may_only_appear_in_declaration_files:t(1315,e.DiagnosticCategory.Error,"Global_module_exports_may_only_appear_in_declaration_files_1315","Global module exports may only appear in declaration files."),Global_module_exports_may_only_appear_at_top_level:t(1316,e.DiagnosticCategory.Error,"Global_module_exports_may_only_appear_at_top_level_1316","Global module exports may only appear at top level."),A_parameter_property_cannot_be_declared_using_a_rest_parameter:t(1317,e.DiagnosticCategory.Error,"A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317","A parameter property cannot be declared using a rest parameter."),An_abstract_accessor_cannot_have_an_implementation:t(1318,e.DiagnosticCategory.Error,"An_abstract_accessor_cannot_have_an_implementation_1318","An abstract accessor cannot have an implementation."),A_default_export_can_only_be_used_in_an_ECMAScript_style_module:t(1319,e.DiagnosticCategory.Error,"A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319","A default export can only be used in an ECMAScript-style module."),Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member:t(1320,e.DiagnosticCategory.Error,"Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320","Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member:t(1321,e.DiagnosticCategory.Error,"Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321","Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member:t(1322,e.DiagnosticCategory.Error,"Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322","Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext:t(1323,e.DiagnosticCategory.Error,"Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323","Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."),Dynamic_import_must_have_one_specifier_as_an_argument:t(1324,e.DiagnosticCategory.Error,"Dynamic_import_must_have_one_specifier_as_an_argument_1324","Dynamic import must have one specifier as an argument."),Specifier_of_dynamic_import_cannot_be_spread_element:t(1325,e.DiagnosticCategory.Error,"Specifier_of_dynamic_import_cannot_be_spread_element_1325","Specifier of dynamic import cannot be spread element."),Dynamic_import_cannot_have_type_arguments:t(1326,e.DiagnosticCategory.Error,"Dynamic_import_cannot_have_type_arguments_1326","Dynamic import cannot have type arguments"),String_literal_with_double_quotes_expected:t(1327,e.DiagnosticCategory.Error,"String_literal_with_double_quotes_expected_1327","String literal with double quotes expected."),Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal:t(1328,e.DiagnosticCategory.Error,"Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328","Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."),_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0:t(1329,e.DiagnosticCategory.Error,"_0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write__1329","'{0}' accepts too few arguments to be used as a decorator here. Did you mean to call it first and write '@{0}()'?"),A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly:t(1330,e.DiagnosticCategory.Error,"A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly_1330","A property of an interface or type literal whose type is a 'unique symbol' type must be 'readonly'."),A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly:t(1331,e.DiagnosticCategory.Error,"A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly_1331","A property of a class whose type is a 'unique symbol' type must be both 'static' and 'readonly'."),A_variable_whose_type_is_a_unique_symbol_type_must_be_const:t(1332,e.DiagnosticCategory.Error,"A_variable_whose_type_is_a_unique_symbol_type_must_be_const_1332","A variable whose type is a 'unique symbol' type must be 'const'."),unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name:t(1333,e.DiagnosticCategory.Error,"unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333","'unique symbol' types may not be used on a variable declaration with a binding name."),unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement:t(1334,e.DiagnosticCategory.Error,"unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334","'unique symbol' types are only allowed on variables in a variable statement."),unique_symbol_types_are_not_allowed_here:t(1335,e.DiagnosticCategory.Error,"unique_symbol_types_are_not_allowed_here_1335","'unique symbol' types are not allowed here."),An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead:t(1336,e.DiagnosticCategory.Error,"An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336","An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."),An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead:t(1337,e.DiagnosticCategory.Error,"An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337","An index signature parameter type cannot be a union type. Consider using a mapped object type instead."),infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type:t(1338,e.DiagnosticCategory.Error,"infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338","'infer' declarations are only permitted in the 'extends' clause of a conditional type."),Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here:t(1339,e.DiagnosticCategory.Error,"Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339","Module '{0}' does not refer to a value, but is used as a value here."),Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0:t(1340,e.DiagnosticCategory.Error,"Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340","Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"),Type_arguments_cannot_be_used_here:t(1342,e.DiagnosticCategory.Error,"Type_arguments_cannot_be_used_here_1342","Type arguments cannot be used here."),The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options:t(1343,e.DiagnosticCategory.Error,"The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343","The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."),A_label_is_not_allowed_here:t(1344,e.DiagnosticCategory.Error,"A_label_is_not_allowed_here_1344","'A label is not allowed here."),An_expression_of_type_void_cannot_be_tested_for_truthiness:t(1345,e.DiagnosticCategory.Error,"An_expression_of_type_void_cannot_be_tested_for_truthiness_1345","An expression of type 'void' cannot be tested for truthiness"),This_parameter_is_not_allowed_with_use_strict_directive:t(1346,e.DiagnosticCategory.Error,"This_parameter_is_not_allowed_with_use_strict_directive_1346","This parameter is not allowed with 'use strict' directive."),use_strict_directive_cannot_be_used_with_non_simple_parameter_list:t(1347,e.DiagnosticCategory.Error,"use_strict_directive_cannot_be_used_with_non_simple_parameter_list_1347","'use strict' directive cannot be used with non-simple parameter list."),Non_simple_parameter_declared_here:t(1348,e.DiagnosticCategory.Error,"Non_simple_parameter_declared_here_1348","Non-simple parameter declared here."),use_strict_directive_used_here:t(1349,e.DiagnosticCategory.Error,"use_strict_directive_used_here_1349","'use strict' directive used here."),Print_the_final_configuration_instead_of_building:t(1350,e.DiagnosticCategory.Message,"Print_the_final_configuration_instead_of_building_1350","Print the final configuration instead of building."),Duplicate_identifier_0:t(2300,e.DiagnosticCategory.Error,"Duplicate_identifier_0_2300","Duplicate identifier '{0}'."),Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor:t(2301,e.DiagnosticCategory.Error,"Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301","Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."),Static_members_cannot_reference_class_type_parameters:t(2302,e.DiagnosticCategory.Error,"Static_members_cannot_reference_class_type_parameters_2302","Static members cannot reference class type parameters."),Circular_definition_of_import_alias_0:t(2303,e.DiagnosticCategory.Error,"Circular_definition_of_import_alias_0_2303","Circular definition of import alias '{0}'."),Cannot_find_name_0:t(2304,e.DiagnosticCategory.Error,"Cannot_find_name_0_2304","Cannot find name '{0}'."),Module_0_has_no_exported_member_1:t(2305,e.DiagnosticCategory.Error,"Module_0_has_no_exported_member_1_2305","Module '{0}' has no exported member '{1}'."),File_0_is_not_a_module:t(2306,e.DiagnosticCategory.Error,"File_0_is_not_a_module_2306","File '{0}' is not a module."),Cannot_find_module_0:t(2307,e.DiagnosticCategory.Error,"Cannot_find_module_0_2307","Cannot find module '{0}'."),Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity:t(2308,e.DiagnosticCategory.Error,"Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308","Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."),An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements:t(2309,e.DiagnosticCategory.Error,"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309","An export assignment cannot be used in a module with other exported elements."),Type_0_recursively_references_itself_as_a_base_type:t(2310,e.DiagnosticCategory.Error,"Type_0_recursively_references_itself_as_a_base_type_2310","Type '{0}' recursively references itself as a base type."),A_class_may_only_extend_another_class:t(2311,e.DiagnosticCategory.Error,"A_class_may_only_extend_another_class_2311","A class may only extend another class."),An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members:t(2312,e.DiagnosticCategory.Error,"An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312","An interface can only extend an object type or intersection of object types with statically known members."),Type_parameter_0_has_a_circular_constraint:t(2313,e.DiagnosticCategory.Error,"Type_parameter_0_has_a_circular_constraint_2313","Type parameter '{0}' has a circular constraint."),Generic_type_0_requires_1_type_argument_s:t(2314,e.DiagnosticCategory.Error,"Generic_type_0_requires_1_type_argument_s_2314","Generic type '{0}' requires {1} type argument(s)."),Type_0_is_not_generic:t(2315,e.DiagnosticCategory.Error,"Type_0_is_not_generic_2315","Type '{0}' is not generic."),Global_type_0_must_be_a_class_or_interface_type:t(2316,e.DiagnosticCategory.Error,"Global_type_0_must_be_a_class_or_interface_type_2316","Global type '{0}' must be a class or interface type."),Global_type_0_must_have_1_type_parameter_s:t(2317,e.DiagnosticCategory.Error,"Global_type_0_must_have_1_type_parameter_s_2317","Global type '{0}' must have {1} type parameter(s)."),Cannot_find_global_type_0:t(2318,e.DiagnosticCategory.Error,"Cannot_find_global_type_0_2318","Cannot find global type '{0}'."),Named_property_0_of_types_1_and_2_are_not_identical:t(2319,e.DiagnosticCategory.Error,"Named_property_0_of_types_1_and_2_are_not_identical_2319","Named property '{0}' of types '{1}' and '{2}' are not identical."),Interface_0_cannot_simultaneously_extend_types_1_and_2:t(2320,e.DiagnosticCategory.Error,"Interface_0_cannot_simultaneously_extend_types_1_and_2_2320","Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."),Excessive_stack_depth_comparing_types_0_and_1:t(2321,e.DiagnosticCategory.Error,"Excessive_stack_depth_comparing_types_0_and_1_2321","Excessive stack depth comparing types '{0}' and '{1}'."),Type_0_is_not_assignable_to_type_1:t(2322,e.DiagnosticCategory.Error,"Type_0_is_not_assignable_to_type_1_2322","Type '{0}' is not assignable to type '{1}'."),Cannot_redeclare_exported_variable_0:t(2323,e.DiagnosticCategory.Error,"Cannot_redeclare_exported_variable_0_2323","Cannot redeclare exported variable '{0}'."),Property_0_is_missing_in_type_1:t(2324,e.DiagnosticCategory.Error,"Property_0_is_missing_in_type_1_2324","Property '{0}' is missing in type '{1}'."),Property_0_is_private_in_type_1_but_not_in_type_2:t(2325,e.DiagnosticCategory.Error,"Property_0_is_private_in_type_1_but_not_in_type_2_2325","Property '{0}' is private in type '{1}' but not in type '{2}'."),Types_of_property_0_are_incompatible:t(2326,e.DiagnosticCategory.Error,"Types_of_property_0_are_incompatible_2326","Types of property '{0}' are incompatible."),Property_0_is_optional_in_type_1_but_required_in_type_2:t(2327,e.DiagnosticCategory.Error,"Property_0_is_optional_in_type_1_but_required_in_type_2_2327","Property '{0}' is optional in type '{1}' but required in type '{2}'."),Types_of_parameters_0_and_1_are_incompatible:t(2328,e.DiagnosticCategory.Error,"Types_of_parameters_0_and_1_are_incompatible_2328","Types of parameters '{0}' and '{1}' are incompatible."),Index_signature_is_missing_in_type_0:t(2329,e.DiagnosticCategory.Error,"Index_signature_is_missing_in_type_0_2329","Index signature is missing in type '{0}'."),Index_signatures_are_incompatible:t(2330,e.DiagnosticCategory.Error,"Index_signatures_are_incompatible_2330","Index signatures are incompatible."),this_cannot_be_referenced_in_a_module_or_namespace_body:t(2331,e.DiagnosticCategory.Error,"this_cannot_be_referenced_in_a_module_or_namespace_body_2331","'this' cannot be referenced in a module or namespace body."),this_cannot_be_referenced_in_current_location:t(2332,e.DiagnosticCategory.Error,"this_cannot_be_referenced_in_current_location_2332","'this' cannot be referenced in current location."),this_cannot_be_referenced_in_constructor_arguments:t(2333,e.DiagnosticCategory.Error,"this_cannot_be_referenced_in_constructor_arguments_2333","'this' cannot be referenced in constructor arguments."),this_cannot_be_referenced_in_a_static_property_initializer:t(2334,e.DiagnosticCategory.Error,"this_cannot_be_referenced_in_a_static_property_initializer_2334","'this' cannot be referenced in a static property initializer."),super_can_only_be_referenced_in_a_derived_class:t(2335,e.DiagnosticCategory.Error,"super_can_only_be_referenced_in_a_derived_class_2335","'super' can only be referenced in a derived class."),super_cannot_be_referenced_in_constructor_arguments:t(2336,e.DiagnosticCategory.Error,"super_cannot_be_referenced_in_constructor_arguments_2336","'super' cannot be referenced in constructor arguments."),Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors:t(2337,e.DiagnosticCategory.Error,"Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337","Super calls are not permitted outside constructors or in nested functions inside constructors."),super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class:t(2338,e.DiagnosticCategory.Error,"super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338","'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."),Property_0_does_not_exist_on_type_1:t(2339,e.DiagnosticCategory.Error,"Property_0_does_not_exist_on_type_1_2339","Property '{0}' does not exist on type '{1}'."),Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword:t(2340,e.DiagnosticCategory.Error,"Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340","Only public and protected methods of the base class are accessible via the 'super' keyword."),Property_0_is_private_and_only_accessible_within_class_1:t(2341,e.DiagnosticCategory.Error,"Property_0_is_private_and_only_accessible_within_class_1_2341","Property '{0}' is private and only accessible within class '{1}'."),An_index_expression_argument_must_be_of_type_string_number_symbol_or_any:t(2342,e.DiagnosticCategory.Error,"An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342","An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."),This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1:t(2343,e.DiagnosticCategory.Error,"This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343","This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."),Type_0_does_not_satisfy_the_constraint_1:t(2344,e.DiagnosticCategory.Error,"Type_0_does_not_satisfy_the_constraint_1_2344","Type '{0}' does not satisfy the constraint '{1}'."),Argument_of_type_0_is_not_assignable_to_parameter_of_type_1:t(2345,e.DiagnosticCategory.Error,"Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345","Argument of type '{0}' is not assignable to parameter of type '{1}'."),Call_target_does_not_contain_any_signatures:t(2346,e.DiagnosticCategory.Error,"Call_target_does_not_contain_any_signatures_2346","Call target does not contain any signatures."),Untyped_function_calls_may_not_accept_type_arguments:t(2347,e.DiagnosticCategory.Error,"Untyped_function_calls_may_not_accept_type_arguments_2347","Untyped function calls may not accept type arguments."),Value_of_type_0_is_not_callable_Did_you_mean_to_include_new:t(2348,e.DiagnosticCategory.Error,"Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348","Value of type '{0}' is not callable. Did you mean to include 'new'?"),Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures:t(2349,e.DiagnosticCategory.Error,"Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349","Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."),Only_a_void_function_can_be_called_with_the_new_keyword:t(2350,e.DiagnosticCategory.Error,"Only_a_void_function_can_be_called_with_the_new_keyword_2350","Only a void function can be called with the 'new' keyword."),Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature:t(2351,e.DiagnosticCategory.Error,"Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351","Cannot use 'new' with an expression whose type lacks a call or construct signature."),Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first:t(2352,e.DiagnosticCategory.Error,"Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the__2352","Conversion of type '{0}' to type '{1}' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first."),Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1:t(2353,e.DiagnosticCategory.Error,"Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353","Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."),This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found:t(2354,e.DiagnosticCategory.Error,"This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354","This syntax requires an imported helper but module '{0}' cannot be found."),A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value:t(2355,e.DiagnosticCategory.Error,"A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355","A function whose declared type is neither 'void' nor 'any' must return a value."),An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type:t(2356,e.DiagnosticCategory.Error,"An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type_2356","An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type."),The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access:t(2357,e.DiagnosticCategory.Error,"The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357","The operand of an increment or decrement operator must be a variable or a property access."),The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter:t(2358,e.DiagnosticCategory.Error,"The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358","The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."),The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type:t(2359,e.DiagnosticCategory.Error,"The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359","The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."),The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol:t(2360,e.DiagnosticCategory.Error,"The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360","The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."),The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter:t(2361,e.DiagnosticCategory.Error,"The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361","The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."),The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type:t(2362,e.DiagnosticCategory.Error,"The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2362","The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."),The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type:t(2363,e.DiagnosticCategory.Error,"The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type_2363","The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."),The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access:t(2364,e.DiagnosticCategory.Error,"The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364","The left-hand side of an assignment expression must be a variable or a property access."),Operator_0_cannot_be_applied_to_types_1_and_2:t(2365,e.DiagnosticCategory.Error,"Operator_0_cannot_be_applied_to_types_1_and_2_2365","Operator '{0}' cannot be applied to types '{1}' and '{2}'."),Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined:t(2366,e.DiagnosticCategory.Error,"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366","Function lacks ending return statement and return type does not include 'undefined'."),This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap:t(2367,e.DiagnosticCategory.Error,"This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367","This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."),Type_parameter_name_cannot_be_0:t(2368,e.DiagnosticCategory.Error,"Type_parameter_name_cannot_be_0_2368","Type parameter name cannot be '{0}'."),A_parameter_property_is_only_allowed_in_a_constructor_implementation:t(2369,e.DiagnosticCategory.Error,"A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369","A parameter property is only allowed in a constructor implementation."),A_rest_parameter_must_be_of_an_array_type:t(2370,e.DiagnosticCategory.Error,"A_rest_parameter_must_be_of_an_array_type_2370","A rest parameter must be of an array type."),A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation:t(2371,e.DiagnosticCategory.Error,"A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371","A parameter initializer is only allowed in a function or constructor implementation."),Parameter_0_cannot_be_referenced_in_its_initializer:t(2372,e.DiagnosticCategory.Error,"Parameter_0_cannot_be_referenced_in_its_initializer_2372","Parameter '{0}' cannot be referenced in its initializer."),Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it:t(2373,e.DiagnosticCategory.Error,"Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373","Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."),Duplicate_string_index_signature:t(2374,e.DiagnosticCategory.Error,"Duplicate_string_index_signature_2374","Duplicate string index signature."),Duplicate_number_index_signature:t(2375,e.DiagnosticCategory.Error,"Duplicate_number_index_signature_2375","Duplicate number index signature."),A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties:t(2376,e.DiagnosticCategory.Error,"A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376","A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."),Constructors_for_derived_classes_must_contain_a_super_call:t(2377,e.DiagnosticCategory.Error,"Constructors_for_derived_classes_must_contain_a_super_call_2377","Constructors for derived classes must contain a 'super' call."),A_get_accessor_must_return_a_value:t(2378,e.DiagnosticCategory.Error,"A_get_accessor_must_return_a_value_2378","A 'get' accessor must return a value."),Getter_and_setter_accessors_do_not_agree_in_visibility:t(2379,e.DiagnosticCategory.Error,"Getter_and_setter_accessors_do_not_agree_in_visibility_2379","Getter and setter accessors do not agree in visibility."),get_and_set_accessor_must_have_the_same_type:t(2380,e.DiagnosticCategory.Error,"get_and_set_accessor_must_have_the_same_type_2380","'get' and 'set' accessor must have the same type."),A_signature_with_an_implementation_cannot_use_a_string_literal_type:t(2381,e.DiagnosticCategory.Error,"A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381","A signature with an implementation cannot use a string literal type."),Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature:t(2382,e.DiagnosticCategory.Error,"Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382","Specialized overload signature is not assignable to any non-specialized signature."),Overload_signatures_must_all_be_exported_or_non_exported:t(2383,e.DiagnosticCategory.Error,"Overload_signatures_must_all_be_exported_or_non_exported_2383","Overload signatures must all be exported or non-exported."),Overload_signatures_must_all_be_ambient_or_non_ambient:t(2384,e.DiagnosticCategory.Error,"Overload_signatures_must_all_be_ambient_or_non_ambient_2384","Overload signatures must all be ambient or non-ambient."),Overload_signatures_must_all_be_public_private_or_protected:t(2385,e.DiagnosticCategory.Error,"Overload_signatures_must_all_be_public_private_or_protected_2385","Overload signatures must all be public, private or protected."),Overload_signatures_must_all_be_optional_or_required:t(2386,e.DiagnosticCategory.Error,"Overload_signatures_must_all_be_optional_or_required_2386","Overload signatures must all be optional or required."),Function_overload_must_be_static:t(2387,e.DiagnosticCategory.Error,"Function_overload_must_be_static_2387","Function overload must be static."),Function_overload_must_not_be_static:t(2388,e.DiagnosticCategory.Error,"Function_overload_must_not_be_static_2388","Function overload must not be static."),Function_implementation_name_must_be_0:t(2389,e.DiagnosticCategory.Error,"Function_implementation_name_must_be_0_2389","Function implementation name must be '{0}'."),Constructor_implementation_is_missing:t(2390,e.DiagnosticCategory.Error,"Constructor_implementation_is_missing_2390","Constructor implementation is missing."),Function_implementation_is_missing_or_not_immediately_following_the_declaration:t(2391,e.DiagnosticCategory.Error,"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391","Function implementation is missing or not immediately following the declaration."),Multiple_constructor_implementations_are_not_allowed:t(2392,e.DiagnosticCategory.Error,"Multiple_constructor_implementations_are_not_allowed_2392","Multiple constructor implementations are not allowed."),Duplicate_function_implementation:t(2393,e.DiagnosticCategory.Error,"Duplicate_function_implementation_2393","Duplicate function implementation."),Overload_signature_is_not_compatible_with_function_implementation:t(2394,e.DiagnosticCategory.Error,"Overload_signature_is_not_compatible_with_function_implementation_2394","Overload signature is not compatible with function implementation."),Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local:t(2395,e.DiagnosticCategory.Error,"Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395","Individual declarations in merged declaration '{0}' must be all exported or all local."),Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters:t(2396,e.DiagnosticCategory.Error,"Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396","Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."),Declaration_name_conflicts_with_built_in_global_identifier_0:t(2397,e.DiagnosticCategory.Error,"Declaration_name_conflicts_with_built_in_global_identifier_0_2397","Declaration name conflicts with built-in global identifier '{0}'."),Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference:t(2399,e.DiagnosticCategory.Error,"Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399","Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."),Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference:t(2400,e.DiagnosticCategory.Error,"Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400","Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."),Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference:t(2401,e.DiagnosticCategory.Error,"Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401","Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."),Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference:t(2402,e.DiagnosticCategory.Error,"Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402","Expression resolves to '_super' that compiler uses to capture base class reference."),Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2:t(2403,e.DiagnosticCategory.Error,"Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403","Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."),The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation:t(2404,e.DiagnosticCategory.Error,"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404","The left-hand side of a 'for...in' statement cannot use a type annotation."),The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any:t(2405,e.DiagnosticCategory.Error,"The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405","The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."),The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access:t(2406,e.DiagnosticCategory.Error,"The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406","The left-hand side of a 'for...in' statement must be a variable or a property access."),The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0:t(2407,e.DiagnosticCategory.Error,"The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407","The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."),Setters_cannot_return_a_value:t(2408,e.DiagnosticCategory.Error,"Setters_cannot_return_a_value_2408","Setters cannot return a value."),Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class:t(2409,e.DiagnosticCategory.Error,"Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409","Return type of constructor signature must be assignable to the instance type of the class."),The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any:t(2410,e.DiagnosticCategory.Error,"The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410","The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."),Property_0_of_type_1_is_not_assignable_to_string_index_type_2:t(2411,e.DiagnosticCategory.Error,"Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411","Property '{0}' of type '{1}' is not assignable to string index type '{2}'."),Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2:t(2412,e.DiagnosticCategory.Error,"Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412","Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."),Numeric_index_type_0_is_not_assignable_to_string_index_type_1:t(2413,e.DiagnosticCategory.Error,"Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413","Numeric index type '{0}' is not assignable to string index type '{1}'."),Class_name_cannot_be_0:t(2414,e.DiagnosticCategory.Error,"Class_name_cannot_be_0_2414","Class name cannot be '{0}'."),Class_0_incorrectly_extends_base_class_1:t(2415,e.DiagnosticCategory.Error,"Class_0_incorrectly_extends_base_class_1_2415","Class '{0}' incorrectly extends base class '{1}'."),Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2:t(2416,e.DiagnosticCategory.Error,"Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416","Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."),Class_static_side_0_incorrectly_extends_base_class_static_side_1:t(2417,e.DiagnosticCategory.Error,"Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417","Class static side '{0}' incorrectly extends base class static side '{1}'."),Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1:t(2418,e.DiagnosticCategory.Error,"Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418","Type of computed property's value is '{0}', which is not assignable to type '{1}'."),Class_0_incorrectly_implements_interface_1:t(2420,e.DiagnosticCategory.Error,"Class_0_incorrectly_implements_interface_1_2420","Class '{0}' incorrectly implements interface '{1}'."),A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members:t(2422,e.DiagnosticCategory.Error,"A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422","A class can only implement an object type or intersection of object types with statically known members."),Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor:t(2423,e.DiagnosticCategory.Error,"Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423","Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."),Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property:t(2424,e.DiagnosticCategory.Error,"Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424","Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."),Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function:t(2425,e.DiagnosticCategory.Error,"Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425","Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."),Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function:t(2426,e.DiagnosticCategory.Error,"Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426","Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."),Interface_name_cannot_be_0:t(2427,e.DiagnosticCategory.Error,"Interface_name_cannot_be_0_2427","Interface name cannot be '{0}'."),All_declarations_of_0_must_have_identical_type_parameters:t(2428,e.DiagnosticCategory.Error,"All_declarations_of_0_must_have_identical_type_parameters_2428","All declarations of '{0}' must have identical type parameters."),Interface_0_incorrectly_extends_interface_1:t(2430,e.DiagnosticCategory.Error,"Interface_0_incorrectly_extends_interface_1_2430","Interface '{0}' incorrectly extends interface '{1}'."),Enum_name_cannot_be_0:t(2431,e.DiagnosticCategory.Error,"Enum_name_cannot_be_0_2431","Enum name cannot be '{0}'."),In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element:t(2432,e.DiagnosticCategory.Error,"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432","In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."),A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged:t(2433,e.DiagnosticCategory.Error,"A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433","A namespace declaration cannot be in a different file from a class or function with which it is merged."),A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged:t(2434,e.DiagnosticCategory.Error,"A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434","A namespace declaration cannot be located prior to a class or function with which it is merged."),Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces:t(2435,e.DiagnosticCategory.Error,"Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435","Ambient modules cannot be nested in other modules or namespaces."),Ambient_module_declaration_cannot_specify_relative_module_name:t(2436,e.DiagnosticCategory.Error,"Ambient_module_declaration_cannot_specify_relative_module_name_2436","Ambient module declaration cannot specify relative module name."),Module_0_is_hidden_by_a_local_declaration_with_the_same_name:t(2437,e.DiagnosticCategory.Error,"Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437","Module '{0}' is hidden by a local declaration with the same name."),Import_name_cannot_be_0:t(2438,e.DiagnosticCategory.Error,"Import_name_cannot_be_0_2438","Import name cannot be '{0}'."),Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name:t(2439,e.DiagnosticCategory.Error,"Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439","Import or export declaration in an ambient module declaration cannot reference module through relative module name."),Import_declaration_conflicts_with_local_declaration_of_0:t(2440,e.DiagnosticCategory.Error,"Import_declaration_conflicts_with_local_declaration_of_0_2440","Import declaration conflicts with local declaration of '{0}'."),Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module:t(2441,e.DiagnosticCategory.Error,"Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441","Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."),Types_have_separate_declarations_of_a_private_property_0:t(2442,e.DiagnosticCategory.Error,"Types_have_separate_declarations_of_a_private_property_0_2442","Types have separate declarations of a private property '{0}'."),Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2:t(2443,e.DiagnosticCategory.Error,"Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443","Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."),Property_0_is_protected_in_type_1_but_public_in_type_2:t(2444,e.DiagnosticCategory.Error,"Property_0_is_protected_in_type_1_but_public_in_type_2_2444","Property '{0}' is protected in type '{1}' but public in type '{2}'."),Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses:t(2445,e.DiagnosticCategory.Error,"Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445","Property '{0}' is protected and only accessible within class '{1}' and its subclasses."),Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1:t(2446,e.DiagnosticCategory.Error,"Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446","Property '{0}' is protected and only accessible through an instance of class '{1}'."),The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead:t(2447,e.DiagnosticCategory.Error,"The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447","The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."),Block_scoped_variable_0_used_before_its_declaration:t(2448,e.DiagnosticCategory.Error,"Block_scoped_variable_0_used_before_its_declaration_2448","Block-scoped variable '{0}' used before its declaration."),Class_0_used_before_its_declaration:t(2449,e.DiagnosticCategory.Error,"Class_0_used_before_its_declaration_2449","Class '{0}' used before its declaration."),Enum_0_used_before_its_declaration:t(2450,e.DiagnosticCategory.Error,"Enum_0_used_before_its_declaration_2450","Enum '{0}' used before its declaration."),Cannot_redeclare_block_scoped_variable_0:t(2451,e.DiagnosticCategory.Error,"Cannot_redeclare_block_scoped_variable_0_2451","Cannot redeclare block-scoped variable '{0}'."),An_enum_member_cannot_have_a_numeric_name:t(2452,e.DiagnosticCategory.Error,"An_enum_member_cannot_have_a_numeric_name_2452","An enum member cannot have a numeric name."),The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly:t(2453,e.DiagnosticCategory.Error,"The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453","The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."),Variable_0_is_used_before_being_assigned:t(2454,e.DiagnosticCategory.Error,"Variable_0_is_used_before_being_assigned_2454","Variable '{0}' is used before being assigned."),Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0:t(2455,e.DiagnosticCategory.Error,"Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455","Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."),Type_alias_0_circularly_references_itself:t(2456,e.DiagnosticCategory.Error,"Type_alias_0_circularly_references_itself_2456","Type alias '{0}' circularly references itself."),Type_alias_name_cannot_be_0:t(2457,e.DiagnosticCategory.Error,"Type_alias_name_cannot_be_0_2457","Type alias name cannot be '{0}'."),An_AMD_module_cannot_have_multiple_name_assignments:t(2458,e.DiagnosticCategory.Error,"An_AMD_module_cannot_have_multiple_name_assignments_2458","An AMD module cannot have multiple name assignments."),Type_0_has_no_property_1_and_no_string_index_signature:t(2459,e.DiagnosticCategory.Error,"Type_0_has_no_property_1_and_no_string_index_signature_2459","Type '{0}' has no property '{1}' and no string index signature."),Type_0_has_no_property_1:t(2460,e.DiagnosticCategory.Error,"Type_0_has_no_property_1_2460","Type '{0}' has no property '{1}'."),Type_0_is_not_an_array_type:t(2461,e.DiagnosticCategory.Error,"Type_0_is_not_an_array_type_2461","Type '{0}' is not an array type."),A_rest_element_must_be_last_in_a_destructuring_pattern:t(2462,e.DiagnosticCategory.Error,"A_rest_element_must_be_last_in_a_destructuring_pattern_2462","A rest element must be last in a destructuring pattern."),A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature:t(2463,e.DiagnosticCategory.Error,"A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463","A binding pattern parameter cannot be optional in an implementation signature."),A_computed_property_name_must_be_of_type_string_number_symbol_or_any:t(2464,e.DiagnosticCategory.Error,"A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464","A computed property name must be of type 'string', 'number', 'symbol', or 'any'."),this_cannot_be_referenced_in_a_computed_property_name:t(2465,e.DiagnosticCategory.Error,"this_cannot_be_referenced_in_a_computed_property_name_2465","'this' cannot be referenced in a computed property name."),super_cannot_be_referenced_in_a_computed_property_name:t(2466,e.DiagnosticCategory.Error,"super_cannot_be_referenced_in_a_computed_property_name_2466","'super' cannot be referenced in a computed property name."),A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type:t(2467,e.DiagnosticCategory.Error,"A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467","A computed property name cannot reference a type parameter from its containing type."),Cannot_find_global_value_0:t(2468,e.DiagnosticCategory.Error,"Cannot_find_global_value_0_2468","Cannot find global value '{0}'."),The_0_operator_cannot_be_applied_to_type_symbol:t(2469,e.DiagnosticCategory.Error,"The_0_operator_cannot_be_applied_to_type_symbol_2469","The '{0}' operator cannot be applied to type 'symbol'."),Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object:t(2470,e.DiagnosticCategory.Error,"Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470","'Symbol' reference does not refer to the global Symbol constructor object."),A_computed_property_name_of_the_form_0_must_be_of_type_symbol:t(2471,e.DiagnosticCategory.Error,"A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471","A computed property name of the form '{0}' must be of type 'symbol'."),Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher:t(2472,e.DiagnosticCategory.Error,"Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472","Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."),Enum_declarations_must_all_be_const_or_non_const:t(2473,e.DiagnosticCategory.Error,"Enum_declarations_must_all_be_const_or_non_const_2473","Enum declarations must all be const or non-const."),In_const_enum_declarations_member_initializer_must_be_constant_expression:t(2474,e.DiagnosticCategory.Error,"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474","In 'const' enum declarations member initializer must be constant expression."),const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query:t(2475,e.DiagnosticCategory.Error,"const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475","'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."),A_const_enum_member_can_only_be_accessed_using_a_string_literal:t(2476,e.DiagnosticCategory.Error,"A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476","A const enum member can only be accessed using a string literal."),const_enum_member_initializer_was_evaluated_to_a_non_finite_value:t(2477,e.DiagnosticCategory.Error,"const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477","'const' enum member initializer was evaluated to a non-finite value."),const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN:t(2478,e.DiagnosticCategory.Error,"const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478","'const' enum member initializer was evaluated to disallowed value 'NaN'."),Property_0_does_not_exist_on_const_enum_1:t(2479,e.DiagnosticCategory.Error,"Property_0_does_not_exist_on_const_enum_1_2479","Property '{0}' does not exist on 'const' enum '{1}'."),let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations:t(2480,e.DiagnosticCategory.Error,"let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480","'let' is not allowed to be used as a name in 'let' or 'const' declarations."),Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1:t(2481,e.DiagnosticCategory.Error,"Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481","Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."),The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation:t(2483,e.DiagnosticCategory.Error,"The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483","The left-hand side of a 'for...of' statement cannot use a type annotation."),Export_declaration_conflicts_with_exported_declaration_of_0:t(2484,e.DiagnosticCategory.Error,"Export_declaration_conflicts_with_exported_declaration_of_0_2484","Export declaration conflicts with exported declaration of '{0}'."),The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access:t(2487,e.DiagnosticCategory.Error,"The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487","The left-hand side of a 'for...of' statement must be a variable or a property access."),Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator:t(2488,e.DiagnosticCategory.Error,"Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488","Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."),An_iterator_must_have_a_next_method:t(2489,e.DiagnosticCategory.Error,"An_iterator_must_have_a_next_method_2489","An iterator must have a 'next()' method."),The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property:t(2490,e.DiagnosticCategory.Error,"The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490","The type returned by the 'next()' method of an iterator must have a 'value' property."),The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern:t(2491,e.DiagnosticCategory.Error,"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491","The left-hand side of a 'for...in' statement cannot be a destructuring pattern."),Cannot_redeclare_identifier_0_in_catch_clause:t(2492,e.DiagnosticCategory.Error,"Cannot_redeclare_identifier_0_in_catch_clause_2492","Cannot redeclare identifier '{0}' in catch clause."),Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2:t(2493,e.DiagnosticCategory.Error,"Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493","Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."),Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher:t(2494,e.DiagnosticCategory.Error,"Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494","Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."),Type_0_is_not_an_array_type_or_a_string_type:t(2495,e.DiagnosticCategory.Error,"Type_0_is_not_an_array_type_or_a_string_type_2495","Type '{0}' is not an array type or a string type."),The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression:t(2496,e.DiagnosticCategory.Error,"The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496","The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."),Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct:t(2497,e.DiagnosticCategory.Error,"Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497","Module '{0}' resolves to a non-module entity and cannot be imported using this construct."),Module_0_uses_export_and_cannot_be_used_with_export_Asterisk:t(2498,e.DiagnosticCategory.Error,"Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498","Module '{0}' uses 'export =' and cannot be used with 'export *'."),An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments:t(2499,e.DiagnosticCategory.Error,"An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499","An interface can only extend an identifier/qualified-name with optional type arguments."),A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments:t(2500,e.DiagnosticCategory.Error,"A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500","A class can only implement an identifier/qualified-name with optional type arguments."),A_rest_element_cannot_contain_a_binding_pattern:t(2501,e.DiagnosticCategory.Error,"A_rest_element_cannot_contain_a_binding_pattern_2501","A rest element cannot contain a binding pattern."),_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation:t(2502,e.DiagnosticCategory.Error,"_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502","'{0}' is referenced directly or indirectly in its own type annotation."),Cannot_find_namespace_0:t(2503,e.DiagnosticCategory.Error,"Cannot_find_namespace_0_2503","Cannot find namespace '{0}'."),Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator:t(2504,e.DiagnosticCategory.Error,"Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504","Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."),A_generator_cannot_have_a_void_type_annotation:t(2505,e.DiagnosticCategory.Error,"A_generator_cannot_have_a_void_type_annotation_2505","A generator cannot have a 'void' type annotation."),_0_is_referenced_directly_or_indirectly_in_its_own_base_expression:t(2506,e.DiagnosticCategory.Error,"_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506","'{0}' is referenced directly or indirectly in its own base expression."),Type_0_is_not_a_constructor_function_type:t(2507,e.DiagnosticCategory.Error,"Type_0_is_not_a_constructor_function_type_2507","Type '{0}' is not a constructor function type."),No_base_constructor_has_the_specified_number_of_type_arguments:t(2508,e.DiagnosticCategory.Error,"No_base_constructor_has_the_specified_number_of_type_arguments_2508","No base constructor has the specified number of type arguments."),Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members:t(2509,e.DiagnosticCategory.Error,"Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_2509","Base constructor return type '{0}' is not an object type or intersection of object types with statically known members."),Base_constructors_must_all_have_the_same_return_type:t(2510,e.DiagnosticCategory.Error,"Base_constructors_must_all_have_the_same_return_type_2510","Base constructors must all have the same return type."),Cannot_create_an_instance_of_an_abstract_class:t(2511,e.DiagnosticCategory.Error,"Cannot_create_an_instance_of_an_abstract_class_2511","Cannot create an instance of an abstract class."),Overload_signatures_must_all_be_abstract_or_non_abstract:t(2512,e.DiagnosticCategory.Error,"Overload_signatures_must_all_be_abstract_or_non_abstract_2512","Overload signatures must all be abstract or non-abstract."),Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression:t(2513,e.DiagnosticCategory.Error,"Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513","Abstract method '{0}' in class '{1}' cannot be accessed via super expression."),Classes_containing_abstract_methods_must_be_marked_abstract:t(2514,e.DiagnosticCategory.Error,"Classes_containing_abstract_methods_must_be_marked_abstract_2514","Classes containing abstract methods must be marked abstract."),Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2:t(2515,e.DiagnosticCategory.Error,"Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515","Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."),All_declarations_of_an_abstract_method_must_be_consecutive:t(2516,e.DiagnosticCategory.Error,"All_declarations_of_an_abstract_method_must_be_consecutive_2516","All declarations of an abstract method must be consecutive."),Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type:t(2517,e.DiagnosticCategory.Error,"Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517","Cannot assign an abstract constructor type to a non-abstract constructor type."),A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard:t(2518,e.DiagnosticCategory.Error,"A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518","A 'this'-based type guard is not compatible with a parameter-based type guard."),An_async_iterator_must_have_a_next_method:t(2519,e.DiagnosticCategory.Error,"An_async_iterator_must_have_a_next_method_2519","An async iterator must have a 'next()' method."),Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions:t(2520,e.DiagnosticCategory.Error,"Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520","Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."),Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions:t(2521,e.DiagnosticCategory.Error,"Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521","Expression resolves to variable declaration '{0}' that compiler uses to support async functions."),The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method:t(2522,e.DiagnosticCategory.Error,"The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522","The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."),yield_expressions_cannot_be_used_in_a_parameter_initializer:t(2523,e.DiagnosticCategory.Error,"yield_expressions_cannot_be_used_in_a_parameter_initializer_2523","'yield' expressions cannot be used in a parameter initializer."),await_expressions_cannot_be_used_in_a_parameter_initializer:t(2524,e.DiagnosticCategory.Error,"await_expressions_cannot_be_used_in_a_parameter_initializer_2524","'await' expressions cannot be used in a parameter initializer."),Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value:t(2525,e.DiagnosticCategory.Error,"Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525","Initializer provides no value for this binding element and the binding element has no default value."),A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface:t(2526,e.DiagnosticCategory.Error,"A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526","A 'this' type is available only in a non-static member of a class or interface."),The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary:t(2527,e.DiagnosticCategory.Error,"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527","The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."),A_module_cannot_have_multiple_default_exports:t(2528,e.DiagnosticCategory.Error,"A_module_cannot_have_multiple_default_exports_2528","A module cannot have multiple default exports."),Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions:t(2529,e.DiagnosticCategory.Error,"Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529","Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."),Property_0_is_incompatible_with_index_signature:t(2530,e.DiagnosticCategory.Error,"Property_0_is_incompatible_with_index_signature_2530","Property '{0}' is incompatible with index signature."),Object_is_possibly_null:t(2531,e.DiagnosticCategory.Error,"Object_is_possibly_null_2531","Object is possibly 'null'."),Object_is_possibly_undefined:t(2532,e.DiagnosticCategory.Error,"Object_is_possibly_undefined_2532","Object is possibly 'undefined'."),Object_is_possibly_null_or_undefined:t(2533,e.DiagnosticCategory.Error,"Object_is_possibly_null_or_undefined_2533","Object is possibly 'null' or 'undefined'."),A_function_returning_never_cannot_have_a_reachable_end_point:t(2534,e.DiagnosticCategory.Error,"A_function_returning_never_cannot_have_a_reachable_end_point_2534","A function returning 'never' cannot have a reachable end point."),Enum_type_0_has_members_with_initializers_that_are_not_literals:t(2535,e.DiagnosticCategory.Error,"Enum_type_0_has_members_with_initializers_that_are_not_literals_2535","Enum type '{0}' has members with initializers that are not literals."),Type_0_cannot_be_used_to_index_type_1:t(2536,e.DiagnosticCategory.Error,"Type_0_cannot_be_used_to_index_type_1_2536","Type '{0}' cannot be used to index type '{1}'."),Type_0_has_no_matching_index_signature_for_type_1:t(2537,e.DiagnosticCategory.Error,"Type_0_has_no_matching_index_signature_for_type_1_2537","Type '{0}' has no matching index signature for type '{1}'."),Type_0_cannot_be_used_as_an_index_type:t(2538,e.DiagnosticCategory.Error,"Type_0_cannot_be_used_as_an_index_type_2538","Type '{0}' cannot be used as an index type."),Cannot_assign_to_0_because_it_is_not_a_variable:t(2539,e.DiagnosticCategory.Error,"Cannot_assign_to_0_because_it_is_not_a_variable_2539","Cannot assign to '{0}' because it is not a variable."),Cannot_assign_to_0_because_it_is_a_read_only_property:t(2540,e.DiagnosticCategory.Error,"Cannot_assign_to_0_because_it_is_a_read_only_property_2540","Cannot assign to '{0}' because it is a read-only property."),The_target_of_an_assignment_must_be_a_variable_or_a_property_access:t(2541,e.DiagnosticCategory.Error,"The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541","The target of an assignment must be a variable or a property access."),Index_signature_in_type_0_only_permits_reading:t(2542,e.DiagnosticCategory.Error,"Index_signature_in_type_0_only_permits_reading_2542","Index signature in type '{0}' only permits reading."),Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference:t(2543,e.DiagnosticCategory.Error,"Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543","Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."),Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference:t(2544,e.DiagnosticCategory.Error,"Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544","Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."),A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any:t(2545,e.DiagnosticCategory.Error,"A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545","A mixin class must have a constructor with a single rest parameter of type 'any[]'."),Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1:t(2546,e.DiagnosticCategory.Error,"Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546","Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."),The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property:t(2547,e.DiagnosticCategory.Error,"The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547","The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."),Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator:t(2548,e.DiagnosticCategory.Error,"Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548","Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."),Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator:t(2549,e.DiagnosticCategory.Error,"Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549","Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."),Property_0_does_not_exist_on_type_1_Did_you_mean_2:t(2551,e.DiagnosticCategory.Error,"Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551","Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"),Cannot_find_name_0_Did_you_mean_1:t(2552,e.DiagnosticCategory.Error,"Cannot_find_name_0_Did_you_mean_1_2552","Cannot find name '{0}'. Did you mean '{1}'?"),Computed_values_are_not_permitted_in_an_enum_with_string_valued_members:t(2553,e.DiagnosticCategory.Error,"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553","Computed values are not permitted in an enum with string valued members."),Expected_0_arguments_but_got_1:t(2554,e.DiagnosticCategory.Error,"Expected_0_arguments_but_got_1_2554","Expected {0} arguments, but got {1}."),Expected_at_least_0_arguments_but_got_1:t(2555,e.DiagnosticCategory.Error,"Expected_at_least_0_arguments_but_got_1_2555","Expected at least {0} arguments, but got {1}."),Expected_0_arguments_but_got_1_or_more:t(2556,e.DiagnosticCategory.Error,"Expected_0_arguments_but_got_1_or_more_2556","Expected {0} arguments, but got {1} or more."),Expected_at_least_0_arguments_but_got_1_or_more:t(2557,e.DiagnosticCategory.Error,"Expected_at_least_0_arguments_but_got_1_or_more_2557","Expected at least {0} arguments, but got {1} or more."),Expected_0_type_arguments_but_got_1:t(2558,e.DiagnosticCategory.Error,"Expected_0_type_arguments_but_got_1_2558","Expected {0} type arguments, but got {1}."),Type_0_has_no_properties_in_common_with_type_1:t(2559,e.DiagnosticCategory.Error,"Type_0_has_no_properties_in_common_with_type_1_2559","Type '{0}' has no properties in common with type '{1}'."),Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it:t(2560,e.DiagnosticCategory.Error,"Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560","Value of type '{0}' has no properties in common with type '{1}'. Did you mean to call it?"),Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2:t(2561,e.DiagnosticCategory.Error,"Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_writ_2561","Object literal may only specify known properties, but '{0}' does not exist in type '{1}'. Did you mean to write '{2}'?"),Base_class_expressions_cannot_reference_class_type_parameters:t(2562,e.DiagnosticCategory.Error,"Base_class_expressions_cannot_reference_class_type_parameters_2562","Base class expressions cannot reference class type parameters."),The_containing_function_or_module_body_is_too_large_for_control_flow_analysis:t(2563,e.DiagnosticCategory.Error,"The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563","The containing function or module body is too large for control flow analysis."),Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor:t(2564,e.DiagnosticCategory.Error,"Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564","Property '{0}' has no initializer and is not definitely assigned in the constructor."),Property_0_is_used_before_being_assigned:t(2565,e.DiagnosticCategory.Error,"Property_0_is_used_before_being_assigned_2565","Property '{0}' is used before being assigned."),A_rest_element_cannot_have_a_property_name:t(2566,e.DiagnosticCategory.Error,"A_rest_element_cannot_have_a_property_name_2566","A rest element cannot have a property name."),Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations:t(2567,e.DiagnosticCategory.Error,"Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567","Enum declarations can only merge with namespace or other enum declarations."),Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators:t(2568,e.DiagnosticCategory.Error,"Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568","Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators."),Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators:t(2569,e.DiagnosticCategory.Error,"Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569","Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."),Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await:t(2570,e.DiagnosticCategory.Error,"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570","Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"),Object_is_of_type_unknown:t(2571,e.DiagnosticCategory.Error,"Object_is_of_type_unknown_2571","Object is of type 'unknown'."),Rest_signatures_are_incompatible:t(2572,e.DiagnosticCategory.Error,"Rest_signatures_are_incompatible_2572","Rest signatures are incompatible."),Property_0_is_incompatible_with_rest_element_type:t(2573,e.DiagnosticCategory.Error,"Property_0_is_incompatible_with_rest_element_type_2573","Property '{0}' is incompatible with rest element type."),A_rest_element_type_must_be_an_array_type:t(2574,e.DiagnosticCategory.Error,"A_rest_element_type_must_be_an_array_type_2574","A rest element type must be an array type."),No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments:t(2575,e.DiagnosticCategory.Error,"No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575","No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."),Property_0_is_a_static_member_of_type_1:t(2576,e.DiagnosticCategory.Error,"Property_0_is_a_static_member_of_type_1_2576","Property '{0}' is a static member of type '{1}'"),Return_type_annotation_circularly_references_itself:t(2577,e.DiagnosticCategory.Error,"Return_type_annotation_circularly_references_itself_2577","Return type annotation circularly references itself."),Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig:t(2580,e.DiagnosticCategory.Error,"Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580","Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig:t(2581,e.DiagnosticCategory.Error,"Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581","Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig:t(2582,e.DiagnosticCategory.Error,"Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582","Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later:t(2583,e.DiagnosticCategory.Error,"Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583","Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom:t(2584,e.DiagnosticCategory.Error,"Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584","Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."),_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later:t(2585,e.DiagnosticCategory.Error,"_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585","'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),Enum_type_0_circularly_references_itself:t(2586,e.DiagnosticCategory.Error,"Enum_type_0_circularly_references_itself_2586","Enum type '{0}' circularly references itself."),JSDoc_type_0_circularly_references_itself:t(2587,e.DiagnosticCategory.Error,"JSDoc_type_0_circularly_references_itself_2587","JSDoc type '{0}' circularly references itself."),Cannot_assign_to_0_because_it_is_a_constant:t(2588,e.DiagnosticCategory.Error,"Cannot_assign_to_0_because_it_is_a_constant_2588","Cannot assign to '{0}' because it is a constant."),JSX_element_attributes_type_0_may_not_be_a_union_type:t(2600,e.DiagnosticCategory.Error,"JSX_element_attributes_type_0_may_not_be_a_union_type_2600","JSX element attributes type '{0}' may not be a union type."),The_return_type_of_a_JSX_element_constructor_must_return_an_object_type:t(2601,e.DiagnosticCategory.Error,"The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601","The return type of a JSX element constructor must return an object type."),JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist:t(2602,e.DiagnosticCategory.Error,"JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602","JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."),Property_0_in_type_1_is_not_assignable_to_type_2:t(2603,e.DiagnosticCategory.Error,"Property_0_in_type_1_is_not_assignable_to_type_2_2603","Property '{0}' in type '{1}' is not assignable to type '{2}'."),JSX_element_type_0_does_not_have_any_construct_or_call_signatures:t(2604,e.DiagnosticCategory.Error,"JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604","JSX element type '{0}' does not have any construct or call signatures."),JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements:t(2605,e.DiagnosticCategory.Error,"JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605","JSX element type '{0}' is not a constructor function for JSX elements."),Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property:t(2606,e.DiagnosticCategory.Error,"Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606","Property '{0}' of JSX spread attribute is not assignable to target property."),JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property:t(2607,e.DiagnosticCategory.Error,"JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607","JSX element class does not support attributes because it does not have a '{0}' property."),The_global_type_JSX_0_may_not_have_more_than_one_property:t(2608,e.DiagnosticCategory.Error,"The_global_type_JSX_0_may_not_have_more_than_one_property_2608","The global type 'JSX.{0}' may not have more than one property."),JSX_spread_child_must_be_an_array_type:t(2609,e.DiagnosticCategory.Error,"JSX_spread_child_must_be_an_array_type_2609","JSX spread child must be an array type."),Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity:t(2649,e.DiagnosticCategory.Error,"Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649","Cannot augment module '{0}' with value exports because it resolves to a non-module entity."),A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums:t(2651,e.DiagnosticCategory.Error,"A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651","A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."),Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead:t(2652,e.DiagnosticCategory.Error,"Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652","Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."),Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1:t(2653,e.DiagnosticCategory.Error,"Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653","Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."),Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition:t(2654,e.DiagnosticCategory.Error,"Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654","Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."),Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition:t(2656,e.DiagnosticCategory.Error,"Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656","Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."),JSX_expressions_must_have_one_parent_element:t(2657,e.DiagnosticCategory.Error,"JSX_expressions_must_have_one_parent_element_2657","JSX expressions must have one parent element."),Type_0_provides_no_match_for_the_signature_1:t(2658,e.DiagnosticCategory.Error,"Type_0_provides_no_match_for_the_signature_1_2658","Type '{0}' provides no match for the signature '{1}'."),super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher:t(2659,e.DiagnosticCategory.Error,"super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659","'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."),super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions:t(2660,e.DiagnosticCategory.Error,"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660","'super' can only be referenced in members of derived classes or object literal expressions."),Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module:t(2661,e.DiagnosticCategory.Error,"Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661","Cannot export '{0}'. Only local declarations can be exported from a module."),Cannot_find_name_0_Did_you_mean_the_static_member_1_0:t(2662,e.DiagnosticCategory.Error,"Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662","Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"),Cannot_find_name_0_Did_you_mean_the_instance_member_this_0:t(2663,e.DiagnosticCategory.Error,"Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663","Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"),Invalid_module_name_in_augmentation_module_0_cannot_be_found:t(2664,e.DiagnosticCategory.Error,"Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664","Invalid module name in augmentation, module '{0}' cannot be found."),Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented:t(2665,e.DiagnosticCategory.Error,"Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665","Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."),Exports_and_export_assignments_are_not_permitted_in_module_augmentations:t(2666,e.DiagnosticCategory.Error,"Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666","Exports and export assignments are not permitted in module augmentations."),Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module:t(2667,e.DiagnosticCategory.Error,"Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667","Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."),export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible:t(2668,e.DiagnosticCategory.Error,"export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668","'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."),Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations:t(2669,e.DiagnosticCategory.Error,"Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669","Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."),Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context:t(2670,e.DiagnosticCategory.Error,"Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670","Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."),Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity:t(2671,e.DiagnosticCategory.Error,"Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671","Cannot augment module '{0}' because it resolves to a non-module entity."),Cannot_assign_a_0_constructor_type_to_a_1_constructor_type:t(2672,e.DiagnosticCategory.Error,"Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672","Cannot assign a '{0}' constructor type to a '{1}' constructor type."),Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration:t(2673,e.DiagnosticCategory.Error,"Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673","Constructor of class '{0}' is private and only accessible within the class declaration."),Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration:t(2674,e.DiagnosticCategory.Error,"Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674","Constructor of class '{0}' is protected and only accessible within the class declaration."),Cannot_extend_a_class_0_Class_constructor_is_marked_as_private:t(2675,e.DiagnosticCategory.Error,"Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675","Cannot extend a class '{0}'. Class constructor is marked as private."),Accessors_must_both_be_abstract_or_non_abstract:t(2676,e.DiagnosticCategory.Error,"Accessors_must_both_be_abstract_or_non_abstract_2676","Accessors must both be abstract or non-abstract."),A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type:t(2677,e.DiagnosticCategory.Error,"A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677","A type predicate's type must be assignable to its parameter's type."),Type_0_is_not_comparable_to_type_1:t(2678,e.DiagnosticCategory.Error,"Type_0_is_not_comparable_to_type_1_2678","Type '{0}' is not comparable to type '{1}'."),A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void:t(2679,e.DiagnosticCategory.Error,"A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679","A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."),A_0_parameter_must_be_the_first_parameter:t(2680,e.DiagnosticCategory.Error,"A_0_parameter_must_be_the_first_parameter_2680","A '{0}' parameter must be the first parameter."),A_constructor_cannot_have_a_this_parameter:t(2681,e.DiagnosticCategory.Error,"A_constructor_cannot_have_a_this_parameter_2681","A constructor cannot have a 'this' parameter."),get_and_set_accessor_must_have_the_same_this_type:t(2682,e.DiagnosticCategory.Error,"get_and_set_accessor_must_have_the_same_this_type_2682","'get' and 'set' accessor must have the same 'this' type."),this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation:t(2683,e.DiagnosticCategory.Error,"this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683","'this' implicitly has type 'any' because it does not have a type annotation."),The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1:t(2684,e.DiagnosticCategory.Error,"The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684","The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."),The_this_types_of_each_signature_are_incompatible:t(2685,e.DiagnosticCategory.Error,"The_this_types_of_each_signature_are_incompatible_2685","The 'this' types of each signature are incompatible."),_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead:t(2686,e.DiagnosticCategory.Error,"_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686","'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."),All_declarations_of_0_must_have_identical_modifiers:t(2687,e.DiagnosticCategory.Error,"All_declarations_of_0_must_have_identical_modifiers_2687","All declarations of '{0}' must have identical modifiers."),Cannot_find_type_definition_file_for_0:t(2688,e.DiagnosticCategory.Error,"Cannot_find_type_definition_file_for_0_2688","Cannot find type definition file for '{0}'."),Cannot_extend_an_interface_0_Did_you_mean_implements:t(2689,e.DiagnosticCategory.Error,"Cannot_extend_an_interface_0_Did_you_mean_implements_2689","Cannot extend an interface '{0}'. Did you mean 'implements'?"),An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead:t(2691,e.DiagnosticCategory.Error,"An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691","An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."),_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible:t(2692,e.DiagnosticCategory.Error,"_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692","'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."),_0_only_refers_to_a_type_but_is_being_used_as_a_value_here:t(2693,e.DiagnosticCategory.Error,"_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693","'{0}' only refers to a type, but is being used as a value here."),Namespace_0_has_no_exported_member_1:t(2694,e.DiagnosticCategory.Error,"Namespace_0_has_no_exported_member_1_2694","Namespace '{0}' has no exported member '{1}'."),Left_side_of_comma_operator_is_unused_and_has_no_side_effects:t(2695,e.DiagnosticCategory.Error,"Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695","Left side of comma operator is unused and has no side effects.",!0),The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead:t(2696,e.DiagnosticCategory.Error,"The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696","The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"),An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option:t(2697,e.DiagnosticCategory.Error,"An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697","An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."),Spread_types_may_only_be_created_from_object_types:t(2698,e.DiagnosticCategory.Error,"Spread_types_may_only_be_created_from_object_types_2698","Spread types may only be created from object types."),Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1:t(2699,e.DiagnosticCategory.Error,"Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699","Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."),Rest_types_may_only_be_created_from_object_types:t(2700,e.DiagnosticCategory.Error,"Rest_types_may_only_be_created_from_object_types_2700","Rest types may only be created from object types."),The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access:t(2701,e.DiagnosticCategory.Error,"The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701","The target of an object rest assignment must be a variable or a property access."),_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here:t(2702,e.DiagnosticCategory.Error,"_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702","'{0}' only refers to a type, but is being used as a namespace here."),The_operand_of_a_delete_operator_must_be_a_property_reference:t(2703,e.DiagnosticCategory.Error,"The_operand_of_a_delete_operator_must_be_a_property_reference_2703","The operand of a delete operator must be a property reference."),The_operand_of_a_delete_operator_cannot_be_a_read_only_property:t(2704,e.DiagnosticCategory.Error,"The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704","The operand of a delete operator cannot be a read-only property."),An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option:t(2705,e.DiagnosticCategory.Error,"An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705","An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."),Required_type_parameters_may_not_follow_optional_type_parameters:t(2706,e.DiagnosticCategory.Error,"Required_type_parameters_may_not_follow_optional_type_parameters_2706","Required type parameters may not follow optional type parameters."),Generic_type_0_requires_between_1_and_2_type_arguments:t(2707,e.DiagnosticCategory.Error,"Generic_type_0_requires_between_1_and_2_type_arguments_2707","Generic type '{0}' requires between {1} and {2} type arguments."),Cannot_use_namespace_0_as_a_value:t(2708,e.DiagnosticCategory.Error,"Cannot_use_namespace_0_as_a_value_2708","Cannot use namespace '{0}' as a value."),Cannot_use_namespace_0_as_a_type:t(2709,e.DiagnosticCategory.Error,"Cannot_use_namespace_0_as_a_type_2709","Cannot use namespace '{0}' as a type."),_0_are_specified_twice_The_attribute_named_0_will_be_overwritten:t(2710,e.DiagnosticCategory.Error,"_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710","'{0}' are specified twice. The attribute named '{0}' will be overwritten."),A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option:t(2711,e.DiagnosticCategory.Error,"A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711","A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."),A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option:t(2712,e.DiagnosticCategory.Error,"A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712","A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."),Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1:t(2713,e.DiagnosticCategory.Error,"Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713","Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"),The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context:t(2714,e.DiagnosticCategory.Error,"The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714","The expression of an export assignment must be an identifier or qualified name in an ambient context."),Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor:t(2715,e.DiagnosticCategory.Error,"Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715","Abstract property '{0}' in class '{1}' cannot be accessed in the constructor."),Type_parameter_0_has_a_circular_default:t(2716,e.DiagnosticCategory.Error,"Type_parameter_0_has_a_circular_default_2716","Type parameter '{0}' has a circular default."),Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2:t(2717,e.DiagnosticCategory.Error,"Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_t_2717","Subsequent property declarations must have the same type. Property '{0}' must be of type '{1}', but here has type '{2}'."),Duplicate_declaration_0:t(2718,e.DiagnosticCategory.Error,"Duplicate_declaration_0_2718","Duplicate declaration '{0}'."),Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated:t(2719,e.DiagnosticCategory.Error,"Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719","Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."),Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass:t(2720,e.DiagnosticCategory.Error,"Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720","Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"),Cannot_invoke_an_object_which_is_possibly_null:t(2721,e.DiagnosticCategory.Error,"Cannot_invoke_an_object_which_is_possibly_null_2721","Cannot invoke an object which is possibly 'null'."),Cannot_invoke_an_object_which_is_possibly_undefined:t(2722,e.DiagnosticCategory.Error,"Cannot_invoke_an_object_which_is_possibly_undefined_2722","Cannot invoke an object which is possibly 'undefined'."),Cannot_invoke_an_object_which_is_possibly_null_or_undefined:t(2723,e.DiagnosticCategory.Error,"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723","Cannot invoke an object which is possibly 'null' or 'undefined'."),Module_0_has_no_exported_member_1_Did_you_mean_2:t(2724,e.DiagnosticCategory.Error,"Module_0_has_no_exported_member_1_Did_you_mean_2_2724","Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),Class_name_cannot_be_Object_when_targeting_ES5_with_module_0:t(2725,e.DiagnosticCategory.Error,"Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725","Class name cannot be 'Object' when targeting ES5 with module {0}."),Cannot_find_lib_definition_for_0:t(2726,e.DiagnosticCategory.Error,"Cannot_find_lib_definition_for_0_2726","Cannot find lib definition for '{0}'."),Cannot_find_lib_definition_for_0_Did_you_mean_1:t(2727,e.DiagnosticCategory.Error,"Cannot_find_lib_definition_for_0_Did_you_mean_1_2727","Cannot find lib definition for '{0}'. Did you mean '{1}'?"),_0_is_declared_here:t(2728,e.DiagnosticCategory.Message,"_0_is_declared_here_2728","'{0}' is declared here."),Property_0_is_used_before_its_initialization:t(2729,e.DiagnosticCategory.Error,"Property_0_is_used_before_its_initialization_2729","Property '{0}' is used before its initialization."),An_arrow_function_cannot_have_a_this_parameter:t(2730,e.DiagnosticCategory.Error,"An_arrow_function_cannot_have_a_this_parameter_2730","An arrow function cannot have a 'this' parameter."),Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String:t(2731,e.DiagnosticCategory.Error,"Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731","Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."),Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension:t(2732,e.DiagnosticCategory.Error,"Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732","Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"),It_is_highly_likely_that_you_are_missing_a_semicolon:t(2734,e.DiagnosticCategory.Error,"It_is_highly_likely_that_you_are_missing_a_semicolon_2734","It is highly likely that you are missing a semicolon."),Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1:t(2735,e.DiagnosticCategory.Error,"Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735","Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"),Operator_0_cannot_be_applied_to_type_1:t(2736,e.DiagnosticCategory.Error,"Operator_0_cannot_be_applied_to_type_1_2736","Operator '{0}' cannot be applied to type '{1}'."),BigInt_literals_are_not_available_when_targeting_lower_than_ESNext:t(2737,e.DiagnosticCategory.Error,"BigInt_literals_are_not_available_when_targeting_lower_than_ESNext_2737","BigInt literals are not available when targeting lower than ESNext."),An_outer_value_of_this_is_shadowed_by_this_container:t(2738,e.DiagnosticCategory.Message,"An_outer_value_of_this_is_shadowed_by_this_container_2738","An outer value of 'this' is shadowed by this container."),Type_0_is_missing_the_following_properties_from_type_1_Colon_2:t(2739,e.DiagnosticCategory.Error,"Type_0_is_missing_the_following_properties_from_type_1_Colon_2_2739","Type '{0}' is missing the following properties from type '{1}': {2}"),Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more:t(2740,e.DiagnosticCategory.Error,"Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740","Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."),Property_0_is_missing_in_type_1_but_required_in_type_2:t(2741,e.DiagnosticCategory.Error,"Property_0_is_missing_in_type_1_but_required_in_type_2_2741","Property '{0}' is missing in type '{1}' but required in type '{2}'."),The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary:t(2742,e.DiagnosticCategory.Error,"The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742","The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."),Import_declaration_0_is_using_private_name_1:t(4e3,e.DiagnosticCategory.Error,"Import_declaration_0_is_using_private_name_1_4000","Import declaration '{0}' is using private name '{1}'."),Type_parameter_0_of_exported_class_has_or_is_using_private_name_1:t(4002,e.DiagnosticCategory.Error,"Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002","Type parameter '{0}' of exported class has or is using private name '{1}'."),Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1:t(4004,e.DiagnosticCategory.Error,"Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004","Type parameter '{0}' of exported interface has or is using private name '{1}'."),Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1:t(4006,e.DiagnosticCategory.Error,"Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006","Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1:t(4008,e.DiagnosticCategory.Error,"Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008","Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1:t(4010,e.DiagnosticCategory.Error,"Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010","Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."),Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1:t(4012,e.DiagnosticCategory.Error,"Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012","Type parameter '{0}' of public method from exported class has or is using private name '{1}'."),Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1:t(4014,e.DiagnosticCategory.Error,"Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014","Type parameter '{0}' of method from exported interface has or is using private name '{1}'."),Type_parameter_0_of_exported_function_has_or_is_using_private_name_1:t(4016,e.DiagnosticCategory.Error,"Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016","Type parameter '{0}' of exported function has or is using private name '{1}'."),Implements_clause_of_exported_class_0_has_or_is_using_private_name_1:t(4019,e.DiagnosticCategory.Error,"Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019","Implements clause of exported class '{0}' has or is using private name '{1}'."),extends_clause_of_exported_class_0_has_or_is_using_private_name_1:t(4020,e.DiagnosticCategory.Error,"extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020","'extends' clause of exported class '{0}' has or is using private name '{1}'."),extends_clause_of_exported_interface_0_has_or_is_using_private_name_1:t(4022,e.DiagnosticCategory.Error,"extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022","'extends' clause of exported interface '{0}' has or is using private name '{1}'."),Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4023,e.DiagnosticCategory.Error,"Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023","Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."),Exported_variable_0_has_or_is_using_name_1_from_private_module_2:t(4024,e.DiagnosticCategory.Error,"Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024","Exported variable '{0}' has or is using name '{1}' from private module '{2}'."),Exported_variable_0_has_or_is_using_private_name_1:t(4025,e.DiagnosticCategory.Error,"Exported_variable_0_has_or_is_using_private_name_1_4025","Exported variable '{0}' has or is using private name '{1}'."),Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4026,e.DiagnosticCategory.Error,"Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026","Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2:t(4027,e.DiagnosticCategory.Error,"Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027","Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),Public_static_property_0_of_exported_class_has_or_is_using_private_name_1:t(4028,e.DiagnosticCategory.Error,"Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028","Public static property '{0}' of exported class has or is using private name '{1}'."),Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4029,e.DiagnosticCategory.Error,"Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029","Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2:t(4030,e.DiagnosticCategory.Error,"Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030","Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."),Public_property_0_of_exported_class_has_or_is_using_private_name_1:t(4031,e.DiagnosticCategory.Error,"Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031","Public property '{0}' of exported class has or is using private name '{1}'."),Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2:t(4032,e.DiagnosticCategory.Error,"Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032","Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),Property_0_of_exported_interface_has_or_is_using_private_name_1:t(4033,e.DiagnosticCategory.Error,"Property_0_of_exported_interface_has_or_is_using_private_name_1_4033","Property '{0}' of exported interface has or is using private name '{1}'."),Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2:t(4034,e.DiagnosticCategory.Error,"Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_mod_4034","Parameter type of public static setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1:t(4035,e.DiagnosticCategory.Error,"Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1_4035","Parameter type of public static setter '{0}' from exported class has or is using private name '{1}'."),Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2:t(4036,e.DiagnosticCategory.Error,"Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4036","Parameter type of public setter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1:t(4037,e.DiagnosticCategory.Error,"Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1_4037","Parameter type of public setter '{0}' from exported class has or is using private name '{1}'."),Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4038,e.DiagnosticCategory.Error,"Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_modul_4038","Return type of public static getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2:t(4039,e.DiagnosticCategory.Error,"Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_4039","Return type of public static getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1:t(4040,e.DiagnosticCategory.Error,"Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1_4040","Return type of public static getter '{0}' from exported class has or is using private name '{1}'."),Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4041,e.DiagnosticCategory.Error,"Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_4041","Return type of public getter '{0}' from exported class has or is using name '{1}' from external module {2} but cannot be named."),Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2:t(4042,e.DiagnosticCategory.Error,"Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2_4042","Return type of public getter '{0}' from exported class has or is using name '{1}' from private module '{2}'."),Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1:t(4043,e.DiagnosticCategory.Error,"Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1_4043","Return type of public getter '{0}' from exported class has or is using private name '{1}'."),Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1:t(4044,e.DiagnosticCategory.Error,"Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044","Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."),Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0:t(4045,e.DiagnosticCategory.Error,"Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045","Return type of constructor signature from exported interface has or is using private name '{0}'."),Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1:t(4046,e.DiagnosticCategory.Error,"Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046","Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."),Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0:t(4047,e.DiagnosticCategory.Error,"Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047","Return type of call signature from exported interface has or is using private name '{0}'."),Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1:t(4048,e.DiagnosticCategory.Error,"Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048","Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."),Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0:t(4049,e.DiagnosticCategory.Error,"Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049","Return type of index signature from exported interface has or is using private name '{0}'."),Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named:t(4050,e.DiagnosticCategory.Error,"Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050","Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."),Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1:t(4051,e.DiagnosticCategory.Error,"Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051","Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."),Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0:t(4052,e.DiagnosticCategory.Error,"Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052","Return type of public static method from exported class has or is using private name '{0}'."),Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named:t(4053,e.DiagnosticCategory.Error,"Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053","Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."),Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1:t(4054,e.DiagnosticCategory.Error,"Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054","Return type of public method from exported class has or is using name '{0}' from private module '{1}'."),Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0:t(4055,e.DiagnosticCategory.Error,"Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055","Return type of public method from exported class has or is using private name '{0}'."),Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1:t(4056,e.DiagnosticCategory.Error,"Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056","Return type of method from exported interface has or is using name '{0}' from private module '{1}'."),Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0:t(4057,e.DiagnosticCategory.Error,"Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057","Return type of method from exported interface has or is using private name '{0}'."),Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named:t(4058,e.DiagnosticCategory.Error,"Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058","Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."),Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1:t(4059,e.DiagnosticCategory.Error,"Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059","Return type of exported function has or is using name '{0}' from private module '{1}'."),Return_type_of_exported_function_has_or_is_using_private_name_0:t(4060,e.DiagnosticCategory.Error,"Return_type_of_exported_function_has_or_is_using_private_name_0_4060","Return type of exported function has or is using private name '{0}'."),Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4061,e.DiagnosticCategory.Error,"Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061","Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."),Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2:t(4062,e.DiagnosticCategory.Error,"Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062","Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."),Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1:t(4063,e.DiagnosticCategory.Error,"Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063","Parameter '{0}' of constructor from exported class has or is using private name '{1}'."),Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2:t(4064,e.DiagnosticCategory.Error,"Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064","Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."),Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1:t(4065,e.DiagnosticCategory.Error,"Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065","Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."),Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2:t(4066,e.DiagnosticCategory.Error,"Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066","Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."),Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1:t(4067,e.DiagnosticCategory.Error,"Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067","Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."),Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4068,e.DiagnosticCategory.Error,"Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068","Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."),Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2:t(4069,e.DiagnosticCategory.Error,"Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069","Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."),Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1:t(4070,e.DiagnosticCategory.Error,"Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070","Parameter '{0}' of public static method from exported class has or is using private name '{1}'."),Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4071,e.DiagnosticCategory.Error,"Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071","Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."),Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2:t(4072,e.DiagnosticCategory.Error,"Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072","Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."),Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1:t(4073,e.DiagnosticCategory.Error,"Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073","Parameter '{0}' of public method from exported class has or is using private name '{1}'."),Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2:t(4074,e.DiagnosticCategory.Error,"Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074","Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."),Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1:t(4075,e.DiagnosticCategory.Error,"Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075","Parameter '{0}' of method from exported interface has or is using private name '{1}'."),Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4076,e.DiagnosticCategory.Error,"Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076","Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."),Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2:t(4077,e.DiagnosticCategory.Error,"Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077","Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."),Parameter_0_of_exported_function_has_or_is_using_private_name_1:t(4078,e.DiagnosticCategory.Error,"Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078","Parameter '{0}' of exported function has or is using private name '{1}'."),Exported_type_alias_0_has_or_is_using_private_name_1:t(4081,e.DiagnosticCategory.Error,"Exported_type_alias_0_has_or_is_using_private_name_1_4081","Exported type alias '{0}' has or is using private name '{1}'."),Default_export_of_the_module_has_or_is_using_private_name_0:t(4082,e.DiagnosticCategory.Error,"Default_export_of_the_module_has_or_is_using_private_name_0_4082","Default export of the module has or is using private name '{0}'."),Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1:t(4083,e.DiagnosticCategory.Error,"Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083","Type parameter '{0}' of exported type alias has or is using private name '{1}'."),Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict:t(4090,e.DiagnosticCategory.Error,"Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090","Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."),Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2:t(4091,e.DiagnosticCategory.Error,"Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091","Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."),Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1:t(4092,e.DiagnosticCategory.Error,"Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092","Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."),Property_0_of_exported_class_expression_may_not_be_private_or_protected:t(4094,e.DiagnosticCategory.Error,"Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094","Property '{0}' of exported class expression may not be private or protected."),Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4095,e.DiagnosticCategory.Error,"Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095","Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2:t(4096,e.DiagnosticCategory.Error,"Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096","Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),Public_static_method_0_of_exported_class_has_or_is_using_private_name_1:t(4097,e.DiagnosticCategory.Error,"Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097","Public static method '{0}' of exported class has or is using private name '{1}'."),Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named:t(4098,e.DiagnosticCategory.Error,"Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4098","Public method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."),Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2:t(4099,e.DiagnosticCategory.Error,"Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4099","Public method '{0}' of exported class has or is using name '{1}' from private module '{2}'."),Public_method_0_of_exported_class_has_or_is_using_private_name_1:t(4100,e.DiagnosticCategory.Error,"Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100","Public method '{0}' of exported class has or is using private name '{1}'."),Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2:t(4101,e.DiagnosticCategory.Error,"Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101","Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),Method_0_of_exported_interface_has_or_is_using_private_name_1:t(4102,e.DiagnosticCategory.Error,"Method_0_of_exported_interface_has_or_is_using_private_name_1_4102","Method '{0}' of exported interface has or is using private name '{1}'."),The_current_host_does_not_support_the_0_option:t(5001,e.DiagnosticCategory.Error,"The_current_host_does_not_support_the_0_option_5001","The current host does not support the '{0}' option."),Cannot_find_the_common_subdirectory_path_for_the_input_files:t(5009,e.DiagnosticCategory.Error,"Cannot_find_the_common_subdirectory_path_for_the_input_files_5009","Cannot find the common subdirectory path for the input files."),File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0:t(5010,e.DiagnosticCategory.Error,"File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010","File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),Cannot_read_file_0_Colon_1:t(5012,e.DiagnosticCategory.Error,"Cannot_read_file_0_Colon_1_5012","Cannot read file '{0}': {1}."),Failed_to_parse_file_0_Colon_1:t(5014,e.DiagnosticCategory.Error,"Failed_to_parse_file_0_Colon_1_5014","Failed to parse file '{0}': {1}."),Unknown_compiler_option_0:t(5023,e.DiagnosticCategory.Error,"Unknown_compiler_option_0_5023","Unknown compiler option '{0}'."),Compiler_option_0_requires_a_value_of_type_1:t(5024,e.DiagnosticCategory.Error,"Compiler_option_0_requires_a_value_of_type_1_5024","Compiler option '{0}' requires a value of type {1}."),Could_not_write_file_0_Colon_1:t(5033,e.DiagnosticCategory.Error,"Could_not_write_file_0_Colon_1_5033","Could not write file '{0}': {1}."),Option_project_cannot_be_mixed_with_source_files_on_a_command_line:t(5042,e.DiagnosticCategory.Error,"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042","Option 'project' cannot be mixed with source files on a command line."),Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher:t(5047,e.DiagnosticCategory.Error,"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047","Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."),Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided:t(5051,e.DiagnosticCategory.Error,"Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051","Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."),Option_0_cannot_be_specified_without_specifying_option_1:t(5052,e.DiagnosticCategory.Error,"Option_0_cannot_be_specified_without_specifying_option_1_5052","Option '{0}' cannot be specified without specifying option '{1}'."),Option_0_cannot_be_specified_with_option_1:t(5053,e.DiagnosticCategory.Error,"Option_0_cannot_be_specified_with_option_1_5053","Option '{0}' cannot be specified with option '{1}'."),A_tsconfig_json_file_is_already_defined_at_Colon_0:t(5054,e.DiagnosticCategory.Error,"A_tsconfig_json_file_is_already_defined_at_Colon_0_5054","A 'tsconfig.json' file is already defined at: '{0}'."),Cannot_write_file_0_because_it_would_overwrite_input_file:t(5055,e.DiagnosticCategory.Error,"Cannot_write_file_0_because_it_would_overwrite_input_file_5055","Cannot write file '{0}' because it would overwrite input file."),Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files:t(5056,e.DiagnosticCategory.Error,"Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056","Cannot write file '{0}' because it would be overwritten by multiple input files."),Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0:t(5057,e.DiagnosticCategory.Error,"Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057","Cannot find a tsconfig.json file at the specified directory: '{0}'."),The_specified_path_does_not_exist_Colon_0:t(5058,e.DiagnosticCategory.Error,"The_specified_path_does_not_exist_Colon_0_5058","The specified path does not exist: '{0}'."),Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier:t(5059,e.DiagnosticCategory.Error,"Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059","Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."),Option_paths_cannot_be_used_without_specifying_baseUrl_option:t(5060,e.DiagnosticCategory.Error,"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060","Option 'paths' cannot be used without specifying '--baseUrl' option."),Pattern_0_can_have_at_most_one_Asterisk_character:t(5061,e.DiagnosticCategory.Error,"Pattern_0_can_have_at_most_one_Asterisk_character_5061","Pattern '{0}' can have at most one '*' character."),Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character:t(5062,e.DiagnosticCategory.Error,"Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062","Substitution '{0}' in pattern '{1}' in can have at most one '*' character."),Substitutions_for_pattern_0_should_be_an_array:t(5063,e.DiagnosticCategory.Error,"Substitutions_for_pattern_0_should_be_an_array_5063","Substitutions for pattern '{0}' should be an array."),Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2:t(5064,e.DiagnosticCategory.Error,"Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064","Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."),File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0:t(5065,e.DiagnosticCategory.Error,"File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065","File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."),Substitutions_for_pattern_0_shouldn_t_be_an_empty_array:t(5066,e.DiagnosticCategory.Error,"Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066","Substitutions for pattern '{0}' shouldn't be an empty array."),Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name:t(5067,e.DiagnosticCategory.Error,"Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067","Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig:t(5068,e.DiagnosticCategory.Error,"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068","Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),Option_0_cannot_be_specified_without_specifying_option_1_or_option_2:t(5069,e.DiagnosticCategory.Error,"Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069","Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy:t(5070,e.DiagnosticCategory.Error,"Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070","Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext:t(5071,e.DiagnosticCategory.Error,"Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_5071","Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'."),Unknown_build_option_0:t(5072,e.DiagnosticCategory.Error,"Unknown_build_option_0_5072","Unknown build option '{0}'."),Build_option_0_requires_a_value_of_type_1:t(5073,e.DiagnosticCategory.Error,"Build_option_0_requires_a_value_of_type_1_5073","Build option '{0}' requires a value of type {1}."),Generates_a_sourcemap_for_each_corresponding_d_ts_file:t(6e3,e.DiagnosticCategory.Message,"Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000","Generates a sourcemap for each corresponding '.d.ts' file."),Concatenate_and_emit_output_to_single_file:t(6001,e.DiagnosticCategory.Message,"Concatenate_and_emit_output_to_single_file_6001","Concatenate and emit output to single file."),Generates_corresponding_d_ts_file:t(6002,e.DiagnosticCategory.Message,"Generates_corresponding_d_ts_file_6002","Generates corresponding '.d.ts' file."),Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations:t(6003,e.DiagnosticCategory.Message,"Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003","Specify the location where debugger should locate map files instead of generated locations."),Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations:t(6004,e.DiagnosticCategory.Message,"Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004","Specify the location where debugger should locate TypeScript files instead of source locations."),Watch_input_files:t(6005,e.DiagnosticCategory.Message,"Watch_input_files_6005","Watch input files."),Redirect_output_structure_to_the_directory:t(6006,e.DiagnosticCategory.Message,"Redirect_output_structure_to_the_directory_6006","Redirect output structure to the directory."),Do_not_erase_const_enum_declarations_in_generated_code:t(6007,e.DiagnosticCategory.Message,"Do_not_erase_const_enum_declarations_in_generated_code_6007","Do not erase const enum declarations in generated code."),Do_not_emit_outputs_if_any_errors_were_reported:t(6008,e.DiagnosticCategory.Message,"Do_not_emit_outputs_if_any_errors_were_reported_6008","Do not emit outputs if any errors were reported."),Do_not_emit_comments_to_output:t(6009,e.DiagnosticCategory.Message,"Do_not_emit_comments_to_output_6009","Do not emit comments to output."),Do_not_emit_outputs:t(6010,e.DiagnosticCategory.Message,"Do_not_emit_outputs_6010","Do not emit outputs."),Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking:t(6011,e.DiagnosticCategory.Message,"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011","Allow default imports from modules with no default export. This does not affect code emit, just typechecking."),Skip_type_checking_of_declaration_files:t(6012,e.DiagnosticCategory.Message,"Skip_type_checking_of_declaration_files_6012","Skip type checking of declaration files."),Do_not_resolve_the_real_path_of_symlinks:t(6013,e.DiagnosticCategory.Message,"Do_not_resolve_the_real_path_of_symlinks_6013","Do not resolve the real path of symlinks."),Only_emit_d_ts_declaration_files:t(6014,e.DiagnosticCategory.Message,"Only_emit_d_ts_declaration_files_6014","Only emit '.d.ts' declaration files."),Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT:t(6015,e.DiagnosticCategory.Message,"Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015","Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."),Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext:t(6016,e.DiagnosticCategory.Message,"Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016","Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."),Print_this_message:t(6017,e.DiagnosticCategory.Message,"Print_this_message_6017","Print this message."),Print_the_compiler_s_version:t(6019,e.DiagnosticCategory.Message,"Print_the_compiler_s_version_6019","Print the compiler's version."),Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json:t(6020,e.DiagnosticCategory.Message,"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020","Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."),Syntax_Colon_0:t(6023,e.DiagnosticCategory.Message,"Syntax_Colon_0_6023","Syntax: {0}"),options:t(6024,e.DiagnosticCategory.Message,"options_6024","options"),file:t(6025,e.DiagnosticCategory.Message,"file_6025","file"),Examples_Colon_0:t(6026,e.DiagnosticCategory.Message,"Examples_Colon_0_6026","Examples: {0}"),Options_Colon:t(6027,e.DiagnosticCategory.Message,"Options_Colon_6027","Options:"),Version_0:t(6029,e.DiagnosticCategory.Message,"Version_0_6029","Version {0}"),Insert_command_line_options_and_files_from_a_file:t(6030,e.DiagnosticCategory.Message,"Insert_command_line_options_and_files_from_a_file_6030","Insert command line options and files from a file."),Starting_compilation_in_watch_mode:t(6031,e.DiagnosticCategory.Message,"Starting_compilation_in_watch_mode_6031","Starting compilation in watch mode..."),File_change_detected_Starting_incremental_compilation:t(6032,e.DiagnosticCategory.Message,"File_change_detected_Starting_incremental_compilation_6032","File change detected. Starting incremental compilation..."),KIND:t(6034,e.DiagnosticCategory.Message,"KIND_6034","KIND"),FILE:t(6035,e.DiagnosticCategory.Message,"FILE_6035","FILE"),VERSION:t(6036,e.DiagnosticCategory.Message,"VERSION_6036","VERSION"),LOCATION:t(6037,e.DiagnosticCategory.Message,"LOCATION_6037","LOCATION"),DIRECTORY:t(6038,e.DiagnosticCategory.Message,"DIRECTORY_6038","DIRECTORY"),STRATEGY:t(6039,e.DiagnosticCategory.Message,"STRATEGY_6039","STRATEGY"),FILE_OR_DIRECTORY:t(6040,e.DiagnosticCategory.Message,"FILE_OR_DIRECTORY_6040","FILE OR DIRECTORY"),Generates_corresponding_map_file:t(6043,e.DiagnosticCategory.Message,"Generates_corresponding_map_file_6043","Generates corresponding '.map' file."),Compiler_option_0_expects_an_argument:t(6044,e.DiagnosticCategory.Error,"Compiler_option_0_expects_an_argument_6044","Compiler option '{0}' expects an argument."),Unterminated_quoted_string_in_response_file_0:t(6045,e.DiagnosticCategory.Error,"Unterminated_quoted_string_in_response_file_0_6045","Unterminated quoted string in response file '{0}'."),Argument_for_0_option_must_be_Colon_1:t(6046,e.DiagnosticCategory.Error,"Argument_for_0_option_must_be_Colon_1_6046","Argument for '{0}' option must be: {1}."),Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1:t(6048,e.DiagnosticCategory.Error,"Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048","Locale must be of the form or -. For example '{0}' or '{1}'."),Unsupported_locale_0:t(6049,e.DiagnosticCategory.Error,"Unsupported_locale_0_6049","Unsupported locale '{0}'."),Unable_to_open_file_0:t(6050,e.DiagnosticCategory.Error,"Unable_to_open_file_0_6050","Unable to open file '{0}'."),Corrupted_locale_file_0:t(6051,e.DiagnosticCategory.Error,"Corrupted_locale_file_0_6051","Corrupted locale file {0}."),Raise_error_on_expressions_and_declarations_with_an_implied_any_type:t(6052,e.DiagnosticCategory.Message,"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052","Raise error on expressions and declarations with an implied 'any' type."),File_0_not_found:t(6053,e.DiagnosticCategory.Error,"File_0_not_found_6053","File '{0}' not found."),File_0_has_unsupported_extension_The_only_supported_extensions_are_1:t(6054,e.DiagnosticCategory.Error,"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054","File '{0}' has unsupported extension. The only supported extensions are {1}."),Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures:t(6055,e.DiagnosticCategory.Message,"Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055","Suppress noImplicitAny errors for indexing objects lacking index signatures."),Do_not_emit_declarations_for_code_that_has_an_internal_annotation:t(6056,e.DiagnosticCategory.Message,"Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056","Do not emit declarations for code that has an '@internal' annotation."),Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir:t(6058,e.DiagnosticCategory.Message,"Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058","Specify the root directory of input files. Use to control the output directory structure with --outDir."),File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files:t(6059,e.DiagnosticCategory.Error,"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059","File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."),Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix:t(6060,e.DiagnosticCategory.Message,"Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060","Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."),NEWLINE:t(6061,e.DiagnosticCategory.Message,"NEWLINE_6061","NEWLINE"),Option_0_can_only_be_specified_in_tsconfig_json_file:t(6064,e.DiagnosticCategory.Error,"Option_0_can_only_be_specified_in_tsconfig_json_file_6064","Option '{0}' can only be specified in 'tsconfig.json' file."),Enables_experimental_support_for_ES7_decorators:t(6065,e.DiagnosticCategory.Message,"Enables_experimental_support_for_ES7_decorators_6065","Enables experimental support for ES7 decorators."),Enables_experimental_support_for_emitting_type_metadata_for_decorators:t(6066,e.DiagnosticCategory.Message,"Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066","Enables experimental support for emitting type metadata for decorators."),Enables_experimental_support_for_ES7_async_functions:t(6068,e.DiagnosticCategory.Message,"Enables_experimental_support_for_ES7_async_functions_6068","Enables experimental support for ES7 async functions."),Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6:t(6069,e.DiagnosticCategory.Message,"Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069","Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."),Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file:t(6070,e.DiagnosticCategory.Message,"Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070","Initializes a TypeScript project and creates a tsconfig.json file."),Successfully_created_a_tsconfig_json_file:t(6071,e.DiagnosticCategory.Message,"Successfully_created_a_tsconfig_json_file_6071","Successfully created a tsconfig.json file."),Suppress_excess_property_checks_for_object_literals:t(6072,e.DiagnosticCategory.Message,"Suppress_excess_property_checks_for_object_literals_6072","Suppress excess property checks for object literals."),Stylize_errors_and_messages_using_color_and_context_experimental:t(6073,e.DiagnosticCategory.Message,"Stylize_errors_and_messages_using_color_and_context_experimental_6073","Stylize errors and messages using color and context (experimental)."),Do_not_report_errors_on_unused_labels:t(6074,e.DiagnosticCategory.Message,"Do_not_report_errors_on_unused_labels_6074","Do not report errors on unused labels."),Report_error_when_not_all_code_paths_in_function_return_a_value:t(6075,e.DiagnosticCategory.Message,"Report_error_when_not_all_code_paths_in_function_return_a_value_6075","Report error when not all code paths in function return a value."),Report_errors_for_fallthrough_cases_in_switch_statement:t(6076,e.DiagnosticCategory.Message,"Report_errors_for_fallthrough_cases_in_switch_statement_6076","Report errors for fallthrough cases in switch statement."),Do_not_report_errors_on_unreachable_code:t(6077,e.DiagnosticCategory.Message,"Do_not_report_errors_on_unreachable_code_6077","Do not report errors on unreachable code."),Disallow_inconsistently_cased_references_to_the_same_file:t(6078,e.DiagnosticCategory.Message,"Disallow_inconsistently_cased_references_to_the_same_file_6078","Disallow inconsistently-cased references to the same file."),Specify_library_files_to_be_included_in_the_compilation:t(6079,e.DiagnosticCategory.Message,"Specify_library_files_to_be_included_in_the_compilation_6079","Specify library files to be included in the compilation."),Specify_JSX_code_generation_Colon_preserve_react_native_or_react:t(6080,e.DiagnosticCategory.Message,"Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080","Specify JSX code generation: 'preserve', 'react-native', or 'react'."),File_0_has_an_unsupported_extension_so_skipping_it:t(6081,e.DiagnosticCategory.Message,"File_0_has_an_unsupported_extension_so_skipping_it_6081","File '{0}' has an unsupported extension, so skipping it."),Only_amd_and_system_modules_are_supported_alongside_0:t(6082,e.DiagnosticCategory.Error,"Only_amd_and_system_modules_are_supported_alongside_0_6082","Only 'amd' and 'system' modules are supported alongside --{0}."),Base_directory_to_resolve_non_absolute_module_names:t(6083,e.DiagnosticCategory.Message,"Base_directory_to_resolve_non_absolute_module_names_6083","Base directory to resolve non-absolute module names."),Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit:t(6084,e.DiagnosticCategory.Message,"Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084","[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"),Enable_tracing_of_the_name_resolution_process:t(6085,e.DiagnosticCategory.Message,"Enable_tracing_of_the_name_resolution_process_6085","Enable tracing of the name resolution process."),Resolving_module_0_from_1:t(6086,e.DiagnosticCategory.Message,"Resolving_module_0_from_1_6086","======== Resolving module '{0}' from '{1}'. ========"),Explicitly_specified_module_resolution_kind_Colon_0:t(6087,e.DiagnosticCategory.Message,"Explicitly_specified_module_resolution_kind_Colon_0_6087","Explicitly specified module resolution kind: '{0}'."),Module_resolution_kind_is_not_specified_using_0:t(6088,e.DiagnosticCategory.Message,"Module_resolution_kind_is_not_specified_using_0_6088","Module resolution kind is not specified, using '{0}'."),Module_name_0_was_successfully_resolved_to_1:t(6089,e.DiagnosticCategory.Message,"Module_name_0_was_successfully_resolved_to_1_6089","======== Module name '{0}' was successfully resolved to '{1}'. ========"),Module_name_0_was_not_resolved:t(6090,e.DiagnosticCategory.Message,"Module_name_0_was_not_resolved_6090","======== Module name '{0}' was not resolved. ========"),paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0:t(6091,e.DiagnosticCategory.Message,"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091","'paths' option is specified, looking for a pattern to match module name '{0}'."),Module_name_0_matched_pattern_1:t(6092,e.DiagnosticCategory.Message,"Module_name_0_matched_pattern_1_6092","Module name '{0}', matched pattern '{1}'."),Trying_substitution_0_candidate_module_location_Colon_1:t(6093,e.DiagnosticCategory.Message,"Trying_substitution_0_candidate_module_location_Colon_1_6093","Trying substitution '{0}', candidate module location: '{1}'."),Resolving_module_name_0_relative_to_base_url_1_2:t(6094,e.DiagnosticCategory.Message,"Resolving_module_name_0_relative_to_base_url_1_2_6094","Resolving module name '{0}' relative to base url '{1}' - '{2}'."),Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1:t(6095,e.DiagnosticCategory.Message,"Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095","Loading module as file / folder, candidate module location '{0}', target file type '{1}'."),File_0_does_not_exist:t(6096,e.DiagnosticCategory.Message,"File_0_does_not_exist_6096","File '{0}' does not exist."),File_0_exist_use_it_as_a_name_resolution_result:t(6097,e.DiagnosticCategory.Message,"File_0_exist_use_it_as_a_name_resolution_result_6097","File '{0}' exist - use it as a name resolution result."),Loading_module_0_from_node_modules_folder_target_file_type_1:t(6098,e.DiagnosticCategory.Message,"Loading_module_0_from_node_modules_folder_target_file_type_1_6098","Loading module '{0}' from 'node_modules' folder, target file type '{1}'."),Found_package_json_at_0:t(6099,e.DiagnosticCategory.Message,"Found_package_json_at_0_6099","Found 'package.json' at '{0}'."),package_json_does_not_have_a_0_field:t(6100,e.DiagnosticCategory.Message,"package_json_does_not_have_a_0_field_6100","'package.json' does not have a '{0}' field."),package_json_has_0_field_1_that_references_2:t(6101,e.DiagnosticCategory.Message,"package_json_has_0_field_1_that_references_2_6101","'package.json' has '{0}' field '{1}' that references '{2}'."),Allow_javascript_files_to_be_compiled:t(6102,e.DiagnosticCategory.Message,"Allow_javascript_files_to_be_compiled_6102","Allow javascript files to be compiled."),Option_0_should_have_array_of_strings_as_a_value:t(6103,e.DiagnosticCategory.Error,"Option_0_should_have_array_of_strings_as_a_value_6103","Option '{0}' should have array of strings as a value."),Checking_if_0_is_the_longest_matching_prefix_for_1_2:t(6104,e.DiagnosticCategory.Message,"Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104","Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."),Expected_type_of_0_field_in_package_json_to_be_1_got_2:t(6105,e.DiagnosticCategory.Message,"Expected_type_of_0_field_in_package_json_to_be_1_got_2_6105","Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'."),baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1:t(6106,e.DiagnosticCategory.Message,"baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106","'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."),rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0:t(6107,e.DiagnosticCategory.Message,"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107","'rootDirs' option is set, using it to resolve relative module name '{0}'."),Longest_matching_prefix_for_0_is_1:t(6108,e.DiagnosticCategory.Message,"Longest_matching_prefix_for_0_is_1_6108","Longest matching prefix for '{0}' is '{1}'."),Loading_0_from_the_root_dir_1_candidate_location_2:t(6109,e.DiagnosticCategory.Message,"Loading_0_from_the_root_dir_1_candidate_location_2_6109","Loading '{0}' from the root dir '{1}', candidate location '{2}'."),Trying_other_entries_in_rootDirs:t(6110,e.DiagnosticCategory.Message,"Trying_other_entries_in_rootDirs_6110","Trying other entries in 'rootDirs'."),Module_resolution_using_rootDirs_has_failed:t(6111,e.DiagnosticCategory.Message,"Module_resolution_using_rootDirs_has_failed_6111","Module resolution using 'rootDirs' has failed."),Do_not_emit_use_strict_directives_in_module_output:t(6112,e.DiagnosticCategory.Message,"Do_not_emit_use_strict_directives_in_module_output_6112","Do not emit 'use strict' directives in module output."),Enable_strict_null_checks:t(6113,e.DiagnosticCategory.Message,"Enable_strict_null_checks_6113","Enable strict null checks."),Unknown_option_excludes_Did_you_mean_exclude:t(6114,e.DiagnosticCategory.Error,"Unknown_option_excludes_Did_you_mean_exclude_6114","Unknown option 'excludes'. Did you mean 'exclude'?"),Raise_error_on_this_expressions_with_an_implied_any_type:t(6115,e.DiagnosticCategory.Message,"Raise_error_on_this_expressions_with_an_implied_any_type_6115","Raise error on 'this' expressions with an implied 'any' type."),Resolving_type_reference_directive_0_containing_file_1_root_directory_2:t(6116,e.DiagnosticCategory.Message,"Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116","======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"),Resolving_using_primary_search_paths:t(6117,e.DiagnosticCategory.Message,"Resolving_using_primary_search_paths_6117","Resolving using primary search paths..."),Resolving_from_node_modules_folder:t(6118,e.DiagnosticCategory.Message,"Resolving_from_node_modules_folder_6118","Resolving from node_modules folder..."),Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2:t(6119,e.DiagnosticCategory.Message,"Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119","======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"),Type_reference_directive_0_was_not_resolved:t(6120,e.DiagnosticCategory.Message,"Type_reference_directive_0_was_not_resolved_6120","======== Type reference directive '{0}' was not resolved. ========"),Resolving_with_primary_search_path_0:t(6121,e.DiagnosticCategory.Message,"Resolving_with_primary_search_path_0_6121","Resolving with primary search path '{0}'."),Root_directory_cannot_be_determined_skipping_primary_search_paths:t(6122,e.DiagnosticCategory.Message,"Root_directory_cannot_be_determined_skipping_primary_search_paths_6122","Root directory cannot be determined, skipping primary search paths."),Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set:t(6123,e.DiagnosticCategory.Message,"Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123","======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"),Type_declaration_files_to_be_included_in_compilation:t(6124,e.DiagnosticCategory.Message,"Type_declaration_files_to_be_included_in_compilation_6124","Type declaration files to be included in compilation."),Looking_up_in_node_modules_folder_initial_location_0:t(6125,e.DiagnosticCategory.Message,"Looking_up_in_node_modules_folder_initial_location_0_6125","Looking up in 'node_modules' folder, initial location '{0}'."),Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder:t(6126,e.DiagnosticCategory.Message,"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126","Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."),Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1:t(6127,e.DiagnosticCategory.Message,"Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127","======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"),Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set:t(6128,e.DiagnosticCategory.Message,"Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128","======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"),Resolving_real_path_for_0_result_1:t(6130,e.DiagnosticCategory.Message,"Resolving_real_path_for_0_result_1_6130","Resolving real path for '{0}', result '{1}'."),Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system:t(6131,e.DiagnosticCategory.Error,"Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131","Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."),File_name_0_has_a_1_extension_stripping_it:t(6132,e.DiagnosticCategory.Message,"File_name_0_has_a_1_extension_stripping_it_6132","File name '{0}' has a '{1}' extension - stripping it."),_0_is_declared_but_its_value_is_never_read:t(6133,e.DiagnosticCategory.Error,"_0_is_declared_but_its_value_is_never_read_6133","'{0}' is declared but its value is never read.",!0),Report_errors_on_unused_locals:t(6134,e.DiagnosticCategory.Message,"Report_errors_on_unused_locals_6134","Report errors on unused locals."),Report_errors_on_unused_parameters:t(6135,e.DiagnosticCategory.Message,"Report_errors_on_unused_parameters_6135","Report errors on unused parameters."),The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files:t(6136,e.DiagnosticCategory.Message,"The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136","The maximum dependency depth to search under node_modules and load JavaScript files."),Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1:t(6137,e.DiagnosticCategory.Error,"Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137","Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."),Property_0_is_declared_but_its_value_is_never_read:t(6138,e.DiagnosticCategory.Error,"Property_0_is_declared_but_its_value_is_never_read_6138","Property '{0}' is declared but its value is never read.",!0),Import_emit_helpers_from_tslib:t(6139,e.DiagnosticCategory.Message,"Import_emit_helpers_from_tslib_6139","Import emit helpers from 'tslib'."),Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2:t(6140,e.DiagnosticCategory.Error,"Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140","Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."),Parse_in_strict_mode_and_emit_use_strict_for_each_source_file:t(6141,e.DiagnosticCategory.Message,"Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141",'Parse in strict mode and emit "use strict" for each source file.'),Module_0_was_resolved_to_1_but_jsx_is_not_set:t(6142,e.DiagnosticCategory.Error,"Module_0_was_resolved_to_1_but_jsx_is_not_set_6142","Module '{0}' was resolved to '{1}', but '--jsx' is not set."),Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1:t(6144,e.DiagnosticCategory.Message,"Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144","Module '{0}' was resolved as locally declared ambient module in file '{1}'."),Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified:t(6145,e.DiagnosticCategory.Message,"Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145","Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."),Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h:t(6146,e.DiagnosticCategory.Message,"Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146","Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."),Resolution_for_module_0_was_found_in_cache_from_location_1:t(6147,e.DiagnosticCategory.Message,"Resolution_for_module_0_was_found_in_cache_from_location_1_6147","Resolution for module '{0}' was found in cache from location '{1}'."),Directory_0_does_not_exist_skipping_all_lookups_in_it:t(6148,e.DiagnosticCategory.Message,"Directory_0_does_not_exist_skipping_all_lookups_in_it_6148","Directory '{0}' does not exist, skipping all lookups in it."),Show_diagnostic_information:t(6149,e.DiagnosticCategory.Message,"Show_diagnostic_information_6149","Show diagnostic information."),Show_verbose_diagnostic_information:t(6150,e.DiagnosticCategory.Message,"Show_verbose_diagnostic_information_6150","Show verbose diagnostic information."),Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file:t(6151,e.DiagnosticCategory.Message,"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151","Emit a single file with source maps instead of having a separate file."),Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set:t(6152,e.DiagnosticCategory.Message,"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152","Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."),Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule:t(6153,e.DiagnosticCategory.Message,"Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153","Transpile each file as a separate module (similar to 'ts.transpileModule')."),Print_names_of_generated_files_part_of_the_compilation:t(6154,e.DiagnosticCategory.Message,"Print_names_of_generated_files_part_of_the_compilation_6154","Print names of generated files part of the compilation."),Print_names_of_files_part_of_the_compilation:t(6155,e.DiagnosticCategory.Message,"Print_names_of_files_part_of_the_compilation_6155","Print names of files part of the compilation."),The_locale_used_when_displaying_messages_to_the_user_e_g_en_us:t(6156,e.DiagnosticCategory.Message,"The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156","The locale used when displaying messages to the user (e.g. 'en-us')"),Do_not_generate_custom_helper_functions_like_extends_in_compiled_output:t(6157,e.DiagnosticCategory.Message,"Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157","Do not generate custom helper functions like '__extends' in compiled output."),Do_not_include_the_default_library_file_lib_d_ts:t(6158,e.DiagnosticCategory.Message,"Do_not_include_the_default_library_file_lib_d_ts_6158","Do not include the default library file (lib.d.ts)."),Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files:t(6159,e.DiagnosticCategory.Message,"Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159","Do not add triple-slash references or imported modules to the list of compiled files."),Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files:t(6160,e.DiagnosticCategory.Message,"Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160","[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."),List_of_folders_to_include_type_definitions_from:t(6161,e.DiagnosticCategory.Message,"List_of_folders_to_include_type_definitions_from_6161","List of folders to include type definitions from."),Disable_size_limitations_on_JavaScript_projects:t(6162,e.DiagnosticCategory.Message,"Disable_size_limitations_on_JavaScript_projects_6162","Disable size limitations on JavaScript projects."),The_character_set_of_the_input_files:t(6163,e.DiagnosticCategory.Message,"The_character_set_of_the_input_files_6163","The character set of the input files."),Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files:t(6164,e.DiagnosticCategory.Message,"Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164","Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."),Do_not_truncate_error_messages:t(6165,e.DiagnosticCategory.Message,"Do_not_truncate_error_messages_6165","Do not truncate error messages."),Output_directory_for_generated_declaration_files:t(6166,e.DiagnosticCategory.Message,"Output_directory_for_generated_declaration_files_6166","Output directory for generated declaration files."),A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl:t(6167,e.DiagnosticCategory.Message,"A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167","A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."),List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime:t(6168,e.DiagnosticCategory.Message,"List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168","List of root folders whose combined content represents the structure of the project at runtime."),Show_all_compiler_options:t(6169,e.DiagnosticCategory.Message,"Show_all_compiler_options_6169","Show all compiler options."),Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file:t(6170,e.DiagnosticCategory.Message,"Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170","[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"),Command_line_Options:t(6171,e.DiagnosticCategory.Message,"Command_line_Options_6171","Command-line Options"),Basic_Options:t(6172,e.DiagnosticCategory.Message,"Basic_Options_6172","Basic Options"),Strict_Type_Checking_Options:t(6173,e.DiagnosticCategory.Message,"Strict_Type_Checking_Options_6173","Strict Type-Checking Options"),Module_Resolution_Options:t(6174,e.DiagnosticCategory.Message,"Module_Resolution_Options_6174","Module Resolution Options"),Source_Map_Options:t(6175,e.DiagnosticCategory.Message,"Source_Map_Options_6175","Source Map Options"),Additional_Checks:t(6176,e.DiagnosticCategory.Message,"Additional_Checks_6176","Additional Checks"),Experimental_Options:t(6177,e.DiagnosticCategory.Message,"Experimental_Options_6177","Experimental Options"),Advanced_Options:t(6178,e.DiagnosticCategory.Message,"Advanced_Options_6178","Advanced Options"),Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3:t(6179,e.DiagnosticCategory.Message,"Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179","Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."),Enable_all_strict_type_checking_options:t(6180,e.DiagnosticCategory.Message,"Enable_all_strict_type_checking_options_6180","Enable all strict type-checking options."),List_of_language_service_plugins:t(6181,e.DiagnosticCategory.Message,"List_of_language_service_plugins_6181","List of language service plugins."),Scoped_package_detected_looking_in_0:t(6182,e.DiagnosticCategory.Message,"Scoped_package_detected_looking_in_0_6182","Scoped package detected, looking in '{0}'"),Reusing_resolution_of_module_0_to_file_1_from_old_program:t(6183,e.DiagnosticCategory.Message,"Reusing_resolution_of_module_0_to_file_1_from_old_program_6183","Reusing resolution of module '{0}' to file '{1}' from old program."),Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program:t(6184,e.DiagnosticCategory.Message,"Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184","Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."),Disable_strict_checking_of_generic_signatures_in_function_types:t(6185,e.DiagnosticCategory.Message,"Disable_strict_checking_of_generic_signatures_in_function_types_6185","Disable strict checking of generic signatures in function types."),Enable_strict_checking_of_function_types:t(6186,e.DiagnosticCategory.Message,"Enable_strict_checking_of_function_types_6186","Enable strict checking of function types."),Enable_strict_checking_of_property_initialization_in_classes:t(6187,e.DiagnosticCategory.Message,"Enable_strict_checking_of_property_initialization_in_classes_6187","Enable strict checking of property initialization in classes."),Numeric_separators_are_not_allowed_here:t(6188,e.DiagnosticCategory.Error,"Numeric_separators_are_not_allowed_here_6188","Numeric separators are not allowed here."),Multiple_consecutive_numeric_separators_are_not_permitted:t(6189,e.DiagnosticCategory.Error,"Multiple_consecutive_numeric_separators_are_not_permitted_6189","Multiple consecutive numeric separators are not permitted."),Found_package_json_at_0_Package_ID_is_1:t(6190,e.DiagnosticCategory.Message,"Found_package_json_at_0_Package_ID_is_1_6190","Found 'package.json' at '{0}'. Package ID is '{1}'."),Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen:t(6191,e.DiagnosticCategory.Message,"Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191","Whether to keep outdated console output in watch mode instead of clearing the screen."),All_imports_in_import_declaration_are_unused:t(6192,e.DiagnosticCategory.Error,"All_imports_in_import_declaration_are_unused_6192","All imports in import declaration are unused.",!0),Found_1_error_Watching_for_file_changes:t(6193,e.DiagnosticCategory.Message,"Found_1_error_Watching_for_file_changes_6193","Found 1 error. Watching for file changes."),Found_0_errors_Watching_for_file_changes:t(6194,e.DiagnosticCategory.Message,"Found_0_errors_Watching_for_file_changes_6194","Found {0} errors. Watching for file changes."),Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols:t(6195,e.DiagnosticCategory.Message,"Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195","Resolve 'keyof' to string valued property names only (no numbers or symbols)."),_0_is_declared_but_never_used:t(6196,e.DiagnosticCategory.Error,"_0_is_declared_but_never_used_6196","'{0}' is declared but never used.",!0),Include_modules_imported_with_json_extension:t(6197,e.DiagnosticCategory.Message,"Include_modules_imported_with_json_extension_6197","Include modules imported with '.json' extension"),All_destructured_elements_are_unused:t(6198,e.DiagnosticCategory.Error,"All_destructured_elements_are_unused_6198","All destructured elements are unused.",!0),All_variables_are_unused:t(6199,e.DiagnosticCategory.Error,"All_variables_are_unused_6199","All variables are unused.",!0),Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0:t(6200,e.DiagnosticCategory.Error,"Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200","Definitions of the following identifiers conflict with those in another file: {0}"),Conflicts_are_in_this_file:t(6201,e.DiagnosticCategory.Message,"Conflicts_are_in_this_file_6201","Conflicts are in this file."),_0_was_also_declared_here:t(6203,e.DiagnosticCategory.Message,"_0_was_also_declared_here_6203","'{0}' was also declared here."),and_here:t(6204,e.DiagnosticCategory.Message,"and_here_6204","and here."),All_type_parameters_are_unused:t(6205,e.DiagnosticCategory.Error,"All_type_parameters_are_unused_6205","All type parameters are unused"),package_json_has_a_typesVersions_field_with_version_specific_path_mappings:t(6206,e.DiagnosticCategory.Message,"package_json_has_a_typesVersions_field_with_version_specific_path_mappings_6206","'package.json' has a 'typesVersions' field with version-specific path mappings."),package_json_does_not_have_a_typesVersions_entry_that_matches_version_0:t(6207,e.DiagnosticCategory.Message,"package_json_does_not_have_a_typesVersions_entry_that_matches_version_0_6207","'package.json' does not have a 'typesVersions' entry that matches version '{0}'."),package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2:t(6208,e.DiagnosticCategory.Message,"package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_ma_6208","'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'."),package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range:t(6209,e.DiagnosticCategory.Message,"package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range_6209","'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range."),An_argument_for_0_was_not_provided:t(6210,e.DiagnosticCategory.Message,"An_argument_for_0_was_not_provided_6210","An argument for '{0}' was not provided."),An_argument_matching_this_binding_pattern_was_not_provided:t(6211,e.DiagnosticCategory.Message,"An_argument_matching_this_binding_pattern_was_not_provided_6211","An argument matching this binding pattern was not provided."),Did_you_mean_to_call_this_expression:t(6212,e.DiagnosticCategory.Message,"Did_you_mean_to_call_this_expression_6212","Did you mean to call this expression?"),Did_you_mean_to_use_new_with_this_expression:t(6213,e.DiagnosticCategory.Message,"Did_you_mean_to_use_new_with_this_expression_6213","Did you mean to use 'new' with this expression?"),Enable_strict_bind_call_and_apply_methods_on_functions:t(6214,e.DiagnosticCategory.Message,"Enable_strict_bind_call_and_apply_methods_on_functions_6214","Enable strict 'bind', 'call', and 'apply' methods on functions."),Using_compiler_options_of_project_reference_redirect_0:t(6215,e.DiagnosticCategory.Message,"Using_compiler_options_of_project_reference_redirect_0_6215","Using compiler options of project reference redirect '{0}'."),Found_1_error:t(6216,e.DiagnosticCategory.Message,"Found_1_error_6216","Found 1 error."),Found_0_errors:t(6217,e.DiagnosticCategory.Message,"Found_0_errors_6217","Found {0} errors."),Projects_to_reference:t(6300,e.DiagnosticCategory.Message,"Projects_to_reference_6300","Projects to reference"),Enable_project_compilation:t(6302,e.DiagnosticCategory.Message,"Enable_project_compilation_6302","Enable project compilation"),Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0:t(6202,e.DiagnosticCategory.Error,"Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202","Project references may not form a circular graph. Cycle detected: {0}"),Composite_projects_may_not_disable_declaration_emit:t(6304,e.DiagnosticCategory.Error,"Composite_projects_may_not_disable_declaration_emit_6304","Composite projects may not disable declaration emit."),Output_file_0_has_not_been_built_from_source_file_1:t(6305,e.DiagnosticCategory.Error,"Output_file_0_has_not_been_built_from_source_file_1_6305","Output file '{0}' has not been built from source file '{1}'."),Referenced_project_0_must_have_setting_composite_Colon_true:t(6306,e.DiagnosticCategory.Error,"Referenced_project_0_must_have_setting_composite_Colon_true_6306","Referenced project '{0}' must have setting \"composite\": true."),File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern:t(6307,e.DiagnosticCategory.Error,"File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307","File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."),Cannot_prepend_project_0_because_it_does_not_have_outFile_set:t(6308,e.DiagnosticCategory.Error,"Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308","Cannot prepend project '{0}' because it does not have 'outFile' set"),Output_file_0_from_project_1_does_not_exist:t(6309,e.DiagnosticCategory.Error,"Output_file_0_from_project_1_does_not_exist_6309","Output file '{0}' from project '{1}' does not exist"),Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2:t(6350,e.DiagnosticCategory.Message,"Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350","Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"),Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2:t(6351,e.DiagnosticCategory.Message,"Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351","Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"),Project_0_is_out_of_date_because_output_file_1_does_not_exist:t(6352,e.DiagnosticCategory.Message,"Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352","Project '{0}' is out of date because output file '{1}' does not exist"),Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date:t(6353,e.DiagnosticCategory.Message,"Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353","Project '{0}' is out of date because its dependency '{1}' is out of date"),Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies:t(6354,e.DiagnosticCategory.Message,"Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354","Project '{0}' is up to date with .d.ts files from its dependencies"),Projects_in_this_build_Colon_0:t(6355,e.DiagnosticCategory.Message,"Projects_in_this_build_Colon_0_6355","Projects in this build: {0}"),A_non_dry_build_would_delete_the_following_files_Colon_0:t(6356,e.DiagnosticCategory.Message,"A_non_dry_build_would_delete_the_following_files_Colon_0_6356","A non-dry build would delete the following files: {0}"),A_non_dry_build_would_build_project_0:t(6357,e.DiagnosticCategory.Message,"A_non_dry_build_would_build_project_0_6357","A non-dry build would build project '{0}'"),Building_project_0:t(6358,e.DiagnosticCategory.Message,"Building_project_0_6358","Building project '{0}'..."),Updating_output_timestamps_of_project_0:t(6359,e.DiagnosticCategory.Message,"Updating_output_timestamps_of_project_0_6359","Updating output timestamps of project '{0}'..."),delete_this_Project_0_is_up_to_date_because_it_was_previously_built:t(6360,e.DiagnosticCategory.Message,"delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360","delete this - Project '{0}' is up to date because it was previously built"),Project_0_is_up_to_date:t(6361,e.DiagnosticCategory.Message,"Project_0_is_up_to_date_6361","Project '{0}' is up to date"),Skipping_build_of_project_0_because_its_dependency_1_has_errors:t(6362,e.DiagnosticCategory.Message,"Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362","Skipping build of project '{0}' because its dependency '{1}' has errors"),Project_0_can_t_be_built_because_its_dependency_1_has_errors:t(6363,e.DiagnosticCategory.Message,"Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363","Project '{0}' can't be built because its dependency '{1}' has errors"),Build_one_or_more_projects_and_their_dependencies_if_out_of_date:t(6364,e.DiagnosticCategory.Message,"Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364","Build one or more projects and their dependencies, if out of date"),Delete_the_outputs_of_all_projects:t(6365,e.DiagnosticCategory.Message,"Delete_the_outputs_of_all_projects_6365","Delete the outputs of all projects"),Enable_verbose_logging:t(6366,e.DiagnosticCategory.Message,"Enable_verbose_logging_6366","Enable verbose logging"),Show_what_would_be_built_or_deleted_if_specified_with_clean:t(6367,e.DiagnosticCategory.Message,"Show_what_would_be_built_or_deleted_if_specified_with_clean_6367","Show what would be built (or deleted, if specified with '--clean')"),Build_all_projects_including_those_that_appear_to_be_up_to_date:t(6368,e.DiagnosticCategory.Message,"Build_all_projects_including_those_that_appear_to_be_up_to_date_6368","Build all projects, including those that appear to be up to date"),Option_build_must_be_the_first_command_line_argument:t(6369,e.DiagnosticCategory.Error,"Option_build_must_be_the_first_command_line_argument_6369","Option '--build' must be the first command line argument."),Options_0_and_1_cannot_be_combined:t(6370,e.DiagnosticCategory.Error,"Options_0_and_1_cannot_be_combined_6370","Options '{0}' and '{1}' cannot be combined."),The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1:t(6500,e.DiagnosticCategory.Message,"The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500","The expected type comes from property '{0}' which is declared here on type '{1}'"),The_expected_type_comes_from_this_index_signature:t(6501,e.DiagnosticCategory.Message,"The_expected_type_comes_from_this_index_signature_6501","The expected type comes from this index signature."),The_expected_type_comes_from_the_return_type_of_this_signature:t(6502,e.DiagnosticCategory.Message,"The_expected_type_comes_from_the_return_type_of_this_signature_6502","The expected type comes from the return type of this signature."),Variable_0_implicitly_has_an_1_type:t(7005,e.DiagnosticCategory.Error,"Variable_0_implicitly_has_an_1_type_7005","Variable '{0}' implicitly has an '{1}' type."),Parameter_0_implicitly_has_an_1_type:t(7006,e.DiagnosticCategory.Error,"Parameter_0_implicitly_has_an_1_type_7006","Parameter '{0}' implicitly has an '{1}' type."),Member_0_implicitly_has_an_1_type:t(7008,e.DiagnosticCategory.Error,"Member_0_implicitly_has_an_1_type_7008","Member '{0}' implicitly has an '{1}' type."),new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type:t(7009,e.DiagnosticCategory.Error,"new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009","'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."),_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type:t(7010,e.DiagnosticCategory.Error,"_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010","'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."),Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type:t(7011,e.DiagnosticCategory.Error,"Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011","Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."),Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type:t(7013,e.DiagnosticCategory.Error,"Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013","Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."),Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type:t(7014,e.DiagnosticCategory.Error,"Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7014","Function type, which lacks return-type annotation, implicitly has an '{0}' return type."),Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number:t(7015,e.DiagnosticCategory.Error,"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015","Element implicitly has an 'any' type because index expression is not of type 'number'."),Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type:t(7016,e.DiagnosticCategory.Error,"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."),Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature:t(7017,e.DiagnosticCategory.Error,"Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017","Element implicitly has an 'any' type because type '{0}' has no index signature."),Object_literal_s_property_0_implicitly_has_an_1_type:t(7018,e.DiagnosticCategory.Error,"Object_literal_s_property_0_implicitly_has_an_1_type_7018","Object literal's property '{0}' implicitly has an '{1}' type."),Rest_parameter_0_implicitly_has_an_any_type:t(7019,e.DiagnosticCategory.Error,"Rest_parameter_0_implicitly_has_an_any_type_7019","Rest parameter '{0}' implicitly has an 'any[]' type."),Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type:t(7020,e.DiagnosticCategory.Error,"Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020","Call signature, which lacks return-type annotation, implicitly has an 'any' return type."),_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer:t(7022,e.DiagnosticCategory.Error,"_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022","'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."),_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions:t(7023,e.DiagnosticCategory.Error,"_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023","'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."),Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions:t(7024,e.DiagnosticCategory.Error,"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024","Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."),Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type:t(7025,e.DiagnosticCategory.Error,"Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025","Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."),JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists:t(7026,e.DiagnosticCategory.Error,"JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026","JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."),Unreachable_code_detected:t(7027,e.DiagnosticCategory.Error,"Unreachable_code_detected_7027","Unreachable code detected.",!0),Unused_label:t(7028,e.DiagnosticCategory.Error,"Unused_label_7028","Unused label.",!0),Fallthrough_case_in_switch:t(7029,e.DiagnosticCategory.Error,"Fallthrough_case_in_switch_7029","Fallthrough case in switch."),Not_all_code_paths_return_a_value:t(7030,e.DiagnosticCategory.Error,"Not_all_code_paths_return_a_value_7030","Not all code paths return a value."),Binding_element_0_implicitly_has_an_1_type:t(7031,e.DiagnosticCategory.Error,"Binding_element_0_implicitly_has_an_1_type_7031","Binding element '{0}' implicitly has an '{1}' type."),Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation:t(7032,e.DiagnosticCategory.Error,"Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032","Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."),Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation:t(7033,e.DiagnosticCategory.Error,"Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033","Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."),Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined:t(7034,e.DiagnosticCategory.Error,"Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034","Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."),Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0:t(7035,e.DiagnosticCategory.Error,"Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035","Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"),Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0:t(7036,e.DiagnosticCategory.Error,"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036","Dynamic import's specifier must be of type 'string', but here has type '{0}'."),Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports:t(7037,e.DiagnosticCategory.Message,"Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037","Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."),Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead:t(7038,e.DiagnosticCategory.Message,"Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038","Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."),Mapped_object_type_implicitly_has_an_any_template_type:t(7039,e.DiagnosticCategory.Error,"Mapped_object_type_implicitly_has_an_any_template_type_7039","Mapped object type implicitly has an 'any' template type."),If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1:t(7040,e.DiagnosticCategory.Error,"If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040","If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"),The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any:t(7041,e.DiagnosticCategory.Error,"The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041","The containing arrow function captures the global value of 'this' which implicitly has type 'any'."),Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used:t(7042,e.DiagnosticCategory.Error,"Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042","Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."),Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage:t(7043,e.DiagnosticCategory.Suggestion,"Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043","Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage:t(7044,e.DiagnosticCategory.Suggestion,"Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044","Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage:t(7045,e.DiagnosticCategory.Suggestion,"Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7045","Member '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."),Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage:t(7046,e.DiagnosticCategory.Suggestion,"Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage_7046","Variable '{0}' implicitly has type '{1}' in some locations, but a better type may be inferred from usage."),Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage:t(7047,e.DiagnosticCategory.Suggestion,"Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage_7047","Rest parameter '{0}' implicitly has an 'any[]' type, but a better type may be inferred from usage."),Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage:t(7048,e.DiagnosticCategory.Suggestion,"Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage_7048","Property '{0}' implicitly has type 'any', but a better type for its get accessor may be inferred from usage."),Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage:t(7049,e.DiagnosticCategory.Suggestion,"Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage_7049","Property '{0}' implicitly has type 'any', but a better type for its set accessor may be inferred from usage."),_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage:t(7050,e.DiagnosticCategory.Suggestion,"_0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage_7050","'{0}' implicitly has an '{1}' return type, but a better type may be inferred from usage."),Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1:t(7051,e.DiagnosticCategory.Error,"Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1_7051","Parameter has a name but no type. Did you mean '{0}: {1}'?"),You_cannot_rename_this_element:t(8e3,e.DiagnosticCategory.Error,"You_cannot_rename_this_element_8000","You cannot rename this element."),You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library:t(8001,e.DiagnosticCategory.Error,"You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001","You cannot rename elements that are defined in the standard TypeScript library."),import_can_only_be_used_in_a_ts_file:t(8002,e.DiagnosticCategory.Error,"import_can_only_be_used_in_a_ts_file_8002","'import ... =' can only be used in a .ts file."),export_can_only_be_used_in_a_ts_file:t(8003,e.DiagnosticCategory.Error,"export_can_only_be_used_in_a_ts_file_8003","'export=' can only be used in a .ts file."),type_parameter_declarations_can_only_be_used_in_a_ts_file:t(8004,e.DiagnosticCategory.Error,"type_parameter_declarations_can_only_be_used_in_a_ts_file_8004","'type parameter declarations' can only be used in a .ts file."),implements_clauses_can_only_be_used_in_a_ts_file:t(8005,e.DiagnosticCategory.Error,"implements_clauses_can_only_be_used_in_a_ts_file_8005","'implements clauses' can only be used in a .ts file."),interface_declarations_can_only_be_used_in_a_ts_file:t(8006,e.DiagnosticCategory.Error,"interface_declarations_can_only_be_used_in_a_ts_file_8006","'interface declarations' can only be used in a .ts file."),module_declarations_can_only_be_used_in_a_ts_file:t(8007,e.DiagnosticCategory.Error,"module_declarations_can_only_be_used_in_a_ts_file_8007","'module declarations' can only be used in a .ts file."),type_aliases_can_only_be_used_in_a_ts_file:t(8008,e.DiagnosticCategory.Error,"type_aliases_can_only_be_used_in_a_ts_file_8008","'type aliases' can only be used in a .ts file."),_0_can_only_be_used_in_a_ts_file:t(8009,e.DiagnosticCategory.Error,"_0_can_only_be_used_in_a_ts_file_8009","'{0}' can only be used in a .ts file."),types_can_only_be_used_in_a_ts_file:t(8010,e.DiagnosticCategory.Error,"types_can_only_be_used_in_a_ts_file_8010","'types' can only be used in a .ts file."),type_arguments_can_only_be_used_in_a_ts_file:t(8011,e.DiagnosticCategory.Error,"type_arguments_can_only_be_used_in_a_ts_file_8011","'type arguments' can only be used in a .ts file."),parameter_modifiers_can_only_be_used_in_a_ts_file:t(8012,e.DiagnosticCategory.Error,"parameter_modifiers_can_only_be_used_in_a_ts_file_8012","'parameter modifiers' can only be used in a .ts file."),non_null_assertions_can_only_be_used_in_a_ts_file:t(8013,e.DiagnosticCategory.Error,"non_null_assertions_can_only_be_used_in_a_ts_file_8013","'non-null assertions' can only be used in a .ts file."),enum_declarations_can_only_be_used_in_a_ts_file:t(8015,e.DiagnosticCategory.Error,"enum_declarations_can_only_be_used_in_a_ts_file_8015","'enum declarations' can only be used in a .ts file."),type_assertion_expressions_can_only_be_used_in_a_ts_file:t(8016,e.DiagnosticCategory.Error,"type_assertion_expressions_can_only_be_used_in_a_ts_file_8016","'type assertion expressions' can only be used in a .ts file."),Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0:t(8017,e.DiagnosticCategory.Error,"Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017","Octal literal types must use ES2015 syntax. Use the syntax '{0}'."),Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0:t(8018,e.DiagnosticCategory.Error,"Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018","Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."),Report_errors_in_js_files:t(8019,e.DiagnosticCategory.Message,"Report_errors_in_js_files_8019","Report errors in .js files."),JSDoc_types_can_only_be_used_inside_documentation_comments:t(8020,e.DiagnosticCategory.Error,"JSDoc_types_can_only_be_used_inside_documentation_comments_8020","JSDoc types can only be used inside documentation comments."),JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags:t(8021,e.DiagnosticCategory.Error,"JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags_8021","JSDoc '@typedef' tag should either have a type annotation or be followed by '@property' or '@member' tags."),JSDoc_0_is_not_attached_to_a_class:t(8022,e.DiagnosticCategory.Error,"JSDoc_0_is_not_attached_to_a_class_8022","JSDoc '@{0}' is not attached to a class."),JSDoc_0_1_does_not_match_the_extends_2_clause:t(8023,e.DiagnosticCategory.Error,"JSDoc_0_1_does_not_match_the_extends_2_clause_8023","JSDoc '@{0} {1}' does not match the 'extends {2}' clause."),JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name:t(8024,e.DiagnosticCategory.Error,"JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_8024","JSDoc '@param' tag has name '{0}', but there is no parameter with that name."),Class_declarations_cannot_have_more_than_one_augments_or_extends_tag:t(8025,e.DiagnosticCategory.Error,"Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025","Class declarations cannot have more than one `@augments` or `@extends` tag."),Expected_0_type_arguments_provide_these_with_an_extends_tag:t(8026,e.DiagnosticCategory.Error,"Expected_0_type_arguments_provide_these_with_an_extends_tag_8026","Expected {0} type arguments; provide these with an '@extends' tag."),Expected_0_1_type_arguments_provide_these_with_an_extends_tag:t(8027,e.DiagnosticCategory.Error,"Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027","Expected {0}-{1} type arguments; provide these with an '@extends' tag."),JSDoc_may_only_appear_in_the_last_parameter_of_a_signature:t(8028,e.DiagnosticCategory.Error,"JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028","JSDoc '...' may only appear in the last parameter of a signature."),JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type:t(8029,e.DiagnosticCategory.Error,"JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029","JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."),The_type_of_a_function_declaration_must_match_the_function_s_signature:t(8030,e.DiagnosticCategory.Error,"The_type_of_a_function_declaration_must_match_the_function_s_signature_8030","The type of a function declaration must match the function's signature."),You_cannot_rename_a_module_via_a_global_import:t(8031,e.DiagnosticCategory.Error,"You_cannot_rename_a_module_via_a_global_import_8031","You cannot rename a module via a global import."),Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause:t(9002,e.DiagnosticCategory.Error,"Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002","Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."),class_expressions_are_not_currently_supported:t(9003,e.DiagnosticCategory.Error,"class_expressions_are_not_currently_supported_9003","'class' expressions are not currently supported."),Language_service_is_disabled:t(9004,e.DiagnosticCategory.Error,"Language_service_is_disabled_9004","Language service is disabled."),JSX_attributes_must_only_be_assigned_a_non_empty_expression:t(17e3,e.DiagnosticCategory.Error,"JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000","JSX attributes must only be assigned a non-empty 'expression'."),JSX_elements_cannot_have_multiple_attributes_with_the_same_name:t(17001,e.DiagnosticCategory.Error,"JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001","JSX elements cannot have multiple attributes with the same name."),Expected_corresponding_JSX_closing_tag_for_0:t(17002,e.DiagnosticCategory.Error,"Expected_corresponding_JSX_closing_tag_for_0_17002","Expected corresponding JSX closing tag for '{0}'."),JSX_attribute_expected:t(17003,e.DiagnosticCategory.Error,"JSX_attribute_expected_17003","JSX attribute expected."),Cannot_use_JSX_unless_the_jsx_flag_is_provided:t(17004,e.DiagnosticCategory.Error,"Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004","Cannot use JSX unless the '--jsx' flag is provided."),A_constructor_cannot_contain_a_super_call_when_its_class_extends_null:t(17005,e.DiagnosticCategory.Error,"A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005","A constructor cannot contain a 'super' call when its class extends 'null'."),An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses:t(17006,e.DiagnosticCategory.Error,"An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006","An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses:t(17007,e.DiagnosticCategory.Error,"A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007","A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."),JSX_element_0_has_no_corresponding_closing_tag:t(17008,e.DiagnosticCategory.Error,"JSX_element_0_has_no_corresponding_closing_tag_17008","JSX element '{0}' has no corresponding closing tag."),super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class:t(17009,e.DiagnosticCategory.Error,"super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009","'super' must be called before accessing 'this' in the constructor of a derived class."),Unknown_type_acquisition_option_0:t(17010,e.DiagnosticCategory.Error,"Unknown_type_acquisition_option_0_17010","Unknown type acquisition option '{0}'."),super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class:t(17011,e.DiagnosticCategory.Error,"super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011","'super' must be called before accessing a property of 'super' in the constructor of a derived class."),_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2:t(17012,e.DiagnosticCategory.Error,"_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012","'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"),Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor:t(17013,e.DiagnosticCategory.Error,"Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013","Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."),JSX_fragment_has_no_corresponding_closing_tag:t(17014,e.DiagnosticCategory.Error,"JSX_fragment_has_no_corresponding_closing_tag_17014","JSX fragment has no corresponding closing tag."),Expected_corresponding_closing_tag_for_JSX_fragment:t(17015,e.DiagnosticCategory.Error,"Expected_corresponding_closing_tag_for_JSX_fragment_17015","Expected corresponding closing tag for JSX fragment."),JSX_fragment_is_not_supported_when_using_jsxFactory:t(17016,e.DiagnosticCategory.Error,"JSX_fragment_is_not_supported_when_using_jsxFactory_17016","JSX fragment is not supported when using --jsxFactory"),JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma:t(17017,e.DiagnosticCategory.Error,"JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017","JSX fragment is not supported when using an inline JSX factory pragma"),Circularity_detected_while_resolving_configuration_Colon_0:t(18e3,e.DiagnosticCategory.Error,"Circularity_detected_while_resolving_configuration_Colon_0_18000","Circularity detected while resolving configuration: {0}"),A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not:t(18001,e.DiagnosticCategory.Error,"A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001","A path in an 'extends' option must be relative or rooted, but '{0}' is not."),The_files_list_in_config_file_0_is_empty:t(18002,e.DiagnosticCategory.Error,"The_files_list_in_config_file_0_is_empty_18002","The 'files' list in config file '{0}' is empty."),No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2:t(18003,e.DiagnosticCategory.Error,"No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003","No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."),File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module:t(80001,e.DiagnosticCategory.Suggestion,"File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001","File is a CommonJS module; it may be converted to an ES6 module."),This_constructor_function_may_be_converted_to_a_class_declaration:t(80002,e.DiagnosticCategory.Suggestion,"This_constructor_function_may_be_converted_to_a_class_declaration_80002","This constructor function may be converted to a class declaration."),Import_may_be_converted_to_a_default_import:t(80003,e.DiagnosticCategory.Suggestion,"Import_may_be_converted_to_a_default_import_80003","Import may be converted to a default import."),JSDoc_types_may_be_moved_to_TypeScript_types:t(80004,e.DiagnosticCategory.Suggestion,"JSDoc_types_may_be_moved_to_TypeScript_types_80004","JSDoc types may be moved to TypeScript types."),require_call_may_be_converted_to_an_import:t(80005,e.DiagnosticCategory.Suggestion,"require_call_may_be_converted_to_an_import_80005","'require' call may be converted to an import."),This_may_be_converted_to_an_async_function:t(80006,e.DiagnosticCategory.Suggestion,"This_may_be_converted_to_an_async_function_80006","This may be converted to an async function."),Add_missing_super_call:t(90001,e.DiagnosticCategory.Message,"Add_missing_super_call_90001","Add missing 'super()' call"),Make_super_call_the_first_statement_in_the_constructor:t(90002,e.DiagnosticCategory.Message,"Make_super_call_the_first_statement_in_the_constructor_90002","Make 'super()' call the first statement in the constructor"),Change_extends_to_implements:t(90003,e.DiagnosticCategory.Message,"Change_extends_to_implements_90003","Change 'extends' to 'implements'"),Remove_declaration_for_Colon_0:t(90004,e.DiagnosticCategory.Message,"Remove_declaration_for_Colon_0_90004","Remove declaration for: '{0}'"),Remove_import_from_0:t(90005,e.DiagnosticCategory.Message,"Remove_import_from_0_90005","Remove import from '{0}'"),Implement_interface_0:t(90006,e.DiagnosticCategory.Message,"Implement_interface_0_90006","Implement interface '{0}'"),Implement_inherited_abstract_class:t(90007,e.DiagnosticCategory.Message,"Implement_inherited_abstract_class_90007","Implement inherited abstract class"),Add_0_to_unresolved_variable:t(90008,e.DiagnosticCategory.Message,"Add_0_to_unresolved_variable_90008","Add '{0}.' to unresolved variable"),Remove_destructuring:t(90009,e.DiagnosticCategory.Message,"Remove_destructuring_90009","Remove destructuring"),Remove_variable_statement:t(90010,e.DiagnosticCategory.Message,"Remove_variable_statement_90010","Remove variable statement"),Remove_template_tag:t(90011,e.DiagnosticCategory.Message,"Remove_template_tag_90011","Remove template tag"),Remove_type_parameters:t(90012,e.DiagnosticCategory.Message,"Remove_type_parameters_90012","Remove type parameters"),Import_0_from_module_1:t(90013,e.DiagnosticCategory.Message,"Import_0_from_module_1_90013","Import '{0}' from module \"{1}\""),Change_0_to_1:t(90014,e.DiagnosticCategory.Message,"Change_0_to_1_90014","Change '{0}' to '{1}'"),Add_0_to_existing_import_declaration_from_1:t(90015,e.DiagnosticCategory.Message,"Add_0_to_existing_import_declaration_from_1_90015","Add '{0}' to existing import declaration from \"{1}\""),Declare_property_0:t(90016,e.DiagnosticCategory.Message,"Declare_property_0_90016","Declare property '{0}'"),Add_index_signature_for_property_0:t(90017,e.DiagnosticCategory.Message,"Add_index_signature_for_property_0_90017","Add index signature for property '{0}'"),Disable_checking_for_this_file:t(90018,e.DiagnosticCategory.Message,"Disable_checking_for_this_file_90018","Disable checking for this file"),Ignore_this_error_message:t(90019,e.DiagnosticCategory.Message,"Ignore_this_error_message_90019","Ignore this error message"),Initialize_property_0_in_the_constructor:t(90020,e.DiagnosticCategory.Message,"Initialize_property_0_in_the_constructor_90020","Initialize property '{0}' in the constructor"),Initialize_static_property_0:t(90021,e.DiagnosticCategory.Message,"Initialize_static_property_0_90021","Initialize static property '{0}'"),Change_spelling_to_0:t(90022,e.DiagnosticCategory.Message,"Change_spelling_to_0_90022","Change spelling to '{0}'"),Declare_method_0:t(90023,e.DiagnosticCategory.Message,"Declare_method_0_90023","Declare method '{0}'"),Declare_static_method_0:t(90024,e.DiagnosticCategory.Message,"Declare_static_method_0_90024","Declare static method '{0}'"),Prefix_0_with_an_underscore:t(90025,e.DiagnosticCategory.Message,"Prefix_0_with_an_underscore_90025","Prefix '{0}' with an underscore"),Rewrite_as_the_indexed_access_type_0:t(90026,e.DiagnosticCategory.Message,"Rewrite_as_the_indexed_access_type_0_90026","Rewrite as the indexed access type '{0}'"),Declare_static_property_0:t(90027,e.DiagnosticCategory.Message,"Declare_static_property_0_90027","Declare static property '{0}'"),Call_decorator_expression:t(90028,e.DiagnosticCategory.Message,"Call_decorator_expression_90028","Call decorator expression"),Add_async_modifier_to_containing_function:t(90029,e.DiagnosticCategory.Message,"Add_async_modifier_to_containing_function_90029","Add async modifier to containing function"),Replace_infer_0_with_unknown:t(90030,e.DiagnosticCategory.Message,"Replace_infer_0_with_unknown_90030","Replace 'infer {0}' with 'unknown'"),Replace_all_unused_infer_with_unknown:t(90031,e.DiagnosticCategory.Message,"Replace_all_unused_infer_with_unknown_90031","Replace all unused 'infer' with 'unknown'"),Import_default_0_from_module_1:t(90032,e.DiagnosticCategory.Message,"Import_default_0_from_module_1_90032","Import default '{0}' from module \"{1}\""),Add_default_import_0_to_existing_import_declaration_from_1:t(90033,e.DiagnosticCategory.Message,"Add_default_import_0_to_existing_import_declaration_from_1_90033","Add default import '{0}' to existing import declaration from \"{1}\""),Add_parameter_name:t(90034,e.DiagnosticCategory.Message,"Add_parameter_name_90034","Add parameter name"),Convert_function_to_an_ES2015_class:t(95001,e.DiagnosticCategory.Message,"Convert_function_to_an_ES2015_class_95001","Convert function to an ES2015 class"),Convert_function_0_to_class:t(95002,e.DiagnosticCategory.Message,"Convert_function_0_to_class_95002","Convert function '{0}' to class"),Extract_to_0_in_1:t(95004,e.DiagnosticCategory.Message,"Extract_to_0_in_1_95004","Extract to {0} in {1}"),Extract_function:t(95005,e.DiagnosticCategory.Message,"Extract_function_95005","Extract function"),Extract_constant:t(95006,e.DiagnosticCategory.Message,"Extract_constant_95006","Extract constant"),Extract_to_0_in_enclosing_scope:t(95007,e.DiagnosticCategory.Message,"Extract_to_0_in_enclosing_scope_95007","Extract to {0} in enclosing scope"),Extract_to_0_in_1_scope:t(95008,e.DiagnosticCategory.Message,"Extract_to_0_in_1_scope_95008","Extract to {0} in {1} scope"),Annotate_with_type_from_JSDoc:t(95009,e.DiagnosticCategory.Message,"Annotate_with_type_from_JSDoc_95009","Annotate with type from JSDoc"),Annotate_with_types_from_JSDoc:t(95010,e.DiagnosticCategory.Message,"Annotate_with_types_from_JSDoc_95010","Annotate with types from JSDoc"),Infer_type_of_0_from_usage:t(95011,e.DiagnosticCategory.Message,"Infer_type_of_0_from_usage_95011","Infer type of '{0}' from usage"),Infer_parameter_types_from_usage:t(95012,e.DiagnosticCategory.Message,"Infer_parameter_types_from_usage_95012","Infer parameter types from usage"),Convert_to_default_import:t(95013,e.DiagnosticCategory.Message,"Convert_to_default_import_95013","Convert to default import"),Install_0:t(95014,e.DiagnosticCategory.Message,"Install_0_95014","Install '{0}'"),Replace_import_with_0:t(95015,e.DiagnosticCategory.Message,"Replace_import_with_0_95015","Replace import with '{0}'."),Use_synthetic_default_member:t(95016,e.DiagnosticCategory.Message,"Use_synthetic_default_member_95016","Use synthetic 'default' member."),Convert_to_ES6_module:t(95017,e.DiagnosticCategory.Message,"Convert_to_ES6_module_95017","Convert to ES6 module"),Add_undefined_type_to_property_0:t(95018,e.DiagnosticCategory.Message,"Add_undefined_type_to_property_0_95018","Add 'undefined' type to property '{0}'"),Add_initializer_to_property_0:t(95019,e.DiagnosticCategory.Message,"Add_initializer_to_property_0_95019","Add initializer to property '{0}'"),Add_definite_assignment_assertion_to_property_0:t(95020,e.DiagnosticCategory.Message,"Add_definite_assignment_assertion_to_property_0_95020","Add definite assignment assertion to property '{0}'"),Add_all_missing_members:t(95022,e.DiagnosticCategory.Message,"Add_all_missing_members_95022","Add all missing members"),Infer_all_types_from_usage:t(95023,e.DiagnosticCategory.Message,"Infer_all_types_from_usage_95023","Infer all types from usage"),Delete_all_unused_declarations:t(95024,e.DiagnosticCategory.Message,"Delete_all_unused_declarations_95024","Delete all unused declarations"),Prefix_all_unused_declarations_with_where_possible:t(95025,e.DiagnosticCategory.Message,"Prefix_all_unused_declarations_with_where_possible_95025","Prefix all unused declarations with '_' where possible"),Fix_all_detected_spelling_errors:t(95026,e.DiagnosticCategory.Message,"Fix_all_detected_spelling_errors_95026","Fix all detected spelling errors"),Add_initializers_to_all_uninitialized_properties:t(95027,e.DiagnosticCategory.Message,"Add_initializers_to_all_uninitialized_properties_95027","Add initializers to all uninitialized properties"),Add_definite_assignment_assertions_to_all_uninitialized_properties:t(95028,e.DiagnosticCategory.Message,"Add_definite_assignment_assertions_to_all_uninitialized_properties_95028","Add definite assignment assertions to all uninitialized properties"),Add_undefined_type_to_all_uninitialized_properties:t(95029,e.DiagnosticCategory.Message,"Add_undefined_type_to_all_uninitialized_properties_95029","Add undefined type to all uninitialized properties"),Change_all_jsdoc_style_types_to_TypeScript:t(95030,e.DiagnosticCategory.Message,"Change_all_jsdoc_style_types_to_TypeScript_95030","Change all jsdoc-style types to TypeScript"),Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types:t(95031,e.DiagnosticCategory.Message,"Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031","Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"),Implement_all_unimplemented_interfaces:t(95032,e.DiagnosticCategory.Message,"Implement_all_unimplemented_interfaces_95032","Implement all unimplemented interfaces"),Install_all_missing_types_packages:t(95033,e.DiagnosticCategory.Message,"Install_all_missing_types_packages_95033","Install all missing types packages"),Rewrite_all_as_indexed_access_types:t(95034,e.DiagnosticCategory.Message,"Rewrite_all_as_indexed_access_types_95034","Rewrite all as indexed access types"),Convert_all_to_default_imports:t(95035,e.DiagnosticCategory.Message,"Convert_all_to_default_imports_95035","Convert all to default imports"),Make_all_super_calls_the_first_statement_in_their_constructor:t(95036,e.DiagnosticCategory.Message,"Make_all_super_calls_the_first_statement_in_their_constructor_95036","Make all 'super()' calls the first statement in their constructor"),Add_qualifier_to_all_unresolved_variables_matching_a_member_name:t(95037,e.DiagnosticCategory.Message,"Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037","Add qualifier to all unresolved variables matching a member name"),Change_all_extended_interfaces_to_implements:t(95038,e.DiagnosticCategory.Message,"Change_all_extended_interfaces_to_implements_95038","Change all extended interfaces to 'implements'"),Add_all_missing_super_calls:t(95039,e.DiagnosticCategory.Message,"Add_all_missing_super_calls_95039","Add all missing super calls"),Implement_all_inherited_abstract_classes:t(95040,e.DiagnosticCategory.Message,"Implement_all_inherited_abstract_classes_95040","Implement all inherited abstract classes"),Add_all_missing_async_modifiers:t(95041,e.DiagnosticCategory.Message,"Add_all_missing_async_modifiers_95041","Add all missing 'async' modifiers"),Add_ts_ignore_to_all_error_messages:t(95042,e.DiagnosticCategory.Message,"Add_ts_ignore_to_all_error_messages_95042","Add '@ts-ignore' to all error messages"),Annotate_everything_with_types_from_JSDoc:t(95043,e.DiagnosticCategory.Message,"Annotate_everything_with_types_from_JSDoc_95043","Annotate everything with types from JSDoc"),Add_to_all_uncalled_decorators:t(95044,e.DiagnosticCategory.Message,"Add_to_all_uncalled_decorators_95044","Add '()' to all uncalled decorators"),Convert_all_constructor_functions_to_classes:t(95045,e.DiagnosticCategory.Message,"Convert_all_constructor_functions_to_classes_95045","Convert all constructor functions to classes"),Generate_get_and_set_accessors:t(95046,e.DiagnosticCategory.Message,"Generate_get_and_set_accessors_95046","Generate 'get' and 'set' accessors"),Convert_require_to_import:t(95047,e.DiagnosticCategory.Message,"Convert_require_to_import_95047","Convert 'require' to 'import'"),Convert_all_require_to_import:t(95048,e.DiagnosticCategory.Message,"Convert_all_require_to_import_95048","Convert all 'require' to 'import'"),Move_to_a_new_file:t(95049,e.DiagnosticCategory.Message,"Move_to_a_new_file_95049","Move to a new file"),Remove_unreachable_code:t(95050,e.DiagnosticCategory.Message,"Remove_unreachable_code_95050","Remove unreachable code"),Remove_all_unreachable_code:t(95051,e.DiagnosticCategory.Message,"Remove_all_unreachable_code_95051","Remove all unreachable code"),Add_missing_typeof:t(95052,e.DiagnosticCategory.Message,"Add_missing_typeof_95052","Add missing 'typeof'"),Remove_unused_label:t(95053,e.DiagnosticCategory.Message,"Remove_unused_label_95053","Remove unused label"),Remove_all_unused_labels:t(95054,e.DiagnosticCategory.Message,"Remove_all_unused_labels_95054","Remove all unused labels"),Convert_0_to_mapped_object_type:t(95055,e.DiagnosticCategory.Message,"Convert_0_to_mapped_object_type_95055","Convert '{0}' to mapped object type"),Convert_namespace_import_to_named_imports:t(95056,e.DiagnosticCategory.Message,"Convert_namespace_import_to_named_imports_95056","Convert namespace import to named imports"),Convert_named_imports_to_namespace_import:t(95057,e.DiagnosticCategory.Message,"Convert_named_imports_to_namespace_import_95057","Convert named imports to namespace import"),Add_or_remove_braces_in_an_arrow_function:t(95058,e.DiagnosticCategory.Message,"Add_or_remove_braces_in_an_arrow_function_95058","Add or remove braces in an arrow function"),Add_braces_to_arrow_function:t(95059,e.DiagnosticCategory.Message,"Add_braces_to_arrow_function_95059","Add braces to arrow function"),Remove_braces_from_arrow_function:t(95060,e.DiagnosticCategory.Message,"Remove_braces_from_arrow_function_95060","Remove braces from arrow function"),Convert_default_export_to_named_export:t(95061,e.DiagnosticCategory.Message,"Convert_default_export_to_named_export_95061","Convert default export to named export"),Convert_named_export_to_default_export:t(95062,e.DiagnosticCategory.Message,"Convert_named_export_to_default_export_95062","Convert named export to default export"),Add_missing_enum_member_0:t(95063,e.DiagnosticCategory.Message,"Add_missing_enum_member_0_95063","Add missing enum member '{0}'"),Add_all_missing_imports:t(95064,e.DiagnosticCategory.Message,"Add_all_missing_imports_95064","Add all missing imports"),Convert_to_async_function:t(95065,e.DiagnosticCategory.Message,"Convert_to_async_function_95065","Convert to async function"),Convert_all_to_async_functions:t(95066,e.DiagnosticCategory.Message,"Convert_all_to_async_functions_95066","Convert all to async functions"),Generate_types_for_0:t(95067,e.DiagnosticCategory.Message,"Generate_types_for_0_95067","Generate types for '{0}'"),Generate_types_for_all_packages_without_types:t(95068,e.DiagnosticCategory.Message,"Generate_types_for_all_packages_without_types_95068","Generate types for all packages without types"),Add_unknown_conversion_for_non_overlapping_types:t(95069,e.DiagnosticCategory.Message,"Add_unknown_conversion_for_non_overlapping_types_95069","Add 'unknown' conversion for non-overlapping types"),Add_unknown_to_all_conversions_of_non_overlapping_types:t(95070,e.DiagnosticCategory.Message,"Add_unknown_to_all_conversions_of_non_overlapping_types_95070","Add 'unknown' to all conversions of non-overlapping types"),Add_missing_new_operator_to_call:t(95071,e.DiagnosticCategory.Message,"Add_missing_new_operator_to_call_95071","Add missing 'new' operator to call"),Add_missing_new_operator_to_all_calls:t(95072,e.DiagnosticCategory.Message,"Add_missing_new_operator_to_all_calls_95072","Add missing 'new' operator to all calls"),Add_names_to_all_parameters_without_names:t(95073,e.DiagnosticCategory.Message,"Add_names_to_all_parameters_without_names_95073","Add names to all parameters without names")}}(c||(c={})),function(e){var t;function r(e){return e>=72}e.tokenIsIdentifierOrKeyword=r,e.tokenIsIdentifierOrKeywordOrGreaterThan=function(e){return 30===e||r(e)};var n=((t={abstract:118,any:120,as:119,bigint:146,boolean:123,break:73,case:74,catch:75,class:76,continue:78,const:77}).constructor=124,t.debugger=79,t.declare=125,t.default=80,t.delete=81,t.do=82,t.else=83,t.enum=84,t.export=85,t.extends=86,t.false=87,t.finally=88,t.for=89,t.from=144,t.function=90,t.get=126,t.if=91,t.implements=109,t.import=92,t.in=93,t.infer=127,t.instanceof=94,t.interface=110,t.is=128,t.keyof=129,t.let=111,t.module=130,t.namespace=131,t.never=132,t.new=95,t.null=96,t.number=135,t.object=136,t.package=112,t.private=113,t.protected=114,t.public=115,t.readonly=133,t.require=134,t.global=145,t.return=97,t.set=137,t.static=116,t.string=138,t.super=98,t.switch=99,t.symbol=139,t.this=100,t.throw=101,t.true=102,t.try=103,t.type=140,t.typeof=104,t.undefined=141,t.unique=142,t.unknown=143,t.var=105,t.void=106,t.while=107,t.with=108,t.yield=117,t.async=121,t.await=122,t.of=147,t),a=e.createMapFromTemplate(n),o=e.createMapFromTemplate(i({},n,{"{":18,"}":19,"(":20,")":21,"[":22,"]":23,".":24,"...":25,";":26,",":27,"<":28,">":30,"<=":31,">=":32,"==":33,"!=":34,"===":35,"!==":36,"=>":37,"+":38,"-":39,"**":41,"*":40,"/":42,"%":43,"++":44,"--":45,"<<":46,">":47,">>>":48,"&":49,"|":50,"^":51,"!":52,"~":53,"&&":54,"||":55,"?":56,":":57,"=":59,"+=":60,"-=":61,"*=":62,"**=":63,"/=":64,"%=":65,"<<=":66,">>=":67,">>>=":68,"&=":69,"|=":70,"^=":71,"@":58})),s=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1569,1594,1600,1610,1649,1747,1749,1749,1765,1766,1786,1788,1808,1808,1810,1836,1920,1957,2309,2361,2365,2365,2384,2384,2392,2401,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2784,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2877,2877,2908,2909,2911,2913,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3294,3294,3296,3297,3333,3340,3342,3344,3346,3368,3370,3385,3424,3425,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3805,3840,3840,3904,3911,3913,3946,3976,3979,4096,4129,4131,4135,4137,4138,4176,4181,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6067,6176,6263,6272,6312,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8319,8319,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12329,12337,12341,12344,12346,12353,12436,12445,12446,12449,12538,12540,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65138,65140,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],c=[170,170,181,181,186,186,192,214,216,246,248,543,546,563,592,685,688,696,699,705,720,721,736,740,750,750,768,846,864,866,890,890,902,902,904,906,908,908,910,929,931,974,976,983,986,1011,1024,1153,1155,1158,1164,1220,1223,1224,1227,1228,1232,1269,1272,1273,1329,1366,1369,1369,1377,1415,1425,1441,1443,1465,1467,1469,1471,1471,1473,1474,1476,1476,1488,1514,1520,1522,1569,1594,1600,1621,1632,1641,1648,1747,1749,1756,1759,1768,1770,1773,1776,1788,1808,1836,1840,1866,1920,1968,2305,2307,2309,2361,2364,2381,2384,2388,2392,2403,2406,2415,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2492,2494,2500,2503,2504,2507,2509,2519,2519,2524,2525,2527,2531,2534,2545,2562,2562,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2649,2652,2654,2654,2662,2676,2689,2691,2693,2699,2701,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2784,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2870,2873,2876,2883,2887,2888,2891,2893,2902,2903,2908,2909,2911,2913,2918,2927,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,2997,2999,3001,3006,3010,3014,3016,3018,3021,3031,3031,3047,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3134,3140,3142,3144,3146,3149,3157,3158,3168,3169,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3262,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3297,3302,3311,3330,3331,3333,3340,3342,3344,3346,3368,3370,3385,3390,3395,3398,3400,3402,3405,3415,3415,3424,3425,3430,3439,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3805,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3946,3953,3972,3974,3979,3984,3991,3993,4028,4038,4038,4096,4129,4131,4135,4137,4138,4140,4146,4150,4153,4160,4169,4176,4185,4256,4293,4304,4342,4352,4441,4447,4514,4520,4601,4608,4614,4616,4678,4680,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4742,4744,4744,4746,4749,4752,4782,4784,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4814,4816,4822,4824,4846,4848,4878,4880,4880,4882,4885,4888,4894,4896,4934,4936,4954,4969,4977,5024,5108,5121,5740,5743,5750,5761,5786,5792,5866,6016,6099,6112,6121,6160,6169,6176,6263,6272,6313,7680,7835,7840,7929,7936,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8255,8256,8319,8319,8400,8412,8417,8417,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8497,8499,8505,8544,8579,12293,12295,12321,12335,12337,12341,12344,12346,12353,12436,12441,12442,12445,12446,12449,12542,12549,12588,12593,12686,12704,12727,13312,19893,19968,40869,40960,42124,44032,55203,63744,64045,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65056,65059,65075,65076,65101,65103,65136,65138,65140,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65381,65470,65474,65479,65482,65487,65490,65495,65498,65500],u=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1319,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1568,1610,1646,1647,1649,1747,1749,1749,1765,1766,1774,1775,1786,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1994,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2208,2208,2210,2220,2308,2361,2365,2365,2384,2384,2392,2401,2417,2423,2425,2431,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2929,2929,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3160,3161,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3294,3294,3296,3297,3313,3314,3333,3340,3342,3344,3346,3386,3389,3389,3406,3406,3424,3425,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3807,3840,3840,3904,3911,3913,3948,3976,3980,4096,4138,4159,4159,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5920,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6176,6263,6272,6312,6314,6314,6320,6389,6400,6428,6480,6509,6512,6516,6528,6571,6593,6599,6656,6678,6688,6740,6823,6823,6917,6963,6981,6987,7043,7072,7086,7087,7098,7141,7168,7203,7245,7247,7258,7293,7401,7404,7406,7409,7413,7414,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8305,8305,8319,8319,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11502,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42527,42538,42539,42560,42606,42623,42647,42656,42735,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43009,43011,43013,43015,43018,43020,43042,43072,43123,43138,43187,43250,43255,43259,43259,43274,43301,43312,43334,43360,43388,43396,43442,43471,43471,43520,43560,43584,43586,43588,43595,43616,43638,43642,43642,43648,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500],l=[170,170,181,181,186,186,192,214,216,246,248,705,710,721,736,740,748,748,750,750,768,884,886,887,890,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1155,1159,1162,1319,1329,1366,1369,1369,1377,1415,1425,1469,1471,1471,1473,1474,1476,1477,1479,1479,1488,1514,1520,1522,1552,1562,1568,1641,1646,1747,1749,1756,1759,1768,1770,1788,1791,1791,1808,1866,1869,1969,1984,2037,2042,2042,2048,2093,2112,2139,2208,2208,2210,2220,2276,2302,2304,2403,2406,2415,2417,2423,2425,2431,2433,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2500,2503,2504,2507,2510,2519,2519,2524,2525,2527,2531,2534,2545,2561,2563,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2626,2631,2632,2635,2637,2641,2641,2649,2652,2654,2654,2662,2677,2689,2691,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2757,2759,2761,2763,2765,2768,2768,2784,2787,2790,2799,2817,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2876,2884,2887,2888,2891,2893,2902,2903,2908,2909,2911,2915,2918,2927,2929,2929,2946,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3006,3010,3014,3016,3018,3021,3024,3024,3031,3031,3046,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3140,3142,3144,3146,3149,3157,3158,3160,3161,3168,3171,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3260,3268,3270,3272,3274,3277,3285,3286,3294,3294,3296,3299,3302,3311,3313,3314,3330,3331,3333,3340,3342,3344,3346,3386,3389,3396,3398,3400,3402,3406,3415,3415,3424,3427,3430,3439,3450,3455,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3540,3542,3542,3544,3551,3570,3571,3585,3642,3648,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3769,3771,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3807,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3911,3913,3948,3953,3972,3974,3991,3993,4028,4038,4038,4096,4169,4176,4253,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4957,4959,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5908,5920,5940,5952,5971,5984,5996,5998,6e3,6002,6003,6016,6099,6103,6103,6108,6109,6112,6121,6155,6157,6160,6169,6176,6263,6272,6314,6320,6389,6400,6428,6432,6443,6448,6459,6470,6509,6512,6516,6528,6571,6576,6601,6608,6617,6656,6683,6688,6750,6752,6780,6783,6793,6800,6809,6823,6823,6912,6987,6992,7001,7019,7027,7040,7155,7168,7223,7232,7241,7245,7293,7376,7378,7380,7414,7424,7654,7676,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8204,8205,8255,8256,8276,8276,8305,8305,8319,8319,8336,8348,8400,8412,8417,8417,8421,8432,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8544,8584,11264,11310,11312,11358,11360,11492,11499,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11647,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11744,11775,11823,11823,12293,12295,12321,12335,12337,12341,12344,12348,12353,12438,12441,12442,12445,12447,12449,12538,12540,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,42124,42192,42237,42240,42508,42512,42539,42560,42607,42612,42621,42623,42647,42655,42737,42775,42783,42786,42888,42891,42894,42896,42899,42912,42922,43e3,43047,43072,43123,43136,43204,43216,43225,43232,43255,43259,43259,43264,43309,43312,43347,43360,43388,43392,43456,43471,43481,43520,43574,43584,43597,43600,43609,43616,43638,43642,43643,43648,43714,43739,43741,43744,43759,43762,43766,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44010,44012,44013,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65024,65039,65056,65062,65075,65076,65101,65103,65136,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500];function _(e,t){if(e=1?u:s)}e.isUnicodeIdentifierStart=d;var p,f=(p=[],o.forEach(function(e,t){p[e]=t}),p);function m(e){for(var t=new Array,r=0,n=0;r127&&D(i)&&(t.push(n),n=r)}}return t.push(n),t}function g(t,r,n,i,a){(r<0||r>=t.length)&&(a?r=r<0?0:r>=t.length?t.length-1:r:e.Debug.fail("Bad line number. Line: "+r+", lineStarts.length: "+t.length+" , line map is correct? "+(void 0!==i?e.arraysEqual(t,m(i)):"unknown")));var o=t[r]+n;return a?o>t[r+1]?t[r+1]:"string"==typeof i&&o>i.length?i.length:o:(r=8192&&e<=8203||8239===e||8287===e||12288===e||65279===e}function D(e){return 10===e||13===e||8232===e||8233===e}function x(e){return e>=48&&e<=57}function S(e){return e>=48&&e<=55}e.tokenToString=function(e){return f[e]},e.stringToToken=function(e){return o.get(e)},e.computeLineStarts=m,e.getPositionOfLineAndCharacter=function(e,t,r){return g(y(e),t,r,e.text)},e.getPositionOfLineAndCharacterWithEdits=function(e,t,r){return g(y(e),t,r,e.text,!0)},e.computePositionOfLineAndCharacter=g,e.getLineStarts=y,e.computeLineAndCharacterOfPosition=v,e.getLineAndCharacterOfPosition=function(e,t){return v(y(e),t)},e.isWhiteSpaceLike=h,e.isWhiteSpaceSingleLine=b,e.isLineBreak=D,e.isOctalDigit=S,e.couldStartTrivia=function(e,t){var r=e.charCodeAt(t);switch(r){case 13:case 10:case 9:case 11:case 12:case 32:case 47:case 60:case 124:case 61:case 62:return!0;case 35:return 0===t;default:return r>127}},e.skipTrivia=function(t,r,n,i){if(void 0===i&&(i=!1),e.positionIsSynthesized(r))return r;for(;;){var a=t.charCodeAt(r);switch(a){case 13:10===t.charCodeAt(r+1)&&r++;case 10:if(r++,n)return r;continue;case 9:case 11:case 12:case 32:r++;continue;case 47:if(i)break;if(47===t.charCodeAt(r+1)){for(r+=2;r127&&h(a)){r++;continue}}return r}};var T="<<<<<<<".length;function C(t,r){if(e.Debug.assert(r>=0),0===r||D(t.charCodeAt(r-1))){var n=t.charCodeAt(r);if(r+T=0&&r127&&h(f)){_&&D(f)&&(l=!0),r++;continue}break e}}return _&&(p=i(s,c,u,l,a,p)),p}function P(e,t,r,n,i){return F(!0,e,t,!1,r,n,i)}function w(e,t,r,n,i){return F(!0,e,t,!0,r,n,i)}function O(e,t,r,n,i,a){return a||(a=[]),a.push({kind:r,pos:e,end:t,hasTrailingNewLine:n}),a}function I(e,t){return e>=65&&e<=90||e>=97&&e<=122||36===e||95===e||e>127&&d(e,t)}function M(e,t){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||36===e||95===e||e>127&&function(e,t){return _(e,t>=1?l:c)}(e,t)}e.forEachLeadingCommentRange=function(e,t,r,n){return F(!1,e,t,!1,r,n)},e.forEachTrailingCommentRange=function(e,t,r,n){return F(!1,e,t,!0,r,n)},e.reduceEachLeadingCommentRange=P,e.reduceEachTrailingCommentRange=w,e.getLeadingCommentRanges=function(e,t){return P(e,t,O,void 0,void 0)},e.getTrailingCommentRanges=function(e,t){return w(e,t,O,void 0,void 0)},e.getShebang=function(e){var t=E.exec(e);if(t)return t[0]},e.isIdentifierStart=I,e.isIdentifierPart=M,e.isIdentifierText=function(e,t){if(!I(e.charCodeAt(0),t))return!1;for(var r=1;r108},isReservedWord:function(){return f>=73&&f<=108},isUnterminated:function(){return 0!=(4&g)},getTokenFlags:function(){return g},reScanGreaterToken:function(){if(30===f){if(62===y.charCodeAt(l))return 62===y.charCodeAt(l+1)?61===y.charCodeAt(l+2)?(l+=3,f=68):(l+=2,f=48):61===y.charCodeAt(l+1)?(l+=2,f=67):(l++,f=47);if(61===y.charCodeAt(l))return l++,f=32}return f},reScanSlashToken:function(){if(42===f||64===f){for(var r=p+1,n=!1,i=!1;;){if(r>=_){g|=4,T(e.Diagnostics.Unterminated_regular_expression_literal);break}var a=y.charCodeAt(r);if(D(a)){g|=4,T(e.Diagnostics.Unterminated_regular_expression_literal);break}if(n)n=!1;else{if(47===a&&!i){r++;break}91===a?i=!0:92===a?n=!0:93===a&&(i=!1)}r++}for(;r<_&&M(y.charCodeAt(r),t);)r++;l=r,m=y.substring(p,l),f=13}return f},reScanTemplateToken:function(){return e.Debug.assert(19===f,"'reScanTemplateToken' should only be called on a '}'"),l=p,f=B()},scanJsxIdentifier:function(){if(r(f)){for(var e=l;l<_;){var n=y.charCodeAt(l);if(45!==n&&(e===l?!I(n,t):!M(n,t)))break;l++}m+=y.substring(e,l)}return f},scanJsxAttributeValue:function(){switch(d=l,y.charCodeAt(l)){case 34:case 39:return m=R(!0),f=10;default:return W()}},reScanJsxToken:function(){return l=p=d,f=H()},scanJsxToken:H,scanJSDocToken:function(){if(d=p=l,g=0,l>=_)return f=1;var e=y.charCodeAt(l);switch(l++,e){case 9:case 11:case 12:case 32:for(;l<_&&b(y.charCodeAt(l));)l++;return f=5;case 64:return f=58;case 10:case 13:return g|=1,f=4;case 42:return f=40;case 123:return f=18;case 125:return f=19;case 91:return f=22;case 93:return f=23;case 60:return f=28;case 61:return f=59;case 44:return f=27;case 46:return f=24;case 96:for(;l<_&&96!==y.charCodeAt(l);)l++;return m=y.substring(p+1,l),l++,f=14}if(I(e,6)){for(;M(y.charCodeAt(l),6)&&l<_;)l++;return m=y.substring(p,l),f=U()}return f=0},scan:W,getText:function(){return y},setText:Y,setScriptTarget:function(e){t=e},setLanguageVariant:function(e){i=e},setOnError:function(e){s=e},setTextPos:X,setInJSDocType:function(e){v+=e?1:-1},tryScan:function(e){return G(e,!1)},lookAhead:function(e){return G(e,!0)},scanRange:function(e,t,r){var n=_,i=l,a=d,o=p,s=f,c=m,u=g;Y(y,e,t);var v=r();return _=n,l=i,d=a,p=o,f=s,m=c,g=u,v}};function T(e,t,r){if(void 0===t&&(t=l),s){var n=l;l=t,s(e,r||0),l=n}}function E(){for(var t=l,r=!1,n=!1,i="";;){var a=y.charCodeAt(l);if(95!==a){if(!x(a))break;r=!0,n=!1,l++}else g|=512,r?(r=!1,n=!0,i+=y.substring(t,l)):T(n?e.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted:e.Diagnostics.Numeric_separators_are_not_allowed_here,l,1),t=++l}return 95===y.charCodeAt(l-1)&&T(e.Diagnostics.Numeric_separators_are_not_allowed_here,l-1,1),i+y.substring(t,l)}function F(){var t,r,n=l,i=E();46===y.charCodeAt(l)&&(l++,t=E());var a,o=l;if(69===y.charCodeAt(l)||101===y.charCodeAt(l)){l++,g|=16,43!==y.charCodeAt(l)&&45!==y.charCodeAt(l)||l++;var s=l,c=E();c?(r=y.substring(o,s)+c,o=l):T(e.Diagnostics.Digit_expected)}return 512&g?(a=i,t&&(a+="."+t),r&&(a+=r)):a=y.substring(n,o),void 0!==t||16&g?{type:8,value:""+ +a}:(m=a,{type:q(),value:m})}function P(){for(var e=l;S(y.charCodeAt(l));)l++;return+y.substring(e,l)}function w(e,t){var r=L(e,!1,t);return r?parseInt(r,16):-1}function O(e,t){return L(e,!0,t)}function L(t,r,n){for(var i=[],a=!1,o=!1;i.length=65&&s<=70)s+=32;else if(!(s>=48&&s<=57||s>=97&&s<=102))break;i.push(s),l++,o=!1}}return i.length=_){n+=y.substring(i,l),g|=4,T(e.Diagnostics.Unterminated_string_literal);break}var a=y.charCodeAt(l);if(a===r){n+=y.substring(i,l),l++;break}if(92!==a||t){if(D(a)&&!t){n+=y.substring(i,l),g|=4,T(e.Diagnostics.Unterminated_string_literal);break}l++}else n+=y.substring(i,l),n+=j(),i=l}return n}function B(){for(var t,r=96===y.charCodeAt(l),n=++l,i="";;){if(l>=_){i+=y.substring(n,l),g|=4,T(e.Diagnostics.Unterminated_template_literal),t=r?14:17;break}var a=y.charCodeAt(l);if(96===a){i+=y.substring(n,l),l++,t=r?14:17;break}if(36===a&&l+1<_&&123===y.charCodeAt(l+1)){i+=y.substring(n,l),l+=2,t=r?15:16;break}92!==a?13!==a?l++:(i+=y.substring(n,l),++l<_&&10===y.charCodeAt(l)&&l++,i+="\n",n=l):(i+=y.substring(n,l),i+=j(),n=l)}return e.Debug.assert(void 0!==t),m=i,t}function j(){if(++l>=_)return T(e.Diagnostics.Unexpected_end_of_text),"";var t,r,n,i=y.charCodeAt(l);switch(l++,i){case 48:return"\0";case 98:return"\b";case 116:return"\t";case 110:return"\n";case 118:return"\v";case 102:return"\f";case 114:return"\r";case 39:return"'";case 34:return'"';case 117:return l<_&&123===y.charCodeAt(l)?(g|=8,l++,t=O(1,!1),r=t?parseInt(t,16):-1,n=!1,r<0?(T(e.Diagnostics.Hexadecimal_digit_expected),n=!0):r>1114111&&(T(e.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive),n=!0),l>=_?(T(e.Diagnostics.Unexpected_end_of_text),n=!0):125===y.charCodeAt(l)?l++:(T(e.Diagnostics.Unterminated_Unicode_escape_sequence),n=!0),n?"":function(t){if(e.Debug.assert(0<=t&&t<=1114111),t<=65535)return String.fromCharCode(t);var r=Math.floor((t-65536)/1024)+55296,n=(t-65536)%1024+56320;return String.fromCharCode(r,n)}(r)):J(4);case 120:return J(2);case 13:l<_&&10===y.charCodeAt(l)&&l++;case 10:case 8232:case 8233:return"";default:return String.fromCharCode(i)}}function J(t){var r=w(t,!1);return r>=0?String.fromCharCode(r):(T(e.Diagnostics.Hexadecimal_digit_expected),"")}function z(){if(l+5<_&&117===y.charCodeAt(l+1)){var e=l;l+=2;var t=w(4,!1);return l=e,t}return-1}function K(){for(var e="",r=l;l<_;){var n=y.charCodeAt(l);if(M(n,t))l++;else{if(92!==n)break;if(!((n=z())>=0&&M(n,t)))break;e+=y.substring(r,l),e+=String.fromCharCode(n),r=l+=6}}return e+=y.substring(r,l)}function U(){var e=m.length;if(e>=2&&e<=11){var t=m.charCodeAt(0);if(t>=97&&t<=122){var r=a.get(m);if(void 0!==r)return f=r}}return f=72}function V(t){for(var r="",n=!1,i=!1;;){var a=y.charCodeAt(l);if(95!==a){if(n=!0,!x(a)||a-48>=t)break;r+=y[l],l++,i=!1}else g|=512,n?(n=!1,i=!0):T(i?e.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted:e.Diagnostics.Numeric_separators_are_not_allowed_here,l,1),l++}return 95===y.charCodeAt(l-1)&&T(e.Diagnostics.Numeric_separators_are_not_allowed_here,l-1,1),r}function q(){if(110===y.charCodeAt(l))return m+="n",384&g&&(m=e.parsePseudoBigInt(m)+"n"),l++,9;var t=128&g?parseInt(m.slice(2),2):256&g?parseInt(m.slice(2),8):+m;return m=""+t,8}function W(){var r;d=l,g=0;for(var a=!1;;){if(p=l,l>=_)return f=1;var o=y.charCodeAt(l);if(35===o&&0===l&&N(y,l)){if(l=A(y,l),n)continue;return f=6}switch(o){case 10:case 13:if(g|=1,n){l++;continue}return 13===o&&l+1<_&&10===y.charCodeAt(l+1)?l+=2:l++,f=4;case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8203:case 8239:case 8287:case 12288:case 65279:if(n){l++;continue}for(;l<_&&b(y.charCodeAt(l));)l++;return f=5;case 33:return 61===y.charCodeAt(l+1)?61===y.charCodeAt(l+2)?(l+=3,f=36):(l+=2,f=34):(l++,f=52);case 34:case 39:return m=R(),f=10;case 96:return f=B();case 37:return 61===y.charCodeAt(l+1)?(l+=2,f=65):(l++,f=43);case 38:return 38===y.charCodeAt(l+1)?(l+=2,f=54):61===y.charCodeAt(l+1)?(l+=2,f=69):(l++,f=49);case 40:return l++,f=20;case 41:return l++,f=21;case 42:if(61===y.charCodeAt(l+1))return l+=2,f=62;if(42===y.charCodeAt(l+1))return 61===y.charCodeAt(l+2)?(l+=3,f=63):(l+=2,f=41);if(l++,v&&!a&&1&g){a=!0;continue}return f=40;case 43:return 43===y.charCodeAt(l+1)?(l+=2,f=44):61===y.charCodeAt(l+1)?(l+=2,f=60):(l++,f=38);case 44:return l++,f=27;case 45:return 45===y.charCodeAt(l+1)?(l+=2,f=45):61===y.charCodeAt(l+1)?(l+=2,f=61):(l++,f=39);case 46:return x(y.charCodeAt(l+1))?(m=F().value,f=8):46===y.charCodeAt(l+1)&&46===y.charCodeAt(l+2)?(l+=3,f=25):(l++,f=24);case 47:if(47===y.charCodeAt(l+1)){for(l+=2;l<_&&!D(y.charCodeAt(l));)l++;if(n)continue;return f=2}if(42===y.charCodeAt(l+1)){l+=2,42===y.charCodeAt(l)&&47!==y.charCodeAt(l+1)&&(g|=2);for(var s=!1;l<_;){var c=y.charCodeAt(l);if(42===c&&47===y.charCodeAt(l+1)){l+=2,s=!0;break}D(c)&&(g|=1),l++}if(s||T(e.Diagnostics.Asterisk_Slash_expected),n)continue;return s||(g|=4),f=3}return 61===y.charCodeAt(l+1)?(l+=2,f=64):(l++,f=42);case 48:if(l+2<_&&(88===y.charCodeAt(l+1)||120===y.charCodeAt(l+1)))return l+=2,(m=O(1,!0))||(T(e.Diagnostics.Hexadecimal_digit_expected),m="0"),m="0x"+m,g|=64,f=q();if(l+2<_&&(66===y.charCodeAt(l+1)||98===y.charCodeAt(l+1)))return l+=2,(m=V(2))||(T(e.Diagnostics.Binary_digit_expected),m="0"),m="0b"+m,g|=128,f=q();if(l+2<_&&(79===y.charCodeAt(l+1)||111===y.charCodeAt(l+1)))return l+=2,(m=V(8))||(T(e.Diagnostics.Octal_digit_expected),m="0"),m="0o"+m,g|=256,f=q();if(l+1<_&&S(y.charCodeAt(l+1)))return m=""+P(),g|=32,f=8;case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return r=F(),f=r.type,m=r.value,f;case 58:return l++,f=57;case 59:return l++,f=26;case 60:if(C(y,l)){if(l=k(y,l,T),n)continue;return f=7}return 60===y.charCodeAt(l+1)?61===y.charCodeAt(l+2)?(l+=3,f=66):(l+=2,f=46):61===y.charCodeAt(l+1)?(l+=2,f=31):1===i&&47===y.charCodeAt(l+1)&&42!==y.charCodeAt(l+2)?(l+=2,f=29):(l++,f=28);case 61:if(C(y,l)){if(l=k(y,l,T),n)continue;return f=7}return 61===y.charCodeAt(l+1)?61===y.charCodeAt(l+2)?(l+=3,f=35):(l+=2,f=33):62===y.charCodeAt(l+1)?(l+=2,f=37):(l++,f=59);case 62:if(C(y,l)){if(l=k(y,l,T),n)continue;return f=7}return l++,f=30;case 63:return l++,f=56;case 91:return l++,f=22;case 93:return l++,f=23;case 94:return 61===y.charCodeAt(l+1)?(l+=2,f=71):(l++,f=51);case 123:return l++,f=18;case 124:if(C(y,l)){if(l=k(y,l,T),n)continue;return f=7}return 124===y.charCodeAt(l+1)?(l+=2,f=55):61===y.charCodeAt(l+1)?(l+=2,f=70):(l++,f=50);case 125:return l++,f=19;case 126:return l++,f=53;case 64:return l++,f=58;case 92:var u=z();return u>=0&&I(u,t)?(l+=6,m=String.fromCharCode(u)+K(),f=U()):(T(e.Diagnostics.Invalid_character),l++,f=0);default:if(I(o,t)){for(l++;l<_&&M(o=y.charCodeAt(l),t);)l++;return m=y.substring(p,l),92===o&&(m+=K()),f=U()}if(b(o)){l++;continue}if(D(o)){g|=1,l++;continue}return T(e.Diagnostics.Invalid_character),l++,f=0}}}function H(){if(d=p=l,l>=_)return f=1;var e=y.charCodeAt(l);if(60===e)return 47===y.charCodeAt(l+1)?(l+=2,f=29):(l++,f=28);if(123===e)return l++,f=18;for(var t=0;l<_&&123!==(e=y.charCodeAt(l));){if(60===e){if(C(y,l))return l=k(y,l,T),f=7;break}D(e)&&0===t?t=-1:h(e)||(t=l),l++}return-1===t?12:11}function G(e,t){var r=l,n=d,i=p,a=f,o=m,s=g,c=e();return c&&!t||(l=r,d=n,p=i,f=a,m=o,g=s),c}function Y(e,t,r){y=e||"",_=void 0===r?y.length:t+r,X(t||0)}function X(t){e.Debug.assert(t>=0),l=t,d=t,p=t,f=0,m=void 0,g=0}}}(c||(c={})),function(e){e.isExternalModuleNameRelative=function(t){return e.pathIsRelative(t)||e.isRootedDiskPath(t)},e.sortAndDeduplicateDiagnostics=function(t){return e.sortAndDeduplicate(t,e.compareDiagnostics)}}(c||(c={})),function(e){e.resolvingEmptyArray=[],e.emptyMap=e.createMap(),e.emptyUnderscoreEscapedMap=e.emptyMap,e.externalHelpersModuleNameText="tslib",e.defaultMaximumTruncationLength=160,e.getDeclarationOfKind=function(e,t){var r=e.declarations;if(r)for(var n=0,i=r;n=0);var n=e.getLineStarts(r),i=t,a=r.text;if(i+1===n.length)return a.length-1;var o=n[i],s=n[i+1]-1;for(e.Debug.assert(e.isLineBreak(a.charCodeAt(s)));o<=s&&e.isLineBreak(a.charCodeAt(s));)s--;return s}function d(e){return void 0===e||e.pos===e.end&&e.pos>=0&&1!==e.kind}function p(e){return!d(e)}function m(e,t){return 42===e.charCodeAt(t+1)&&33===e.charCodeAt(t+2)}function g(t,r,n){return d(t)?t.pos:e.isJSDocNode(t)?e.skipTrivia((r||l(t)).text,t.pos,!1,!0):n&&e.hasJSDocNodes(t)?g(t.jsDoc[0]):306===t.kind&&t._children.length>0?g(t._children[0],r,n):e.skipTrivia((r||l(t)).text,t.pos)}function y(e,t,r){return void 0===r&&(r=!1),v(e.text,t,r)}function v(t,r,n){if(void 0===n&&(n=!1),d(r))return"";var i=t.substring(n?r.pos:e.skipTrivia(t,r.pos),r.end);return function e(t){return 283===t.kind||t.parent&&e(t.parent)}(r)&&(i=i.replace(/(^|\r?\n|\r)\s*\*\s*/g,"$1")),i}function h(e,t){return void 0===t&&(t=!1),y(l(e),e,t)}function b(e){return e.pos}function D(e){var t=e.emitNode;return t&&t.flags||0}function x(e){var t=qe(e);return 237===t.kind&&274===t.parent.kind}function S(t){return e.isModuleDeclaration(t)&&(10===t.name.kind||T(t))}function T(e){return!!(512&e.flags)}function C(e){return S(e)&&k(e)}function k(t){switch(t.parent.kind){case 279:return e.isExternalModule(t.parent);case 245:return S(t.parent.parent)&&e.isSourceFile(t.parent.parent.parent)&&!e.isExternalModule(t.parent.parent.parent)}return!1}function E(t,r){switch(t.kind){case 279:case 246:case 274:case 244:case 225:case 226:case 227:case 157:case 156:case 158:case 159:case 239:case 196:case 197:return!0;case 218:return!e.isFunctionLike(r)}return!1}function N(t){switch(t.kind){case 160:case 161:case 155:case 162:case 165:case 166:case 289:case 240:case 209:case 241:case 242:case 303:case 239:case 156:case 157:case 158:case 159:case 196:case 197:return!0;default:return e.assertType(t),!1}}function A(e){switch(e.kind){case 249:case 248:return!0;default:return!1}}function F(e){return e&&0!==c(e)?h(e):"(Missing)"}function P(t){switch(t.kind){case 72:return t.escapedText;case 10:case 8:case 14:return e.escapeLeadingUnderscores(t.text);case 149:return Be(t.expression)?e.escapeLeadingUnderscores(t.expression.text):void 0;default:return e.Debug.assertNever(t)}}function w(t,r,n,i,a,o,s){var c=I(t,r);return e.createFileDiagnostic(t,c.start,c.length,n,i,a,o,s)}function O(t,r){var n=e.createScanner(t.languageVersion,!0,t.languageVariant,t.text,void 0,r);n.scan();var i=n.getTokenPos();return e.createTextSpanFromBounds(i,n.getTextPos())}function I(t,r){var n=r;switch(r.kind){case 279:var i=e.skipTrivia(t.text,0,!1);return i===t.text.length?e.createTextSpan(0,0):O(t,i);case 237:case 186:case 240:case 209:case 241:case 244:case 243:case 278:case 239:case 196:case 156:case 158:case 159:case 242:case 154:case 153:n=r.name;break;case 197:return function(t,r){var n=e.skipTrivia(t.text,r.pos);if(r.body&&218===r.body.kind){var i=e.getLineAndCharacterOfPosition(t,r.body.pos).line;if(i=n.pos,"This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809"),e.Debug.assert(o<=n.end,"This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809")),e.createTextSpanFromBounds(o,n.end)}function M(t){return!!(2&e.getCombinedNodeFlags(t))}function L(e){return 191===e.kind&&92===e.expression.kind}function R(t){return e.isImportTypeNode(t)&&e.isLiteralTypeNode(t.argument)&&e.isStringLiteral(t.argument.literal)}function B(e){return 221===e.kind&&10===e.expression.kind}e.toPath=a,e.changesAffectModuleResolution=function(t,r){return t.configFilePath!==r.configFilePath||e.moduleResolutionOptionDeclarations.some(function(n){return!e.isJsonEqual(e.getCompilerOptionValue(t,n),e.getCompilerOptionValue(r,n))})},e.findAncestor=o,e.forEachAncestor=function(t,r){for(;;){var n=r(t);if("quit"===n)return;if(void 0!==n)return n;if(e.isSourceFile(t))return;t=t.parent}},e.forEachEntry=function(e,t){for(var r,n=e.entries(),i=n.next(),a=i.value,o=i.done;!o;a=(r=n.next()).value,o=r.done,r){var s=a[0],c=t(a[1],s);if(c)return c}},e.forEachKey=function(e,t){for(var r,n=e.keys(),i=n.next(),a=i.value,o=i.done;!o;a=(r=n.next()).value,o=r.done,r){var s=t(a);if(s)return s}},e.copyEntries=s,e.arrayToSet=function(t,r){return e.arrayToMap(t,r||function(e){return e},function(){return!0})},e.cloneMap=function(t){var r=e.createMap();return s(t,r),r},e.usingSingleLineStringWriter=function(e){var t=n.getText();try{return e(n),n.getText()}finally{n.clear(),n.writeKeyword(t)}},e.getFullWidth=c,e.getResolvedModule=function(e,t){return e&&e.resolvedModules&&e.resolvedModules.get(t)},e.setResolvedModule=function(t,r,n){t.resolvedModules||(t.resolvedModules=e.createMap()),t.resolvedModules.set(r,n)},e.setResolvedTypeReferenceDirective=function(t,r,n){t.resolvedTypeReferenceDirectiveNames||(t.resolvedTypeReferenceDirectiveNames=e.createMap()),t.resolvedTypeReferenceDirectiveNames.set(r,n)},e.projectReferenceIsEqualTo=function(e,t){return e.path===t.path&&!e.prepend==!t.prepend&&!e.circular==!t.circular},e.moduleResolutionIsEqualTo=function(e,t){return e.isExternalLibraryImport===t.isExternalLibraryImport&&e.extension===t.extension&&e.resolvedFileName===t.resolvedFileName&&e.originalPath===t.originalPath&&(r=e.packageId,n=t.packageId,r===n||!!r&&!!n&&r.name===n.name&&r.subModuleName===n.subModuleName&&r.version===n.version);var r,n},e.packageIdToString=function(e){var t=e.name,r=e.subModuleName,n=e.version;return(r?t+"/"+r:t)+"@"+n},e.typeDirectiveIsEqualTo=function(e,t){return e.resolvedFileName===t.resolvedFileName&&e.primary===t.primary},e.hasChangesInResolutions=function(t,r,n,i){e.Debug.assert(t.length===r.length);for(var a=0;a=0),e.getLineStarts(r)[t]},e.nodePosToString=function(t){var r=l(t),n=e.getLineAndCharacterOfPosition(r,t.pos);return r.fileName+"("+(n.line+1)+","+(n.character+1)+")"},e.getEndLinePosition=_,e.isFileLevelUniqueName=function(e,t,r){return!(r&&r(t)||e.identifiers.has(t))},e.nodeIsMissing=d,e.nodeIsPresent=p,e.addStatementsAfterPrologue=function(e,t){if(void 0===t||0===t.length)return e;for(var r=0;r/;var j=/^(\/\/\/\s*/;e.fullTripleSlashAMDReferencePathRegEx=/^(\/\/\/\s*/;var J=/^(\/\/\/\s*/;function z(t){if(163<=t.kind&&t.kind<=183)return!0;switch(t.kind){case 120:case 143:case 135:case 146:case 138:case 123:case 139:case 136:case 141:case 132:return!0;case 106:return 200!==t.parent.kind;case 211:return!Bt(t);case 150:return 181===t.parent.kind||176===t.parent.kind;case 72:148===t.parent.kind&&t.parent.right===t?t=t.parent:189===t.parent.kind&&t.parent.name===t&&(t=t.parent),e.Debug.assert(72===t.kind||148===t.kind||189===t.kind,"'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");case 148:case 189:case 100:var r=t.parent;if(167===r.kind)return!1;if(183===r.kind)return!r.isTypeOf;if(163<=r.kind&&r.kind<=183)return!0;switch(r.kind){case 211:return!Bt(r);case 150:case 303:return t===r.constraint;case 154:case 153:case 151:case 237:return t===r.type;case 239:case 196:case 197:case 157:case 156:case 155:case 158:case 159:return t===r.type;case 160:case 161:case 162:case 194:return t===r.type;case 191:case 192:return e.contains(r.typeArguments,t);case 193:return!1}}return!1}function K(e){if(e)switch(e.kind){case 186:case 278:case 151:case 275:case 154:case 153:case 276:case 237:return!0}return!1}function U(e){return 238===e.parent.kind&&219===e.parent.parent.kind}function V(e,t,r){return e.properties.filter(function(e){if(275===e.kind){var n=P(e.name);return t===n||!!r&&r===n}return!1})}function q(t){if(t&&t.statements.length){var r=t.statements[0].expression;return e.tryCast(r,e.isObjectLiteralExpression)}}function W(t,r){var n=q(t);return n?V(n,r):e.emptyArray}function H(t,r){for(e.Debug.assert(279!==t.kind);;){if(!(t=t.parent))return e.Debug.fail();switch(t.kind){case 149:if(e.isClassLike(t.parent.parent))return t;t=t.parent;break;case 152:151===t.parent.kind&&e.isClassElement(t.parent.parent)?t=t.parent.parent:e.isClassElement(t.parent)&&(t=t.parent);break;case 197:if(!r)continue;case 239:case 196:case 244:case 154:case 153:case 156:case 155:case 157:case 158:case 159:case 160:case 161:case 162:case 243:case 279:return t}}}function G(e,t,r){switch(e.kind){case 240:return!0;case 154:return 240===t.kind;case 158:case 159:case 156:return void 0!==e.body&&240===t.kind;case 151:return void 0!==t.body&&(157===t.kind||156===t.kind||159===t.kind)&&240===r.kind}return!1}function Y(e,t,r){return void 0!==e.decorators&&G(e,t,r)}function X(e,t,r){return Y(e,t,r)||Q(e,t)}function Q(t,r){switch(t.kind){case 240:return e.some(t.members,function(e){return X(e,t,r)});case 156:case 159:return e.some(t.parameters,function(e){return Y(e,t,r)});default:return!1}}function $(e){var t=e.parent;return(262===t.kind||261===t.kind||263===t.kind)&&t.tagName===e}function Z(e){switch(e.kind){case 98:case 96:case 102:case 87:case 13:case 187:case 188:case 189:case 190:case 191:case 192:case 193:case 212:case 194:case 213:case 195:case 196:case 209:case 197:case 200:case 198:case 199:case 202:case 203:case 204:case 205:case 208:case 206:case 14:case 210:case 260:case 261:case 264:case 207:case 201:case 214:return!0;case 148:for(;148===e.parent.kind;)e=e.parent;return 167===e.parent.kind||$(e);case 72:if(167===e.parent.kind||$(e))return!0;case 8:case 9:case 10:case 100:return ee(e);default:return!1}}function ee(e){var t=e.parent;switch(t.kind){case 237:case 151:case 154:case 153:case 278:case 275:case 186:return t.initializer===e;case 221:case 222:case 223:case 224:case 230:case 231:case 232:case 271:case 234:return t.expression===e;case 225:var r=t;return r.initializer===e&&238!==r.initializer.kind||r.condition===e||r.incrementor===e;case 226:case 227:var n=t;return n.initializer===e&&238!==n.initializer.kind||n.expression===e;case 194:case 212:case 216:case 149:return e===t.expression;case 152:case 270:case 269:case 277:return!0;case 211:return t.expression===e&&Bt(t);case 276:return t.objectAssignmentInitializer===e;default:return Z(t)}}function te(e){return 248===e.kind&&259===e.moduleReference.kind}function re(e){return ne(e)}function ne(e){return!!e&&!!(65536&e.flags)}function ie(t,r){if(191!==t.kind)return!1;var n=t,i=n.expression,a=n.arguments;if(72!==i.kind||"require"!==i.escapedText)return!1;if(1!==a.length)return!1;var o=a[0];return!r||e.isStringLiteralLike(o)}function ae(t){return ne(t)&&t.initializer&&e.isBinaryExpression(t.initializer)&&55===t.initializer.operatorToken.kind&&t.name&&jt(t.name)&&se(t.name,t.initializer.left)?t.initializer.right:t.initializer}function oe(t,r){if(e.isCallExpression(t)){var n=Ne(t.expression);return 196===n.kind||197===n.kind?t:void 0}return 196===t.kind||209===t.kind||197===t.kind?t:e.isObjectLiteralExpression(t)&&(0===t.properties.length||r)?t:void 0}function se(t,r){return e.isIdentifier(t)&&e.isIdentifier(r)?t.escapedText===r.escapedText:e.isIdentifier(t)&&e.isPropertyAccessExpression(r)?(100===r.expression.kind||e.isIdentifier(r.expression)&&("window"===r.expression.escapedText||"self"===r.expression.escapedText||"global"===r.expression.escapedText))&&se(t,r.name):!(!e.isPropertyAccessExpression(t)||!e.isPropertyAccessExpression(r))&&(t.name.escapedText===r.name.escapedText&&se(t.expression,r.expression))}function ce(t){return e.isIdentifier(t)&&"exports"===t.escapedText}function ue(t){return e.isPropertyAccessExpression(t)&&e.isIdentifier(t.expression)&&"module"===t.expression.escapedText&&"exports"===t.name.escapedText}function le(t){var r=function(t){if(e.isCallExpression(t)){if(!_e(t))return 0;var r=t.arguments[0];return ce(r)||ue(r)?8:e.isPropertyAccessExpression(r)&&"prototype"===r.name.escapedText&&jt(r.expression)?9:7}if(59!==t.operatorToken.kind||!e.isPropertyAccessExpression(t.left))return 0;var n=t.left;if(jt(n.expression)&&"prototype"===n.name.escapedText&&e.isObjectLiteralExpression(pe(t)))return 6;return de(n)}(t);return 5===r||ne(t)?r:0}function _e(t){return 3===e.length(t.arguments)&&e.isPropertyAccessExpression(t.expression)&&e.isIdentifier(t.expression.expression)&&"Object"===e.idText(t.expression.expression)&&"defineProperty"===e.idText(t.expression.name)&&Be(t.arguments[1])&&jt(t.arguments[0])}function de(t){if(100===t.expression.kind)return 4;if(ue(t))return 2;if(jt(t.expression)){if(zt(t.expression))return 3;for(var r=t;e.isPropertyAccessExpression(r.expression);)r=r.expression;e.Debug.assert(e.isIdentifier(r.expression));var n=r.expression;return"exports"===n.escapedText||"module"===n.escapedText&&"exports"===r.name.escapedText?1:5}return 0}function pe(t){for(;e.isBinaryExpression(t.right);)t=t.right;return t.right}function fe(t){switch(t.parent.kind){case 249:case 255:return t.parent;case 259:return t.parent.parent;case 191:return L(t.parent)||ie(t.parent,!1)?t.parent:void 0;case 182:return e.Debug.assert(e.isStringLiteral(t)),e.tryCast(t.parent.parent,e.isImportTypeNode);default:return}}function me(e){return 304===e.kind||297===e.kind}function ge(t){return e.isExpressionStatement(t)&&e.isBinaryExpression(t.expression)&&0!==le(t.expression)&&e.isBinaryExpression(t.expression.right)&&55===t.expression.right.operatorToken.kind?t.expression.right.right:void 0}function ye(e){switch(e.kind){case 219:var t=ve(e);return t&&t.initializer;case 154:case 275:return e.initializer}}function ve(t){return e.isVariableStatement(t)?e.firstOrUndefined(t.declarationList.declarations):void 0}function he(t){return e.isModuleDeclaration(t)&&t.body&&244===t.body.kind?t.body:void 0}function be(t){var r=t.parent;return 275===r.kind||154===r.kind||221===r.kind&&189===t.kind||he(r)||e.isBinaryExpression(t)&&59===t.operatorToken.kind?r:r.parent&&(ve(r.parent)===t||e.isBinaryExpression(r)&&59===r.operatorToken.kind)?r.parent:r.parent&&r.parent.parent&&(ve(r.parent.parent)||ye(r.parent.parent)===t||ge(r.parent.parent))?r.parent.parent:void 0}function De(e){return xe(Se(e))}function xe(t){var r,n=ge(t)||(r=t,e.isExpressionStatement(r)&&r.expression&&e.isBinaryExpression(r.expression)&&59===r.expression.operatorToken.kind?r.expression.right:void 0)||ye(t)||ve(t)||he(t)||t;return n&&e.isFunctionLike(n)?n:void 0}function Se(t){return e.Debug.assertDefined(o(t.parent,e.isJSDoc)).parent}function Te(t){var r=e.isJSDocParameterTag(t)?t.typeExpression&&t.typeExpression.type:t.type;return void 0!==t.dotDotDotToken||!!r&&290===r.kind}function Ce(e){for(var t=e.parent;;){switch(t.kind){case 204:var r=t.operatorToken.kind;return It(r)&&t.left===e?59===r?1:2:0;case 202:case 203:var n=t.operator;return 44===n||45===n?2:0;case 226:case 227:return t.initializer===e?1:0;case 195:case 187:case 208:case 213:e=t;break;case 276:if(t.name!==e)return 0;e=t.parent;break;case 275:if(t.name===e)return 0;e=t.parent;break;default:return 0}t=e.parent}}function ke(e,t){for(;e&&e.kind===t;)e=e.parent;return e}function Ee(e){return ke(e,195)}function Ne(e){for(;195===e.kind;)e=e.expression;return e}function Ae(t){var r=e.isExportAssignment(t)?t.expression:t.right;return jt(r)||e.isClassExpression(r)}function Fe(t){if(ne(t)){var r=e.getJSDocAugmentsTag(t);if(r)return r.class}return Pe(t)}function Pe(e){var t=Ie(e.heritageClauses,86);return t&&t.types.length>0?t.types[0]:void 0}function we(e){var t=Ie(e.heritageClauses,109);return t?t.types:void 0}function Oe(e){var t=Ie(e.heritageClauses,86);return t?t.types:void 0}function Ie(e,t){if(e)for(var r=0,n=e;r=0?i[a]:void 0}},getGlobalDiagnostics:function(){return i=!0,t},getDiagnostics:function(i){if(i)return n.get(i)||[];var a=e.flatMapToMutable(r,function(e){return n.get(e)});return t.length?(a.unshift.apply(a,t),a):a},reattachFileDiagnostics:function(t){e.forEach(n.get(t.fileName),function(e){return e.file=t})}}};var Qe=/[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g,$e=/[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g,Ze=/[\\\`\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g,et=e.createMapFromTemplate({"\t":"\\t","\v":"\\v","\f":"\\f","\b":"\\b","\r":"\\r","\n":"\\n","\\":"\\\\",'"':'\\"',"'":"\\'","`":"\\`","\u2028":"\\u2028","\u2029":"\\u2029","…":"\\u0085"});function tt(e,t){var r=96===t?Ze:39===t?$e:Qe;return e.replace(r,rt)}function rt(e,t,r){if(0===e.charCodeAt(0)){var n=r.charCodeAt(t+e.length);return n>=48&&n<=57?"\\x00":"\\0"}return et.get(e)||nt(e.charCodeAt(0))}function nt(e){return"\\u"+("0000"+e.toString(16).toUpperCase()).slice(-4)}e.escapeString=tt,e.isIntrinsicJsxName=function(t){var r=t.charCodeAt(0);return r>=97&&r<=122||e.stringContains(t,"-")};var it=/[^\u0000-\u007F]/g;function at(e,t){return e=tt(e,t),it.test(e)?e.replace(it,function(e){return nt(e.charCodeAt(0))}):e}e.escapeNonAsciiString=at;var ot=[""," "];function st(e){return void 0===ot[e]&&(ot[e]=st(e-1)+ot[1]),ot[e]}function ct(){return ot[1].length}function ut(e,t,r){return t.moduleName||lt(e,t.fileName,r&&r.fileName)}function lt(t,r,n){var i=function(e){return t.getCanonicalFileName(e)},o=a(n?e.getDirectoryPath(n):t.getCommonSourceDirectory(),t.getCurrentDirectory(),i),s=e.getNormalizedAbsolutePath(r,t.getCurrentDirectory()),c=e.getRelativePathToDirectoryOrUrl(o,s,o,i,!1),u=e.removeFileExtension(c);return n?e.ensurePathIsNonModuleName(u):u}function _t(t,r,n,i,a){var o=r.declarationDir||r.outDir,s=o?ft(t,o,n,i,a):t;return e.removeFileExtension(s)+".d.ts"}function dt(e,t,r){return!(t.noEmitForJsFiles&&re(e)||e.isDeclarationFile||r(e))}function pt(e,t,r){return ft(e,r,t.getCurrentDirectory(),t.getCommonSourceDirectory(),function(e){return t.getCanonicalFileName(e)})}function ft(t,r,n,i,a){var o=e.getNormalizedAbsolutePath(t,n);return o=0===a(o).indexOf(a(i))?o.substring(i.length):o,e.combinePaths(r,o)}function mt(t,r){return e.getLineAndCharacterOfPosition(t,r).line}function gt(t,r){return e.computeLineAndCharacterOfPosition(t,r).line}function yt(e){if(e&&e.parameters.length>0){var t=2===e.parameters.length&&vt(e.parameters[0]);return e.parameters[t?1:0]}}function vt(e){return ht(e.name)}function ht(e){return!!e&&72===e.kind&&bt(e)}function bt(e){return 100===e.originalKeywordKind}function Dt(t){var r=t.type;return r||!ne(t)?r:e.isJSDocPropertyLikeTag(t)?t.typeExpression&&t.typeExpression.type:e.getJSDocType(t)}function xt(e,t,r,n){St(e,t,r.pos,n)}function St(e,t,r,n){n&&n.length&&r!==n[0].pos&>(e,r)!==gt(e,n[0].pos)&&t.writeLine()}function Tt(e,t,r,n,i,a,o,s){if(n&&n.length>0){i&&r.writeSpace(" ");for(var c=!1,u=0,l=n;u=59&&e<=71}function Mt(e){var t=Lt(e);return t&&!t.isImplements?t.class:void 0}function Lt(t){return e.isExpressionWithTypeArguments(t)&&e.isHeritageClause(t.parent)&&e.isClassLike(t.parent.parent)?{class:t.parent.parent,isImplements:109===t.parent.token}:void 0}function Rt(t,r){return e.isBinaryExpression(t)&&(r?59===t.operatorToken.kind:It(t.operatorToken.kind))&&e.isLeftHandSideExpression(t.left)}function Bt(e){return void 0!==Mt(e)}function jt(e){return 72===e.kind||Jt(e)}function Jt(t){return e.isPropertyAccessExpression(t)&&jt(t.expression)}function zt(t){return e.isPropertyAccessExpression(t)&&"prototype"===t.name.escapedText}e.getIndentString=st,e.getIndentSize=ct,e.createTextWriter=function(t){var r,n,i,a,o;function s(t){var n=e.computeLineStarts(t);n.length>1?(a=a+n.length-1,o=r.length-t.length+e.last(n),i=o-r.length==0):i=!1}function c(e){e&&e.length&&(i&&(e=st(n)+e,i=!1),r+=e,s(e))}function u(){r="",n=0,i=!0,a=0,o=0}return u(),{write:c,rawWrite:function(e){void 0!==e&&(r+=e,s(e))},writeLiteral:function(e){e&&e.length&&c(e)},writeLine:function(){i||(a++,o=(r+=t).length,i=!0)},increaseIndent:function(){n++},decreaseIndent:function(){n--},getIndent:function(){return n},getTextPos:function(){return r.length},getLine:function(){return a},getColumn:function(){return i?n*ct():r.length-o},getText:function(){return r},isAtStartOfLine:function(){return i},clear:u,reportInaccessibleThisError:e.noop,reportPrivateInBaseOfClassExpression:e.noop,reportInaccessibleUniqueSymbolError:e.noop,trackSymbol:e.noop,writeKeyword:c,writeOperator:c,writeParameter:c,writeProperty:c,writePunctuation:c,writeSpace:c,writeStringLiteral:c,writeSymbol:function(e,t){return c(e)},writeTrailingSemicolon:c,writeComment:c}},e.getTrailingSemicolonOmittingWriter=function(e){var t=!1;function r(){t&&(e.writeTrailingSemicolon(";"),t=!1)}return i({},e,{writeTrailingSemicolon:function(){t=!0},writeLiteral:function(t){r(),e.writeLiteral(t)},writeStringLiteral:function(t){r(),e.writeStringLiteral(t)},writeSymbol:function(t,n){r(),e.writeSymbol(t,n)},writePunctuation:function(t){r(),e.writePunctuation(t)},writeKeyword:function(t){r(),e.writeKeyword(t)},writeOperator:function(t){r(),e.writeOperator(t)},writeParameter:function(t){r(),e.writeParameter(t)},writeSpace:function(t){r(),e.writeSpace(t)},writeProperty:function(t){r(),e.writeProperty(t)},writeComment:function(t){r(),e.writeComment(t)},writeLine:function(){r(),e.writeLine()},increaseIndent:function(){r(),e.increaseIndent()},decreaseIndent:function(){r(),e.decreaseIndent()}})},e.getResolvedExternalModuleName=ut,e.getExternalModuleNameFromDeclaration=function(e,t,r){var n=t.getExternalModuleFileFromDeclaration(r);if(n&&!n.isDeclarationFile)return ut(e,n)},e.getExternalModuleNameFromPath=lt,e.getOwnEmitOutputFilePath=function(t,r,n){var i=r.getCompilerOptions();return(i.outDir?e.removeFileExtension(pt(t,r,i.outDir)):e.removeFileExtension(t))+n},e.getDeclarationEmitOutputFilePath=function(e,t){return _t(e,t.getCompilerOptions(),t.getCurrentDirectory(),t.getCommonSourceDirectory(),function(e){return t.getCanonicalFileName(e)})},e.getDeclarationEmitOutputFilePathWorker=_t,e.getSourceFilesToEmit=function(t,r){var n=t.getCompilerOptions(),i=function(e){return t.isSourceFileFromExternalLibrary(e)};if(n.outFile||n.out){var a=e.getEmitModuleKind(n),o=n.emitDeclarationOnly||a===e.ModuleKind.AMD||a===e.ModuleKind.System;return e.filter(t.getSourceFiles(),function(t){return(o||!e.isExternalModule(t))&&dt(t,n,i)})}var s=void 0===r?t.getSourceFiles():[r];return e.filter(s,function(e){return dt(e,n,i)})},e.sourceFileMayBeEmitted=dt,e.getSourceFilePathInNewDir=pt,e.getSourceFilePathInNewDirWorker=ft,e.writeFile=function(t,r,n,i,a,o){t.writeFile(n,i,a,function(t){r.add(e.createCompilerDiagnostic(e.Diagnostics.Could_not_write_file_0_Colon_1,n,t))},o)},e.getLineOfLocalPosition=mt,e.getLineOfLocalPositionFromLineMap=gt,e.getFirstConstructorWithBody=function(t){return e.find(t.members,function(t){return e.isConstructorDeclaration(t)&&p(t.body)})},e.getSetAccessorTypeAnnotationNode=function(e){var t=yt(e);return t&&t.type},e.getThisParameter=function(t){if(t.parameters.length&&!e.isJSDocSignature(t)){var r=t.parameters[0];if(vt(r))return r}},e.parameterIsThisKeyword=vt,e.isThisIdentifier=ht,e.identifierIsThisKeyword=bt,e.getAllAccessorDeclarations=function(t,r){var n,i,a,o;return je(r)?(n=r,158===r.kind?a=r:159===r.kind?o=r:e.Debug.fail("Accessor has wrong kind")):e.forEach(t,function(t){e.isAccessor(t)&&Et(t,32)===Et(r,32)&&Ke(t.name)===Ke(r.name)&&(n?i||(i=t):n=t,158!==t.kind||a||(a=t),159!==t.kind||o||(o=t))}),{firstAccessor:n,secondAccessor:i,getAccessor:a,setAccessor:o}},e.getEffectiveTypeAnnotationNode=Dt,e.getTypeAnnotationNode=function(e){return e.type},e.getEffectiveReturnTypeNode=function(t){return e.isJSDocSignature(t)?t.type&&t.type.typeExpression&&t.type.typeExpression.type:t.type||(ne(t)?e.getJSDocReturnType(t):void 0)},e.getJSDocTypeParameterDeclarations=function(t){return e.flatMap(e.getJSDocTags(t),function(t){return function(t){return e.isJSDocTemplateTag(t)&&!(291===t.parent.kind&&t.parent.tags.some(me))}(t)?t.typeParameters:void 0})},e.getEffectiveSetAccessorTypeAnnotationNode=function(e){var t=yt(e);return t&&Dt(t)},e.emitNewLineBeforeLeadingComments=xt,e.emitNewLineBeforeLeadingCommentsOfPosition=St,e.emitNewLineBeforeLeadingCommentOfPosition=function(e,t,r,n){r!==n&>(e,r)!==gt(e,n)&&t.writeLine()},e.emitComments=Tt,e.emitDetachedComments=function(t,r,n,i,a,o,s){var c,u;if(s?0===a.pos&&(c=e.filter(e.getLeadingCommentRanges(t,a.pos),function(e){return m(t,e.pos)})):c=e.getLeadingCommentRanges(t,a.pos),c){for(var l=[],_=void 0,d=0,p=c;d=g+2)break}l.push(f),_=f}l.length&&(g=gt(r,e.last(l).end),gt(r,e.skipTrivia(t,a.pos))>=g+2&&(xt(r,n,a,c),Tt(t,r,n,l,!1,!0,o,i),u={nodePos:a.pos,detachedCommentEndPos:e.last(l).end}))}return u},e.writeCommentRange=function(t,r,n,i,a,o){if(42===t.charCodeAt(i+1))for(var s=e.computeLineAndCharacterOfPosition(r,i),c=r.length,u=void 0,l=i,_=s.line;l0){var f=p%ct(),m=st((p-f)/ct());for(n.rawWrite(m);f;)n.rawWrite(" "),f--}else n.rawWrite("")}Ct(t,a,n,o,l,d),l=d}else n.writeComment(t.substring(i,a))},e.hasModifiers=function(e){return 0!==Pt(e)},e.hasModifier=Et,e.hasStaticModifier=Nt,e.hasReadonlyModifier=At,e.getSelectedModifierFlags=Ft,e.getModifierFlags=Pt,e.getModifierFlagsNoCache=wt,e.modifierToFlag=Ot,e.isLogicalOperator=function(e){return 55===e||54===e||52===e},e.isAssignmentOperator=It,e.tryGetClassExtendingExpressionWithTypeArguments=Mt,e.tryGetClassImplementingOrExtendingExpressionWithTypeArguments=Lt,e.isAssignmentExpression=Rt,e.isDestructuringAssignment=function(e){if(Rt(e,!0)){var t=e.left.kind;return 188===t||187===t}return!1},e.isExpressionWithTypeArgumentsInClassExtendsClause=Bt,e.isEntityNameExpression=jt,e.isPropertyAccessEntityNameExpression=Jt,e.isPrototypeAccess=zt,e.isRightSideOfQualifiedNameOrPropertyAccess=function(e){return 148===e.parent.kind&&e.parent.right===e||189===e.parent.kind&&e.parent.name===e},e.isEmptyObjectLiteral=function(e){return 188===e.kind&&0===e.properties.length},e.isEmptyArrayLiteral=function(e){return 187===e.kind&&0===e.elements.length},e.getLocalSymbolForExportDefault=function(t){return function(t){return t&&e.length(t.declarations)>0&&Et(t.declarations[0],512)}(t)?t.declarations[0].localSymbol:void 0},e.tryExtractTSExtension=function(t){return e.find(e.supportedTSExtensionsForExtractExtension,function(r){return e.fileExtensionIs(t,r)})};var Kt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function Ut(t){for(var r,n,i,a,o="",s=function(t){for(var r=[],n=t.length,i=0;i>6|192),r.push(63&a|128)):a<65536?(r.push(a>>12|224),r.push(a>>6&63|128),r.push(63&a|128)):a<131072?(r.push(a>>18|240),r.push(a>>12&63|128),r.push(a>>6&63|128),r.push(63&a|128)):e.Debug.assert(!1,"Unexpected code point")}return r}(t),c=0,u=s.length;c>2,n=(3&s[c])<<4|s[c+1]>>4,i=(15&s[c+1])<<2|s[c+2]>>6,a=63&s[c+2],c+1>=u?i=a=64:c+2>=u&&(a=64),o+=Kt.charAt(r)+Kt.charAt(n)+Kt.charAt(i)+Kt.charAt(a),c+=3;return o}e.convertToBase64=Ut,e.base64encode=function(e,t){return e&&e.base64encode?e.base64encode(t):Ut(t)},e.base64decode=function(e,t){if(e&&e.base64decode)return e.base64decode(t);for(var r=t.length,n=[],i=0;i>4&3,l=(15&o)<<4|s>>2&15,_=(3&s)<<6|63&c;0===l&&0!==s?n.push(u):0===_&&0!==c?n.push(u,l):n.push(u,l,_),i+=4}return function(e){for(var t="",r=0,n=e.length;r0&&0===i[0][0]?i[0][1]:"0";if(n){for(var a="",o=t,s=i.length-1;s>=0&&0!==o;s--){var c=i[s],u=c[0],l=c[1];0!==u&&(o&u)===u&&(o&=~u,a=l+(a?", ":"")+a)}if(0===o)return a}else for(var _=0,d=i;_=t||-1===r),{pos:t,end:r}}function Yt(e,t){return Gt(t,e.end)}function Xt(e){return e.decorators&&e.decorators.length>0?Yt(e,e.decorators.end):e}function Qt(e,t,r){return $t(Zt(e,r),t.end,r)}function $t(e,t,r){return e===t||mt(r,e)===mt(r,t)}function Zt(t,r){return e.positionIsSynthesized(t.pos)?-1:e.skipTrivia(r.text,t.pos)}function er(e){return void 0!==e.initializer}function tr(e){return 33554432&e.flags?e.checkFlags:0}function rr(t){var r=t.parent;if(!r)return 0;switch(r.kind){case 195:return rr(r);case 203:case 202:var n=r.operator;return 44===n||45===n?c():0;case 204:var i=r,a=i.left,o=i.operatorToken;return a===t&&It(o.kind)?59===o.kind?1:c():0;case 189:return r.name!==t?0:rr(r);case 275:var s=rr(r.parent);return t===r.name?function(t){switch(t){case 0:return 1;case 1:return 0;case 2:return 2;default:return e.Debug.assertNever(t)}}(s):s;case 276:return t===r.objectAssignmentInitializer?0:rr(r.parent);case 187:return rr(r);default:return 0}function c(){return r.parent&&221===function(e){for(;195===e.kind;)e=e.parent;return e}(r.parent).kind?1:2}}function nr(t,r){for(;;){var n=r(t);if(void 0!==n)return n;var i=e.getDirectoryPath(t);if(i===t)return;t=i}}function ir(e){if(32&e.flags){var t=ar(e);return!!t&&Et(t,128)}return!1}function ar(t){return e.find(t.declarations,e.isClassLike)}function or(e){return 524288&e.flags?e.objectFlags:0}e.getNewLineCharacter=function(t,r){switch(t.newLine){case 0:return qt;case 1:return Wt}return r?r():e.sys?e.sys.newLine:qt},e.formatSyntaxKind=function(t){return Ht(t,e.SyntaxKind,!1)},e.formatModifierFlags=function(t){return Ht(t,e.ModifierFlags,!0)},e.formatTransformFlags=function(t){return Ht(t,e.TransformFlags,!0)},e.formatEmitFlags=function(t){return Ht(t,e.EmitFlags,!0)},e.formatSymbolFlags=function(t){return Ht(t,e.SymbolFlags,!0)},e.formatTypeFlags=function(t){return Ht(t,e.TypeFlags,!0)},e.formatObjectFlags=function(t){return Ht(t,e.ObjectFlags,!0)},e.createRange=Gt,e.moveRangeEnd=function(e,t){return Gt(e.pos,t)},e.moveRangePos=Yt,e.moveRangePastDecorators=Xt,e.moveRangePastModifiers=function(e){return e.modifiers&&e.modifiers.length>0?Yt(e,e.modifiers.end):Xt(e)},e.isCollapsedRange=function(e){return e.pos===e.end},e.createTokenRange=function(t,r){return Gt(t,t+e.tokenToString(r).length)},e.rangeIsOnSingleLine=function(e,t){return Qt(e,e,t)},e.rangeStartPositionsAreOnSameLine=function(e,t,r){return $t(Zt(e,r),Zt(t,r),r)},e.rangeEndPositionsAreOnSameLine=function(e,t,r){return $t(e.end,t.end,r)},e.rangeStartIsOnSameLineAsRangeEnd=Qt,e.rangeEndIsOnSameLineAsRangeStart=function(e,t,r){return $t(e.end,Zt(t,r),r)},e.positionsAreOnSameLine=$t,e.getStartPositionOfRange=Zt,e.isDeclarationNameOfEnumOrNamespace=function(t){var r=e.getParseTreeNode(t);if(r)switch(r.parent.kind){case 243:case 244:return r===r.parent.name}return!1},e.getInitializedVariables=function(t){return e.filter(t.declarations,er)},e.isWatchSet=function(e){return e.watch&&e.hasOwnProperty("watch")},e.closeFileWatcher=function(e){e.close()},e.getCheckFlags=tr,e.getDeclarationModifierFlagsFromSymbol=function(t){if(t.valueDeclaration){var r=e.getCombinedModifierFlags(t.valueDeclaration);return t.parent&&32&t.parent.flags?r:-29&r}if(6&tr(t)){var n=t.checkFlags;return(256&n?8:64&n?4:16)|(512&n?32:0)}return 4194304&t.flags?36:0},e.skipAlias=function(e,t){return 2097152&e.flags?t.getAliasedSymbol(e):e},e.getCombinedLocalAndExportSymbolFlags=function(e){return e.exportSymbol?e.exportSymbol.flags|e.flags:e.flags},e.isWriteOnlyAccess=function(e){return 1===rr(e)},e.isWriteAccess=function(e){return 0!==rr(e)},function(e){e[e.Read=0]="Read",e[e.Write=1]="Write",e[e.ReadWrite=2]="ReadWrite"}(Vt||(Vt={})),e.compareDataObjects=function e(t,r){if(!t||!r||Object.keys(t).length!==Object.keys(r).length)return!1;for(var n in t)if("object"===f(t[n])){if(!e(t[n],r[n]))return!1}else if("function"!=typeof t[n]&&t[n]!==r[n])return!1;return!0},e.clearMap=function(e,t){e.forEach(t),e.clear()},e.mutateMap=function(e,t,r){var n=r.createNewValue,i=r.onDeleteValue,a=r.onExistingValue;e.forEach(function(r,n){var o=t.get(n);void 0===o?(e.delete(n),i(r,n)):a&&a(r,o,n)}),t.forEach(function(t,r){e.has(r)||e.set(r,n(r,t))})},e.forEachAncestorDirectory=nr,e.isAbstractConstructorType=function(e){return!!(16&or(e))&&!!e.symbol&&ir(e.symbol)},e.isAbstractConstructorSymbol=ir,e.getClassLikeDeclarationOfSymbol=ar,e.getObjectFlags=or,e.typeHasCallOrConstructSignatures=function(e,t){return 0!==t.getSignaturesOfType(e,0).length||0!==t.getSignaturesOfType(e,1).length},e.forSomeAncestorDirectory=function(e,t){return!!nr(e,function(e){return!!t(e)||void 0})},e.isUMDExportSymbol=function(t){return!!t&&!!t.declarations&&!!t.declarations[0]&&e.isNamespaceExportDeclaration(t.declarations[0])},e.showModuleSpecifier=function(t){var r=t.moduleSpecifier;return e.isStringLiteral(r)?r.text:h(r)},e.getLastChild=function(t){var r;return e.forEachChild(t,function(e){p(e)&&(r=e)},function(e){for(var t=e.length-1;t>=0;t--)if(p(e[t])){r=e[t];break}}),r},e.addToSeen=function(e,t,r){return void 0===r&&(r=!0),t=String(t),!e.has(t)&&(e.set(t,r),!0)},e.isObjectTypeDeclaration=function(t){return e.isClassLike(t)||e.isInterfaceDeclaration(t)||e.isTypeLiteralNode(t)},e.isTypeNodeKind=function(e){return e>=163&&e<=183||120===e||143===e||135===e||146===e||136===e||123===e||138===e||139===e||100===e||106===e||141===e||96===e||132===e||211===e||284===e||285===e||286===e||287===e||288===e||289===e||290===e}}(c||(c={})),function(e){function t(e){return e.start+e.length}function r(e){return 0===e.length}function n(e,t){var r=a(e,t);return r&&0===r.length?void 0:r}function i(e,t,r,n){return r<=e+t&&r+n>=e}function a(e,r){var n=Math.max(e.start,r.start),i=Math.min(t(e),t(r));return n<=i?s(n,i):void 0}function o(e,t){if(e<0)throw new Error("start < 0");if(t<0)throw new Error("length < 0");return{start:e,length:t}}function s(e,t){return o(e,t-e)}function c(e,t){if(t<0)throw new Error("newLength < 0");return{span:e,newLength:t}}function u(t){return!!e.isBindingPattern(t)&&e.every(t.elements,l)}function l(t){return!!e.isOmittedExpression(t)||u(t.name)}function _(t){for(var r=t.parent;e.isBindingElement(r.parent);)r=r.parent.parent;return r.parent}function d(t,r){e.isBindingElement(t)&&(t=_(t));var n=r(t);return 237===t.kind&&(t=t.parent),t&&238===t.kind&&(n|=r(t),t=t.parent),t&&219===t.kind&&(n|=r(t)),n}function p(e,t){if(e)for(;void 0!==e.original;)e=e.original;return!t||t(e)?e:void 0}function f(e){return 0==(8&e.flags)}function m(e){var t=e;return t.length>=3&&95===t.charCodeAt(0)&&95===t.charCodeAt(1)&&95===t.charCodeAt(2)?t.substr(1):t}function g(t){var r=h(t);return r&&e.isIdentifier(r)?r:void 0}function y(t){return t.name||function(t){var r=t.parent.parent;if(r){if(e.isDeclaration(r))return g(r);switch(r.kind){case 219:if(r.declarationList&&r.declarationList.declarations[0])return g(r.declarationList.declarations[0]);break;case 221:var n=r.expression;switch(n.kind){case 189:return n.name;case 190:var i=n.argumentExpression;if(e.isIdentifier(i))return i}break;case 195:return g(r.expression);case 233:if(e.isDeclaration(r.statement)||e.isExpression(r.statement))return g(r.statement)}}}(t)}function v(t){switch(t.kind){case 72:return t;case 305:case 299:var r=t.name;if(148===r.kind)return r.right;break;case 191:case 204:var n=t;switch(e.getAssignmentDeclarationKind(n)){case 1:case 4:case 5:case 3:return n.left.name;case 7:case 8:case 9:return n.arguments[1];default:return}case 304:return y(t);case 254:var i=t.expression;return e.isIdentifier(i)?i:void 0}return t.name}function h(t){if(void 0!==t)return v(t)||(e.isFunctionExpression(t)||e.isClassExpression(t)?function(t){if(!t.parent)return;if(e.isPropertyAssignment(t.parent)||e.isBindingElement(t.parent))return t.parent.name;if(e.isBinaryExpression(t.parent)&&t===t.parent.right){if(e.isIdentifier(t.parent.left))return t.parent.left;if(e.isPropertyAccessExpression(t.parent.left))return t.parent.left.name}}(t):void 0)}function b(t){if(t.name){if(e.isIdentifier(t.name)){var r=t.name.escapedText;return T(t.parent).filter(function(t){return e.isJSDocParameterTag(t)&&e.isIdentifier(t.name)&&t.name.escapedText===r})}var n=t.parent.parameters.indexOf(t);e.Debug.assert(n>-1,"Parameters should always be in their parents' parameter list");var i=T(t.parent).filter(e.isJSDocParameterTag);if(n=e.start&&r=e.pos&&t<=e.end},e.textSpanContainsTextSpan=function(e,r){return r.start>=e.start&&t(r)<=t(e)},e.textSpanOverlapsWith=function(e,t){return void 0!==n(e,t)},e.textSpanOverlap=n,e.textSpanIntersectsWithTextSpan=function(e,t){return i(e.start,e.length,t.start,t.length)},e.textSpanIntersectsWith=function(e,t,r){return i(e.start,e.length,t,r)},e.decodedTextSpanIntersectsWith=i,e.textSpanIntersectsWithPosition=function(e,r){return r<=t(e)&&r>=e.start},e.textSpanIntersection=a,e.createTextSpan=o,e.createTextSpanFromBounds=s,e.textChangeRangeNewSpan=function(e){return o(e.span.start,e.newLength)},e.textChangeRangeIsUnchanged=function(e){return r(e.span)&&0===e.newLength},e.createTextChangeRange=c,e.unchangedTextChangeRange=c(o(0,0),0),e.collapseTextChangeRangesAcrossMultipleVersions=function(r){if(0===r.length)return e.unchangedTextChangeRange;if(1===r.length)return r[0];for(var n=r[0],i=n.span.start,a=t(n.span),o=i+n.newLength,u=1;u=2&&95===e.charCodeAt(0)&&95===e.charCodeAt(1)?"_"+e:e},e.unescapeLeadingUnderscores=m,e.idText=function(e){return m(e.escapedText)},e.symbolName=function(e){return m(e.escapedName)},e.getNameOfJSDocTypedef=y,e.isNamedDeclaration=function(e){return!!e.name},e.getNonAssignedNameOfDeclaration=v,e.getNameOfDeclaration=h,e.getJSDocParameterTags=b,e.getJSDocTypeParameterTags=function(t){var r=t.name.escapedText;return T(t.parent).filter(function(t){return e.isJSDocTemplateTag(t)&&t.typeParameters.some(function(e){return e.name.escapedText===r})})},e.hasJSDocParameterTags=function(t){return!!C(t,e.isJSDocParameterTag)},e.getJSDocAugmentsTag=function(t){return C(t,e.isJSDocAugmentsTag)},e.getJSDocClassTag=function(t){return C(t,e.isJSDocClassTag)},e.getJSDocEnumTag=function(t){return C(t,e.isJSDocEnumTag)},e.getJSDocThisTag=function(t){return C(t,e.isJSDocThisTag)},e.getJSDocReturnTag=D,e.getJSDocTemplateTag=function(t){return C(t,e.isJSDocTemplateTag)},e.getJSDocTypeTag=x,e.getJSDocType=S,e.getJSDocReturnType=function(t){var r=D(t);if(r&&r.typeExpression)return r.typeExpression.type;var n=x(t);if(n&&n.typeExpression){var i=n.typeExpression.type;if(e.isTypeLiteralNode(i)){var a=e.find(i.members,e.isCallSignatureDeclaration);return a&&a.type}if(e.isFunctionTypeNode(i))return i.type}},e.getJSDocTags=T,e.getAllJSDocTagsOfKind=function(e,t){return T(e).filter(function(e){return e.kind===t})},e.getEffectiveTypeParameterDeclarations=function(t){if(e.isJSDocSignature(t))return e.emptyArray;if(e.isJSDocTypeAlias(t))return e.Debug.assert(291===t.parent.kind),e.flatMap(t.parent.tags,function(t){return e.isJSDocTemplateTag(t)?t.typeParameters:void 0});if(t.typeParameters)return t.typeParameters;if(e.isInJSFile(t)){var r=e.getJSDocTypeParameterDeclarations(t);if(r.length)return r;var n=S(t);if(n&&e.isFunctionTypeNode(n)&&n.typeParameters)return n.typeParameters}return e.emptyArray},e.getEffectiveConstraintOfTypeParameter=function(t){return t.constraint?t.constraint:e.isJSDocTemplateTag(t.parent)&&t===t.parent.typeParameters[0]?t.parent.constraint:void 0}}(c||(c={})),function(e){e.isNumericLiteral=function(e){return 8===e.kind},e.isBigIntLiteral=function(e){return 9===e.kind},e.isStringLiteral=function(e){return 10===e.kind},e.isJsxText=function(e){return 11===e.kind},e.isRegularExpressionLiteral=function(e){return 13===e.kind},e.isNoSubstitutionTemplateLiteral=function(e){return 14===e.kind},e.isTemplateHead=function(e){return 15===e.kind},e.isTemplateMiddle=function(e){return 16===e.kind},e.isTemplateTail=function(e){return 17===e.kind},e.isIdentifier=function(e){return 72===e.kind},e.isQualifiedName=function(e){return 148===e.kind},e.isComputedPropertyName=function(e){return 149===e.kind},e.isTypeParameterDeclaration=function(e){return 150===e.kind},e.isParameter=function(e){return 151===e.kind},e.isDecorator=function(e){return 152===e.kind},e.isPropertySignature=function(e){return 153===e.kind},e.isPropertyDeclaration=function(e){return 154===e.kind},e.isMethodSignature=function(e){return 155===e.kind},e.isMethodDeclaration=function(e){return 156===e.kind},e.isConstructorDeclaration=function(e){return 157===e.kind},e.isGetAccessorDeclaration=function(e){return 158===e.kind},e.isSetAccessorDeclaration=function(e){return 159===e.kind},e.isCallSignatureDeclaration=function(e){return 160===e.kind},e.isConstructSignatureDeclaration=function(e){return 161===e.kind},e.isIndexSignatureDeclaration=function(e){return 162===e.kind},e.isGetOrSetAccessorDeclaration=function(e){return 159===e.kind||158===e.kind},e.isTypePredicateNode=function(e){return 163===e.kind},e.isTypeReferenceNode=function(e){return 164===e.kind},e.isFunctionTypeNode=function(e){return 165===e.kind},e.isConstructorTypeNode=function(e){return 166===e.kind},e.isTypeQueryNode=function(e){return 167===e.kind},e.isTypeLiteralNode=function(e){return 168===e.kind},e.isArrayTypeNode=function(e){return 169===e.kind},e.isTupleTypeNode=function(e){return 170===e.kind},e.isUnionTypeNode=function(e){return 173===e.kind},e.isIntersectionTypeNode=function(e){return 174===e.kind},e.isConditionalTypeNode=function(e){return 175===e.kind},e.isInferTypeNode=function(e){return 176===e.kind},e.isParenthesizedTypeNode=function(e){return 177===e.kind},e.isThisTypeNode=function(e){return 178===e.kind},e.isTypeOperatorNode=function(e){return 179===e.kind},e.isIndexedAccessTypeNode=function(e){return 180===e.kind},e.isMappedTypeNode=function(e){return 181===e.kind},e.isLiteralTypeNode=function(e){return 182===e.kind},e.isImportTypeNode=function(e){return 183===e.kind},e.isObjectBindingPattern=function(e){return 184===e.kind},e.isArrayBindingPattern=function(e){return 185===e.kind},e.isBindingElement=function(e){return 186===e.kind},e.isArrayLiteralExpression=function(e){return 187===e.kind},e.isObjectLiteralExpression=function(e){return 188===e.kind},e.isPropertyAccessExpression=function(e){return 189===e.kind},e.isElementAccessExpression=function(e){return 190===e.kind},e.isCallExpression=function(e){return 191===e.kind},e.isNewExpression=function(e){return 192===e.kind},e.isTaggedTemplateExpression=function(e){return 193===e.kind},e.isTypeAssertion=function(e){return 194===e.kind},e.isParenthesizedExpression=function(e){return 195===e.kind},e.skipPartiallyEmittedExpressions=function(e){for(;308===e.kind;)e=e.expression;return e},e.isFunctionExpression=function(e){return 196===e.kind},e.isArrowFunction=function(e){return 197===e.kind},e.isDeleteExpression=function(e){return 198===e.kind},e.isTypeOfExpression=function(e){return 199===e.kind},e.isVoidExpression=function(e){return 200===e.kind},e.isAwaitExpression=function(e){return 201===e.kind},e.isPrefixUnaryExpression=function(e){return 202===e.kind},e.isPostfixUnaryExpression=function(e){return 203===e.kind},e.isBinaryExpression=function(e){return 204===e.kind},e.isConditionalExpression=function(e){return 205===e.kind},e.isTemplateExpression=function(e){return 206===e.kind},e.isYieldExpression=function(e){return 207===e.kind},e.isSpreadElement=function(e){return 208===e.kind},e.isClassExpression=function(e){return 209===e.kind},e.isOmittedExpression=function(e){return 210===e.kind},e.isExpressionWithTypeArguments=function(e){return 211===e.kind},e.isAsExpression=function(e){return 212===e.kind},e.isNonNullExpression=function(e){return 213===e.kind},e.isMetaProperty=function(e){return 214===e.kind},e.isTemplateSpan=function(e){return 216===e.kind},e.isSemicolonClassElement=function(e){return 217===e.kind},e.isBlock=function(e){return 218===e.kind},e.isVariableStatement=function(e){return 219===e.kind},e.isEmptyStatement=function(e){return 220===e.kind},e.isExpressionStatement=function(e){return 221===e.kind},e.isIfStatement=function(e){return 222===e.kind},e.isDoStatement=function(e){return 223===e.kind},e.isWhileStatement=function(e){return 224===e.kind},e.isForStatement=function(e){return 225===e.kind},e.isForInStatement=function(e){return 226===e.kind},e.isForOfStatement=function(e){return 227===e.kind},e.isContinueStatement=function(e){return 228===e.kind},e.isBreakStatement=function(e){return 229===e.kind},e.isBreakOrContinueStatement=function(e){return 229===e.kind||228===e.kind},e.isReturnStatement=function(e){return 230===e.kind},e.isWithStatement=function(e){return 231===e.kind},e.isSwitchStatement=function(e){return 232===e.kind},e.isLabeledStatement=function(e){return 233===e.kind},e.isThrowStatement=function(e){return 234===e.kind},e.isTryStatement=function(e){return 235===e.kind},e.isDebuggerStatement=function(e){return 236===e.kind},e.isVariableDeclaration=function(e){return 237===e.kind},e.isVariableDeclarationList=function(e){return 238===e.kind},e.isFunctionDeclaration=function(e){return 239===e.kind},e.isClassDeclaration=function(e){return 240===e.kind},e.isInterfaceDeclaration=function(e){return 241===e.kind},e.isTypeAliasDeclaration=function(e){return 242===e.kind},e.isEnumDeclaration=function(e){return 243===e.kind},e.isModuleDeclaration=function(e){return 244===e.kind},e.isModuleBlock=function(e){return 245===e.kind},e.isCaseBlock=function(e){return 246===e.kind},e.isNamespaceExportDeclaration=function(e){return 247===e.kind},e.isImportEqualsDeclaration=function(e){return 248===e.kind},e.isImportDeclaration=function(e){return 249===e.kind},e.isImportClause=function(e){return 250===e.kind},e.isNamespaceImport=function(e){return 251===e.kind},e.isNamedImports=function(e){return 252===e.kind},e.isImportSpecifier=function(e){return 253===e.kind},e.isExportAssignment=function(e){return 254===e.kind},e.isExportDeclaration=function(e){return 255===e.kind},e.isNamedExports=function(e){return 256===e.kind},e.isExportSpecifier=function(e){return 257===e.kind},e.isMissingDeclaration=function(e){return 258===e.kind},e.isExternalModuleReference=function(e){return 259===e.kind},e.isJsxElement=function(e){return 260===e.kind},e.isJsxSelfClosingElement=function(e){return 261===e.kind},e.isJsxOpeningElement=function(e){return 262===e.kind},e.isJsxClosingElement=function(e){return 263===e.kind},e.isJsxFragment=function(e){return 264===e.kind},e.isJsxOpeningFragment=function(e){return 265===e.kind},e.isJsxClosingFragment=function(e){return 266===e.kind},e.isJsxAttribute=function(e){return 267===e.kind},e.isJsxAttributes=function(e){return 268===e.kind},e.isJsxSpreadAttribute=function(e){return 269===e.kind},e.isJsxExpression=function(e){return 270===e.kind},e.isCaseClause=function(e){return 271===e.kind},e.isDefaultClause=function(e){return 272===e.kind},e.isHeritageClause=function(e){return 273===e.kind},e.isCatchClause=function(e){return 274===e.kind},e.isPropertyAssignment=function(e){return 275===e.kind},e.isShorthandPropertyAssignment=function(e){return 276===e.kind},e.isSpreadAssignment=function(e){return 277===e.kind},e.isEnumMember=function(e){return 278===e.kind},e.isSourceFile=function(e){return 279===e.kind},e.isBundle=function(e){return 280===e.kind},e.isUnparsedSource=function(e){return 281===e.kind},e.isJSDocTypeExpression=function(e){return 283===e.kind},e.isJSDocAllType=function(e){return 284===e.kind},e.isJSDocUnknownType=function(e){return 285===e.kind},e.isJSDocNullableType=function(e){return 286===e.kind},e.isJSDocNonNullableType=function(e){return 287===e.kind},e.isJSDocOptionalType=function(e){return 288===e.kind},e.isJSDocFunctionType=function(e){return 289===e.kind},e.isJSDocVariadicType=function(e){return 290===e.kind},e.isJSDoc=function(e){return 291===e.kind},e.isJSDocAugmentsTag=function(e){return 295===e.kind},e.isJSDocClassTag=function(e){return 296===e.kind},e.isJSDocEnumTag=function(e){return 298===e.kind},e.isJSDocThisTag=function(e){return 301===e.kind},e.isJSDocParameterTag=function(e){return 299===e.kind},e.isJSDocReturnTag=function(e){return 300===e.kind},e.isJSDocTypeTag=function(e){return 302===e.kind},e.isJSDocTemplateTag=function(e){return 303===e.kind},e.isJSDocTypedefTag=function(e){return 304===e.kind},e.isJSDocPropertyTag=function(e){return 305===e.kind},e.isJSDocPropertyLikeTag=function(e){return 305===e.kind||299===e.kind},e.isJSDocTypeLiteral=function(e){return 292===e.kind},e.isJSDocCallbackTag=function(e){return 297===e.kind},e.isJSDocSignature=function(e){return 293===e.kind}}(c||(c={})),function(e){function t(e){return e>=148}function r(e){return 8<=e&&e<=14}function n(e){return 14<=e&&e<=17}function i(e){switch(e){case 118:case 121:case 77:case 125:case 80:case 85:case 115:case 113:case 114:case 133:case 116:return!0}return!1}function a(t){return!!(92&e.modifierToFlag(t))}function o(e){return e&&c(e.kind)}function s(e){switch(e){case 239:case 156:case 157:case 158:case 159:case 196:case 197:return!0;default:return!1}}function c(e){switch(e){case 155:case 160:case 293:case 161:case 162:case 165:case 289:case 166:return!0;default:return s(e)}}function u(e){var t=e.kind;return 157===t||154===t||156===t||158===t||159===t||162===t||217===t}function l(e){var t=e.kind;return 161===t||160===t||153===t||155===t||162===t}function _(e){var t=e.kind;return 275===t||276===t||277===t||156===t||158===t||159===t}function d(e){switch(e.kind){case 184:case 188:return!0}return!1}function p(e){switch(e.kind){case 185:case 187:return!0}return!1}function f(e){switch(e){case 189:case 190:case 192:case 191:case 260:case 261:case 264:case 193:case 187:case 195:case 188:case 209:case 196:case 72:case 13:case 8:case 9:case 10:case 14:case 206:case 87:case 96:case 100:case 102:case 98:case 213:case 214:case 92:return!0;default:return!1}}function m(e){switch(e){case 202:case 203:case 198:case 199:case 200:case 201:case 194:return!0;default:return f(e)}}function g(t){return function(e){switch(e){case 205:case 207:case 197:case 204:case 208:case 212:case 210:case 309:case 308:return!0;default:return m(e)}}(e.skipPartiallyEmittedExpressions(t).kind)}function y(e){return 308===e.kind}function v(e){return 307===e.kind}function h(e){return 239===e||258===e||240===e||241===e||242===e||243===e||244===e||249===e||248===e||255===e||254===e||247===e}function b(e){return 229===e||228===e||236===e||223===e||221===e||220===e||226===e||227===e||225===e||222===e||233===e||230===e||232===e||234===e||235===e||219===e||224===e||231===e||307===e||311===e||310===e}function D(e){return e.kind>=294&&e.kind<=305}function x(e){return!!e.initializer}e.isSyntaxList=function(e){return 306===e.kind},e.isNode=function(e){return t(e.kind)},e.isNodeKind=t,e.isToken=function(e){return e.kind>=0&&e.kind<=147},e.isNodeArray=function(e){return e.hasOwnProperty("pos")&&e.hasOwnProperty("end")},e.isLiteralKind=r,e.isLiteralExpression=function(e){return r(e.kind)},e.isTemplateLiteralKind=n,e.isTemplateLiteralToken=function(e){return n(e.kind)},e.isTemplateMiddleOrTemplateTail=function(e){var t=e.kind;return 16===t||17===t},e.isImportOrExportSpecifier=function(t){return e.isImportSpecifier(t)||e.isExportSpecifier(t)},e.isStringTextContainingNode=function(e){return 10===e.kind||n(e.kind)},e.isGeneratedIdentifier=function(t){return e.isIdentifier(t)&&(7&t.autoGenerateFlags)>0},e.isModifierKind=i,e.isParameterPropertyModifier=a,e.isClassMemberModifier=function(e){return a(e)||116===e},e.isModifier=function(e){return i(e.kind)},e.isEntityName=function(e){var t=e.kind;return 148===t||72===t},e.isPropertyName=function(e){var t=e.kind;return 72===t||10===t||8===t||149===t},e.isBindingName=function(e){var t=e.kind;return 72===t||184===t||185===t},e.isFunctionLike=o,e.isFunctionLikeDeclaration=function(e){return e&&s(e.kind)},e.isFunctionLikeKind=c,e.isFunctionOrModuleBlock=function(t){return e.isSourceFile(t)||e.isModuleBlock(t)||e.isBlock(t)&&o(t.parent)},e.isClassElement=u,e.isClassLike=function(e){return e&&(240===e.kind||209===e.kind)},e.isAccessor=function(e){return e&&(158===e.kind||159===e.kind)},e.isMethodOrAccessor=function(e){switch(e.kind){case 156:case 158:case 159:return!0;default:return!1}},e.isTypeElement=l,e.isClassOrTypeElement=function(e){return l(e)||u(e)},e.isObjectLiteralElementLike=_,e.isTypeNode=function(t){return e.isTypeNodeKind(t.kind)},e.isFunctionOrConstructorTypeNode=function(e){switch(e.kind){case 165:case 166:return!0}return!1},e.isBindingPattern=function(e){if(e){var t=e.kind;return 185===t||184===t}return!1},e.isAssignmentPattern=function(e){var t=e.kind;return 187===t||188===t},e.isArrayBindingElement=function(e){var t=e.kind;return 186===t||210===t},e.isDeclarationBindingElement=function(e){switch(e.kind){case 237:case 151:case 186:return!0}return!1},e.isBindingOrAssignmentPattern=function(e){return d(e)||p(e)},e.isObjectBindingOrAssignmentPattern=d,e.isArrayBindingOrAssignmentPattern=p,e.isPropertyAccessOrQualifiedNameOrImportTypeNode=function(e){var t=e.kind;return 189===t||148===t||183===t},e.isPropertyAccessOrQualifiedName=function(e){var t=e.kind;return 189===t||148===t},e.isCallLikeExpression=function(e){switch(e.kind){case 262:case 261:case 191:case 192:case 193:case 152:return!0;default:return!1}},e.isCallOrNewExpression=function(e){return 191===e.kind||192===e.kind},e.isTemplateLiteral=function(e){var t=e.kind;return 206===t||14===t},e.isLeftHandSideExpression=function(t){return f(e.skipPartiallyEmittedExpressions(t).kind)},e.isUnaryExpression=function(t){return m(e.skipPartiallyEmittedExpressions(t).kind)},e.isUnaryExpressionWithWrite=function(e){switch(e.kind){case 203:return!0;case 202:return 44===e.operator||45===e.operator;default:return!1}},e.isExpression=g,e.isAssertionExpression=function(e){var t=e.kind;return 194===t||212===t},e.isPartiallyEmittedExpression=y,e.isNotEmittedStatement=v,e.isNotEmittedOrPartiallyEmittedNode=function(e){return v(e)||y(e)},e.isIterationStatement=function e(t,r){switch(t.kind){case 225:case 226:case 227:case 223:case 224:return!0;case 233:return r&&e(t.statement,r)}return!1},e.isForInOrOfStatement=function(e){return 226===e.kind||227===e.kind},e.isConciseBody=function(t){return e.isBlock(t)||g(t)},e.isFunctionBody=function(t){return e.isBlock(t)},e.isForInitializer=function(t){return e.isVariableDeclarationList(t)||g(t)},e.isModuleBody=function(e){var t=e.kind;return 245===t||244===t||72===t},e.isNamespaceBody=function(e){var t=e.kind;return 245===t||244===t},e.isJSDocNamespaceBody=function(e){var t=e.kind;return 72===t||244===t},e.isNamedImportBindings=function(e){var t=e.kind;return 252===t||251===t},e.isModuleOrEnumDeclaration=function(e){return 244===e.kind||243===e.kind},e.isDeclaration=function(t){return 150===t.kind?303!==t.parent.kind||e.isInJSFile(t):197===(r=t.kind)||186===r||240===r||209===r||157===r||243===r||278===r||257===r||239===r||196===r||158===r||250===r||248===r||253===r||241===r||267===r||156===r||155===r||244===r||247===r||251===r||151===r||275===r||154===r||153===r||159===r||276===r||242===r||150===r||237===r||304===r||297===r||305===r;var r},e.isDeclarationStatement=function(e){return h(e.kind)},e.isStatementButNotDeclaration=function(e){return b(e.kind)},e.isStatement=function(t){var r=t.kind;return b(r)||h(r)||function(t){return 218===t.kind&&((void 0===t.parent||235!==t.parent.kind&&274!==t.parent.kind)&&!e.isFunctionBlock(t))}(t)},e.isModuleReference=function(e){var t=e.kind;return 259===t||148===t||72===t},e.isJsxTagNameExpression=function(e){var t=e.kind;return 100===t||72===t||189===t},e.isJsxChild=function(e){var t=e.kind;return 260===t||270===t||261===t||11===t||264===t},e.isJsxAttributeLike=function(e){var t=e.kind;return 267===t||269===t},e.isStringLiteralOrJsxExpression=function(e){var t=e.kind;return 10===t||270===t},e.isJsxOpeningLikeElement=function(e){var t=e.kind;return 262===t||261===t},e.isCaseOrDefaultClause=function(e){var t=e.kind;return 271===t||272===t},e.isJSDocNode=function(e){return e.kind>=283&&e.kind<=305},e.isJSDocCommentContainingNode=function(t){return 291===t.kind||D(t)||e.isJSDocTypeLiteral(t)||e.isJSDocSignature(t)},e.isJSDocTag=D,e.isSetAccessor=function(e){return 159===e.kind},e.isGetAccessor=function(e){return 158===e.kind},e.hasJSDocNodes=function(e){var t=e.jsDoc;return!!t&&t.length>0},e.hasType=function(e){return!!e.type},e.hasInitializer=x,e.hasOnlyExpressionInitializer=function(t){return x(t)&&!e.isForStatement(t)&&!e.isForInStatement(t)&&!e.isForOfStatement(t)&&!e.isJsxAttribute(t)},e.isObjectLiteralElement=function(e){return 267===e.kind||269===e.kind||_(e)},e.isTypeReferenceType=function(e){return 164===e.kind||211===e.kind};var S=1073741823;e.guessIndentation=function(t){for(var r=S,n=0,i=t;n=2?e.ModuleKind.ES2015:e.ModuleKind.CommonJS}function p(e){return!(!e.declaration&&!e.composite)}function f(e,t){return void 0===e[t]?!!e.strict:!!e[t]}function m(e,t){return t.strictFlag?f(e,t.name):e[t.name]}e.isNamedImportsOrExports=function(e){return 252===e.kind||256===e.kind},e.objectAllocator={getNodeConstructor:function(){return i},getTokenConstructor:function(){return i},getIdentifierConstructor:function(){return i},getSourceFileConstructor:function(){return i},getSymbolConstructor:function(){return t},getTypeConstructor:function(){return r},getSignatureConstructor:function(){return n},getSourceMapSourceConstructor:function(){return a}},e.formatStringFromArgs=o,e.getLocaleSpecificMessage=s,e.createFileDiagnostic=function(t,r,n,i){e.Debug.assertGreaterThanOrEqual(r,0),e.Debug.assertGreaterThanOrEqual(n,0),t&&(e.Debug.assertLessThanOrEqual(r,t.text.length),e.Debug.assertLessThanOrEqual(r+n,t.text.length));var a=s(i);return arguments.length>4&&(a=o(a,arguments,4)),{file:t,start:r,length:n,messageText:a,category:i.category,code:i.code,reportsUnnecessary:i.reportsUnnecessary}},e.formatMessage=function(e,t){var r=s(t);return arguments.length>2&&(r=o(r,arguments,2)),r},e.createCompilerDiagnostic=function(e){var t=s(e);return arguments.length>1&&(t=o(t,arguments,1)),{file:void 0,start:void 0,length:void 0,messageText:t,category:e.category,code:e.code,reportsUnnecessary:e.reportsUnnecessary}},e.createCompilerDiagnosticFromMessageChain=function(e){return{file:void 0,start:void 0,length:void 0,code:e.code,category:e.category,messageText:e.next?e:e.messageText}},e.chainDiagnosticMessages=function(e,t){var r=s(t);return arguments.length>2&&(r=o(r,arguments,2)),{messageText:r,category:t.category,code:t.code,next:e}},e.concatenateDiagnosticMessageChains=function(e,t){for(var r=e;r.next;)r=r.next;return r.next=t,e},e.compareDiagnostics=u,e.compareDiagnosticsSkipRelatedInformation=l,e.getEmitScriptTarget=_,e.getEmitModuleKind=d,e.getEmitModuleResolutionKind=function(t){var r=t.moduleResolution;return void 0===r&&(r=d(t)===e.ModuleKind.CommonJS?e.ModuleResolutionKind.NodeJs:e.ModuleResolutionKind.Classic),r},e.hasJsonModuleEmitEnabled=function(t){switch(d(t)){case e.ModuleKind.CommonJS:case e.ModuleKind.AMD:case e.ModuleKind.ES2015:case e.ModuleKind.ESNext:return!0;default:return!1}},e.unreachableCodeIsError=function(e){return!1===e.allowUnreachableCode},e.unusedLabelIsError=function(e){return!1===e.allowUnusedLabels},e.getAreDeclarationMapsEnabled=function(e){return!(!p(e)||!e.declarationMap)},e.getAllowSyntheticDefaultImports=function(t){var r=d(t);return void 0!==t.allowSyntheticDefaultImports?t.allowSyntheticDefaultImports:t.esModuleInterop||r===e.ModuleKind.System},e.getEmitDeclarations=p,e.getStrictOptionValue=f,e.compilerOptionsAffectSemanticDiagnostics=function(t,r){return r!==t&&e.semanticDiagnosticsOptionDeclarations.some(function(n){return!e.isJsonEqual(m(r,n),m(t,n))})},e.getCompilerOptionValue=m,e.hasZeroOrOneAsteriskCharacter=function(e){for(var t=!1,r=0;r=97&&e<=122||e>=65&&e<=90}function D(t){if(!t)return 0;var r=t.charCodeAt(0);if(47===r||92===r){if(t.charCodeAt(1)!==r)return 1;var n=t.indexOf(47===r?e.directorySeparator:g,2);return n<0?t.length:n+1}if(b(r)&&58===t.charCodeAt(1)){var i=t.charCodeAt(2);if(47===i||92===i)return 3;if(2===t.length)return 2}var a=t.indexOf(y);if(-1!==a){var o=a+y.length,s=t.indexOf(e.directorySeparator,o);if(-1!==s){var c=t.slice(0,a),u=t.slice(o,s);if("file"===c&&(""===u||"localhost"===u)&&b(t.charCodeAt(s+1))){var l=function(e,t){var r=e.charCodeAt(t);if(58===r)return t+1;if(37===r&&51===e.charCodeAt(t+1)){var n=e.charCodeAt(t+2);if(97===n||65===n)return t+3}return-1}(t,s+2);if(-1!==l){if(47===t.charCodeAt(l))return~(l+1);if(l===t.length)return~l}}return~(s+1)}return~t.length}return 0}function x(e){var t=D(e);return t<0?~t:t}function S(e){return D(e)>0}function T(t,r){return void 0===r&&(r=""),function(t,r){var n=t.substring(0,r),i=t.substring(r).split(e.directorySeparator);return i.length&&!e.lastOrUndefined(i)&&i.pop(),[n].concat(i)}(t=e.combinePaths(r,t),x(t))}function C(t){if(!e.some(t))return[];for(var r=[t[0]],n=1;n1){if(".."!==r[r.length-1]){r.pop();continue}}else if(r[0])continue;r.push(i)}}return r}function k(e,t){return C(T(e,t))}function E(t){return 0===t.length?"":(t[0]&&e.ensureTrailingDirectorySeparator(t[0]))+t.slice(1).join(e.directorySeparator)}e.normalizeSlashes=h,e.getRootLength=x,e.normalizePath=function(t){return e.resolvePath(t)},e.normalizePathAndParts=function(t){var r=C(T(t=h(t))),n=r[0],i=r.slice(1);if(i.length){var a=n+i.join(e.directorySeparator);return{path:e.hasTrailingDirectorySeparator(t)?e.ensureTrailingDirectorySeparator(a):a,parts:i}}return{path:n,parts:i}},e.getDirectoryPath=function(t){var r=x(t=h(t));return r===t.length?t:(t=e.removeTrailingDirectorySeparator(t)).slice(0,Math.max(r,t.lastIndexOf(e.directorySeparator)))},e.startsWithDirectory=function(t,r,n){var i=n(t),a=n(r);return e.startsWith(i,a+"/")||e.startsWith(i,a+"\\")},e.isUrl=function(e){return D(e)<0},e.pathIsRelative=function(e){return/^\.\.?($|[\\/])/.test(e)},e.isRootedDiskPath=S,e.isDiskPathRoot=function(e){var t=D(e);return t>0&&t===e.length},e.convertToRelativePath=function(t,r,n){return S(t)?e.getRelativePathToDirectoryOrUrl(r,t,r,n,!1):t},e.getPathComponents=T,e.reducePathComponents=C,e.getNormalizedPathComponents=k,e.getNormalizedAbsolutePath=function(e,t){return E(k(e,t))},e.getPathFromPathComponents=E}(c||(c={})),function(e){function t(t,r,n,i){var a,o=e.reducePathComponents(e.getPathComponents(t)),s=e.reducePathComponents(e.getPathComponents(r));for(a=0;a0==e.getRootLength(n)>0,"Paths must either both be absolute or both be relative");var a="function"==typeof i?i:e.identity,o=t(r,n,"boolean"==typeof i&&i?e.equateStringsCaseInsensitive:e.equateStringsCaseSensitive,a);return e.getPathFromPathComponents(o)}function n(t){return 0!==e.getRootLength(t)||e.pathIsRelative(t)?t:"./"+t}function i(t,r,n){if(t=e.normalizeSlashes(t),e.getRootLength(t)===t.length)return"";var i=(t=c(t)).slice(Math.max(e.getRootLength(t),t.lastIndexOf(e.directorySeparator)+1)),a=void 0!==r&&void 0!==n?U(i,r,n):void 0;return a?i.slice(0,i.length-a.length):i}function a(t){for(var r=[],n=1;n0;)u+=")?",f--;return u}(t,r,n,D[n])})}function T(e){return!/[.*?]/.test(e)}function C(e,t){return"*"===e?t:"?"===e?"[^/]":"\\"+e}function k(t,r,n,i,o){t=e.normalizePath(t);var s=a(o=e.normalizePath(o),t);return{includeFilePatterns:e.map(S(n,s,"files"),function(e){return"^"+e+"$"}),includeFilePattern:x(n,s,"files"),includeDirectoryPattern:x(n,s,"directories"),excludePattern:x(r,s,"exclude"),basePaths:function(t,r,n){var i=[t];if(r){for(var o=[],s=0,c=r;s=0;n--)if(e.fileExtensionIs(t,r[n]))return I(n,r);return 0},e.adjustExtensionPriority=I,e.getNextLowestExtensionPriority=function(e,t){return e<2?2:t.length};var M,L=[".d.ts",".ts",".js",".tsx",".jsx",".json"];function R(t,r){return e.fileExtensionIs(t,r)?B(t,r):void 0}function B(e,t){return e.substring(0,e.length-t.length)}function j(t,r,n,i){var a=void 0!==n&&void 0!==i?U(t,n,i):U(t);return a?t.slice(0,t.length-a.length)+(e.startsWith(r,".")?r:"."+r):t}function J(t){M.assert(e.hasZeroOrOneAsteriskCharacter(t));var r=t.indexOf("*");return-1===r?void 0:{prefix:t.substr(0,r),suffix:t.substr(r+1)}}function z(e){return".ts"===e||".tsx"===e||".d.ts"===e}function K(t){return e.find(L,function(r){return e.fileExtensionIs(t,r)})}function U(t,r,n){if(r)return function(t,r,n){"string"==typeof r&&(r=[r]);for(var i=0,a=r;i=o.length&&"."===t.charAt(t.length-o.length)){var s=t.slice(t.length-o.length);if(n(s,o))return s}}return""}(t,r,n?e.equateStringsCaseInsensitive:e.equateStringsCaseSensitive);var a=i(t),o=a.lastIndexOf(".");return o>=0?a.substring(o):""}e.removeFileExtension=function(e){for(var t=0,r=L;t=0)},e.extensionIsTS=z,e.resolutionExtensionIsTSOrJson=function(e){return z(e)||".json"===e},e.extensionFromPath=function(e){var t=K(e);return void 0!==t?t:M.fail("File "+e+" has unknown extension.")},e.isAnySupportedFileExtension=function(e){return void 0!==K(e)},e.tryGetExtensionFromPath=K,e.getAnyExtensionFromPath=U,e.isCheckJsEnabledForFile=function(e,t){return e.checkJsDirective?e.checkJsDirective.enabled:t.checkJs},e.emptyFileSystemEntries={files:e.emptyArray,directories:e.emptyArray},e.matchPatternOrExact=function(t,r){for(var n=[],i=0,a=t;in&&(n=a)}return{min:r,max:n}};var V=function(){function t(){this.map=e.createMap()}return t.prototype.add=function(t){this.map.set(String(e.getNodeId(t)),t)},t.prototype.tryAdd=function(e){return!this.has(e)&&(this.add(e),!0)},t.prototype.has=function(t){return this.map.has(String(e.getNodeId(t)))},t.prototype.forEach=function(e){this.map.forEach(e)},t.prototype.some=function(t){return e.forEachEntry(this.map,t)||!1},t}();e.NodeSet=V;var q=function(){function t(){this.map=e.createMap()}return t.prototype.get=function(t){var r=this.map.get(String(e.getNodeId(t)));return r&&r.value},t.prototype.getOrUpdate=function(e,t){var r=this.get(e);if(r)return r;var n=t();return this.set(e,n),n},t.prototype.set=function(t,r){this.map.set(String(e.getNodeId(t)),{node:t,value:r})},t.prototype.has=function(t){return this.map.has(String(e.getNodeId(t)))},t.prototype.forEach=function(e){this.map.forEach(function(t){var r=t.node,n=t.value;return e(n,r)})},t}();e.NodeMap=q,e.rangeOfNode=function(t){return{pos:e.getTokenPosOfNode(t),end:t.end}},e.rangeOfTypeParameters=function(e){return{pos:e.pos-1,end:e.end+1}},e.skipTypeChecking=function(e,t){return t.skipLibCheck&&e.isDeclarationFile||t.skipDefaultLibCheck&&e.hasNoDefaultLib},e.isJsonEqual=function t(r,n){return r===n||"object"===f(r)&&null!==r&&"object"===f(n)&&null!==n&&e.equalOwnProperties(r,n,t)},e.getOrUpdate=function(e,t,r){var n=e.get(t);if(void 0===n){var i=r();return e.set(t,i),i}return n},e.parsePseudoBigInt=function(e){var t;switch(e.charCodeAt(1)){case 98:case 66:t=1;break;case 111:case 79:t=3;break;case 120:case 88:t=4;break;default:for(var r=e.length-1,n=0;48===e.charCodeAt(n);)n++;return e.slice(n,r)||"0"}for(var i=e.length-1,a=(i-2)*t,o=new Uint16Array((a>>>4)+(15&a?1:0)),s=i-1,c=0;s>=2;s--,c+=t){var u=c>>>4,l=e.charCodeAt(s),_=(l<=57?l-48:10+l-(l<=70?65:97))<<(15&c);o[u]|=_;var d=_>>>16;d&&(o[u+1]|=d)}for(var p="",f=o.length-1,m=!0;m;){var g=0;for(m=!1,u=f;u>=0;u--){var y=g<<16|o[u],v=y/10|0;o[u]=v,g=y-10*v,v&&!m&&(f=u,m=!0)}p=g+p}return p},e.pseudoBigIntToString=function(e){var t=e.negative,r=e.base10Value;return(t&&"0"!==r?"-":"")+r}}(c||(c={})),function(e){var t,r,n,i,a,o,s;function c(e,t){return t&&e(t)}function u(e,t,r){if(r){if(t)return t(r);for(var n=0,i=r;nt.checkJsDirective.pos)&&(t.checkJsDirective={enabled:"ts-check"===i,end:e.range.end,pos:e.range.pos})});break;case"jsx":return;default:e.Debug.fail("Unhandled pragma kind")}})}!function(e){e[e.None=0]="None",e[e.Yield=1]="Yield",e[e.Await=2]="Await",e[e.Type=4]="Type",e[e.IgnoreMissingOpenBrace=16]="IgnoreMissingOpenBrace",e[e.JSDoc=32]="JSDoc"}(t||(t={})),e.createNode=function(t,o,s){return 279===t?new(a||(a=e.objectAllocator.getSourceFileConstructor()))(t,o,s):72===t?new(i||(i=e.objectAllocator.getIdentifierConstructor()))(t,o,s):e.isNodeKind(t)?new(r||(r=e.objectAllocator.getNodeConstructor()))(t,o,s):new(n||(n=e.objectAllocator.getTokenConstructor()))(t,o,s)},e.isJSDocLikeText=l,e.forEachChild=_,e.createSourceFile=function(t,r,n,i,a){var s;return void 0===i&&(i=!1),e.performance.mark("beforeParse"),s=100===n?o.parseSourceFile(t,r,n,void 0,i,6):o.parseSourceFile(t,r,n,void 0,i,a),e.performance.mark("afterParse"),e.performance.measure("Parse","beforeParse","afterParse"),s},e.parseIsolatedEntityName=function(e,t){return o.parseIsolatedEntityName(e,t)},e.parseJsonText=function(e,t){return o.parseJsonText(e,t)},e.isExternalModule=function(e){return void 0!==e.externalModuleIndicator},e.updateSourceFile=function(e,t,r,n){void 0===n&&(n=!1);var i=s.updateSourceFile(e,t,r,n);return i.flags|=1572864&e.flags,i},e.parseIsolatedJSDocComment=function(e,t,r){var n=o.JSDocParser.parseIsolatedJSDocComment(e,t,r);return n&&n.jsDoc&&o.fixupParentReferences(n.jsDoc),n},e.parseJSDocTypeExpressionForTests=function(e,t,r){return o.JSDocParser.parseJSDocTypeExpressionForTests(e,t,r)},function(t){var r,n,i,a,o,s,c,u,m,g,y,v,h,b,x,S,T,C=e.createScanner(6,!0),k=10240,E=!1;function N(t,r,n,i,a){void 0===n&&(n=2),F(r,n,i,6),(o=M(t,2,6,!1)).flags=b,ne();var c=te();if(1===re())o.statements=be([],c,c),o.endOfFileToken=me();else{var u=ve(221);switch(re()){case 22:u.expression=Nr();break;case 102:case 87:case 96:u.expression=me();break;case 39:ce(function(){return 8===ne()&&57!==ne()})?u.expression=cr():u.expression=Fr();break;case 8:case 10:if(ce(function(){return 57!==ne()})){u.expression=rt();break}default:u.expression=Fr()}De(u),o.statements=be([u],c),o.endOfFileToken=fe(1,e.Diagnostics.Unexpected_token)}a&&I(o),o.parseDiagnostics=s;var l=o;return P(),l}function A(e){return 4===e||2===e||1===e||6===e?1:0}function F(t,o,u,l){switch(r=e.objectAllocator.getNodeConstructor(),n=e.objectAllocator.getTokenConstructor(),i=e.objectAllocator.getIdentifierConstructor(),a=e.objectAllocator.getSourceFileConstructor(),m=t,c=u,s=[],h=0,y=e.createMap(),v=0,g=0,l){case 1:case 2:b=65536;break;case 6:b=16842752;break;default:b=0}E=!1,C.setText(m),C.setOnError(ee),C.setScriptTarget(o),C.setLanguageVariant(A(l))}function P(){C.setText(""),C.setOnError(void 0),s=void 0,o=void 0,y=void 0,c=void 0,m=void 0}function w(t,r,n,i){var a=d(t);return a&&(b|=4194304),(o=M(t,r,i,a)).flags=b,ne(),p(o,m),f(o,function(t,r,n){s.push(e.createFileDiagnostic(o,t,r,n))}),o.statements=Ve(0,Hr),e.Debug.assert(1===re()),o.endOfFileToken=O(me()),function(t){t.externalModuleIndicator=e.forEach(t.statements,Mn)||function(e){return 1048576&e.flags?Ln(e):void 0}(t)}(o),o.nodeCount=g,o.identifierCount=v,o.identifiers=y,o.parseDiagnostics=s,n&&I(o),o}function O(t){e.Debug.assert(!t.jsDoc);var r=e.mapDefined(e.getJSDocCommentRanges(t,o.text),function(e){return T.parseJSDocComment(t,e.pos,e.end-e.pos)});return r.length&&(t.jsDoc=r),t}function I(t){var r=t;return void _(t,function t(n){if(n.parent!==r){n.parent=r;var i=r;if(r=n,_(n,t),e.hasJSDocNodes(n))for(var a=0,o=n.jsDoc;a108)}function _e(t,r,n){return void 0===n&&(n=!0),re()===t?(n&&ne(),!0):(r?X(r):X(e.Diagnostics._0_expected,e.tokenToString(t)),!1)}function de(e){return re()===e&&(ne(),!0)}function pe(e){if(re()===e)return me()}function fe(t,r,n){return pe(t)||xe(t,!1,r||e.Diagnostics._0_expected,n||e.tokenToString(t))}function me(){var e=ve(re());return ne(),De(e)}function ge(){return 26===re()||(19===re()||1===re()||C.hasPrecedingLineBreak())}function ye(){return ge()?(26===re()&&ne(),!0):_e(26)}function ve(t,a){g++;var o=a>=0?a:C.getStartPos();return e.isNodeKind(t)||0===t?new r(t,o,o):72===t?new i(t,o,o):new n(t,o,o)}function he(e,t){var r=ve(e,t);return 2&C.getTokenFlags()&&O(r),r}function be(e,t,r){var n=e.length,i=n>=1&&n<=4?e.slice():e;return i.pos=t,i.end=void 0===r?C.getStartPos():r,i}function De(e,t){return e.end=void 0===t?C.getStartPos():t,b&&(e.flags|=b),E&&(E=!1,e.flags|=32768),e}function xe(t,r,n,i){r?Q(C.getStartPos(),0,n,i):n&&X(n,i);var a=ve(t);return 72===t?a.escapedText="":(e.isLiteralKind(t)||e.isTemplateLiteralKind(t))&&(a.text=""),De(a)}function Se(e){var t=y.get(e);return void 0===t&&y.set(e,t=e),t}function Te(t,r){if(v++,t){var n=ve(72);return 72!==re()&&(n.originalKeywordKind=re()),n.escapedText=e.escapeLeadingUnderscores(Se(C.getTokenValue())),ne(),De(n)}return xe(72,1===re(),r||e.Diagnostics.Identifier_expected)}function Ce(e){return Te(le(),e)}function ke(t){return Te(e.tokenIsIdentifierOrKeyword(re()),t)}function Ee(){return e.tokenIsIdentifierOrKeyword(re())||10===re()||8===re()}function Ne(e){if(10===re()||8===re()){var t=rt();return t.text=Se(t.text),t}return e&&22===re()?function(){var e=ve(149);return _e(22),e.expression=U(Gt),_e(23),De(e)}():ke()}function Ae(){return Ne(!0)}function Fe(e){return re()===e&&ue(we)}function Pe(){return ne(),!C.hasPrecedingLineBreak()&&Oe()}function we(){switch(re()){case 77:return 84===ne();case 85:return ne(),80===re()?ce(Ie):40!==re()&&119!==re()&&18!==re()&&Oe();case 80:return Ie();case 116:case 126:case 137:return ne(),Oe();default:return Pe()}}function Oe(){return 22===re()||18===re()||40===re()||25===re()||Ee()}function Ie(){return ne(),76===re()||90===re()||110===re()||118===re()&&ce(Jr)||121===re()&&ce(zr)}function Me(t,r){if(We(t))return!0;switch(t){case 0:case 1:case 3:return!(26===re()&&r)&&qr();case 2:return 74===re()||80===re();case 4:return ce(ht);case 5:return ce(pn)||26===re()&&!r;case 6:return 22===re()||Ee();case 12:switch(re()){case 22:case 40:case 25:case 24:return!0;default:return Ee()}case 18:return Ee();case 9:return 22===re()||25===re()||Ee();case 7:return 18===re()?ce(Le):r?le()&&!Je():Wt()&&!Je();case 8:return tn();case 10:return 27===re()||25===re()||tn();case 19:return le();case 15:switch(re()){case 27:case 24:return!0}case 11:return 25===re()||Ht();case 16:return _t(!1);case 17:return _t(!0);case 20:case 21:return 27===re()||It();case 22:return Tn();case 23:return e.tokenIsIdentifierOrKeyword(re());case 13:return e.tokenIsIdentifierOrKeyword(re())||18===re();case 14:return!0}return e.Debug.fail("Non-exhaustive case in 'isListElement'.")}function Le(){if(e.Debug.assert(18===re()),19===ne()){var t=ne();return 27===t||18===t||86===t||109===t}return!0}function Re(){return ne(),le()}function Be(){return ne(),e.tokenIsIdentifierOrKeyword(re())}function je(){return ne(),e.tokenIsIdentifierOrKeywordOrGreaterThan(re())}function Je(){return(109===re()||86===re())&&ce(ze)}function ze(){return ne(),Ht()}function Ke(){return ne(),It()}function Ue(e){if(1===re())return!0;switch(e){case 1:case 2:case 4:case 5:case 6:case 12:case 9:case 23:return 19===re();case 3:return 19===re()||74===re()||80===re();case 7:return 18===re()||86===re()||109===re();case 8:return function(){if(ge())return!0;if(ir(re()))return!0;if(37===re())return!0;return!1}();case 19:return 30===re()||20===re()||18===re()||86===re()||109===re();case 11:return 21===re()||26===re();case 15:case 21:case 10:return 23===re();case 17:case 16:case 18:return 21===re()||23===re();case 20:return 27!==re();case 22:return 18===re()||19===re();case 13:return 30===re()||42===re();case 14:return 28===re()&&ce(An);default:return!1}}function Ve(e,t){var r=h;h|=1<=0&&(c.hasTrailingComma=!0),c}function Ye(){var e=be([],te());return e.isMissingList=!0,e}function Xe(e,t,r,n){if(_e(r)){var i=Ge(e,t);return _e(n),i}return Ye()}function Qe(e,t){for(var r=e?ke(t):Ce(t),n=C.getStartPos();de(24);){if(28===re()){r.jsdocDotPos=n;break}n=C.getStartPos(),r=$e(r,Ze(e))}return r}function $e(e,t){var r=ve(148,e.pos);return r.left=e,r.right=t,De(r)}function Ze(t){if(C.hasPrecedingLineBreak()&&e.tokenIsIdentifierOrKeyword(re())&&ce(jr))return xe(72,!0,e.Diagnostics.Identifier_expected);return t?ke():Ce()}function et(){var t,r=ve(206);r.head=(t=nt(re()),e.Debug.assert(15===t.kind,"Template head has wrong token kind"),t),e.Debug.assert(15===r.head.kind,"Template head has wrong token kind");var n=[],i=te();do{n.push(tt())}while(16===e.last(n).literal.kind);return r.templateSpans=be(n,i),De(r)}function tt(){var t,r,n=ve(216);return n.expression=U(Gt),19===re()?(u=C.reScanTemplateToken(),r=nt(re()),e.Debug.assert(16===r.kind||17===r.kind,"Template fragment has wrong token kind"),t=r):t=fe(17,e.Diagnostics._0_expected,e.tokenToString(19)),n.literal=t,De(n)}function rt(){return nt(re())}function nt(e){var t=ve(e);return t.text=C.getTokenValue(),C.hasExtendedUnicodeEscape()&&(t.hasExtendedUnicodeEscape=!0),C.isUnterminated()&&(t.isUnterminated=!0),8===t.kind&&(t.numericLiteralFlags=1008&C.getTokenFlags()),ne(),De(t),t}function it(){var t=ve(164);return t.typeName=Qe(!0,e.Diagnostics.Type_expected),C.hasPrecedingLineBreak()||28!==re()||(t.typeArguments=Xe(20,Ut,28,30)),De(t)}function at(e){var t=ve(284);return e?Lt(288,t):(ne(),De(t))}function ot(){var e=ve(151);return 100!==re()&&95!==re()||(e.name=ke(),_e(57)),e.type=st(),De(e)}function st(){C.setInJSDocType(!0);var e=pe(25),t=zt();if(C.setInJSDocType(!1),e){var r=ve(290,e.pos);r.type=t,t=De(r)}return 59===re()?Lt(288,t):t}function ct(){var e=ve(150);return e.name=Ce(),de(86)&&(It()||!Ht()?e.constraint=Ut():e.expression=ur()),de(59)&&(e.default=Ut()),De(e)}function ut(){if(28===re())return Xe(19,ct,28,30)}function lt(){if(de(57))return Ut()}function _t(t){return 25===re()||tn()||e.isModifierKind(re())||58===re()||It(!t)}function dt(){var t=he(151);return 100===re()?(t.name=Te(!0),t.type=lt(),De(t)):(t.decorators=fn(),t.modifiers=mn(),t.dotDotDotToken=pe(25),t.name=rn(),0===e.getFullWidth(t.name)&&!e.hasModifiers(t)&&e.isModifierKind(re())&&ne(),t.questionToken=pe(56),t.type=lt(),t.initializer=Yt(),De(t))}function pt(t,r,n){32&r||(n.typeParameters=ut());var i=function(e,t){if(!_e(20))return e.parameters=Ye(),!1;var r=W(),n=Y();return B(!!(1&t)),J(!!(2&t)),e.parameters=32&t?Ge(17,ot):Ge(16,dt),B(r),J(n),_e(21)}(n,r);return(!function(t,r){if(37===t)return _e(t),!0;if(de(57))return!0;if(r&&37===re())return X(e.Diagnostics._0_expected,e.tokenToString(57)),ne(),!0;return!1}(t,!!(4&r))||(n.type=zt(),!function t(r){switch(r.kind){case 164:return e.nodeIsMissing(r.typeName);case 165:case 166:var n=r,i=n.parameters,a=n.type;return!!i.isMissingList||t(a);case 177:return t(r.type);default:return!1}}(n.type)))&&i}function ft(){de(27)||ye()}function mt(e){var t=he(e);return 161===e&&_e(95),pt(57,4,t),ft(),De(t)}function gt(){return 22===re()&&ce(yt)}function yt(){if(ne(),25===re()||23===re())return!0;if(e.isModifierKind(re())){if(ne(),le())return!0}else{if(!le())return!1;ne()}return 57===re()||27===re()||56===re()&&(ne(),57===re()||27===re()||23===re())}function vt(e){return e.kind=162,e.parameters=Xe(16,dt,22,23),e.type=qt(),ft(),De(e)}function ht(){if(20===re()||28===re())return!0;for(var t=!1;e.isModifierKind(re());)t=!0,ne();return 22===re()||(Ee()&&(t=!0,ne()),!!t&&(20===re()||28===re()||56===re()||57===re()||27===re()||ge()))}function bt(){if(20===re()||28===re())return mt(160);if(95===re()&&ce(Dt))return mt(161);var e=he(0);return e.modifiers=mn(),gt()?vt(e):function(e){return e.name=Ae(),e.questionToken=pe(56),20===re()||28===re()?(e.kind=155,pt(57,4,e)):(e.kind=153,e.type=qt(),59===re()&&(e.initializer=Yt())),ft(),De(e)}(e)}function Dt(){return ne(),20===re()||28===re()}function xt(){return 24===ne()}function St(){switch(ne()){case 20:case 28:case 24:return!0}return!1}function Tt(){var e;return _e(18)?(e=Ve(4,bt),_e(19)):e=Ye(),e}function Ct(){return ne(),38===re()||39===re()?133===ne():(133===re()&&ne(),22===re()&&Re()&&93===ne())}function kt(){var e=ve(181);return _e(18),133!==re()&&38!==re()&&39!==re()||(e.readonlyToken=me(),133!==e.readonlyToken.kind&&fe(133)),_e(22),e.typeParameter=function(){var e=ve(150);return e.name=Ce(),_e(93),e.constraint=Ut(),De(e)}(),_e(23),56!==re()&&38!==re()&&39!==re()||(e.questionToken=me(),56!==e.questionToken.kind&&fe(56)),e.type=qt(),ye(),_e(19),De(e)}function Et(){var e=te();if(de(25)){var t=ve(172,e);return t.type=Ut(),De(t)}var r=Ut();return 2097152&b||286!==r.kind||r.pos!==r.type.pos||(r.kind=171),r}function Nt(){var e=me();return 24===re()?void 0:e}function At(e){var t,r=ve(182);e&&((t=ve(202)).operator=39,ne());var n=102===re()||87===re()?me():nt(re());return e&&(t.operand=n,De(t),n=t),r.literal=n,De(r)}function Ft(){return ne(),92===re()}function Pt(){o.flags|=524288;var t=ve(183);return de(104)&&(t.isTypeOf=!0),_e(92),_e(20),t.argument=Ut(),_e(21),de(24)&&(t.qualifier=Qe(!0,e.Diagnostics.Type_expected)),t.typeArguments=Sn(),De(t)}function wt(){return ne(),8===re()||9===re()}function Ot(){switch(re()){case 120:case 143:case 138:case 135:case 146:case 139:case 123:case 141:case 132:case 136:return ue(Nt)||it();case 40:return at(!1);case 62:return at(!0);case 56:return n=C.getStartPos(),ne(),27===re()||19===re()||21===re()||30===re()||59===re()||50===re()?De(r=ve(285,n)):((r=ve(286,n)).type=Ut(),De(r));case 90:return function(){if(ce(Nn)){var e=he(289);return ne(),pt(57,36,e),De(e)}var t=ve(164);return t.typeName=ke(),De(t)}();case 52:return function(){var e=ve(287);return ne(),e.type=Ot(),De(e)}();case 14:case 10:case 8:case 9:case 102:case 87:return At();case 39:return ce(wt)?At(!0):it();case 106:case 96:return me();case 100:var e=(t=ve(178),ne(),De(t));return 128!==re()||C.hasPrecedingLineBreak()?e:function(e){ne();var t=ve(163,e.pos);return t.parameterName=e,t.type=Ut(),De(t)}(e);case 104:return ce(Ft)?Pt():function(){var e=ve(167);return _e(104),e.exprName=Qe(!0),De(e)}();case 18:return ce(Ct)?kt():function(){var e=ve(168);return e.members=Tt(),De(e)}();case 22:return function(){var e=ve(170);return e.elementTypes=Xe(21,Et,22,23),De(e)}();case 20:return function(){var e=ve(177);return _e(20),e.type=Ut(),_e(21),De(e)}();case 92:return Pt();default:return it()}var t,r,n}function It(e){switch(re()){case 120:case 143:case 138:case 135:case 146:case 123:case 139:case 142:case 106:case 141:case 96:case 100:case 104:case 132:case 18:case 22:case 28:case 50:case 49:case 95:case 10:case 8:case 9:case 102:case 87:case 136:case 40:case 56:case 52:case 25:case 127:case 92:return!0;case 90:return!e;case 39:return!e&&ce(wt);case 20:return!e&&ce(Mt);default:return le()}}function Mt(){return ne(),21===re()||_t(!1)||It()}function Lt(e,t){ne();var r=ve(e,t.pos);return r.type=t,De(r)}function Rt(){var e=re();switch(e){case 129:case 142:return function(e){var t=ve(179);return _e(e),t.operator=e,t.type=Rt(),De(t)}(e);case 127:return function(){var e=ve(176);_e(127);var t=ve(150);return t.name=Ce(),e.typeParameter=De(t),De(e)}()}return function(){for(var e=Ot();!C.hasPrecedingLineBreak();)switch(re()){case 52:e=Lt(287,e);break;case 56:if(!(2097152&b)&&ce(Ke))return e;e=Lt(286,e);break;case 22:var t;_e(22),It()?((t=ve(180,e.pos)).objectType=e,t.indexType=Ut(),_e(23),e=De(t)):((t=ve(169,e.pos)).elementType=e,_e(23),e=De(t));break;default:return e}return e}()}function Bt(e,t,r){de(r);var n=t();if(re()===r){for(var i=[n];de(r);)i.push(t());var a=ve(e,n.pos);a.types=be(i,n.pos),n=De(a)}return n}function jt(){return Bt(174,Rt,49)}function Jt(){if(ne(),21===re()||25===re())return!0;if(function(){if(e.isModifierKind(re())&&mn(),le()||100===re())return ne(),!0;if(22===re()||18===re()){var t=s.length;return rn(),t===s.length}return!1}()){if(57===re()||27===re()||56===re()||59===re())return!0;if(21===re()&&(ne(),37===re()))return!0}return!1}function zt(){var e=le()&&ue(Kt),t=Ut();if(e){var r=ve(163,e.pos);return r.parameterName=e,r.type=t,De(r)}return t}function Kt(){var e=Ce();if(128===re()&&!C.hasPrecedingLineBreak())return ne(),e}function Ut(){return z(20480,Vt)}function Vt(e){if(28===re()||20===re()&&ce(Jt)||95===re())return function(){var e=te(),t=he(de(95)?166:165,e);return pt(37,4,t),De(t)}();var t=Bt(173,jt,50);if(!e&&!C.hasPrecedingLineBreak()&&de(86)){var r=ve(175,t.pos);return r.checkType=t,r.extendsType=Vt(!0),_e(56),r.trueType=Vt(),_e(57),r.falseType=Vt(),De(r)}return t}function qt(){return de(57)?Ut():void 0}function Wt(){switch(re()){case 100:case 98:case 96:case 102:case 87:case 8:case 9:case 10:case 14:case 15:case 20:case 22:case 18:case 90:case 76:case 95:case 42:case 64:case 72:return!0;case 92:return ce(St);default:return le()}}function Ht(){if(Wt())return!0;switch(re()){case 38:case 39:case 53:case 52:case 81:case 104:case 106:case 44:case 45:case 28:case 122:case 117:return!0;default:return!!function(){if(H()&&93===re())return!1;return e.getBinaryOperatorPrecedence(re())>0}()||le()}}function Gt(){var e=G();e&&j(!1);for(var t,r=Xt();t=pe(27);)r=or(r,t,Xt());return e&&j(!0),r}function Yt(){return de(59)?Xt():void 0}function Xt(){if(function(){if(117===re())return!!W()||ce(Kr);return!1}())return t=ve(207),ne(),C.hasPrecedingLineBreak()||40!==re()&&!Ht()?De(t):(t.asteriskToken=pe(40),t.expression=Xt(),De(t));var t,r=function(){var t=function(){if(20===re()||28===re()||121===re())return ce($t);if(37===re())return 1;return 0}();if(0===t)return;var r=1===t?tr(!0):ue(Zt);if(!r)return;var n=e.hasModifier(r,256),i=re();return r.equalsGreaterThanToken=fe(37),r.body=37===i||18===i?rr(n):Ce(),De(r)}()||function(){if(121===re()&&1===ce(er)){var e=gn(),t=nr(0);return Qt(t,e)}return}();if(r)return r;var n=nr(0);return 72===n.kind&&37===re()?Qt(n):e.isLeftHandSideExpression(n)&&e.isAssignmentOperator(ie())?or(n,me(),Xt()):function(t){var r=pe(56);if(!r)return t;var n=ve(205,t.pos);return n.condition=t,n.questionToken=r,n.whenTrue=z(k,Xt),n.colonToken=fe(57),n.whenFalse=e.nodeIsPresent(n.colonToken)?Xt():xe(72,!1,e.Diagnostics._0_expected,e.tokenToString(57)),De(n)}(n)}function Qt(t,r){var n;e.Debug.assert(37===re(),"parseSimpleArrowFunctionExpression should only have been called if we had a =>"),r?(n=ve(197,r.pos)).modifiers=r:n=ve(197,t.pos);var i=ve(151,t.pos);return i.name=t,De(i),n.parameters=be([i],i.pos,i.end),n.equalsGreaterThanToken=fe(37),n.body=rr(!!r),O(De(n))}function $t(){if(121===re()){if(ne(),C.hasPrecedingLineBreak())return 0;if(20!==re()&&28!==re())return 0}var t=re(),r=ne();if(20===t){if(21===r)switch(ne()){case 37:case 57:case 18:return 1;default:return 0}if(22===r||18===r)return 2;if(25===r)return 1;if(e.isModifierKind(r)&&121!==r&&ce(Re))return 1;if(!le()&&100!==r)return 0;switch(ne()){case 57:return 1;case 56:return ne(),57===re()||27===re()||59===re()||21===re()?1:0;case 27:case 59:case 21:return 2}return 0}return e.Debug.assert(28===t),le()?1===o.languageVariant?ce(function(){var e=ne();if(86===e)switch(ne()){case 59:case 30:return!1;default:return!0}else if(27===e)return!0;return!1})?1:0:2:0}function Zt(){return tr(!1)}function er(){if(121===re()){if(ne(),C.hasPrecedingLineBreak()||37===re())return 0;var e=nr(0);if(!C.hasPrecedingLineBreak()&&72===e.kind&&37===re())return 1}return 0}function tr(t){var r=he(197);if(r.modifiers=gn(),(pt(57,e.hasModifier(r,256)?2:0,r)||t)&&(t||37===re()||18===re()))return r}function rr(e){return 18===re()?Ir(e?2:0):26===re()||90===re()||76===re()||!qr()||18!==re()&&90!==re()&&76!==re()&&58!==re()&&Ht()?e?V(Xt):z(16384,Xt):Ir(16|(e?2:0))}function nr(e){return ar(e,ur())}function ir(e){return 93===e||147===e}function ar(t,r){for(;;){ie();var n=e.getBinaryOperatorPrecedence(re());if(!(41===re()?n>=t:n>t))break;if(93===re()&&H())break;if(119===re()){if(C.hasPrecedingLineBreak())break;ne(),r=sr(r,Ut())}else r=or(r,me(),nr(n))}return r}function or(e,t,r){var n=ve(204,e.pos);return n.left=e,n.operatorToken=t,n.right=r,De(n)}function sr(e,t){var r=ve(212,e.pos);return r.expression=e,r.type=t,De(r)}function cr(){var e=ve(202);return e.operator=re(),ne(),e.operand=lr(),De(e)}function ur(){if(function(){switch(re()){case 38:case 39:case 53:case 52:case 81:case 104:case 106:case 122:return!1;case 28:if(1!==o.languageVariant)return!1;default:return!0}}()){var t=_r();return 41===re()?ar(e.getBinaryOperatorPrecedence(re()),t):t}var r=re(),n=lr();if(41===re()){var i=e.skipTrivia(m,n.pos),a=n.end;194===n.kind?$(i,a,e.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses):$(i,a,e.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses,e.tokenToString(r))}return n}function lr(){switch(re()){case 38:case 39:case 53:case 52:return cr();case 81:return e=ve(198),ne(),e.expression=lr(),De(e);case 104:return function(){var e=ve(199);return ne(),e.expression=lr(),De(e)}();case 106:return function(){var e=ve(200);return ne(),e.expression=lr(),De(e)}();case 28:return function(){var e=ve(194);return _e(28),e.type=Ut(),_e(30),e.expression=lr(),De(e)}();case 122:if(122===re()&&(Y()||ce(Kr)))return function(){var e=ve(201);return ne(),e.expression=lr(),De(e)}();default:return _r()}var e}function _r(){if(44===re()||45===re())return(t=ve(202)).operator=re(),ne(),t.operand=dr(),De(t);if(1===o.languageVariant&&28===re()&&ce(je))return fr(!0);var t,r=dr();return e.Debug.assert(e.isLeftHandSideExpression(r)),44!==re()&&45!==re()||C.hasPrecedingLineBreak()?r:((t=ve(203,r.pos)).operand=r,t.operator=re(),ne(),De(t))}function dr(){var t;if(92===re())if(ce(Dt))o.flags|=524288,t=me();else if(ce(xt)){var r=C.getStartPos();ne(),ne();var n=ve(214,r);n.keywordToken=92,n.name=ke(),t=De(n),o.flags|=1048576}else t=pr();else t=98===re()?function(){var t=me();if(20===re()||24===re()||22===re())return t;var r=ve(189,t.pos);return r.expression=t,fe(24,e.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access),r.name=Ze(!0),De(r)}():pr();return function(e){for(;;)if(e=br(e),28!==re()){if(20!==re())return e;var t=ve(191,e.pos);t.expression=e,t.arguments=Sr(),e=De(t)}else{var r=ue(Tr);if(!r)return e;if(Dr()){e=xr(e,r);continue}var t=ve(191,e.pos);t.expression=e,t.typeArguments=r,t.arguments=Sr(),e=De(t)}}(t)}function pr(){return br(Cr())}function fr(t){var r,n=function(e){var t=C.getStartPos();if(_e(28),30===re()){var r=ve(265,t);return oe(),De(r)}var n,i=yr(),a=Sn(),o=(s=ve(268),s.properties=Ve(13,hr),De(s));var s;30===re()?(n=ve(262,t),oe()):(_e(42),e?_e(30):(_e(30,void 0,!1),oe()),n=ve(261,t));return n.tagName=i,n.typeArguments=a,n.attributes=o,De(n)}(t);if(262===n.kind)(i=ve(260,n.pos)).openingElement=n,i.children=gr(i.openingElement),i.closingElement=function(e){var t=ve(263);_e(29),t.tagName=yr(),e?_e(30):(_e(30,void 0,!1),oe());return De(t)}(t),D(i.openingElement.tagName,i.closingElement.tagName)||Z(i.closingElement,e.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0,e.getTextOfNodeFromSourceText(m,i.openingElement.tagName)),r=De(i);else if(265===n.kind){var i;(i=ve(264,n.pos)).openingFragment=n,i.children=gr(i.openingFragment),i.closingFragment=function(t){var r=ve(266);_e(29),e.tokenIsIdentifierOrKeyword(re())&&Z(yr(),e.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);t?_e(30):(_e(30,void 0,!1),oe());return De(r)}(t),r=De(i)}else e.Debug.assert(261===n.kind),r=n;if(t&&28===re()){var a=ue(function(){return fr(!0)});if(a){X(e.Diagnostics.JSX_expressions_must_have_one_parent_element);var o=ve(204,r.pos);return o.end=a.end,o.left=r,o.right=a,o.operatorToken=xe(27,!1,void 0),o.operatorToken.pos=o.operatorToken.end=o.right.pos,o}}return r}function mr(t,r){switch(r){case 1:return void(e.isJsxOpeningFragment(t)?Z(t,e.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag):Z(t.tagName,e.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag,e.getTextOfNodeFromSourceText(m,t.tagName)));case 29:case 7:return;case 11:case 12:return(n=ve(11)).containsOnlyWhiteSpaces=12===u,u=C.scanJsxToken(),De(n);case 18:return vr(!1);case 28:return fr(!1);default:return e.Debug.assertNever(r)}var n}function gr(e){var t=[],r=te(),n=h;for(h|=16384;;){var i=mr(e,u=C.reScanJsxToken());if(!i)break;t.push(i)}return h=n,be(t,r)}function yr(){ae();for(var e=100===re()?me():ke();de(24);){var t=ve(189,e.pos);t.expression=e,t.name=Ze(!0),e=De(t)}return e}function vr(e){var t=ve(270);if(_e(18))return 19!==re()&&(t.dotDotDotToken=pe(25),t.expression=Xt()),e?_e(19):(_e(19,void 0,!1),oe()),De(t)}function hr(){if(18===re())return function(){var e=ve(269);return _e(18),_e(25),e.expression=Gt(),_e(19),De(e)}();ae();var e=ve(267);if(e.name=ke(),59===re())switch(u=C.scanJsxAttributeValue()){case 10:e.initializer=rt();break;default:e.initializer=vr(!0)}return De(e)}function br(t){for(;;){if(pe(24)){var r=ve(189,t.pos);r.expression=t,r.name=Ze(!0),t=De(r)}else if(52!==re()||C.hasPrecedingLineBreak())if(G()||!de(22)){if(!Dr())return t;t=xr(t,void 0)}else{var n=ve(190,t.pos);if(n.expression=t,23===re())n.argumentExpression=xe(72,!0,e.Diagnostics.An_element_access_expression_should_take_an_argument);else{var i=U(Gt);e.isStringOrNumericLiteralLike(i)&&(i.text=Se(i.text)),n.argumentExpression=i}_e(23),t=De(n)}else{ne();var a=ve(213,t.pos);a.expression=t,t=De(a)}}}function Dr(){return 14===re()||15===re()}function xr(e,t){var r=ve(193,e.pos);return r.tag=e,r.typeArguments=t,r.template=14===re()?rt():et(),De(r)}function Sr(){_e(20);var e=Ge(11,Er);return _e(21),e}function Tr(){if(de(28)){var e=Ge(20,Ut);if(_e(30))return e&&function(){switch(re()){case 20:case 14:case 15:case 24:case 21:case 23:case 57:case 26:case 56:case 33:case 35:case 34:case 36:case 54:case 55:case 51:case 49:case 50:case 19:case 1:return!0;case 27:case 18:default:return!1}}()?e:void 0}}function Cr(){switch(re()){case 8:case 9:case 10:case 14:return rt();case 100:case 98:case 96:case 102:case 87:return me();case 20:return t=he(195),_e(20),t.expression=U(Gt),_e(21),De(t);case 22:return Nr();case 18:return Fr();case 121:if(!ce(zr))break;return Pr();case 76:return hn(he(0),209);case 90:return Pr();case 95:return function(){var t=C.getStartPos();if(_e(95),de(24)){var r=ve(214,t);return r.keywordToken=95,r.name=ke(),De(r)}var n,i=Cr();for(;;){i=br(i),n=ue(Tr),Dr()&&(e.Debug.assert(!!n,"Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'"),i=xr(i,n),n=void 0);break}var a=ve(192,t);a.expression=i,a.typeArguments=n,(a.typeArguments||20===re())&&(a.arguments=Sr());return De(a)}();case 42:case 64:if(13===(u=C.reScanSlashToken()))return rt();break;case 15:return et()}var t;return Ce(e.Diagnostics.Expression_expected)}function kr(){return 25===re()?(e=ve(208),_e(25),e.expression=Xt(),De(e)):27===re()?ve(210):Xt();var e}function Er(){return z(k,kr)}function Nr(){var e=ve(187);return _e(22),C.hasPrecedingLineBreak()&&(e.multiLine=!0),e.elements=Ge(15,kr),_e(23),De(e)}function Ar(){var e=he(0);if(pe(25))return e.kind=277,e.expression=Xt(),De(e);if(e.decorators=fn(),e.modifiers=mn(),Fe(126))return dn(e,158);if(Fe(137))return dn(e,159);var t=pe(40),r=le();if(e.name=Ae(),e.questionToken=pe(56),e.exclamationToken=pe(52),t||20===re()||28===re())return ln(e,t);if(r&&57!==re()){e.kind=276;var n=pe(59);n&&(e.equalsToken=n,e.objectAssignmentInitializer=U(Xt))}else e.kind=275,_e(57),e.initializer=U(Xt);return De(e)}function Fr(){var e=ve(188);return _e(18),C.hasPrecedingLineBreak()&&(e.multiLine=!0),e.properties=Ge(12,Ar,!0),_e(19),De(e)}function Pr(){var t=G();t&&j(!1);var r=he(196);r.modifiers=mn(),_e(90),r.asteriskToken=pe(40);var n=r.asteriskToken?1:0,i=e.hasModifier(r,256)?2:0;return r.name=n&&i?K(20480,wr):n?function(e){return K(4096,e)}(wr):i?V(wr):wr(),pt(57,n|i,r),r.body=Ir(n|i),t&&j(!0),De(r)}function wr(){return le()?Ce():void 0}function Or(e,t){var r=ve(218);return _e(18,t)||e?(C.hasPrecedingLineBreak()&&(r.multiLine=!0),r.statements=Ve(1,Hr),_e(19)):r.statements=Ye(),De(r)}function Ir(e,t){var r=W();B(!!(1&e));var n=Y();J(!!(2&e));var i=G();i&&j(!1);var a=Or(!!(16&e),t);return i&&j(!0),B(r),J(n),a}function Mr(){var e=te();_e(89);var t,r,n=pe(122);if(_e(20),26!==re()&&(t=105===re()||111===re()||77===re()?on(!0):K(2048,Gt)),n?_e(147):de(147)){var i=ve(227,e);i.awaitModifier=n,i.initializer=t,i.expression=U(Xt),_e(21),r=i}else if(de(93)){var a=ve(226,e);a.initializer=t,a.expression=U(Gt),_e(21),r=a}else{var o=ve(225,e);o.initializer=t,_e(26),26!==re()&&21!==re()&&(o.condition=U(Gt)),_e(26),21!==re()&&(o.incrementor=U(Gt)),_e(21),r=o}return r.statement=Hr(),De(r)}function Lr(e){var t=ve(e);return _e(229===e?73:78),ge()||(t.label=Ce()),ye(),De(t)}function Rr(){return 74===re()?(e=ve(271),_e(74),e.expression=U(Gt),_e(57),e.statements=Ve(3,Hr),De(e)):function(){var e=ve(272);return _e(80),_e(57),e.statements=Ve(3,Hr),De(e)}();var e}function Br(){var e=ve(235);return _e(103),e.tryBlock=Or(!1),e.catchClause=75===re()?function(){var e=ve(274);_e(75),de(20)?(e.variableDeclaration=an(),_e(21)):e.variableDeclaration=void 0;return e.block=Or(!1),De(e)}():void 0,e.catchClause&&88!==re()||(_e(88),e.finallyBlock=Or(!1)),De(e)}function jr(){return ne(),e.tokenIsIdentifierOrKeyword(re())&&!C.hasPrecedingLineBreak()}function Jr(){return ne(),76===re()&&!C.hasPrecedingLineBreak()}function zr(){return ne(),90===re()&&!C.hasPrecedingLineBreak()}function Kr(){return ne(),(e.tokenIsIdentifierOrKeyword(re())||8===re()||9===re()||10===re())&&!C.hasPrecedingLineBreak()}function Ur(){for(;;)switch(re()){case 105:case 111:case 77:case 90:case 76:case 84:return!0;case 110:case 140:return ne(),!C.hasPrecedingLineBreak()&&le();case 130:case 131:return Qr();case 118:case 121:case 125:case 113:case 114:case 115:case 133:if(ne(),C.hasPrecedingLineBreak())return!1;continue;case 145:return ne(),18===re()||72===re()||85===re();case 92:return ne(),10===re()||40===re()||18===re()||e.tokenIsIdentifierOrKeyword(re());case 85:if(ne(),59===re()||40===re()||18===re()||80===re()||119===re())return!0;continue;case 116:ne();continue;default:return!1}}function Vr(){return ce(Ur)}function qr(){switch(re()){case 58:case 26:case 18:case 105:case 111:case 90:case 76:case 84:case 91:case 82:case 107:case 89:case 78:case 73:case 97:case 108:case 99:case 101:case 103:case 79:case 75:case 88:return!0;case 92:return Vr()||ce(St);case 77:case 85:return Vr();case 121:case 125:case 110:case 130:case 131:case 140:case 145:return!0;case 115:case 113:case 114:case 116:case 133:return Vr()||!ce(jr);default:return Ht()}}function Wr(){return ne(),le()||18===re()||22===re()}function Hr(){switch(re()){case 26:return e=ve(220),_e(26),De(e);case 18:return Or(!1);case 105:return cn(he(237));case 111:if(ce(Wr))return cn(he(237));break;case 90:return un(he(239));case 76:return vn(he(240));case 91:return function(){var e=ve(222);return _e(91),_e(20),e.expression=U(Gt),_e(21),e.thenStatement=Hr(),e.elseStatement=de(83)?Hr():void 0,De(e)}();case 82:return function(){var e=ve(223);return _e(82),e.statement=Hr(),_e(107),_e(20),e.expression=U(Gt),_e(21),de(26),De(e)}();case 107:return function(){var e=ve(224);return _e(107),_e(20),e.expression=U(Gt),_e(21),e.statement=Hr(),De(e)}();case 89:return Mr();case 78:return Lr(228);case 73:return Lr(229);case 97:return function(){var e=ve(230);return _e(97),ge()||(e.expression=U(Gt)),ye(),De(e)}();case 108:return function(){var e=ve(231);return _e(108),_e(20),e.expression=U(Gt),_e(21),e.statement=K(8388608,Hr),De(e)}();case 99:return function(){var e=ve(232);_e(99),_e(20),e.expression=U(Gt),_e(21);var t=ve(246);return _e(18),t.clauses=Ve(2,Rr),_e(19),e.caseBlock=De(t),De(e)}();case 101:return function(){var e=ve(234);return _e(101),e.expression=C.hasPrecedingLineBreak()?void 0:U(Gt),ye(),De(e)}();case 103:case 75:case 88:return Br();case 79:return function(){var e=ve(236);return _e(79),ye(),De(e)}();case 58:return Yr();case 121:case 110:case 140:case 130:case 131:case 125:case 77:case 84:case 85:case 92:case 113:case 114:case 115:case 118:case 116:case 133:case 145:if(Vr())return Yr()}var e;return function(){var e=he(0),t=U(Gt);return 72===t.kind&&de(57)?(e.kind=233,e.label=t,e.statement=Hr()):(e.kind=221,e.expression=t,ye()),De(e)}()}function Gr(e){return 125===e.kind}function Yr(){var t=he(0);if(t.decorators=fn(),t.modifiers=mn(),e.some(t.modifiers,Gr)){for(var r=0,n=t.modifiers;r=0),e.Debug.assert(t<=a),e.Debug.assert(a<=i.length),l(i,t)){var o,s,c,_=[];return C.scanRange(t+3,n-5,function(){var e,r,n=1,u=t-Math.max(i.lastIndexOf("\n",t),0)+4;function l(t){e||(e=u),_.push(t),u+=t.length}for(O();I(5););I(4)&&(n=0,u=0);e:for(;;){switch(re()){case 58:0===n||1===n?(p(_),b(v(u)),n=0,e=void 0,u++):l(C.getTokenText());break;case 4:_.push(C.getTokenText()),n=0,u=0;break;case 40:var f=C.getTokenText();1===n||2===n?(n=2,l(f)):(n=1,u+=f.length);break;case 5:var m=C.getTokenText();2===n?_.push(m):void 0!==e&&u+m.length>e&&_.push(m.slice(e-u-1)),u+=m.length;break;case 1:break e;default:n=2,l(C.getTokenText())}O()}return d(_),p(_),(r=ve(291,t)).tags=o&&be(o,s,c),r.comment=_.length?_.join(""):void 0,De(r,a)})}function d(e){for(;e.length&&("\n"===e[0]||"\r"===e[0]);)e.shift()}function p(e){for(;e.length&&""===e[e.length-1].trim();)e.pop()}function f(){for(;;){if(O(),1===re())return!0;if(5!==re()&&4!==re())return!1}}function g(){if(5!==re()&&4!==re()||!ce(f))for(;5===re()||4===re();)O()}function y(){if(5!==re()&&4!==re()||!ce(f))for(var e=C.hasPrecedingLineBreak();e&&40===re()||5===re()||4===re();)4===re()?e=!0:40===re()&&(e=!1),O()}function v(t){e.Debug.assert(58===re());var n=C.getTokenPos();O();var i,a=M(void 0);switch(y(),a.escapedText){case"augments":case"extends":i=function(e,t){var r=ve(295,e);return r.tagName=t,r.class=function(){var e=de(18),t=ve(211);t.expression=function(){for(var e=M();de(24);){var t=ve(189,e.pos);t.expression=e,t.name=M(),e=De(t)}return e}(),t.typeArguments=Sn();var r=De(t);return e&&_e(19),r}(),De(r)}(n,a);break;case"class":case"constructor":i=function(e,t){var r=ve(296,e);return r.tagName=t,De(r)}(n,a);break;case"this":i=function(e,t){var n=ve(301,e);return n.tagName=t,n.typeExpression=r(!0),g(),De(n)}(n,a);break;case"enum":i=function(e,t){var n=ve(298,e);return n.tagName=t,n.typeExpression=r(!0),g(),De(n)}(n,a);break;case"arg":case"argument":case"param":return T(n,a,2,t);case"return":case"returns":i=function(t,r){e.forEach(o,function(e){return 300===e.kind})&&$(r.pos,C.getTokenPos(),e.Diagnostics._0_tag_already_specified,r.escapedText);var n=ve(300,t);return n.tagName=r,n.typeExpression=D(),De(n)}(n,a);break;case"template":i=function(t,n){var i;18===re()&&(i=r());var a=[],o=te();do{g();var s=ve(150);s.name=M(e.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces),De(s),g(),a.push(s)}while(I(27));var c=ve(303,t);return c.tagName=n,c.constraint=i,c.typeParameters=be(a,o),De(c),c}(n,a);break;case"type":i=k(n,a);break;case"typedef":i=function(t,r,n){var i=D();y();var a,o=ve(304,t);if(o.tagName=r,o.fullName=E(),o.name=N(o.fullName),g(),o.comment=h(n),o.typeExpression=i,!i||S(i.type)){for(var s=void 0,c=void 0,u=void 0;s=ue(function(){return F(n)});)if(c||(c=ve(292,t)),302===s.kind){if(u)break;u=s}else c.jsDocPropertyTags=e.append(c.jsDocPropertyTags,s);c&&(i&&169===i.type.kind&&(c.isArrayType=!0),o.typeExpression=u&&u.typeExpression&&!S(u.typeExpression.type)?u.typeExpression:De(c),a=o.typeExpression.end)}return De(o,a||void 0!==o.comment?C.getStartPos():(o.fullName||o.typeExpression||o.tagName).end)}(n,a,t);break;case"callback":i=function(t,r,n){var i,a=ve(297,t);a.tagName=r,a.fullName=E(),a.name=N(a.fullName),g(),a.comment=h(n);var o=ve(293,t);o.parameters=[];for(;i=ue(function(){return P(4,n)});)o.parameters=e.append(o.parameters,i);var s=ue(function(){if(I(58)){var e=v(n);if(e&&300===e.kind)return e}});s&&(o.type=s);return a.typeExpression=De(o),De(a)}(n,a,t);break;default:i=function(e,t){var r=ve(294,e);return r.tagName=t,De(r)}(n,a)}return i.comment||(i.comment=h(t+i.end-i.pos)),i}function h(t){var r,n=[],i=0;function a(e){r||(r=t),n.push(e),t+=e.length}var o=re();e:for(;;){switch(o){case 4:i>=1&&(i=0,n.push(C.getTokenText())),t=0;break;case 58:C.setTextPos(C.getTextPos()-1);case 1:break e;case 5:if(2===i)a(C.getTokenText());else{var s=C.getTokenText();void 0!==r&&t+s.length>r&&n.push(s.slice(r-t-1)),t+=s.length}break;case 18:i=2,ce(function(){return 58===O()&&e.tokenIsIdentifierOrKeyword(O())&&"link"===C.getTokenText()})&&(a(C.getTokenText()),O(),a(C.getTokenText()),O()),a(C.getTokenText());break;case 40:if(0===i){i=1,t+=1;break}default:i=2,a(C.getTokenText())}o=O()}return d(n),p(n),0===n.length?void 0:n.join("")}function b(e){e&&(o?o.push(e):(o=[e],s=e.pos),c=e.end)}function D(){return y(),18===re()?r():void 0}function x(){if(14===re())return{name:Te(!0),isBracketed:!1};var e=de(22),t=function(){var e=M();de(22)&&_e(23);for(;de(24);){var t=M();de(22)&&_e(23),e=$e(e,t)}return e}();return e&&(g(),pe(59)&&Gt(),_e(23)),{name:t,isBracketed:e}}function S(t){switch(t.kind){case 136:return!0;case 169:return S(t.elementType);default:return e.isTypeReferenceNode(t)&&e.isIdentifier(t.typeName)&&"Object"===t.typeName.escapedText}}function T(t,r,n,i){var a=D(),o=!a;y();var s=x(),c=s.name,u=s.isBracketed;g(),o&&(a=D());var l=ve(1===n?305:299,t),_=h(i+C.getStartPos()-t),d=4!==n&&function(t,r,n,i){if(t&&S(t.type)){for(var a=ve(283,C.getTokenPos()),o=void 0,s=void 0,c=C.getStartPos(),u=void 0;o=ue(function(){return P(n,i,r)});)299!==o.kind&&305!==o.kind||(u=e.append(u,o));if(u)return(s=ve(292,c)).jsDocPropertyTags=u,169===t.type.kind&&(s.isArrayType=!0),a.type=De(s),De(a)}}(a,c,n,i);return d&&(a=d,o=!0),l.tagName=r,l.typeExpression=a,l.name=c,l.isNameFirst=o,l.isBracketed=u,l.comment=_,De(l)}function k(t,n){e.forEach(o,function(e){return 302===e.kind})&&$(n.pos,C.getTokenPos(),e.Diagnostics._0_tag_already_specified,n.escapedText);var i=ve(302,t);return i.tagName=n,i.typeExpression=r(!0),De(i)}function E(t){var r=C.getTokenPos();if(e.tokenIsIdentifierOrKeyword(re())){var n=M();if(de(24)){var i=ve(244,r);return t&&(i.flags|=4),i.name=n,i.body=E(!0),De(i)}return t&&(n.isInJSDocNamespace=!0),n}}function N(t){if(t)for(var r=t;;){if(e.isIdentifier(r)||!r.body)return e.isIdentifier(r)?r:r.name;r=r.body}}function A(t,r){for(;!e.isIdentifier(t)||!e.isIdentifier(r);){if(e.isIdentifier(t)||e.isIdentifier(r)||t.right.escapedText!==r.right.escapedText)return!1;t=t.left,r=r.left}return t.escapedText===r.escapedText}function F(e){return P(1,e)}function P(t,r,n){for(var i=!0,a=!1;;)switch(O()){case 58:if(i){var o=w(t,r);return!(o&&(299===o.kind||305===o.kind)&&4!==t&&n&&(e.isIdentifier(o.name)||!A(n,o.name.left)))&&o}a=!1;break;case 4:i=!0,a=!1;break;case 40:a&&(i=!1),a=!0;break;case 72:i=!1;break;case 1:return!1}}function w(t,r){e.Debug.assert(58===re());var n=C.getStartPos();O();var i,a=M();switch(g(),a.escapedText){case"type":return 1===t&&k(n,a);case"prop":case"property":i=1;break;case"arg":case"argument":case"param":i=6;break;default:return!1}return!!(t&i)&&T(n,a,t,r)}function O(){return u=C.scanJSDocToken()}function I(e){return re()===e&&(O(),!0)}function M(t){if(!e.tokenIsIdentifierOrKeyword(re()))return xe(72,!t,t||e.Diagnostics.Identifier_expected);var r=C.getTokenPos(),n=C.getTextPos(),i=ve(72,r);return i.escapedText=e.escapeLeadingUnderscores(C.getTokenText()),De(i,n),O(),i}}t.parseJSDocTypeExpressionForTests=function(e,t,n){F(e,6,void 0,1),o=M("file.js",6,1,!1),C.setText(e,t,n),u=C.scan();var i=r(),a=s;return P(),i?{jsDocTypeExpression:i,diagnostics:a}:void 0},t.parseJSDocTypeExpression=r,t.parseIsolatedJSDocComment=function(e,t,r){F(e,6,void 0,1),o={languageVariant:0,text:e};var n=a(t,r),i=s;return P(),n?{jsDoc:n,diagnostics:i}:void 0},t.parseJSDocComment=function(e,t,r){var n,i=u,c=s.length,l=E,_=a(t,r);return _&&(_.parent=e),65536&b&&(o.jsDocDiagnostics||(o.jsDocDiagnostics=[]),(n=o.jsDocDiagnostics).push.apply(n,s)),u=i,s.length=c,E=l,_},function(e){e[e.BeginningOfLine=0]="BeginningOfLine",e[e.SawAsterisk=1]="SawAsterisk",e[e.SavingComments=2]="SavingComments"}(n||(n={})),function(e){e[e.Property=1]="Property",e[e.Parameter=2]="Parameter",e[e.CallbackParameter=4]="CallbackParameter"}(i||(i={})),t.parseJSDocCommentWorker=a}(T=t.JSDocParser||(t.JSDocParser={}))}(o||(o={})),function(t){function r(t,r,i,o,s,c){return void(r?l(t):u(t));function u(t){var r="";if(c&&n(t)&&(r=o.substring(t.pos,t.end)),t._children&&(t._children=void 0),t.pos+=i,t.end+=i,c&&n(t)&&e.Debug.assert(r===s.substring(t.pos,t.end)),_(t,u,l),e.hasJSDocNodes(t))for(var d=0,p=t.jsDoc;d=r,"Adjusting an element that was entirely before the change range"),e.Debug.assert(t.pos<=n,"Adjusting an element that was entirely after the change range"),e.Debug.assert(t.pos<=t.end),t.pos=Math.min(t.pos,i),t.end>=n?t.end+=a:t.end=Math.min(t.end,i),e.Debug.assert(t.pos<=t.end),t.parent&&(e.Debug.assert(t.pos>=t.parent.pos),e.Debug.assert(t.end<=t.parent.end))}function a(t,r){if(r){var n=t.pos,i=function(t){e.Debug.assert(t.pos>=n),n=t.end};if(e.hasJSDocNodes(t))for(var a=0,o=t.jsDoc;ar),!0;if(a.pos>=i.pos&&(i=a),ri.pos&&(i=a)}return i}function c(t,r,n,i){var a=t.text;if(n&&(e.Debug.assert(a.length-n.span.length+n.newLength===r.length),i||e.Debug.shouldAssert(3))){var o=a.substr(0,n.span.start),s=r.substr(0,n.span.start);e.Debug.assert(o===s);var c=a.substring(e.textSpanEnd(n.span),a.length),u=r.substring(e.textSpanEnd(e.textChangeRangeNewSpan(n)),r.length);e.Debug.assert(c===u)}}var u;t.updateSourceFile=function(t,n,u,l){if(c(t,n,u,l=l||e.Debug.shouldAssert(2)),e.textChangeRangeIsUnchanged(u))return t;if(0===t.statements.length)return o.parseSourceFile(t.fileName,n,t.languageVersion,void 0,!0,t.scriptKind);var d=t;e.Debug.assert(!d.hasBeenIncrementallyParsed),d.hasBeenIncrementallyParsed=!0;var p=t.text,f=function(t){var r=t.statements,n=0;e.Debug.assert(n=t.pos&&e=t.pos&&e0&&i<=1;i++){var a=s(t,n);e.Debug.assert(a.pos<=n);var o=a.pos;n=Math.max(0,o-1)}var c=e.createTextSpanFromBounds(n,e.textSpanEnd(r.span)),u=r.newLength+(r.span.start-n);return e.createTextChangeRange(c,u)}(t,u);c(t,n,m,l),e.Debug.assert(m.span.start<=u.span.start),e.Debug.assert(e.textSpanEnd(m.span)===e.textSpanEnd(u.span)),e.Debug.assert(e.textSpanEnd(e.textChangeRangeNewSpan(m))===e.textSpanEnd(e.textChangeRangeNewSpan(u)));var g=e.textChangeRangeNewSpan(m).length-m.span.length;return function(t,n,o,s,c,u,l,d){return void p(t);function p(t){if(e.Debug.assert(t.pos<=t.end),t.pos>o)r(t,!1,c,u,l,d);else{var m=t.end;if(m>=n){if(t.intersectsChange=!0,t._children=void 0,i(t,n,o,s,c),_(t,p,f),e.hasJSDocNodes(t))for(var g=0,y=t.jsDoc;go)r(t,!0,c,u,l,d);else{var a=t.end;if(a>=n){t.intersectsChange=!0,t._children=void 0,i(t,n,o,s,c);for(var _=0,f=t;_/im,v=/^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;function h(t,r,n){var i=2===r.kind&&y.exec(n);if(i){var a=i[1].toLowerCase(),o=e.commentPragmas[a];if(!(o&&1&o.kind))return;if(o.args){for(var s={},c=0,u=o.args;c=r.length)break;var o=a;if(34===r.charCodeAt(o)){for(a++;a32;)a++;n.push(r.substring(o,a))}}d(n)}else u.push(e.createCompilerDiagnostic(e.Diagnostics.File_0_not_found,t))}}function p(e,t){return m(o,e,t)}function m(e,t,r){void 0===r&&(r=!1),t=t.toLowerCase();var n=e(),i=n.optionNameMap,a=n.shortOptionNames;if(r){var o=a.get(t);void 0!==o&&(t=o)}return i.get(t)}function g(t){for(var r=[],n=1;n=0)return c.push(e.createCompilerDiagnostic(e.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0,s.concat([u]).join(" -> "))),{raw:t||D(n,c)};var l=t?function(t,r,n,i,a){e.hasProperty(t,"excludes")&&a.push(e.createCompilerDiagnostic(e.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));var o,s=j(t.compilerOptions,n,a,i),c=z(t.typeAcquisition||t.typingOptions,n,a,i);if(t.compileOnSave=function(t,r,n){if(!e.hasProperty(t,e.compileOnSaveCommandLineOption.name))return!1;var i=U(e.compileOnSaveCommandLineOption,t.compileOnSave,r,n);return"boolean"==typeof i&&i}(t,n,a),t.extends)if(e.isString(t.extends)){var u=i?F(i,n):n;o=R(t.extends,r,u,a,e.createCompilerDiagnostic)}else a.push(e.createCompilerDiagnostic(e.Diagnostics.Compiler_option_0_requires_a_value_of_type_1,"extends","string"));return{raw:t,options:s,typeAcquisition:c,extendedConfigPath:o}}(t,i,a,o,c):function(t,n,i,a,o){var s,c,u,l=B(a),_={onSetValidOptionKeyValueInParent:function(t,r,n){e.Debug.assert("compilerOptions"===t||"typeAcquisition"===t||"typingOptions"===t);var o="compilerOptions"===t?l:"typeAcquisition"===t?s||(s=J(a)):c||(c=J(a));o[r.name]=function t(r,n,i){if(A(i))return;if("list"===r.type){var a=r;return a.element.isFilePath||!e.isString(a.element.type)?e.filter(e.map(i,function(e){return t(a.element,n,e)}),function(e){return!!e}):i}if(!e.isString(r.type))return r.type.get(e.isString(i)?i.toLowerCase():i);return V(r,n,i)}(r,i,n)},onSetValidOptionKeyValueInRoot:function(r,s,c,l){switch(r){case"extends":var _=a?F(a,i):i;return void(u=R(c,n,_,o,function(r,n){return e.createDiagnosticForNodeInSourceFile(t,l,r,n)}))}},onSetUnknownOptionKeyValueInRoot:function(r,n,i,a){"excludes"===r&&o.push(e.createDiagnosticForNodeInSourceFile(t,n,e.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude))}},d=x(t,o,!0,(void 0===r&&(r={name:void 0,type:"object",elementOptions:b([{name:"compilerOptions",type:"object",elementOptions:b(e.optionDeclarations),extraKeyDiagnosticMessage:e.Diagnostics.Unknown_compiler_option_0},{name:"typingOptions",type:"object",elementOptions:b(e.typeAcquisitionDeclarations),extraKeyDiagnosticMessage:e.Diagnostics.Unknown_type_acquisition_option_0},{name:"typeAcquisition",type:"object",elementOptions:b(e.typeAcquisitionDeclarations),extraKeyDiagnosticMessage:e.Diagnostics.Unknown_type_acquisition_option_0},{name:"extends",type:"string"},{name:"references",type:"list",element:{name:"references",type:"object"}},{name:"files",type:"list",element:{name:"files",type:"string"}},{name:"include",type:"list",element:{name:"include",type:"string"}},{name:"exclude",type:"list",element:{name:"exclude",type:"string"}},e.compileOnSaveCommandLineOption])}),r),_);s||(s=c?void 0!==c.enableAutoDiscovery?{enable:c.enableAutoDiscovery,include:c.include,exclude:c.exclude}:c:J(a));return{raw:d,options:l,typeAcquisition:s,extendedConfigPath:u}}(n,i,a,o,c);if(l.extendedConfigPath){s=s.concat([u]);var _=function(t,r,n,i,a,o){var s,c=v(r,function(e){return n.readFile(e)});t&&(t.extendedSourceFiles=[c.fileName]);if(c.parseDiagnostics.length)return void o.push.apply(o,c.parseDiagnostics);var u=e.getDirectoryPath(r),l=L(void 0,c,n,u,e.getBaseFileName(r),a,o);t&&c.extendedSourceFiles&&(s=t.extendedSourceFiles).push.apply(s,c.extendedSourceFiles);if(M(l)){var _=e.convertToRelativePath(u,i,e.identity),d=function(t){return e.isRootedDiskPath(t)?t:e.combinePaths(_,t)},p=function(t){f[t]&&(f[t]=e.map(f[t],d))},f=l.raw;p("include"),p("exclude"),p("files")}return l}(n,l.extendedConfigPath,i,a,s,c);if(_&&M(_)){var d=_.raw,p=l.raw,f=function(e){var t=p[e]||d[e];t&&(p[e]=t)};f("include"),f("exclude"),f("files"),void 0===p.compileOnSave&&(p.compileOnSave=d.compileOnSave),l.options=e.assign({},_.options,l.options)}}return l}function R(t,r,n,i,a){if(t=e.normalizeSlashes(t),e.isRootedDiskPath(t)||e.startsWith(t,"./")||e.startsWith(t,"../")){var o=e.getNormalizedAbsolutePath(t,n);return r.fileExists(o)||e.endsWith(o,".json")||(o+=".json",r.fileExists(o))?o:void i.push(a(e.Diagnostics.File_0_does_not_exist,t))}var s=e.nodeModuleNameResolver(t,e.combinePaths(n,"tsconfig.json"),{moduleResolution:e.ModuleResolutionKind.NodeJs},r,void 0,void 0,!0);if(s.resolvedModule)return s.resolvedModule.resolvedFileName;i.push(a(e.Diagnostics.File_0_does_not_exist,t))}function B(t){return t&&"jsconfig.json"===e.getBaseFileName(t)?{allowJs:!0,maxNodeModuleJsDepth:2,allowSyntheticDefaultImports:!0,skipLibCheck:!0,noEmit:!0}:{}}function j(t,r,n,i){var a=B(i);return K(e.optionDeclarations,t,r,a,e.Diagnostics.Unknown_compiler_option_0,n),i&&(a.configFilePath=e.normalizeSlashes(i)),a}function J(t){return{enable:!!t&&"jsconfig.json"===e.getBaseFileName(t),include:[],exclude:[]}}function z(t,r,n,i){var o=J(i),s=a(t);return K(e.typeAcquisitionDeclarations,s,r,o,e.Diagnostics.Unknown_type_acquisition_option_0,n),o}function K(t,r,n,i,a,o){if(r){var s=b(t);for(var c in r){var u=s.get(c);u?i[u.name]=U(u,r[c],n,o):o.push(e.createCompilerDiagnostic(a,c))}}}function U(t,r,n,i){if(T(t,r)){var a=t.type;return"list"===a&&e.isArray(r)?function(t,r,n,i){return e.filter(e.map(r,function(e){return U(t.element,e,n,i)}),function(e){return!!e})}(t,r,n,i):e.isString(a)?V(t,n,r):q(t,r,i)}i.push(e.createCompilerDiagnostic(e.Diagnostics.Compiler_option_0_requires_a_value_of_type_1,t.name,S(t)))}function V(t,r,n){return t.isFilePath&&""===(n=e.normalizePath(e.combinePaths(r,n)))&&(n="."),n}function q(e,t,r){if(!A(t)){var n=t.toLowerCase(),i=e.type.get(n);if(void 0!==i)return i;r.push(c(e))}}function W(e){return"function"==typeof e.trim?e.trim():e.replace(/^[\s]+|[\s]+$/g,"")}e.libs=n.map(function(e){return e[0]}),e.libMap=e.createMapFromEntries(n),e.commonOptionsWithBuild=[{name:"help",shortName:"h",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Print_this_message},{name:"help",shortName:"?",type:"boolean"},{name:"watch",shortName:"w",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Watch_input_files},{name:"preserveWatchOutput",type:"boolean",showInSimplifiedHelpView:!1,category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen},{name:"listFiles",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Print_names_of_files_part_of_the_compilation},{name:"listEmittedFiles",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Print_names_of_generated_files_part_of_the_compilation},{name:"pretty",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental},{name:"traceResolution",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Enable_tracing_of_the_name_resolution_process},{name:"diagnostics",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Show_diagnostic_information},{name:"extendedDiagnostics",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Show_verbose_diagnostic_information}],e.optionDeclarations=e.commonOptionsWithBuild.concat([{name:"all",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Show_all_compiler_options},{name:"version",shortName:"v",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Print_the_compiler_s_version},{name:"init",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file},{name:"project",shortName:"p",type:"string",isFilePath:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Command_line_Options,paramType:e.Diagnostics.FILE_OR_DIRECTORY,description:e.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json},{name:"build",type:"boolean",shortName:"b",showInSimplifiedHelpView:!0,category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date},{name:"showConfig",type:"boolean",category:e.Diagnostics.Command_line_Options,isCommandLineOnly:!0,description:e.Diagnostics.Print_the_final_configuration_instead_of_building},{name:"target",shortName:"t",type:e.createMapFromTemplate({es3:0,es5:1,es6:2,es2015:2,es2016:3,es2017:4,es2018:5,esnext:6}),affectsSourceFile:!0,affectsModuleResolution:!0,paramType:e.Diagnostics.VERSION,showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT},{name:"module",shortName:"m",type:e.createMapFromTemplate({none:e.ModuleKind.None,commonjs:e.ModuleKind.CommonJS,amd:e.ModuleKind.AMD,system:e.ModuleKind.System,umd:e.ModuleKind.UMD,es6:e.ModuleKind.ES2015,es2015:e.ModuleKind.ES2015,esnext:e.ModuleKind.ESNext}),affectsModuleResolution:!0,paramType:e.Diagnostics.KIND,showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext},{name:"lib",type:"list",element:{name:"lib",type:e.libMap},affectsModuleResolution:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Specify_library_files_to_be_included_in_the_compilation},{name:"allowJs",type:"boolean",affectsModuleResolution:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Allow_javascript_files_to_be_compiled},{name:"checkJs",type:"boolean",category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Report_errors_in_js_files},{name:"jsx",type:e.createMapFromTemplate({preserve:1,"react-native":3,react:2}),affectsSourceFile:!0,paramType:e.Diagnostics.KIND,showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react},{name:"declaration",shortName:"d",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Generates_corresponding_d_ts_file},{name:"declarationMap",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file},{name:"emitDeclarationOnly",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Only_emit_d_ts_declaration_files},{name:"sourceMap",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Generates_corresponding_map_file},{name:"outFile",type:"string",isFilePath:!0,paramType:e.Diagnostics.FILE,showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Concatenate_and_emit_output_to_single_file},{name:"outDir",type:"string",isFilePath:!0,paramType:e.Diagnostics.DIRECTORY,showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Redirect_output_structure_to_the_directory},{name:"rootDir",type:"string",isFilePath:!0,paramType:e.Diagnostics.LOCATION,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir},{name:"composite",type:"boolean",isTSConfigOnly:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Enable_project_compilation},{name:"removeComments",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Do_not_emit_comments_to_output},{name:"noEmit",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Do_not_emit_outputs},{name:"importHelpers",type:"boolean",category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Import_emit_helpers_from_tslib},{name:"downlevelIteration",type:"boolean",category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3},{name:"isolatedModules",type:"boolean",category:e.Diagnostics.Basic_Options,description:e.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule},{name:"strict",type:"boolean",showInSimplifiedHelpView:!0,category:e.Diagnostics.Strict_Type_Checking_Options,description:e.Diagnostics.Enable_all_strict_type_checking_options},{name:"noImplicitAny",type:"boolean",affectsSemanticDiagnostics:!0,strictFlag:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Strict_Type_Checking_Options,description:e.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type},{name:"strictNullChecks",type:"boolean",affectsSemanticDiagnostics:!0,strictFlag:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Strict_Type_Checking_Options,description:e.Diagnostics.Enable_strict_null_checks},{name:"strictFunctionTypes",type:"boolean",affectsSemanticDiagnostics:!0,strictFlag:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Strict_Type_Checking_Options,description:e.Diagnostics.Enable_strict_checking_of_function_types},{name:"strictBindCallApply",type:"boolean",strictFlag:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Strict_Type_Checking_Options,description:e.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions},{name:"strictPropertyInitialization",type:"boolean",affectsSemanticDiagnostics:!0,strictFlag:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Strict_Type_Checking_Options,description:e.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes},{name:"noImplicitThis",type:"boolean",affectsSemanticDiagnostics:!0,strictFlag:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Strict_Type_Checking_Options,description:e.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type},{name:"alwaysStrict",type:"boolean",affectsSourceFile:!0,strictFlag:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Strict_Type_Checking_Options,description:e.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file},{name:"noUnusedLocals",type:"boolean",affectsSemanticDiagnostics:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Additional_Checks,description:e.Diagnostics.Report_errors_on_unused_locals},{name:"noUnusedParameters",type:"boolean",affectsSemanticDiagnostics:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Additional_Checks,description:e.Diagnostics.Report_errors_on_unused_parameters},{name:"noImplicitReturns",type:"boolean",affectsSemanticDiagnostics:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Additional_Checks,description:e.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value},{name:"noFallthroughCasesInSwitch",type:"boolean",affectsBindDiagnostics:!0,affectsSemanticDiagnostics:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Additional_Checks,description:e.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement},{name:"moduleResolution",type:e.createMapFromTemplate({node:e.ModuleResolutionKind.NodeJs,classic:e.ModuleResolutionKind.Classic}),affectsModuleResolution:!0,paramType:e.Diagnostics.STRATEGY,category:e.Diagnostics.Module_Resolution_Options,description:e.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6},{name:"baseUrl",type:"string",affectsModuleResolution:!0,isFilePath:!0,category:e.Diagnostics.Module_Resolution_Options,description:e.Diagnostics.Base_directory_to_resolve_non_absolute_module_names},{name:"paths",type:"object",affectsModuleResolution:!0,isTSConfigOnly:!0,category:e.Diagnostics.Module_Resolution_Options,description:e.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl},{name:"rootDirs",type:"list",isTSConfigOnly:!0,element:{name:"rootDirs",type:"string",isFilePath:!0},affectsModuleResolution:!0,category:e.Diagnostics.Module_Resolution_Options,description:e.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime},{name:"typeRoots",type:"list",element:{name:"typeRoots",type:"string",isFilePath:!0},affectsModuleResolution:!0,category:e.Diagnostics.Module_Resolution_Options,description:e.Diagnostics.List_of_folders_to_include_type_definitions_from},{name:"types",type:"list",element:{name:"types",type:"string"},affectsModuleResolution:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Module_Resolution_Options,description:e.Diagnostics.Type_declaration_files_to_be_included_in_compilation},{name:"allowSyntheticDefaultImports",type:"boolean",affectsSemanticDiagnostics:!0,category:e.Diagnostics.Module_Resolution_Options,description:e.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking},{name:"esModuleInterop",type:"boolean",affectsSemanticDiagnostics:!0,showInSimplifiedHelpView:!0,category:e.Diagnostics.Module_Resolution_Options,description:e.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports},{name:"preserveSymlinks",type:"boolean",category:e.Diagnostics.Module_Resolution_Options,description:e.Diagnostics.Do_not_resolve_the_real_path_of_symlinks},{name:"sourceRoot",type:"string",paramType:e.Diagnostics.LOCATION,category:e.Diagnostics.Source_Map_Options,description:e.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations},{name:"mapRoot",type:"string",paramType:e.Diagnostics.LOCATION,category:e.Diagnostics.Source_Map_Options,description:e.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations},{name:"inlineSourceMap",type:"boolean",category:e.Diagnostics.Source_Map_Options,description:e.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file},{name:"inlineSources",type:"boolean",category:e.Diagnostics.Source_Map_Options,description:e.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set},{name:"experimentalDecorators",type:"boolean",category:e.Diagnostics.Experimental_Options,description:e.Diagnostics.Enables_experimental_support_for_ES7_decorators},{name:"emitDecoratorMetadata",type:"boolean",category:e.Diagnostics.Experimental_Options,description:e.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators},{name:"jsxFactory",type:"string",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h},{name:"resolveJsonModule",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Include_modules_imported_with_json_extension},{name:"out",type:"string",isFilePath:!1,category:e.Diagnostics.Advanced_Options,paramType:e.Diagnostics.FILE,description:e.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file},{name:"reactNamespace",type:"string",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit},{name:"skipDefaultLibCheck",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files},{name:"charset",type:"string",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.The_character_set_of_the_input_files},{name:"emitBOM",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files},{name:"locale",type:"string",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us},{name:"newLine",type:e.createMapFromTemplate({crlf:0,lf:1}),paramType:e.Diagnostics.NEWLINE,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix},{name:"noErrorTruncation",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Do_not_truncate_error_messages},{name:"noLib",type:"boolean",affectsModuleResolution:!0,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts},{name:"noResolve",type:"boolean",affectsModuleResolution:!0,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files},{name:"stripInternal",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation},{name:"disableSizeLimit",type:"boolean",affectsSourceFile:!0,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Disable_size_limitations_on_JavaScript_projects},{name:"noImplicitUseStrict",type:"boolean",affectsSemanticDiagnostics:!0,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Do_not_emit_use_strict_directives_in_module_output},{name:"noEmitHelpers",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output},{name:"noEmitOnError",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported},{name:"preserveConstEnums",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code},{name:"declarationDir",type:"string",isFilePath:!0,paramType:e.Diagnostics.DIRECTORY,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Output_directory_for_generated_declaration_files},{name:"skipLibCheck",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Skip_type_checking_of_declaration_files},{name:"allowUnusedLabels",type:"boolean",affectsBindDiagnostics:!0,affectsSemanticDiagnostics:!0,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Do_not_report_errors_on_unused_labels},{name:"allowUnreachableCode",type:"boolean",affectsBindDiagnostics:!0,affectsSemanticDiagnostics:!0,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Do_not_report_errors_on_unreachable_code},{name:"suppressExcessPropertyErrors",type:"boolean",affectsSemanticDiagnostics:!0,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Suppress_excess_property_checks_for_object_literals},{name:"suppressImplicitAnyIndexErrors",type:"boolean",affectsSemanticDiagnostics:!0,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures},{name:"forceConsistentCasingInFileNames",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file},{name:"maxNodeModuleJsDepth",type:"number",affectsModuleResolution:!0,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files},{name:"noStrictGenericChecks",type:"boolean",affectsSemanticDiagnostics:!0,category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types},{name:"keyofStringsOnly",type:"boolean",category:e.Diagnostics.Advanced_Options,description:e.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols},{name:"plugins",type:"list",isTSConfigOnly:!0,element:{name:"plugin",type:"object"},description:e.Diagnostics.List_of_language_service_plugins}]),e.semanticDiagnosticsOptionDeclarations=e.optionDeclarations.filter(function(e){return!!e.affectsSemanticDiagnostics}),e.moduleResolutionOptionDeclarations=e.optionDeclarations.filter(function(e){return!!e.affectsModuleResolution}),e.sourceFileAffectingCompilerOptions=e.optionDeclarations.filter(function(e){return!!e.affectsSourceFile||!!e.affectsModuleResolution||!!e.affectsBindDiagnostics}),e.buildOpts=e.commonOptionsWithBuild.concat([{name:"verbose",shortName:"v",category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Enable_verbose_logging,type:"boolean"},{name:"dry",shortName:"d",category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,type:"boolean"},{name:"force",shortName:"f",category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,type:"boolean"},{name:"clean",category:e.Diagnostics.Command_line_Options,description:e.Diagnostics.Delete_the_outputs_of_all_projects,type:"boolean"}]),e.typeAcquisitionDeclarations=[{name:"enableAutoDiscovery",type:"boolean"},{name:"enable",type:"boolean"},{name:"include",type:"list",element:{name:"include",type:"string"}},{name:"exclude",type:"list",element:{name:"exclude",type:"string"}}],e.defaultInitCompilerOptions={module:e.ModuleKind.CommonJS,target:1,strict:!0,esModuleInterop:!0},e.convertEnableAutoDiscoveryToEnable=a,e.createOptionNameMap=s,e.createCompilerDiagnosticForInvalidCustomType=c,e.parseCustomTypeOption=l,e.parseListTypeOption=_,e.parseCommandLine=function(t,r){return d(o,[e.Diagnostics.Unknown_compiler_option_0,e.Diagnostics.Compiler_option_0_expects_an_argument],t,r)},e.getOptionFromName=p,e.parseBuildCommand=function(t){var r,n=d(function(){return r||(r=s(e.buildOpts))},[e.Diagnostics.Unknown_build_option_0,e.Diagnostics.Build_option_0_requires_a_value_of_type_1],t),i=n.options,a=n.fileNames,o=n.errors,c=i;return 0===a.length&&a.push("."),c.clean&&c.force&&o.push(e.createCompilerDiagnostic(e.Diagnostics.Options_0_and_1_cannot_be_combined,"clean","force")),c.clean&&c.verbose&&o.push(e.createCompilerDiagnostic(e.Diagnostics.Options_0_and_1_cannot_be_combined,"clean","verbose")),c.clean&&c.watch&&o.push(e.createCompilerDiagnostic(e.Diagnostics.Options_0_and_1_cannot_be_combined,"clean","watch")),c.watch&&c.dry&&o.push(e.createCompilerDiagnostic(e.Diagnostics.Options_0_and_1_cannot_be_combined,"watch","dry")),{buildOptions:c,projects:a,errors:o}},e.printVersion=function(){e.sys.write(g(e.Diagnostics.Version_0,e.version)+e.sys.newLine)},e.printHelp=function(t,r){void 0===r&&(r="");var n=[],i=g(e.Diagnostics.Syntax_Colon_0,"").length,a=g(e.Diagnostics.Examples_Colon_0,"").length,o=Math.max(i,a),s=F(o-i);s+="tsc "+r+"["+g(e.Diagnostics.options)+"] ["+g(e.Diagnostics.file)+"...]",n.push(g(e.Diagnostics.Syntax_Colon_0,s)),n.push(e.sys.newLine+e.sys.newLine);var c=F(o);n.push(g(e.Diagnostics.Examples_Colon_0,F(o-a)+"tsc hello.ts")+e.sys.newLine),n.push(c+"tsc --outFile file.js file.ts"+e.sys.newLine),n.push(c+"tsc @args.txt"+e.sys.newLine),n.push(c+"tsc --build tsconfig.json"+e.sys.newLine),n.push(e.sys.newLine),n.push(g(e.Diagnostics.Options_Colon)+e.sys.newLine),o=0;for(var u=[],l=[],_=e.createMap(),d=0,p=t;d";u.push(h),l.push(g(e.Diagnostics.Insert_command_line_options_and_files_from_a_file)),o=Math.max(h.length,o);for(var b=0;b0)for(var D=function(t){if(e.fileExtensionIs(t,".json")){if(!o){var n=d.filter(function(t){return e.endsWith(t,".json")}),a=e.map(e.getRegularExpressionsForWildcards(n,r,"files"),function(e){return"^"+e+"$"});o=a?a.map(function(t){return e.getRegexFromPattern(t,i.useCaseSensitiveFileNames)}):e.emptyArray}if(-1!==e.findIndex(o,function(e){return e.test(t)})){var _=s(t);c.has(_)||l.has(_)||l.set(_,t)}return"continue"}if(function(t,r,n,i,a){for(var o=e.getExtensionPriority(t,i),s=e.adjustExtensionPriority(o,i),c=0;cr.length){var f=d.substring(r.length+1);n=(e.forEach(e.supportedJSExtensions,function(t){return e.tryRemoveExtension(f,t)})||f)+".d.ts"}else n="index.d.ts"}}e.endsWith(n,".d.ts")||(n=I(n));var y=g(l,a),v="string"==typeof l.name&&"string"==typeof l.version?{name:l.name,subModuleName:n,version:l.version}:void 0;return s&&(v?t(o,e.Diagnostics.Found_package_json_at_0_Package_ID_is_1,u,e.packageIdToString(v)):t(o,e.Diagnostics.Found_package_json_at_0,u)),{packageJsonContent:l,packageId:v,versionPaths:y}}c&&s&&t(o,e.Diagnostics.File_0_does_not_exist,u),a.failedLookupLocations.push(u)}function z(r,n,i,c,u,l){var _;if(u)switch(r){case s.JavaScript:case s.Json:_=m(u,n,c);break;case s.TypeScript:_=p(u,n,c)||m(u,n,c);break;case s.DtsOnly:_=p(u,n,c);break;case s.TSConfig:_=function(e,t,r){return d(e,"tsconfig",t,r)}(u,n,c);break;default:return e.Debug.assertNever(r)}var f=function(r,n,i,o){var c=B(n,i,o);if(c){var u=function(t,r){var n=e.tryGetExtensionFromPath(r);return void 0!==n&&function(e,t){switch(e){case s.JavaScript:return".js"===t||".jsx"===t;case s.TSConfig:case s.Json:return".json"===t;case s.TypeScript:return".ts"===t||".tsx"===t||".d.ts"===t;case s.DtsOnly:return".d.ts"===t}}(t,n)?{path:r,ext:n}:void 0}(r,c);if(u)return a(u);o.traceEnabled&&t(o.host,e.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it,c)}return P(r===s.DtsOnly?s.TypeScript:r,n,i,o,!1)},g=_?!e.directoryProbablyExists(e.getDirectoryPath(_),c.host):void 0,y=i||!e.directoryProbablyExists(n,c.host),v=e.combinePaths(n,r===s.TSConfig?"tsconfig":"index");if(l&&(!_||e.containsPath(n,_))){var h=e.getRelativePathFromDirectory(n,_||v,!1);c.traceEnabled&&t(c.host,e.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2,l.version,e.version,h);var b=H(r,h,n,l.paths,f,g||y,c);if(b)return o(b.value)}var D=_&&o(f(r,_,g,c));return D||L(r,v,y,c)}function K(t){var r=t.indexOf(e.directorySeparator);return"@"===t[0]&&(r=t.indexOf(e.directorySeparator,r+1)),-1===r?{packageName:t,rest:""}:{packageName:t.slice(0,r),rest:t.slice(r+1)}}function U(e,t,r,n,i,a){return V(e,t,r,n,!1,i,a)}function V(t,r,n,i,a,o,s){var c=o&&o.getOrCreateCacheForModuleName(r,s);return e.forEachAncestorDirectory(e.normalizeSlashes(n),function(n){if("node_modules"!==e.getBaseFileName(n)){var o=Q(c,r,n,i);return o||Z(q(t,r,n,i,a))}})}function q(r,n,i,a,o){var c=e.combinePaths(i,"node_modules"),u=e.directoryProbablyExists(c,a.host);!u&&a.traceEnabled&&t(a.host,e.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it,c);var l=o?void 0:W(r,n,c,u,a);if(l)return l;if(r===s.TypeScript||r===s.DtsOnly){var _=e.combinePaths(c,"@types"),d=u;return u&&!e.directoryProbablyExists(_,a.host)&&(a.traceEnabled&&t(a.host,e.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it,_),d=!1),W(s.DtsOnly,function(r,n){var i=Y(r);n.traceEnabled&&i!==r&&t(n.host,e.Diagnostics.Scoped_package_detected_looking_in_0,i);return i}(n,a),_,d,a)}}function W(r,i,o,s,c){var u,l,_,d=e.normalizePath(e.combinePaths(o,i)),p=J(d,"",!s,c);if(p){u=p.packageJsonContent,l=p.packageId,_=p.versionPaths;var f=L(r,d,!s,c);if(f)return a(f);var m=z(r,d,!s,c,u,_);return n(l,m)}var g=function(e,t,r,i){var a=L(e,t,r,i)||z(e,t,r,i,u,_);return n(l,a)},y=K(i),v=y.packageName,h=y.rest;if(""!==h){var b=e.combinePaths(o,v),D=J(b,h,!s,c);if(D&&(l=D.packageId,_=D.versionPaths),_){c.traceEnabled&&t(c.host,e.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2,_.version,e.version,h);var x=s&&e.directoryProbablyExists(b,c.host),S=H(r,h,b,_.paths,g,!x,c);if(S)return S.value}}return g(r,d,!s,c)}function H(r,n,i,o,s,c,u){var l=e.matchPatternOrExact(e.getOwnKeys(o),n);if(l){var _=e.isString(l)?void 0:e.matchedText(l,n),d=e.isString(l)?l:e.patternText(l);return u.traceEnabled&&t(u.host,e.Diagnostics.Module_name_0_matched_pattern_1,n,d),{value:e.forEach(o[d],function(n){var o=_?n.replace("*",_):n,l=e.normalizePath(e.combinePaths(i,o));u.traceEnabled&&t(u.host,e.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1,n,o);var d=e.tryGetExtensionFromPath(l);if(void 0!==d){var p=B(l,c,u);if(void 0!==p)return a({path:p,ext:d})}return s(r,l,c||!e.directoryProbablyExists(e.getDirectoryPath(l),u.host),u)})}}}e.nodeModuleNameResolver=N,e.nodeModulesPathPart="/node_modules/",e.pathContainsNodeModules=w,e.parsePackageName=K;var G="__";function Y(t){if(e.startsWith(t,"@")){var r=t.replace(e.directorySeparator,G);if(r!==t)return r.slice(1)}return t}function X(t){return e.stringContains(t,G)?"@"+t.replace(G,e.directorySeparator):t}function Q(r,n,i,a){var o,s=r&&r.get(i);if(s)return a.traceEnabled&&t(a.host,e.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1,n,i),(o=a.failedLookupLocations).push.apply(o,s.failedLookupLocations),{value:s.resolvedModule&&{path:s.resolvedModule.resolvedFileName,originalPath:s.resolvedModule.originalPath||!0,extension:s.resolvedModule.extension,packageId:s.resolvedModule.packageId}}}function $(t,n,i,a,o,c){var u=[],_={compilerOptions:i,host:a,traceEnabled:r(i,a),failedLookupLocations:u},d=e.getDirectoryPath(n),p=f(s.TypeScript)||f(s.JavaScript);return l(p&&p.value,!1,u);function f(r){var n=x(r,t,d,M,_);if(n)return{value:n};if(e.isExternalModuleNameRelative(t)){var i=e.normalizePath(e.combinePaths(d,t));return Z(M(r,i,!1,_))}var a=o&&o.getOrCreateCacheForModuleName(t,c),u=e.forEachAncestorDirectory(d,function(n){var i=Q(a,t,n,_);if(i)return i;var o=e.normalizePath(e.combinePaths(n,t));return Z(M(r,o,!1,_))});return u||(r===s.TypeScript?function(e,t,r){return V(s.DtsOnly,e,t,r,!0,void 0,void 0)}(t,d,_):void 0)}}function Z(e){return void 0!==e?{value:e}:void 0}e.getTypesPackageName=function(e){return"@types/"+Y(e)},e.mangleScopedPackageName=Y,e.getPackageNameFromTypesPackageName=function(t){var r=e.removePrefix(t,"@types/");return r!==t?X(r):t},e.unmangleScopedPackageName=X,e.classicNameResolver=$,e.loadModuleFromGlobalCache=function(n,i,a,o,c){var u=r(a,o);u&&t(o,e.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2,i,n,c);var _=[],d={compilerOptions:a,host:o,traceEnabled:u,failedLookupLocations:_};return l(q(s.DtsOnly,n,c,d,!1),!0,_)}}(c||(c={})),function(e){var t;function r(t){return t.body?function t(n){switch(n.kind){case 241:case 242:return 0;case 243:if(e.isEnumConst(n))return 2;break;case 249:case 248:if(!e.hasModifier(n,1))return 0;break;case 245:var i=0;return e.forEachChild(n,function(r){var n=t(r);switch(n){case 0:return;case 2:return void(i=2);case 1:return i=1,!0;default:e.Debug.assertNever(n)}}),i;case 244:return r(n);case 72:if(n.isInJSDocNamespace)return 0}return 1}(t.body):1}!function(e){e[e.NonInstantiated=0]="NonInstantiated",e[e.Instantiated=1]="Instantiated",e[e.ConstEnumOnly=2]="ConstEnumOnly"}(e.ModuleInstanceState||(e.ModuleInstanceState={})),e.getModuleInstanceState=r,function(e){e[e.None=0]="None",e[e.IsContainer=1]="IsContainer",e[e.IsBlockScopedContainer=2]="IsBlockScopedContainer",e[e.IsControlFlowContainer=4]="IsControlFlowContainer",e[e.IsFunctionLike=8]="IsFunctionLike",e[e.IsFunctionExpression=16]="IsFunctionExpression",e[e.HasLocals=32]="HasLocals",e[e.IsInterface=64]="IsInterface",e[e.IsObjectLiteralOrClassExpressionMethod=128]="IsObjectLiteralOrClassExpressionMethod"}(t||(t={}));var n=function(){var t,n,d,p,f,m,g,y,v,h,b,D,x,S,T,C,k,E,N,A,F,P,w,O,I=0,M={flags:1},L={flags:1},R=0;function B(r,n,i,a,o){return e.createDiagnosticForNodeInSourceFile(e.getSourceFileOfNode(r)||t,r,n,i,a,o)}return function(r,i){t=r,n=i,d=e.getEmitScriptTarget(n),F=function(t,r){return!(!e.getStrictOptionValue(r,"alwaysStrict")||t.isDeclarationFile)||!!t.externalModuleIndicator}(t,i),w=e.createUnderscoreEscapedMap(),I=0,O=t.isDeclarationFile,P=e.objectAllocator.getSymbolConstructor(),t.locals||(Ae(t),t.symbolCount=I,t.classifiableNames=w,function(){if(!v)return;for(var r=f,n=y,i=g,a=p,o=b,s=0,c=v;s=109&&r.originalKeywordKind<=117)||e.isIdentifierName(r)||4194304&r.flags||t.parseDiagnostics.length||t.bindDiagnostics.push(B(r,function(r){if(e.getContainingClass(r))return e.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;if(t.externalModuleIndicator)return e.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;return e.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode}(r),e.declarationNameToString(r)))}function Te(r,n){if(n&&72===n.kind){var i=n;if(o=i,e.isIdentifier(o)&&("eval"===o.escapedText||"arguments"===o.escapedText)){var a=e.getErrorSpanForNode(t,n);t.bindDiagnostics.push(e.createFileDiagnostic(t,a.start,a.length,function(r){if(e.getContainingClass(r))return e.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;if(t.externalModuleIndicator)return e.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;return e.Diagnostics.Invalid_use_of_0_in_strict_mode}(r),e.idText(i)))}}var o}function Ce(e){F&&Te(e,e.name)}function ke(r){if(d<2&&279!==g.kind&&244!==g.kind&&!e.isFunctionLike(g)){var n=e.getErrorSpanForNode(t,r);t.bindDiagnostics.push(e.createFileDiagnostic(t,n.start,n.length,function(r){if(e.getContainingClass(r))return e.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode;if(t.externalModuleIndicator)return e.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;return e.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5}(r)))}}function Ee(r,n,i,a,o){var s=e.getSpanOfTokenAtPosition(t,r.pos);t.bindDiagnostics.push(e.createFileDiagnostic(t,s.start,s.length,n,i,a,o))}function Ne(r,n,a,o){!function(r,n,a){var o=e.createFileDiagnostic(t,n.pos,n.end-n.pos,a);r?t.bindDiagnostics.push(o):t.bindSuggestionDiagnostics=e.append(t.bindSuggestionDiagnostics,i({},o,{category:e.DiagnosticCategory.Suggestion}))}(r,{pos:e.getTokenPosOfNode(n,t),end:a.end},o)}function Ae(r){if(r){r.parent=p;var i=F;if(function(r){switch(r.kind){case 72:if(r.isInJSDocNamespace){for(var i=r.parent;i&&!e.isJSDocTypeAlias(i);)i=i.parent;xe(i,524288,67897832);break}case 100:return b&&(e.isExpression(r)||276===p.kind)&&(r.flowNode=b),Se(r);case 189:case 190:b&&Q(r)&&(r.flowNode=b),e.isSpecialPropertyDeclaration(r)&&function(t){100===t.expression.kind?Me(t):e.isPropertyAccessEntityNameExpression(t)&&279===t.parent.parent.kind&&(e.isPrototypeAccess(t.expression)?Le(t,t.parent):Re(t))}(r),e.isInJSFile(r)&&t.commonJsModuleIndicator&&e.isModuleExportsPropertyAccessExpression(r)&&!c(g,"module")&&U(t.locals,void 0,r.expression,134217729,67220414);break;case 204:var a=e.getAssignmentDeclarationKind(r);switch(a){case 1:Ie(r);break;case 2:!function(r){if(!Oe(r))return;var n=e.getRightMostAssignedExpression(r.right);if(e.isEmptyObjectLiteral(n)||f===t&&o(t,n))return;var i=e.exportAssignmentIsAlias(r)?2097152:1049092;U(t.symbol.exports,t.symbol,r,67108864|i,0)}(r);break;case 3:Le(r.left,r);break;case 6:!function(e){e.left.parent=e,e.right.parent=e;var t=e.left;Je(t.expression,t,!1)}(r);break;case 4:Me(r);break;case 5:!function(r){var n=r.left,i=ze(n.expression);if(!e.isInJSFile(r)&&!e.isFunctionSymbol(i))return;r.left.parent=r,r.right.parent=r,e.isIdentifier(n.expression)&&f===t&&s(t,n.expression)?Ie(r):Re(n)}(r);break;case 0:break;default:e.Debug.fail("Unknown binary expression special property assignment kind")}return function(t){F&&e.isLeftHandSideExpression(t.left)&&e.isAssignmentOperator(t.operatorToken.kind)&&Te(t,t.left)}(r);case 274:return function(e){F&&e.variableDeclaration&&Te(e,e.variableDeclaration.name)}(r);case 198:return function(r){if(F&&72===r.expression.kind){var n=e.getErrorSpanForNode(t,r.expression);t.bindDiagnostics.push(e.createFileDiagnostic(t,n.start,n.length,e.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode))}}(r);case 8:return function(r){F&&32&r.numericLiteralFlags&&t.bindDiagnostics.push(B(r,e.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode))}(r);case 203:return function(e){F&&Te(e,e.operand)}(r);case 202:return function(e){F&&(44!==e.operator&&45!==e.operator||Te(e,e.operand))}(r);case 231:return function(t){F&&Ee(t,e.Diagnostics.with_statements_are_not_allowed_in_strict_mode)}(r);case 233:return function(t){F&&n.target>=2&&(e.isDeclarationStatement(t.statement)||e.isVariableStatement(t.statement))&&Ee(t.label,e.Diagnostics.A_label_is_not_allowed_here)}(r);case 178:return void(h=!0);case 163:break;case 150:return function(t){if(e.isJSDocTemplateTag(t.parent)){var r=e.find(t.parent.parent.tags,e.isJSDocTypeAlias)||e.getHostSignatureFromJSDoc(t.parent);r?(r.locals||(r.locals=e.createSymbolTable()),U(r.locals,void 0,t,262144,67635688)):ve(t,262144,67635688)}else if(176===t.parent.kind){var n=function(t){var r=e.findAncestor(t,function(t){return t.parent&&e.isConditionalTypeNode(t.parent)&&t.parent.extendsType===t});return r&&r.parent}(t.parent);n?(n.locals||(n.locals=e.createSymbolTable()),U(n.locals,void 0,t,262144,67635688)):De(t,262144,K(t))}else ve(t,262144,67635688)}(r);case 151:return Ve(r);case 237:return Ue(r);case 186:return r.flowNode=b,Ue(r);case 154:case 153:return function(e){return qe(e,4|(e.questionToken?16777216:0),0)}(r);case 275:case 276:return qe(r,4,0);case 278:return qe(r,8,68008959);case 160:case 161:case 162:return ve(r,131072,0);case 156:case 155:return qe(r,8192|(r.questionToken?16777216:0),e.isObjectLiteralMethod(r)?0:67212223);case 239:return function(r){t.isDeclarationFile||4194304&r.flags||e.isAsyncFunction(r)&&(A|=1024);Ce(r),F?(ke(r),xe(r,16,67219887)):ve(r,16,67219887)}(r);case 157:return ve(r,16384,0);case 158:return qe(r,32768,67154879);case 159:return qe(r,65536,67187647);case 165:case 289:case 293:case 166:return function(t){var r=j(131072,K(t));J(r,t,131072);var n=j(2048,"__type");J(n,t,2048),n.members=e.createSymbolTable(),n.members.set(r.escapedName,r)}(r);case 168:case 292:case 181:return function(e){return De(e,2048,"__type")}(r);case 188:return function(r){var n;if(function(e){e[e.Property=1]="Property",e[e.Accessor=2]="Accessor"}(n||(n={})),F)for(var i=e.createUnderscoreEscapedMap(),a=0,o=r.properties;a147){var a=p;p=r;var l=ge(r);0===l?q(r):function(t,r){var n=f,i=m,a=g;1&r?(197!==t.kind&&(m=f),f=g=t,32&r&&(f.locals=e.createSymbolTable()),ye(f)):2&r&&((g=t).locals=void 0);if(4&r){var o=b,s=D,c=x,u=S,l=E,_=N,d=16&r&&!e.hasModifier(t,256)&&!t.asteriskToken&&!!e.getImmediatelyInvokedFunctionExpression(t);d||(b={flags:2},144&r&&(b.container=t)),S=d||157===t.kind?ee():void 0,D=void 0,x=void 0,E=void 0,N=!1,q(t),t.flags&=-1409,!(1&b.flags)&&8&r&&e.nodeIsPresent(t.body)&&(t.flags|=128,N&&(t.flags|=256)),279===t.kind&&(t.flags|=A),S&&(ne(S,b),b=ce(S),157===t.kind&&(t.returnFlowNode=b)),d||(b=o),D=s,x=c,S=u,E=l,N=_}else 64&r?(h=!1,q(t),t.flags=h?64|t.flags:-65&t.flags):q(t);f=n,m=i,g=a}(r,l),p=a}else if(!O&&0==(536870912&r.transformFlags)){R|=u(r,0);var a=p;1===r.kind&&(p=r),Fe(r),p=a}F=i}}function Fe(t){if(e.hasJSDocNodes(t))if(e.isInJSFile(t))for(var r=0,n=t.jsDoc;r=163&&e<=183)return-3;switch(e){case 191:case 192:case 187:return 637666625;case 244:return 647001409;case 151:return 637535553;case 197:return 653604161;case 196:case 239:return 653620545;case 238:return 639894849;case 240:case 209:return 638121281;case 157:return 653616449;case 156:case 158:case 159:return 653616449;case 120:case 135:case 146:case 132:case 138:case 136:case 123:case 139:case 106:case 150:case 153:case 155:case 160:case 161:case 162:case 241:case 242:return-3;case 188:return 638358849;case 274:return 637797697;case 184:case 185:return 637666625;case 194:case 212:case 308:case 195:case 98:return 536872257;case 189:case 190:return 570426689;default:return 637535553}}function _(t,r){r.parent=t,e.forEachChild(r,function(e){return _(r,e)})}e.bindSourceFile=function(t,r){e.performance.mark("beforeBind"),n(t,r),e.performance.mark("afterBind"),e.performance.measure("Bind","beforeBind","afterBind")},e.isExportsOrModuleExportsOrAlias=o,e.computeTransformFlagsForNode=u,e.getTransformFlagsSubtreeExclusions=l}(c||(c={})),function(e){e.createGetSymbolWalker=function(t,r,n,i,a,o,s,c,u,l){return function(_){void 0===_&&(_=function(){return!0});var d=[],p=[];return{walkType:function(t){try{return f(t),{visitedTypes:e.getOwnValues(d),visitedSymbols:e.getOwnValues(p)}}finally{e.clear(d),e.clear(p)}},walkSymbol:function(t){try{return y(t),{visitedTypes:e.getOwnValues(d),visitedSymbols:e.getOwnValues(p)}}finally{e.clear(d),e.clear(p)}}};function f(t){if(t&&!d[t.id]){d[t.id]=t;var r=y(t.symbol);if(!r){if(524288&t.flags){var n=t,a=n.objectFlags;4&a&&function(t){f(t.target),e.forEach(t.typeArguments,f)}(t),32&a&&function(e){f(e.typeParameter),f(e.constraintType),f(e.templateType),f(e.modifiersType)}(t),3&a&&(g(o=t),e.forEach(o.typeParameters,f),e.forEach(i(o),f),f(o.thisType)),24&a&&g(n)}var o;262144&t.flags&&function(e){f(u(e))}(t),3145728&t.flags&&function(t){e.forEach(t.types,f)}(t),4194304&t.flags&&function(e){f(e.type)}(t),8388608&t.flags&&function(e){f(e.objectType),f(e.indexType),f(e.constraint)}(t)}}}function m(i){var a=r(i);a&&f(a.type),e.forEach(i.typeParameters,f);for(var o=0,s=i.parameters;o0?e.createPropertyAccess(t(n,i-1),l):l}91===c&&(s=s.substring(1,s.length-1),c=s.charCodeAt(0));var _=void 0;return e.isSingleOrDoubleQuote(c)?(_=e.createLiteral(s.substring(1,s.length-1).replace(/\\./g,function(e){return e.substring(1)}))).singleQuote=39===c:""+ +s===s&&(_=e.createLiteral(+s)),_||((_=e.setEmitFlags(e.createIdentifier(s,a),16777216)).symbol=o),e.createElementAccess(t(n,i-1),_)}(i,i.length-1)}(r,t,n)})},symbolToTypeParameterDeclarations:function(e,r,n,i){return t(r,n,i,function(t){return b(e,t)})},symbolToParameterDeclaration:function(e,r,n,i){return t(r,n,i,function(t){return y(e,t)})},typeParameterToDeclaration:function(e,r,n,i){return t(r,n,i,function(t){return g(e,t)})}};function t(t,r,i,a){e.Debug.assert(void 0===t||0==(8&t.flags));var o={enclosingDeclaration:t,flags:r||0,tracker:i&&i.trackSymbol?i:{trackSymbol:e.noop,moduleResolverHost:134217728&r?{getCommonSourceDirectory:n.getCommonSourceDirectory?function(){return n.getCommonSourceDirectory()}:function(){return""},getSourceFiles:function(){return n.getSourceFiles()},getCurrentDirectory:n.getCurrentDirectory&&function(){return n.getCurrentDirectory()}}:void 0},encounteredError:!1,visitedTypes:void 0,symbolDepth:void 0,inferTypeParameters:void 0,approximateLength:0},s=a(o);return o.encounteredError?void 0:s}function a(t){return t.truncating?t.truncating:t.truncating=!(1&t.flags)&&t.approximateLength>e.defaultMaximumTruncationLength}function o(t,r){m&&m.throwIfCancellationRequested&&m.throwIfCancellationRequested();var n=8388608&r.flags;if(r.flags&=-8388609,t){if(1&t.flags)return r.approximateLength+=3,e.createKeywordTypeNode(120);if(2&t.flags)return e.createKeywordTypeNode(143);if(4&t.flags)return r.approximateLength+=6,e.createKeywordTypeNode(138);if(8&t.flags)return r.approximateLength+=6,e.createKeywordTypeNode(135);if(64&t.flags)return r.approximateLength+=6,e.createKeywordTypeNode(146);if(16&t.flags)return r.approximateLength+=7,e.createKeywordTypeNode(123);if(1024&t.flags&&!(1048576&t.flags)){var i=On(t.symbol),g=S(i,r,67897832),y=ba(i)===t?g:M(g,e.createTypeReferenceNode(e.symbolName(t.symbol),void 0));return y}if(1056&t.flags)return S(t.symbol,r,67897832);if(128&t.flags)return r.approximateLength+=t.value.length+2,e.createLiteralTypeNode(e.setEmitFlags(e.createLiteral(t.value),16777216));if(256&t.flags)return r.approximateLength+=(""+t.value).length,e.createLiteralTypeNode(e.createLiteral(t.value));if(2048&t.flags)return r.approximateLength+=e.pseudoBigIntToString(t.value).length+1,e.createLiteralTypeNode(e.createLiteral(t.value));if(512&t.flags)return r.approximateLength+=t.intrinsicName.length,"true"===t.intrinsicName?e.createTrue():e.createFalse();if(8192&t.flags){if(!(1048576&r.flags)){if($n(t.symbol,r.enclosingDeclaration))return r.approximateLength+=6,S(t.symbol,r,67220415);r.tracker.reportInaccessibleUniqueSymbolError&&r.tracker.reportInaccessibleUniqueSymbolError()}return r.approximateLength+=13,e.createTypeOperatorNode(142,e.createKeywordTypeNode(139))}if(16384&t.flags)return r.approximateLength+=4,e.createKeywordTypeNode(106);if(32768&t.flags)return r.approximateLength+=9,e.createKeywordTypeNode(141);if(65536&t.flags)return r.approximateLength+=4,e.createKeywordTypeNode(96);if(131072&t.flags)return r.approximateLength+=5,e.createKeywordTypeNode(132);if(4096&t.flags)return r.approximateLength+=6,e.createKeywordTypeNode(139);if(67108864&t.flags)return r.approximateLength+=6,e.createKeywordTypeNode(136);if(262144&t.flags&&t.isThisType)return 4194304&r.flags&&(r.encounteredError||32768&r.flags||(r.encounteredError=!0),r.tracker.reportInaccessibleThisError&&r.tracker.reportInaccessibleThisError()),r.approximateLength+=4,e.createThis();var v=e.getObjectFlags(t);if(4&v)return e.Debug.assert(!!(524288&t.flags)),function(t){var n=t.typeArguments||e.emptyArray;if(t.target===Ge){if(2&r.flags){var i=o(n[0],r);return e.createTypeReferenceNode("Array",[i])}var a=o(n[0],r);return e.createArrayTypeNode(a)}if(8&t.target.objectFlags){if(n.length>0){var s=xs(t),c=u(n.slice(0,s),r),l=t.target.hasRestElement;if(c){for(var _=t.target.minLength;_0){var D=(t.target.typeParameters||e.emptyArray).length;b=u(n.slice(_,D),r)}var x=r.flags;r.flags|=16;var T=S(t.symbol,r,67897832,b);return r.flags=x,p?M(p,T):T}(t);if(262144&t.flags||3&v){if(262144&t.flags&&e.contains(r.inferTypeParameters,t))return r.approximateLength+=e.symbolName(t.symbol).length+6,e.createInferTypeNode(f(t,r,void 0));if(4&r.flags&&262144&t.flags&&e.length(t.symbol.declarations)&&e.isTypeParameterDeclaration(t.symbol.declarations[0])&&p(t,r)&&!Qn(t.symbol,r.enclosingDeclaration)){var h=t.symbol.declarations[0].name;return r.approximateLength+=e.idText(h).length,e.createTypeReferenceNode(e.getGeneratedNameForNode(h,24),void 0)}return t.symbol?S(t.symbol,r,67897832):e.createTypeReferenceNode(e.createIdentifier("?"),void 0)}if(!n&&t.aliasSymbol&&(16384&r.flags||Qn(t.aliasSymbol,r.enclosingDeclaration))){var b=u(t.aliasTypeArguments,r);return!Un(t.aliasSymbol.escapedName)||32&t.aliasSymbol.flags?S(t.aliasSymbol,r,67897832,b):e.createTypeReferenceNode(e.createIdentifier(""),b)}if(!(3145728&t.flags)){if(48&v)return e.Debug.assert(!!(524288&t.flags)),O(t);if(4194304&t.flags){var D=t.type;r.approximateLength+=6;var x=o(D,r);return e.createTypeOperatorNode(x)}if(8388608&t.flags){var T=o(t.objectType,r),x=o(t.indexType,r);return r.approximateLength+=2,e.createIndexedAccessTypeNode(T,x)}if(16777216&t.flags){var C=o(t.checkType,r),k=r.inferTypeParameters;r.inferTypeParameters=t.root.inferTypeParameters;var E=o(t.extendsType,r);r.inferTypeParameters=k;var N=o(Kc(t),r),A=o(Uc(t),r);return r.approximateLength+=15,e.createConditionalTypeNode(C,E,N,A)}return 33554432&t.flags?o(t.typeVariable,r):e.Debug.fail("Should be unreachable.")}var F=1048576&t.flags?function(e){for(var t=[],r=0,n=0;n0){var w=e.createUnionOrIntersectionTypeNode(1048576&t.flags?173:174,P);return w}r.encounteredError||262144&r.flags||(r.encounteredError=!0)}else r.encounteredError=!0;function O(t){var n,i=""+t.id,a=t.symbol;if(a){var o=16&e.getObjectFlags(t)&&t.symbol&&32&t.symbol.flags;if(n=(o?"+":"")+l(a),Uf(a.valueDeclaration)){var c=t===Hf(a)?67897832:67220415;return S(a,r,c)}if(32&a.flags&&!Hi(a)&&!(209===a.valueDeclaration.kind&&2048&r.flags)||896&a.flags||function(){var t=!!(8192&a.flags)&&e.some(a.declarations,function(t){return e.hasModifier(t,32)}),n=!!(16&a.flags)&&(a.parent||e.forEach(a.declarations,function(e){return 279===e.parent.kind||245===e.parent.kind}));if(t||n)return(!!(4096&r.flags)||r.visitedTypes&&r.visitedTypes.has(i))&&(!(8&r.flags)||$n(a,r.enclosingDeclaration))}())return S(a,r,67220415);if(r.visitedTypes&&r.visitedTypes.has(i)){var u=function(t){if(t.symbol&&2048&t.symbol.flags){var r=e.findAncestor(t.symbol.declarations[0].parent,function(e){return 177!==e.kind});if(242===r.kind)return wn(r)}}(t);return u?S(u,r,67897832):s(r)}r.visitedTypes||(r.visitedTypes=e.createMap()),r.symbolDepth||(r.symbolDepth=e.createMap());var _=r.symbolDepth.get(n)||0;if(_>10)return s(r);r.symbolDepth.set(n,_+1),r.visitedTypes.set(i,!0);var d=I(t);return r.visitedTypes.delete(i),r.symbolDepth.set(n,_),d}return I(t)}function I(t){if(so(t))return function(t){e.Debug.assert(!!(524288&t.flags));var n,i=t.declaration.readonlyToken?e.createToken(t.declaration.readonlyToken.kind):void 0,a=t.declaration.questionToken?e.createToken(t.declaration.questionToken.kind):void 0;n=ro(t)?e.createTypeOperatorNode(o(no(t),r)):o(Za(t),r);var s=f($a(t),r,n),c=o(eo(t),r),u=e.createMappedTypeNode(i,s,a,c);return r.approximateLength+=10,e.setEmitFlags(u,1)}(t);var n=co(t);if(!n.properties.length&&!n.stringIndexInfo&&!n.numberIndexInfo){if(!n.callSignatures.length&&!n.constructSignatures.length)return r.approximateLength+=2,e.setEmitFlags(e.createTypeLiteralNode(void 0),1);if(1===n.callSignatures.length&&!n.constructSignatures.length){var i=n.callSignatures[0],u=d(i,165,r);return u}if(1===n.constructSignatures.length&&!n.callSignatures.length){var i=n.constructSignatures[0],u=d(i,166,r);return u}}var l=r.flags;r.flags|=4194304;var p=function(t){if(a(r))return[e.createPropertySignature(void 0,"...",void 0,void 0,void 0)];for(var n=[],i=0,o=t.callSignatures;i2)return[o(t[0],r),e.createTypeReferenceNode("... "+(t.length-2)+" more ...",void 0),o(t[t.length-1],r)]}for(var i=[],s=0,c=0,u=t;c=o?4096:0,c=wr(1,i,a);return c.type=n===s?ic(e):e,c});return e.concatenate(t.parameters.slice(0,r),c)}}return t.parameters}(t).map(function(e){return y(e,n,157===r)});if(t.thisParameter){var u=y(t.thisParameter,n);c.unshift(u)}var l=es(t);if(l){var _=1===l.kind?e.setEmitFlags(e.createIdentifier(l.parameterName),16777216):e.createThisTypeNode(),d=o(l.type,n);s=e.createTypePredicateNode(_,d)}else{var p=ts(t);s=p&&o(p,n)}return 256&n.flags?s&&120===s.kind&&(s=void 0):s||(s=e.createKeywordTypeNode(120)),n.approximateLength+=3,e.createSignatureDeclaration(r,i,c,s,a)}function p(e,t){return!!Hr(t.enclosingDeclaration,e.symbol.escapedName,67897832,void 0,e.symbol.escapedName,!1)}function f(t,r,n){var i=r.flags;r.flags&=-513;var a=4&r.flags&&t.symbol.declarations[0]&&e.isTypeParameterDeclaration(t.symbol.declarations[0])&&p(t,r),s=a?e.getGeneratedNameForNode(t.symbol.declarations[0].name,24):T(t.symbol,r,67897832,!0),c=To(t),u=c&&o(c,r);return r.flags=i,e.createTypeParameterDeclaration(s,n,u)}function g(e,t,r){void 0===r&&(r=mo(e));var n=r&&o(r,t);return f(e,t,n)}function y(t,r,n){var i=e.getDeclarationOfKind(t,151);i||Or(t)||(i=e.getDeclarationOfKind(t,299));var a=Qi(t);i&&Dv(i)&&(a=Wl(a));var s=o(a,r),c=!(8192&r.flags)&&n&&i&&i.modifiers?i.modifiers.map(e.getSynthesizedClone):void 0,u=i&&e.isRestParameter(i)||8192&e.getCheckFlags(t),l=u?e.createToken(25):void 0,_=i&&i.name?72===i.name.kind?e.setEmitFlags(e.getSynthesizedClone(i.name),16777216):148===i.name.kind?e.setEmitFlags(e.getSynthesizedClone(i.name.right),16777216):function t(n){r.tracker.trackSymbol&&e.isComputedPropertyName(n)&&Fa(n)&&v(n,r.enclosingDeclaration,r);var i=e.visitEachChild(n,t,e.nullTransformationContext,void 0,t),a=e.nodeIsSynthesized(i)?i:e.getSynthesizedClone(i);return 186===a.kind&&(a.initializer=void 0),e.setEmitFlags(a,16777217)}(i.name):e.symbolName(t),d=i&&Ko(i)||4096&e.getCheckFlags(t),p=d?e.createToken(56):void 0,f=e.createParameter(void 0,c,l,_,p,s,void 0);return r.approximateLength+=e.symbolName(t).length+3,f}function v(e,t,r){if(r.tracker.trackSymbol){var n=My(e.expression),i=Hr(n,n.escapedText,68268991,void 0,void 0,!0);i&&r.tracker.trackSymbol(i,t,67220415)}}function h(t,r,n,i){var a;r.tracker.trackSymbol(t,r.enclosingDeclaration,n);var o=262144&t.flags;return o||!(r.enclosingDeclaration||64&r.flags)||134217728&r.flags?a=[t]:(a=e.Debug.assertDefined(function t(n,a,o){var s,c=Yn(n,r.enclosingDeclaration,a,!!(128&r.flags));if(!c||Xn(c[0],r.enclosingDeclaration,1===c.length?a:Gn(a))){var u=In(c?c[0]:n,r.enclosingDeclaration);if(e.length(u)){s=u.map(function(t){return e.some(t.declarations,ri)?x(t,r):void 0});var l=u.map(function(e,t){return t});l.sort(function(t,r){var n=s[t],i=s[r];if(n&&i){var a=e.pathIsRelative(i);return e.pathIsRelative(n)===a?e.moduleSpecifiers.countPathComponents(n)-e.moduleSpecifiers.countPathComponents(i):a?-1:1}return 0});for(var _=l.map(function(e){return u[e]}),d=0,p=_;d0)),a}function b(t,r){var n,i=Ey(t);return 524384&i.flags&&(n=e.createNodeArray(e.map(ia(t),function(e){return g(e,r)}))),n}function D(t,r,n){e.Debug.assert(t&&0<=r&&r1?g(a,a.length-1,1):void 0,c=i||D(a,0,r),u=x(a[0],r);!(67108864&r.flags)&&e.getEmitModuleResolutionKind(A)===e.ModuleResolutionKind.NodeJs&&u.indexOf("/node_modules/")>=0&&(r.encounteredError=!0,r.tracker.reportLikelyUnsafeImportRequiredError&&r.tracker.reportLikelyUnsafeImportRequiredError(u));var l=e.createLiteralTypeNode(e.createLiteral(u));if(r.tracker.trackExternalModuleSymbolOfImportTypeNode&&r.tracker.trackExternalModuleSymbolOfImportTypeNode(a[0]),r.approximateLength+=u.length+10,!s||e.isEntityName(s)){if(s){var _=e.isIdentifier(s)?s:s.right;_.typeArguments=void 0}return e.createImportTypeNode(l,s,c,o)}var d=function t(r){return e.isIndexedAccessTypeNode(r.objectType)?t(r.objectType):r}(s),p=d.objectType.typeName;return e.createIndexedAccessTypeNode(e.createImportTypeNode(l,p,c,o),d.indexType)}var f=g(a,a.length-1,0);if(e.isIndexedAccessTypeNode(f))return f;if(o)return e.createTypeQueryNode(f);var _=e.isIdentifier(f)?f:f.right,m=_.typeArguments;return _.typeArguments=void 0,e.createTypeReferenceNode(f,m);function g(t,n,a){var o=n===t.length-1?i:D(t,n,r),s=t[n];0===n&&(r.flags|=16777216);var c=pi(s,r);r.approximateLength+=c.length+1,0===n&&(r.flags^=16777216);var u=t[n-1];if(!(16&r.flags)&&u&&Ra(u)&&Ra(u).get(s.escapedName)===s){var l=g(t,n-1,a);return e.isIndexedAccessTypeNode(l)?e.createIndexedAccessTypeNode(l,e.createLiteralTypeNode(e.createLiteral(c))):e.createIndexedAccessTypeNode(e.createTypeReferenceNode(l,o),e.createLiteralTypeNode(e.createLiteral(c)))}var _=e.setEmitFlags(e.createIdentifier(c,o),16777216);if(_.symbol=s,n>a){var l=g(t,n-1,a);return e.isEntityName(l)?e.createQualifiedName(l,_):e.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable")}return _}}function T(t,r,n,i){var a=h(t,r,n);return!i||1===a.length||r.encounteredError||65536&r.flags||(r.encounteredError=!0),function t(n,i){var a=D(n,i,r),o=n[i];0===i&&(r.flags|=16777216);var s=pi(o,r);0===i&&(r.flags^=16777216);var c=e.setEmitFlags(e.createIdentifier(s,a),16777216);return c.symbol=o,i>0?e.createQualifiedName(t(n,i-1),c):c}(a,a.length-1)}}(),U=wr(4,"undefined");U.declarations=[];var V,q=wr(4,"arguments"),W=wr(4,"require"),H={getNodeCount:function(){return e.sum(n.getSourceFiles(),"nodeCount")},getIdentifierCount:function(){return e.sum(n.getSourceFiles(),"identifierCount")},getSymbolCount:function(){return e.sum(n.getSourceFiles(),"symbolCount")+S},getTypeCount:function(){return x},isUndefinedSymbol:function(e){return e===U},isArgumentsSymbol:function(e){return e===q},isUnknownSymbol:function(e){return e===re},getMergedSymbol:Pn,getDiagnostics:Xy,getGlobalDiagnostics:function(){return Qy(),ar.getGlobalDiagnostics()},getTypeOfSymbolAtLocation:function(t,r){return(r=e.getParseTreeNode(r))?function(t,r){if(t=t.exportSymbol||t,72===r.kind&&(e.isRightSideOfQualifiedNameOrPropertyAccess(r)&&(r=r.parent),e.isExpressionNode(r)&&!e.isAssignmentTarget(r))){var n=Zm(r);if(Ln(Ur(r).resolvedSymbol)===t)return n}return Qi(t)}(t,r):se},getSymbolsOfParameterPropertyDeclaration:function(t,r){var n=e.getParseTreeNode(t,e.isParameter);return void 0===n?e.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."):function(t,r){var n=t.parent,i=t.parent.parent,a=qr(n.locals,r,67220415),o=qr(Ra(i.symbol),r,67220415);return a&&o?[a,o]:e.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration")}(n,e.escapeLeadingUnderscores(r))},getDeclaredTypeOfSymbol:ba,getPropertiesOfType:po,getPropertyOfType:function(t,r){return Fo(t,e.escapeLeadingUnderscores(r))},getTypeOfPropertyOfType:function(t,r){return Di(t,e.escapeLeadingUnderscores(r))},getIndexInfoOfType:Mo,getSignaturesOfType:wo,getIndexTypeOfType:Lo,getBaseTypes:_a,getBaseTypeOfLiteralType:Ol,getWidenedType:t_,getTypeFromTypeNode:function(t){var r=e.getParseTreeNode(t,e.isTypeNode);return r?uu(r):se},getParameterType:im,getPromisedTypeOfPromise:Sg,getReturnTypeOfSignature:ts,getNullableType:ql,getNonNullableType:Hl,typeToTypeNode:K.typeToTypeNode,indexInfoToIndexSignatureDeclaration:K.indexInfoToIndexSignatureDeclaration,signatureToSignatureDeclaration:K.signatureToSignatureDeclaration,symbolToEntityName:K.symbolToEntityName,symbolToExpression:K.symbolToExpression,symbolToTypeParameterDeclarations:K.symbolToTypeParameterDeclarations,symbolToParameterDeclaration:K.symbolToParameterDeclaration,typeParameterToDeclaration:K.typeParameterToDeclaration,getSymbolsInScope:function(t,r){return(t=e.getParseTreeNode(t))?function(t,r){if(8388608&t.flags)return[];var n=e.createSymbolTable(),i=!1;return function(){for(;t;){switch(t.locals&&!Vr(t)&&o(t.locals,r),t.kind){case 279:if(!e.isExternalOrCommonJsModule(t))break;case 244:o(wn(t).exports,2623475&r);break;case 243:o(wn(t).exports,8&r);break;case 209:var n=t.name;n&&a(t.symbol,r);case 240:case 241:i||o(Ra(wn(t)),67897832&r);break;case 196:var s=t.name;s&&a(t.symbol,r)}e.introducesArgumentsExoticObject(t)&&a(q,r),i=e.hasModifier(t,32),t=t.parent}o(wt,r)}(),n.delete("this"),jo(n);function a(t,r){if(e.getCombinedLocalAndExportSymbolFlags(t)&r){var i=t.escapedName;n.has(i)||n.set(i,t)}}function o(e,t){t&&e.forEach(function(e){a(e,t)})}}(t,r):[]},getSymbolAtLocation:function(t){return(t=e.getParseTreeNode(t))?iv(t):void 0},getShorthandAssignmentValueSymbol:function(t){return(t=e.getParseTreeNode(t))?function(e){if(e&&276===e.kind)return gn(e.name,69317567)}(t):void 0},getExportSpecifierLocalTargetSymbol:function(t){var r=e.getParseTreeNode(t,e.isExportSpecifier);return r?function(e){return e.parent.parent.moduleSpecifier?on(e.parent.parent,e):gn(e.propertyName||e.name,70107135)}(r):void 0},getExportSymbolOfSymbol:function(e){return Pn(e.exportSymbol||e)},getTypeAtLocation:function(t){return(t=e.getParseTreeNode(t))?av(t):se},getPropertySymbolOfDestructuringAssignment:function(t){var r=e.getParseTreeNode(t,e.isIdentifier);return r?function(t){var r=function t(r){if(e.Debug.assert(188===r.kind||187===r.kind),227===r.parent.kind){var n=_y(r.parent.expression,r.parent.awaitModifier);return Jm(r,n||se)}if(204===r.parent.kind){var n=Zm(r.parent.right);return Jm(r,n||se)}if(275===r.parent.kind){var i=t(r.parent.parent);return Bm(i||se,r.parent)}e.Debug.assert(187===r.parent.kind);var a=t(r.parent),o=dy(a||se,r.parent,!1,!1)||se;return jm(r.parent,a,r.parent.elements.indexOf(r),o||se)}(t.parent.parent);return r&&Fo(r,t.escapedText)}(r):void 0},signatureToString:function(t,r,n,i){return oi(t,e.getParseTreeNode(r),n,i)},typeToString:function(t,r,n){return si(t,e.getParseTreeNode(r),n)},symbolToString:function(t,r,n,i){return ai(t,e.getParseTreeNode(r),n,i)},typePredicateToString:function(t,r,n){return ui(t,e.getParseTreeNode(r),n)},writeSignature:function(t,r,n,i,a){return oi(t,e.getParseTreeNode(r),n,i,a)},writeType:function(t,r,n,i){return si(t,e.getParseTreeNode(r),n,i)},writeSymbol:function(t,r,n,i,a){return ai(t,e.getParseTreeNode(r),n,i,a)},writeTypePredicate:function(t,r,n,i){return ui(t,e.getParseTreeNode(r),n,i)},getAugmentedPropertiesOfType:sv,getRootSymbols:function t(r){var n=function(t){if(6&e.getCheckFlags(t))return e.mapDefined(Kr(t).containingType.types,function(e){return Fo(e,t.escapedName)});if(33554432&t.flags){var r=t,n=r.leftSpread,i=r.rightSpread,a=r.syntheticOrigin;return n?[n,i]:a?[a]:e.singleElementArray(function(e){for(var t,r=e;r=Kr(r).target;)t=r;return t}(t))}}(r);return n?e.flatMap(n,t):[r]},getContextualType:function(t){var r=e.getParseTreeNode(t,e.isExpression);return r?rp(r):void 0},getContextualTypeForObjectLiteralElement:function(t){var r=e.getParseTreeNode(t,e.isObjectLiteralElementLike);return r?Xd(r):void 0},getContextualTypeForArgumentAtIndex:function(t,r){var n=e.getParseTreeNode(t,e.isCallLikeExpression);return n&&Wd(n,r)},getContextualTypeForJsxAttribute:function(t){var r=e.getParseTreeNode(t,e.isJsxAttributeLike);return r&&Zd(r)},isContextSensitive:Pu,getFullyQualifiedName:mn,getResolvedSignature:function(e,t,r){return G(e,t,r,!1)},getResolvedSignatureForSignatureHelp:function(e,t,r){return G(e,t,r,!0)},getConstantValue:function(t){var r=e.getParseTreeNode(t,Ev);return r?Nv(r):void 0},isValidPropertyAccess:function(t,r){var n=e.getParseTreeNode(t,e.isPropertyAccessOrQualifiedNameOrImportTypeNode);return!!n&&function(e,t){switch(e.kind){case 189:return nf(e,98===e.expression.kind,t,t_(tg(e.expression)));case 148:return nf(e,!1,t,t_(tg(e.left)));case 183:return nf(e,!1,t,uu(e))}}(n,e.escapeLeadingUnderscores(r))},isValidPropertyAccessForCompletions:function(t,r,n){var i=e.getParseTreeNode(t,e.isPropertyAccessExpression);return!!i&&function(t,r,n){return nf(t,183!==t.kind&&98===t.expression.kind,n.escapedName,r)&&(!(8192&n.flags)||(a=wo(Hl(Di(i=r,n.escapedName)),0),e.Debug.assert(0!==a.length),a.some(function(e){var t=$o(e);return!t||zu(i,function(e,t,r){if(!e.typeParameters)return t;var n=o_(e.typeParameters,e,0);return y_(n.inferences,r,t),Nu(t,ss(e,C_(n)))}(e,t,i))})));var i,a}(i,r,n)},getSignatureFromDeclaration:function(t){var r=e.getParseTreeNode(t,e.isFunctionLike);return r?Go(r):void 0},isImplementationOfOverload:function(t){var r=e.getParseTreeNode(t,e.isFunctionLike);return r?bv(r):void 0},getImmediateAliasedSymbol:hp,getAliasedSymbol:_n,getEmitResolver:function(e,t){return Xy(e,t),z},getExportsOfModule:Cn,getExportsAndPropertiesOfModule:function(t){var r=Cn(t),n=xn(t);return n!==t&&e.addRange(r,po(Qi(n))),r},getSymbolWalker:e.createGetSymbolWalker(function(e){return ns(e)||ie},es,ts,_a,co,Qi,E_,Io,mo,My),getAmbientModules:function(){return Ke||(Ke=[],wt.forEach(function(e,t){r.test(t)&&Ke.push(e)})),Ke},getJsxIntrinsicTagNamesAt:function(r){var n=Ep(t.IntrinsicElements,r);return n?po(n):e.emptyArray},isOptionalParameter:function(t){var r=e.getParseTreeNode(t,e.isParameter);return!!r&&Ko(r)},tryGetMemberInModuleExports:function(t,r){return kn(e.escapeLeadingUnderscores(t),r)},tryGetMemberInModuleExportsAndProperties:function(t,r){return function(e,t){var r=kn(e,t);if(r)return r;var n=xn(t);if(n!==t){var i=Qi(n);return 131068&i.flags?void 0:Fo(i,e)}}(e.escapeLeadingUnderscores(t),r)},tryFindAmbientModuleWithoutAugmentations:function(e){return zo(e,!1)},getApparentType:ko,getUnionType:gc,createAnonymousType:Wn,createSignature:za,createSymbol:wr,createIndexInfo:fs,getAnyType:function(){return ie},getStringType:function(){return pe},getNumberType:function(){return fe},createPromiseType:mm,createArrayType:ic,getElementTypeOfArrayType:function(e){return Tl(e)&&e.typeArguments?e.typeArguments[0]:void 0},getBooleanType:function(){return be},getFalseType:function(e){return e?ge:ye},getTrueType:function(e){return e?ve:he},getVoidType:function(){return xe},getUndefinedType:function(){return ue},getNullType:function(){return _e},getESSymbolType:function(){return De},getNeverType:function(){return Se},isSymbolAccessible:Zn,getObjectFlags:e.getObjectFlags,isArrayLikeType:kl,isTypeInvalidDueToUnionDiscriminant:function(t,r){return r.properties.some(function(r){var n=r.name&&e.getTextOfPropertyName(r.name),i=void 0===n?void 0:Di(t,n);return!!i&&!!(2944&i.flags)&&!Lu(av(r),i)})},getAllPossiblePropertiesOfTypes:function(t){var r=gc(t);if(!(1048576&r.flags))return sv(r);for(var n=e.createSymbolTable(),i=0,a=t;i>",0,ie),Et=za(void 0,void 0,void 0,e.emptyArray,ie,void 0,0,!1,!1),Nt=za(void 0,void 0,void 0,e.emptyArray,se,void 0,0,!1,!1),At=za(void 0,void 0,void 0,e.emptyArray,ie,void 0,0,!1,!1),Ft=za(void 0,void 0,void 0,e.emptyArray,Te,void 0,0,!1,!1),Pt=fs(pe,!0),wt=e.createSymbolTable(),Ot=e.createMap(),It=e.createMap(),Mt=0,Lt=0,Rt=0,Bt=!1,jt=ou(""),Jt=ou(0),zt=ou({negative:!1,base10Value:"0"}),Kt=[],Ut=[],Vt=[],qt=0,Wt=10,Ht=[],Gt=[],Yt=[],Xt=[],Qt=[],$t=[],Zt=[],er=[],tr=[],rr=[],nr=[],ir=[],ar=e.createDiagnosticCollection(),or=e.createMultiMap();!function(e){e[e.None=0]="None",e[e.TypeofEQString=1]="TypeofEQString",e[e.TypeofEQNumber=2]="TypeofEQNumber",e[e.TypeofEQBigInt=4]="TypeofEQBigInt",e[e.TypeofEQBoolean=8]="TypeofEQBoolean",e[e.TypeofEQSymbol=16]="TypeofEQSymbol",e[e.TypeofEQObject=32]="TypeofEQObject",e[e.TypeofEQFunction=64]="TypeofEQFunction",e[e.TypeofEQHostObject=128]="TypeofEQHostObject",e[e.TypeofNEString=256]="TypeofNEString",e[e.TypeofNENumber=512]="TypeofNENumber",e[e.TypeofNEBigInt=1024]="TypeofNEBigInt",e[e.TypeofNEBoolean=2048]="TypeofNEBoolean",e[e.TypeofNESymbol=4096]="TypeofNESymbol",e[e.TypeofNEObject=8192]="TypeofNEObject",e[e.TypeofNEFunction=16384]="TypeofNEFunction",e[e.TypeofNEHostObject=32768]="TypeofNEHostObject",e[e.EQUndefined=65536]="EQUndefined",e[e.EQNull=131072]="EQNull",e[e.EQUndefinedOrNull=262144]="EQUndefinedOrNull",e[e.NEUndefined=524288]="NEUndefined",e[e.NENull=1048576]="NENull",e[e.NEUndefinedOrNull=2097152]="NEUndefinedOrNull",e[e.Truthy=4194304]="Truthy",e[e.Falsy=8388608]="Falsy",e[e.All=16777215]="All",e[e.BaseStringStrictFacts=3735041]="BaseStringStrictFacts",e[e.BaseStringFacts=12582401]="BaseStringFacts",e[e.StringStrictFacts=16317953]="StringStrictFacts",e[e.StringFacts=16776705]="StringFacts",e[e.EmptyStringStrictFacts=12123649]="EmptyStringStrictFacts",e[e.EmptyStringFacts=12582401]="EmptyStringFacts",e[e.NonEmptyStringStrictFacts=7929345]="NonEmptyStringStrictFacts",e[e.NonEmptyStringFacts=16776705]="NonEmptyStringFacts",e[e.BaseNumberStrictFacts=3734786]="BaseNumberStrictFacts",e[e.BaseNumberFacts=12582146]="BaseNumberFacts",e[e.NumberStrictFacts=16317698]="NumberStrictFacts",e[e.NumberFacts=16776450]="NumberFacts",e[e.ZeroNumberStrictFacts=12123394]="ZeroNumberStrictFacts",e[e.ZeroNumberFacts=12582146]="ZeroNumberFacts",e[e.NonZeroNumberStrictFacts=7929090]="NonZeroNumberStrictFacts",e[e.NonZeroNumberFacts=16776450]="NonZeroNumberFacts",e[e.BaseBigIntStrictFacts=3734276]="BaseBigIntStrictFacts",e[e.BaseBigIntFacts=12581636]="BaseBigIntFacts",e[e.BigIntStrictFacts=16317188]="BigIntStrictFacts",e[e.BigIntFacts=16775940]="BigIntFacts",e[e.ZeroBigIntStrictFacts=12122884]="ZeroBigIntStrictFacts",e[e.ZeroBigIntFacts=12581636]="ZeroBigIntFacts",e[e.NonZeroBigIntStrictFacts=7928580]="NonZeroBigIntStrictFacts",e[e.NonZeroBigIntFacts=16775940]="NonZeroBigIntFacts",e[e.BaseBooleanStrictFacts=3733256]="BaseBooleanStrictFacts",e[e.BaseBooleanFacts=12580616]="BaseBooleanFacts",e[e.BooleanStrictFacts=16316168]="BooleanStrictFacts",e[e.BooleanFacts=16774920]="BooleanFacts",e[e.FalseStrictFacts=12121864]="FalseStrictFacts",e[e.FalseFacts=12580616]="FalseFacts",e[e.TrueStrictFacts=7927560]="TrueStrictFacts",e[e.TrueFacts=16774920]="TrueFacts",e[e.SymbolStrictFacts=7925520]="SymbolStrictFacts",e[e.SymbolFacts=16772880]="SymbolFacts",e[e.ObjectStrictFacts=7888800]="ObjectStrictFacts",e[e.ObjectFacts=16736160]="ObjectFacts",e[e.FunctionStrictFacts=7880640]="FunctionStrictFacts",e[e.FunctionFacts=16728e3]="FunctionFacts",e[e.UndefinedFacts=9830144]="UndefinedFacts",e[e.NullFacts=9363232]="NullFacts",e[e.EmptyObjectStrictFacts=16318463]="EmptyObjectStrictFacts",e[e.EmptyObjectFacts=16777215]="EmptyObjectFacts"}(Tt||(Tt={}));var sr,cr,ur,lr,_r,dr,pr,fr,mr,gr=e.createMapFromTemplate({string:1,number:2,bigint:4,boolean:8,symbol:16,undefined:65536,object:32,function:64}),yr=e.createMapFromTemplate({string:256,number:512,bigint:1024,boolean:2048,symbol:4096,undefined:524288,object:8192,function:16384}),vr=e.createMapFromTemplate({string:pe,number:fe,bigint:me,boolean:be,symbol:De,undefined:ue}),hr=gc(e.arrayFrom(gr.keys(),ou)),br=e.createMap(),Dr=e.createMap(),xr=e.createMap(),Sr=e.createMap(),Tr=e.createMap(),Cr=e.createMap();!function(e){e[e.Type=0]="Type",e[e.ResolvedBaseConstructorType=1]="ResolvedBaseConstructorType",e[e.DeclaredType=2]="DeclaredType",e[e.ResolvedReturnType=3]="ResolvedReturnType",e[e.ImmediateBaseConstraint=4]="ImmediateBaseConstraint",e[e.EnumTagType=5]="EnumTagType",e[e.JSDocTypeReference=6]="JSDocTypeReference"}(ur||(ur={})),function(e){e[e.Normal=0]="Normal",e[e.SkipContextSensitive=1]="SkipContextSensitive",e[e.Inferential=2]="Inferential",e[e.Contextual=3]="Contextual"}(lr||(lr={})),function(e){e[e.None=0]="None",e[e.Bivariant=1]="Bivariant",e[e.Strict=2]="Strict"}(_r||(_r={})),function(e){e[e.IncludeReadonly=1]="IncludeReadonly",e[e.ExcludeReadonly=2]="ExcludeReadonly",e[e.IncludeOptional=4]="IncludeOptional",e[e.ExcludeOptional=8]="ExcludeOptional"}(dr||(dr={})),function(e){e[e.None=0]="None",e[e.Source=1]="Source",e[e.Target=2]="Target",e[e.Both=3]="Both"}(pr||(pr={})),function(e){e.resolvedExports="resolvedExports",e.resolvedMembers="resolvedMembers"}(fr||(fr={})),function(e){e[e.Local=0]="Local",e[e.Parameter=1]="Parameter"}(mr||(mr={}));var kr=e.createSymbolTable();kr.set(U.escapedName,U);var Er=e.and(Ky,function(t){return!e.isAccessor(t)});return function(){for(var t=0,r=n.getSourceFiles();t=5||Ar(a,e.length(a.relatedInformation)?e.createDiagnosticForNode(c,e.Diagnostics.and_here):e.createDiagnosticForNode(c,e.Diagnostics._0_was_also_declared_here,n))}}function Jr(e,t){t.forEach(function(t,r){var n=e.get(r);e.set(r,n?Rr(n,t):t)})}function zr(t){var r=t.parent;if(r.symbol.declarations[0]===r)if(e.isGlobalScopeAugmentation(r))Jr(wt,r.symbol.exports);else{var n=hn(t,t,4194304&t.parent.parent.flags?void 0:e.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found,!0);if(!n)return;1920&(n=xn(n)).flags?n=Rr(n,r.symbol):Fr(t,e.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity,t.text)}else e.Debug.assert(r.symbol.declarations.length>1)}function Kr(e){if(33554432&e.flags)return e;var t=l(e);return Gt[t]||(Gt[t]={})}function Ur(e){var t=u(e);return Yt[t]||(Yt[t]={flags:0})}function Vr(t){return 279===t.kind&&!e.isExternalOrCommonJsModule(t)}function qr(t,r,n){if(n){var i=t.get(r);if(i){if(e.Debug.assert(0==(1&e.getCheckFlags(i)),"Should never get an instantiated symbol here."),i.flags&n)return i;if(2097152&i.flags){var a=_n(i);if(a===re||a.flags&n)return i}}}}function Wr(t,r){var i=e.getSourceFileOfNode(t),a=e.getSourceFileOfNode(r);if(i!==a){if(P&&(i.externalModuleIndicator||a.externalModuleIndicator)||!A.outFile&&!A.out||N_(r)||4194304&t.flags)return!0;if(u(r,t))return!0;var o=n.getSourceFiles();return o.indexOf(i)<=o.indexOf(a)}if(t.pos<=r.pos){if(186===t.kind){var s=e.getAncestor(r,186);return s?e.findAncestor(s,e.isBindingElement)!==e.findAncestor(t,e.isBindingElement)||t.pos=2&&e.isParameter(_)&&h.body&&l.valueDeclaration.pos>=h.body.pos&&l.valueDeclaration.end<=h.body.end?v=!1:1&l.flags&&(v=151===_.kind||_===t.type&&!!e.findAncestor(l.valueDeclaration,e.isParameter))}}else 175===t.kind&&(v=_===t.trueType);if(v)break e;l=void 0}switch(t.kind){case 279:if(!e.isExternalOrCommonJsModule(t))break;y=!0;case 244:var b=wn(t).exports;if(279===t.kind||e.isAmbientModule(t)){if(l=b.get("default")){var D=e.getLocalSymbolForExportDefault(l);if(D&&l.flags&n&&D.escapedName===r)break e;l=void 0}var x=b.get(r);if(x&&2097152===x.flags&&e.getDeclarationOfKind(x,257))break}if("default"!==r&&(l=c(b,r,2623475&n))){if(!e.isSourceFile(t)||!t.commonJsModuleIndicator||l.declarations.some(e.isJSDocTypeAlias))break e;l=void 0}break;case 243:if(l=c(wn(t).exports,r,8&n))break e;break;case 154:case 153:if(e.isClassLike(t.parent)&&!e.hasModifier(t,32)){var S=Bn(t.parent);S&&S.locals&&c(S.locals,r,67220415&n)&&(p=t)}break;case 240:case 209:case 241:if(l=c(wn(t).members||E,r,67897832&n)){if(!Qr(l,t)){l=void 0;break}if(_&&e.hasModifier(_,32))return void Fr(g,e.Diagnostics.Static_members_cannot_reference_class_type_parameters);break e}if(209===t.kind&&32&n){var T=t.name;if(T&&r===T.escapedText){l=t.symbol;break e}}break;case 211:if(_===t.expression&&86===t.parent.token){var C=t.parent.parent;if(e.isClassLike(C)&&(l=c(wn(C).members,r,67897832&n)))return void(i&&Fr(g,e.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters))}break;case 149:if(f=t.parent.parent,(e.isClassLike(f)||241===f.kind)&&(l=c(wn(f).members,r,67897832&n)))return void Fr(g,e.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);break;case 156:case 155:case 157:case 158:case 159:case 239:case 197:if(3&n&&"arguments"===r){l=q;break e}break;case 196:if(3&n&&"arguments"===r){l=q;break e}if(16&n){var k=t.name;if(k&&r===k.escapedText){l=t.symbol;break e}}break;case 152:t.parent&&151===t.parent.kind&&(t=t.parent),t.parent&&e.isClassElement(t.parent)&&(t=t.parent);break;case 304:case 297:t=e.getJSDocHost(t)}Yr(t)&&(d=t),_=t,t=t.parent}if(!o||!l||d&&l===d.symbol||(l.isReferenced|=n),!l){if(_&&(e.Debug.assert(279===_.kind),_.commonJsModuleIndicator&&"exports"===r&&n&_.symbol.flags))return _.symbol;s||(l=c(wt,r,n))}if(!l&&m&&e.isInJSFile(m)&&m.parent&&e.isRequireCall(m.parent,!1))return W;if(l){if(i){if(p){var N=p.name;return void Fr(g,e.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor,e.declarationNameToString(N),Xr(a))}if(g&&(2&n||(32&n||384&n)&&67220415==(67220415&n))){var F=Ln(l);(2&F.flags||32&F.flags||384&F.flags)&&function(t,r){e.Debug.assert(!!(2&t.flags||32&t.flags||384&t.flags));var n=e.find(t.declarations,function(t){return e.isBlockOrCatchScoped(t)||e.isClassLike(t)||243===t.kind||e.isInJSFile(t)&&!!e.getJSDocEnumTag(t)});if(void 0===n)return e.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined");if(!(4194304&n.flags||Wr(n,r))){var i=void 0,a=e.declarationNameToString(e.getNameOfDeclaration(n));2&t.flags?i=Fr(r,e.Diagnostics.Block_scoped_variable_0_used_before_its_declaration,a):32&t.flags?i=Fr(r,e.Diagnostics.Class_0_used_before_its_declaration,a):256&t.flags?i=Fr(r,e.Diagnostics.Enum_0_used_before_its_declaration,a):(e.Debug.assert(!!(128&t.flags)),A.preserveConstEnums&&(i=Fr(r,e.Diagnostics.Class_0_used_before_its_declaration,a))),i&&Ar(i,e.createDiagnosticForNode(n,e.Diagnostics._0_is_declared_here,a))}}(F,g)}!l||!y||67220415!=(67220415&n)||2097152&m.flags||e.some(l.declarations,function(t){return e.isNamespaceExportDeclaration(t)||e.isSourceFile(t)&&!!t.symbol.globalExports})&&Fr(g,e.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead,e.unescapeLeadingUnderscores(r))}return l}if(i&&(!g||!(function(t,r,n){if(!e.isIdentifier(t)||t.escapedText!==r||Zy(t)||N_(t))return!1;for(var i=e.getThisContainer(t,!1),a=i;a;){if(e.isClassLike(a.parent)){var o=wn(a.parent);if(!o)break;var s=Qi(o);if(Fo(s,r))return Fr(t,e.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0,Xr(n),ai(o)),!0;if(a===i&&!e.hasModifier(a,32)){var c=ba(o).thisType;if(Fo(c,r))return Fr(t,e.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0,Xr(n)),!0}}a=a.parent}return!1}(g,r,a)||$r(g)||function(t,r,n){var i=1920|(e.isInJSFile(t)?67220415:0);if(n===i){var a=ln(Hr(t,r,67897832&~i,void 0,void 0,!1)),o=t.parent;if(a){if(e.isQualifiedName(o)){e.Debug.assert(o.left===t,"Should only be resolving left side of qualified name as a namespace");var s=o.right.escapedText,c=Fo(ba(a),s);if(c)return Fr(o,e.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1,e.unescapeLeadingUnderscores(r),e.unescapeLeadingUnderscores(s)),!0}return Fr(t,e.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here,e.unescapeLeadingUnderscores(r)),!0}}return!1}(g,r,n)||function(t,r,n){if(67220415&n){if("any"===r||"string"===r||"number"===r||"boolean"===r||"never"===r)return Fr(t,e.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here,e.unescapeLeadingUnderscores(r)),!0;var i=ln(Hr(t,r,788544,void 0,void 0,!1));if(i&&!(1024&i.flags)){var a="Promise"===r||"Symbol"===r?e.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later:e.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;return Fr(t,a,e.unescapeLeadingUnderscores(r)),!0}}return!1}(g,r,n)||function(t,r,n){if(111127&n){var i=ln(Hr(t,r,1024,void 0,void 0,!1));if(i)return Fr(t,e.Diagnostics.Cannot_use_namespace_0_as_a_value,e.unescapeLeadingUnderscores(r)),!0}else if(788544&n){var i=ln(Hr(t,r,1536,void 0,void 0,!1));if(i)return Fr(t,e.Diagnostics.Cannot_use_namespace_0_as_a_type,e.unescapeLeadingUnderscores(r)),!0}return!1}(g,r,n)))){var P=void 0;if(u&&qt=0)return void Fr(a,e.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1,r,v)}}if(l)Fr(a,l,r,u.resolvedFileName);else{var h=e.tryExtractTSExtension(r);h?Fr(a,e.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead,h,e.removeExtension(r,h)):!A.resolveJsonModule&&e.fileExtensionIs(r,".json")&&e.getEmitModuleResolutionKind(A)===e.ModuleResolutionKind.NodeJs&&e.hasJsonModuleEmitEnabled(A)?Fr(a,e.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension,r):Fr(a,i,r)}}}}function Dn(t,r,n,i){var a,o=n.packageId,s=n.resolvedFileName,c=!e.isExternalModuleNameRelative(i)&&o?(a=o.name,v().has(e.getTypesPackageName(a))?e.chainDiagnosticMessages(void 0,e.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1,o.name,e.mangleScopedPackageName(o.name)):e.chainDiagnosticMessages(void 0,e.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0,i,e.mangleScopedPackageName(o.name))):void 0;Pr(t,r,e.chainDiagnosticMessages(c,e.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type,i,s))}function xn(t,r){if(t)return Pn(function(t,r){if(!t||t===re||t===r||1===r.exports.size||2097152&t.flags)return t;var n=Lr(t);return void 0===n.exports&&(n.flags=512|n.flags,n.exports=e.createSymbolTable()),r.exports.forEach(function(e,t){"export="!==t&&n.exports.set(t,n.exports.has(t)?Rr(n.exports.get(t),e):e)}),n}(ln(t.exports.get("export="),r),t))||t}function Sn(t,r,n){var i=xn(t,n);if(!n&&i){if(!(1539&i.flags||e.getDeclarationOfKind(i,279)))return Fr(r,e.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct,ai(t)),i;if(A.esModuleInterop){var a=r.parent;if(e.isImportDeclaration(a)&&e.getNamespaceDeclarationNode(a)||e.isImportCall(a)){var o=Qi(i),s=Po(o,0);if(s&&s.length||(s=Po(o,1)),s&&s.length){var c=$f(o,i,t),u=wr(i.flags,i.escapedName);u.declarations=i.declarations?i.declarations.slice():[],u.parent=i.parent,u.target=i,u.originatingImport=a,i.valueDeclaration&&(u.valueDeclaration=i.valueDeclaration),i.constEnumOnlyModule&&(u.constEnumOnlyModule=!0),i.members&&(u.members=e.cloneMap(i.members)),i.exports&&(u.exports=e.cloneMap(i.exports));var l=co(c);return u.type=Wn(u,l.members,e.emptyArray,e.emptyArray,l.stringIndexInfo,l.numberIndexInfo),u}}}}return i}function Tn(e){return void 0!==e.exports.get("export=")}function Cn(e){return jo(Nn(e))}function kn(e,t){var r=Nn(t);if(r)return r.get(e)}function En(e){return 32&e.flags?La(e,"resolvedExports"):1536&e.flags?Nn(e):e.exports||E}function Nn(e){var t=Kr(e);return t.resolvedExports||(t.resolvedExports=Fn(e))}function An(t,r,n,i){r&&r.forEach(function(r,a){if("default"!==a){var o=t.get(a);if(o){if(n&&i&&o&&ln(o)!==ln(r)){var s=n.get(a);s.exportsWithDuplicate?s.exportsWithDuplicate.push(i):s.exportsWithDuplicate=[i]}}else t.set(a,r),n&&i&&n.set(a,{specifierText:e.getTextOfNode(i.moduleSpecifier)})}})}function Fn(t){var r=[];return function t(n){if(n&&n.exports&&e.pushIfUnique(r,n)){var i=e.cloneMap(n.exports),a=n.exports.get("__export");if(a){for(var o=e.createSymbolTable(),s=e.createMap(),c=0,u=a.declarations;c=l?u.substr(0,l-"...".length)+"...":u}function ci(e){return void 0===e&&(e=0),9469291&e}function ui(t,r,n,i){return void 0===n&&(n=16384),i?a(i).getText():e.usingSingleLineStringWriter(a);function a(i){var a=e.createTypePredicateNode(1===t.kind?e.createIdentifier(t.parameterName):e.createThisTypeNode(),K.typeToTypeNode(t.type,r,70222336|ci(n))),o=e.createPrinter({removeComments:!0}),s=r&&e.getSourceFileOfNode(r);return o.writeNode(4,a,s,i),i}}function li(e){return 8===e?"private":16===e?"protected":"public"}function _i(t){return t&&t.parent&&245===t.parent.kind&&e.isExternalModuleAugmentation(t.parent.parent)}function di(t){return 279===t.kind||e.isAmbientModule(t)}function pi(t,r){if(r&&"default"===t.escapedName&&!(16384&r.flags)&&(!(16777216&r.flags)||!t.declarations||r.enclosingDeclaration&&e.findAncestor(t.declarations[0],di)!==e.findAncestor(r.enclosingDeclaration,di)))return"default";if(t.declarations&&t.declarations.length){var n=t.declarations[0],i=e.getNameOfDeclaration(n);if(i)return e.isCallExpression(n)&&e.isBindableObjectDefinePropertyCall(n)?e.symbolName(t):e.declarationNameToString(i);if(n.parent&&237===n.parent.kind)return e.declarationNameToString(n.parent.name);switch(n.kind){case 209:case 196:case 197:return!r||r.encounteredError||131072&r.flags||(r.encounteredError=!0),209===n.kind?"(Anonymous class)":"(Anonymous function)"}}var a=t.nameType;if(a){if(128&a.flags&&!e.isIdentifierText(a.value,A.target))return'"'+e.escapeString(a.value,34)+'"';if(a&&8192&a.flags)return"["+pi(a.symbol,r)+"]"}return e.symbolName(t)}function fi(t){if(t){var r=Ur(t);return void 0===r.isVisible&&(r.isVisible=!!function(){switch(t.kind){case 297:case 304:return!!(t.parent&&t.parent.parent&&t.parent.parent.parent&&e.isSourceFile(t.parent.parent.parent));case 186:return fi(t.parent.parent);case 237:if(e.isBindingPattern(t.name)&&!t.name.elements.length)return!1;case 244:case 240:case 241:case 242:case 239:case 243:case 248:if(e.isExternalModuleAugmentation(t))return!0;var r=bi(t);return 1&e.getCombinedModifierFlags(t)||248!==t.kind&&279!==r.kind&&4194304&r.flags?fi(r):Vr(r);case 154:case 153:case 158:case 159:case 156:case 155:if(e.hasModifier(t,24))return!1;case 157:case 161:case 160:case 162:case 151:case 245:case 165:case 166:case 168:case 164:case 169:case 170:case 173:case 174:case 177:return fi(t.parent);case 250:case 251:case 253:return!1;case 150:case 279:case 247:return!0;case 254:default:return!1}}()),r.isVisible}return!1}function mi(t,r){var n,i;return t.parent&&254===t.parent.kind?n=Hr(t,t.escapedText,70107135,void 0,t,!1):257===t.parent.kind&&(n=sn(t.parent,70107135)),n&&function t(n){e.forEach(n,function(n){var a=en(n)||n;if(r?Ur(n).isVisible=!0:(i=i||[],e.pushIfUnique(i,a)),e.isInternalModuleImportEqualsDeclaration(n)){var o=n.moduleReference,s=My(o),c=Hr(n,s.escapedText,68009983,void 0,void 0,!1);c&&t(c.declarations)}})}(n.declarations),i}function gi(e,t){var r=yi(e,t);if(r>=0){for(var n=Kt.length,i=r;i=0;r--){if(vi(Kt[r],Vt[r]))return-1;if(Kt[r]===e&&Vt[r]===t)return r}return-1}function vi(t,r){switch(r){case 0:return!!Kr(t).type;case 5:return!!Ur(t).resolvedEnumType;case 2:return!!Kr(t).declaredType;case 1:return!!t.resolvedBaseConstructorType;case 3:return!!t.resolvedReturnType;case 4:return!!t.immediateBaseConstraint;case 6:return!!Kr(t).resolvedJSDocType}return e.Debug.assertNever(r)}function hi(){return Kt.pop(),Vt.pop(),Ut.pop()}function bi(t){return e.findAncestor(e.getRootDeclaration(t),function(e){switch(e.kind){case 237:case 238:case 253:case 252:case 251:case 250:return!1;default:return!0}}).parent}function Di(e,t){var r=Fo(e,t);return r?Qi(r):void 0}function xi(e){return e&&0!=(1&e.flags)}function Si(e){var t=wn(e);return t&&Kr(t).type||Fi(e,!1)}function Ti(t){return 149===t.kind&&!e.isStringOrNumericLiteralLike(t.expression)}function Ci(t,r,n){if(131072&(t=ad(t,function(e){return!(98304&e.flags)})).flags)return Fe;if(1048576&t.flags)return od(t,function(e){return Ci(e,r,n)});var i=gc(e.map(r,Tc));if(wc(t)||Oc(i)){if(131072&i.flags)return t;var a=xt||(xt=Js("Pick",524288,e.Diagnostics.Cannot_find_global_type_0)),o=Dt||(Dt=Js("Exclude",524288,e.Diagnostics.Cannot_find_global_type_0));return a&&o?Ts(a,[t,Ts(o,[Ec(t),i])]):se}for(var s=e.createSymbolTable(),c=0,u=po(t);c=2?rc(ie):tt;var s=sc(e.map(i,function(t){return e.isOmittedExpression(t)?ie:Li(t,r,n)}),e.findLastIndex(i,function(t){return!e.isOmittedExpression(t)&&!_p(t)},i.length-(o?2:1))+1,o);return r&&((s=Ds(s)).pattern=t),s}(t,r,n)}function Bi(e,t){return ji(Fi(e,!0),e,t)}function ji(t,r,n){return t?(n&&i_(r,t),8192&t.flags&&(e.isBindingElement(r)||!r.type)&&t.symbol!==wn(r)&&(t=De),t_(t)):(t=e.isParameter(r)&&r.dotDotDotToken?tt:ie,n&&(Ji(r)||n_(r,t)),t)}function Ji(t){var r=e.getRootDeclaration(t);return vg(151===r.kind?r.parent:r)}function zi(t){var r=e.getEffectiveTypeAnnotationNode(t);if(r)return uu(r)}function Ki(t){var r=Kr(t);return r.type||(r.type=function(t){if(4194304&t.flags)return(r=ba(On(t))).typeParameters?bs(r,e.map(r.typeParameters,function(e){return ie})):r;var r;if(t===W)return ie;if(134217728&t.flags){var n=wn(e.getSourceFileOfNode(t.valueDeclaration)),i=e.createSymbolTable();return i.set("exports",n),Wn(t,i,e.emptyArray,e.emptyArray,void 0,void 0)}var a,o=t.valueDeclaration;if(e.isCatchClauseVariableDeclarationOrBindingElement(o))return ie;if(e.isSourceFile(o)){var s=e.cast(o,e.isJsonSourceFile);if(!s.statements.length)return Fe;var c=Il(tg(s.statements[0].expression));return 524288&c.flags?Xl(c):c}if(254===o.kind)return ji(Wm(o.expression),o);if(!gi(t,0))return se;if(e.isInJSFile(o)&&(e.isCallExpression(o)||e.isBinaryExpression(o)||e.isPropertyAccessExpression(o)&&e.isBinaryExpression(o.parent)))a=Pi(t);else if(e.isJSDocPropertyLikeTag(o)||e.isPropertyAccessExpression(o)||e.isIdentifier(o)||e.isClassDeclaration(o)||e.isFunctionDeclaration(o)||e.isMethodDeclaration(o)&&!e.isObjectLiteralMethod(o)||e.isMethodSignature(o)){if(9136&t.flags)return Gi(t);a=e.isBinaryExpression(o.parent)?Pi(t):zi(o)||ie}else if(e.isPropertyAssignment(o))a=zi(o)||Xm(o);else if(e.isJsxAttribute(o))a=zi(o)||Tp(o);else if(e.isShorthandPropertyAssignment(o))a=zi(o)||Ym(o.name,0);else if(e.isObjectLiteralMethod(o))a=zi(o)||Qm(o,0);else if(e.isParameter(o)||e.isPropertyDeclaration(o)||e.isPropertySignature(o)||e.isVariableDeclaration(o)||e.isBindingElement(o))a=Bi(o,!0);else if(e.isEnumDeclaration(o))a=Gi(t);else{if(!e.isEnumMember(o))return e.Debug.fail("Unhandled declaration kind! "+e.Debug.showSyntaxKind(o)+" for "+e.Debug.showSymbol(t));a=Yi(t)}return hi()||(a=Xi(t)),a}(t))}function Ui(t){if(t)return 158===t.kind?e.getEffectiveReturnTypeNode(t):e.getEffectiveSetAccessorTypeAnnotationNode(t)}function Vi(e){var t=Ui(e);return t&&uu(t)}function qi(e){return $o(Go(e))}function Wi(t){var r=Kr(t);return r.type||(r.type=function(t){var r,n=e.getDeclarationOfKind(t,158),i=e.getDeclarationOfKind(t,159);if(n&&e.isInJSFile(n)){var a=Ei(n);if(a)return a}if(!gi(t,0))return se;var o=Vi(n);if(o)r=o;else{var s=Vi(i);s?r=s:n&&n.body?r=vm(n):(i?Pr(R,i,e.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation,ai(t)):(e.Debug.assert(!!n,"there must existed getter as we are current checking either setter or getter in this function"),Pr(R,n,e.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation,ai(t))),r=ie)}if(!hi()&&(r=ie,R)){var c=e.getDeclarationOfKind(t,158);Fr(c,e.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions,ai(t))}return r}(t))}function Hi(e){var t=la(pa(e));return 8650752&t.flags?t:void 0}function Gi(t){var r=Kr(t),n=r;if(!r.type){var i=e.getDeclarationOfExpando(t.valueDeclaration);if(i){var a=wn(i);a&&(e.hasEntries(a.exports)||e.hasEntries(a.members))&&(r=t=Lr(t),e.hasEntries(a.exports)&&(t.exports=t.exports||e.createSymbolTable(),Jr(t.exports,a.exports)),e.hasEntries(a.members)&&(t.members=t.members||e.createSymbolTable(),Jr(t.members,a.members)))}n.type=r.type=function(t){var r=t.valueDeclaration;if(1536&t.flags&&e.isShorthandAmbientModuleSymbol(t))return ie;if(204===r.kind||189===r.kind&&204===r.parent.kind)return Pi(t);if(512&t.flags&&r&&e.isSourceFile(r)&&r.commonJsModuleIndicator){var n=xn(t);if(n!==t){if(!gi(t,0))return se;var i=Pn(t.exports.get("export=")),a=Pi(i,i===n?void 0:n);return hi()?a:Xi(t)}}var o=Kn(16,t);if(32&t.flags){var s=Hi(t);return s?xc([o,s]):o}return O&&16777216&t.flags?Wl(o):o}(t)}return r.type}function Yi(e){var t=Kr(e);return t.type||(t.type=va(e))}function Xi(t){return e.getEffectiveTypeAnnotationNode(t.valueDeclaration)?(Fr(t.valueDeclaration,e.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation,ai(t)),se):(R&&Fr(t.valueDeclaration,e.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer,ai(t)),ie)}function Qi(t){return 1&e.getCheckFlags(t)?function(e){var t=Kr(e);if(!t.type){if(!gi(e,0))return t.type=se;var r=Nu(Qi(t.target),t.mapper);hi()||(r=Xi(e)),t.type=r}return t.type}(t):2048&e.getCheckFlags(t)?function(e){return d_(e.propertyType,e.mappedType,e.constraintType)}(t):7&t.flags?Ki(t):9136&t.flags?Gi(t):8&t.flags?Yi(t):98304&t.flags?Wi(t):2097152&t.flags?function(e){var t=Kr(e);if(!t.type){var r=_n(e);t.type=67220415&r.flags?Qi(r):se}return t.type}(t):se}function $i(t,r){return void 0!==t&&void 0!==r&&0!=(4&e.getObjectFlags(t))&&t.target===r}function Zi(t){return 4&e.getObjectFlags(t)?t.target:t}function ea(t,r){return function t(n){if(7&e.getObjectFlags(n)){var i=Zi(n);return i===r||e.some(_a(i),t)}return!!(2097152&n.flags)&&e.some(n.types,t)}(t)}function ta(t,r){for(var n=0,i=r;n0)return!0;if(8650752&e.flags){var t=ho(e);return!!t&&da(t)&&aa(t)}return Vf(e)}function sa(t){return e.getEffectiveBaseTypeNode(t.symbol.valueDeclaration)}function ca(t,r,n){var i=e.length(r),a=e.isInJSFile(n);return e.filter(wo(t,1),function(t){return(a||i>=Wo(t.typeParameters))&&i<=e.length(t.typeParameters)})}function ua(t,r,n){var i=ca(t,r,n),a=e.map(r,uu);return e.sameMap(i,function(t){return e.some(t.typeParameters)?is(t,a,e.isInJSFile(n)):t})}function la(t){if(!t.resolvedBaseConstructorType){var r=t.symbol.valueDeclaration,n=e.getEffectiveBaseTypeNode(r),i=sa(t);if(!i)return t.resolvedBaseConstructorType=ue;if(!gi(t,1))return se;var a=tg(i.expression);if(n&&i!==n&&(e.Debug.assert(!n.typeArguments),tg(n.expression)),2621440&a.flags&&co(a),!hi())return Fr(t.symbol.valueDeclaration,e.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression,ai(t.symbol)),t.resolvedBaseConstructorType=se;if(!(1&a.flags||a===de||oa(a))){var o=Fr(i.expression,e.Diagnostics.Type_0_is_not_a_constructor_function_type,si(a));if(262144&a.flags){var s=gs(a),c=ce;if(s){var u=wo(s,1);u[0]&&(c=ts(u[0]))}Ar(o,e.createDiagnosticForNode(a.symbol.declarations[0],e.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1,ai(a.symbol),si(c)))}return t.resolvedBaseConstructorType=se}t.resolvedBaseConstructorType=a}return t.resolvedBaseConstructorType}function _a(t){return t.resolvedBaseTypes||(8&t.objectFlags?t.resolvedBaseTypes=[ic(gc(t.typeParameters||e.emptyArray))]:96&t.symbol.flags?(32&t.symbol.flags&&function(t){t.resolvedBaseTypes=e.resolvingEmptyArray;var r=ko(la(t));if(!(2621441&r.flags))return t.resolvedBaseTypes=e.emptyArray;var n,i=sa(t),a=Ls(i),o=Vf(r)?r:r.symbol?ba(r.symbol):void 0;if(r.symbol&&32&r.symbol.flags&&function(e){var t=e.outerTypeParameters;if(t){var r=t.length-1,n=e.typeArguments;return t[r].symbol!==n[r].symbol}return!0}(o))n=Ss(i,r.symbol,a);else if(1&r.flags)n=r;else if(Vf(r))n=!i.typeArguments&&qf(r.symbol)||ie;else{var s=ua(r,i.typeArguments,i);if(!s.length)return Fr(i.expression,e.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments),t.resolvedBaseTypes=e.emptyArray;n=ts(s[0])}n===se?t.resolvedBaseTypes=e.emptyArray:da(n)?t===n||ea(n,t)?(Fr(t.symbol.valueDeclaration,e.Diagnostics.Type_0_recursively_references_itself_as_a_base_type,si(t,void 0,2)),t.resolvedBaseTypes=e.emptyArray):(t.resolvedBaseTypes===e.resolvingEmptyArray&&(t.members=void 0),t.resolvedBaseTypes=[n]):(Fr(i.expression,e.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members,si(n)),t.resolvedBaseTypes=e.emptyArray)}(t),64&t.symbol.flags&&function(t){t.resolvedBaseTypes=t.resolvedBaseTypes||e.emptyArray;for(var r=0,n=t.symbol.declarations;r0)return;for(var i=1;i1){var u=o.thisParameter;if(e.forEach(s,function(e){return e.thisParameter})){var l=gc(e.map(s,function(e){return e.thisParameter?Qi(e.thisParameter):ie}),2);u=Yl(o.thisParameter,l)}(c=Ka(o)).thisParameter=u,c.unionSignatures=s}(r||(r=[])).push(c)}}}return r||e.emptyArray}function Wa(e,t){for(var r=[],n=!1,i=0,a=e;i0&&(l=e.map(l,function(e){var t=Ka(e);return t.resolvedReturnType=function(e,t,r){for(var n=[],i=0;i=_&&o<=d){var p=d?os(l,Ho(a,l.typeParameters,_,i)):Ka(l);p.typeParameters=t.localTypeParameters,p.resolvedReturnType=t,s.push(p)}}return s}(c)),t.constructSignatures=s}}}function $a(e){return e.typeParameter||(e.typeParameter=ha(wn(e.declaration.typeParameter)))}function Za(e){return e.constraintType||(e.constraintType=mo($a(e))||se)}function eo(e){return e.templateType||(e.templateType=e.declaration.type?Nu(Ai(uu(e.declaration.type),!!(4&io(e))),e.mapper||N):se)}function to(t){return e.getEffectiveConstraintOfTypeParameter(t.declaration.typeParameter)}function ro(e){var t=to(e);return 179===t.kind&&129===t.operator}function no(e){if(!e.modifiersType)if(ro(e))e.modifiersType=Nu(uu(to(e).type),e.mapper||N);else{var t=Za(jc(e.declaration)),r=t&&262144&t.flags?mo(t):t;e.modifiersType=r&&4194304&r.flags?Nu(r.type,e.mapper||N):Fe}return e.modifiersType}function io(e){var t=e.declaration;return(t.readonlyToken?39===t.readonlyToken.kind?2:1:0)|(t.questionToken?39===t.questionToken.kind?8:4:0)}function ao(e){var t=io(e);return 8&t?-1:4&t?1:0}function oo(e){var t=ao(e),r=no(e);return t||(so(r)?ao(r):0)}function so(t){return!!(32&e.getObjectFlags(t))&&Oc(Za(t))}function co(t){return t.members||(524288&t.flags?4&t.objectFlags?function(t){var r=Na(t.target),n=e.concatenate(r.typeParameters,[r.thisType]);Ja(t,r,n,t.typeArguments&&t.typeArguments.length===n.length?t.typeArguments:e.concatenate(t.typeArguments,[t]))}(t):3&t.objectFlags?function(t){Ja(t,Na(t),e.emptyArray,e.emptyArray)}(t):2048&t.objectFlags?function(t){for(var r=Mo(t.source,0),n=io(t.mappedType),i=!(1&n),a=4&n?0:16777216,o=r&&fs(d_(r.type,t.mappedType,t.constraintType),i&&r.isReadonly),s=e.createSymbolTable(),c=0,u=po(t.source);c=6))||Fe:528&r.flags?$e:12288&r.flags?Us(F>=2):67108864&r.flags?Fe:4194304&r.flags?Ne:r}function Eo(t,r){for(var n,i,a=1048576&t.flags,o=a?24:0,s=a?0:16777216,c=4,u=0,l=0,_=t.types;l<_.length;l++)if((T=ko(_[l]))!==se){var d=(S=Fo(T,r))?e.getDeclarationModifierFlagsFromSymbol(S):0;if(!S||d&o){if(a){var p=!Pa(r)&&(gp(r)&&Mo(T,1)||Mo(T,0));p?(u|=p.isReadonly?8:0,i=e.append(i,Rl(T)?Bl(T)||ue:p.type)):u|=16}}else s&=S.flags,n=e.appendIfUnique(n,S),u|=(Nm(S)?8:0)|(24&d?0:64)|(16&d?128:0)|(8&d?256:0)|(32&d?512:0),Jp(S)||(c=2)}if(n){if(!(1!==n.length||16&u||i))return n[0];for(var f,m,g,y,v=[],h=!0,b=!1,D=0,x=n;D=0),n>=cm(r)}var i=e.getImmediatelyInvokedFunctionExpression(t.parent);return!!i&&!t.type&&!t.dotDotDotToken&&t.parent.parameters.indexOf(t)>=i.arguments.length}function Uo(t){if(!e.isJSDocParameterTag(t))return!1;var r=t.isBracketed,n=t.typeExpression;return r||!!n&&288===n.type.kind}function Vo(e,t,r){return{kind:1,parameterName:e,parameterIndex:t,type:r}}function qo(e){return{kind:0,type:e}}function Wo(t){var r,n=0;if(t)for(var i=0;i=n&&o<=a){for(var s=t?t.slice():[],c=T_(i),u=fu(r,e.map(r,function(){return c})),l=o;lu.arguments.length&&!m||_||Jo(p)||(o=i.length)}if(!(158!==t.kind&&159!==t.kind||Oa(t)||c&&s)){var g=158===t.kind?159:158,y=e.getDeclarationOfKind(wn(t),g);y&&(s=(r=rh(y))&&r.symbol)}var v=157===t.kind?pa(Pn(t.parent.symbol)):void 0,h=v?v.localTypeParameters:Bo(t),b=e.hasRestParameter(t)||e.isInJSFile(t)&&function(t,r){if(e.isJSDocSignature(t)||!Xo(t))return!1;var n=e.lastOrUndefined(t.parameters),i=n?e.getJSDocParameterTags(n):e.getJSDocTags(t).filter(e.isJSDocParameterTag),a=e.firstDefined(i,function(t){return t.typeExpression&&e.isJSDocVariadicType(t.typeExpression.type)?t.typeExpression.type:void 0}),o=wr(3,"args",8192);return o.type=a?ic(uu(a.type)):tt,a&&r.pop(),r.push(o),!0}(t,i);n.resolvedSignature=za(t,h,s,i,void 0,void 0,o,b,a)}return n.resolvedSignature}function Yo(t){var r=e.isInJSFile(t)?e.getJSDocTypeTag(t):void 0,n=r&&r.typeExpression&&gf(uu(r.typeExpression));return n&&cs(n)}function Xo(t){var r=Ur(t);return void 0===r.containsArgumentsReference&&(8192&r.flags?r.containsArgumentsReference=!0:r.containsArgumentsReference=function t(r){if(!r)return!1;switch(r.kind){case 72:return"arguments"===r.escapedText&&e.isExpressionNode(r);case 154:case 156:case 158:case 159:return 149===r.name.kind&&t(r.name);default:return!e.nodeStartsNewLexicalEnvironment(r)&&!e.isPartOfTypeNode(r)&&!!e.forEachChild(r,t)}}(t.body)),r.containsArgumentsReference}function Qo(t){if(!t)return e.emptyArray;for(var r=[],n=0;n0&&i.body){var a=t.declarations[n-1];if(i.parent===a.parent&&i.kind===a.kind&&i.pos===a.end)continue}r.push(Go(i))}}return r}function $o(e){if(e.thisParameter)return Qi(e.thisParameter)}function Zo(e){return void 0!==es(e)}function es(t){if(!t.resolvedTypePredicate){if(t.target){var r=es(t.target);t.resolvedTypePredicate=r?(o=r,s=t.mapper,e.isIdentifierTypePredicate(o)?{kind:1,parameterName:o.parameterName,parameterIndex:o.parameterIndex,type:Nu(o.type,s)}:{kind:0,type:Nu(o.type,s)}):kt}else if(t.unionSignatures)t.resolvedTypePredicate=function(t){for(var r,n=[],i=0,a=t;i1&&(t+=":"+a),n+=a}return t}function hs(e,t){for(var r=0,n=0,i=e;na.length)){var u=c&&e.isExpressionWithTypeArguments(t)&&!e.isJSDocAugmentsTag(t.parent);if(Fr(t,s===a.length?u?e.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag:e.Diagnostics.Generic_type_0_requires_1_type_argument_s:u?e.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag:e.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments,si(i,void 0,2),s,a.length),!c)return se}return bs(i,e.concatenate(i.outerTypeParameters,Ho(n,a,s,c)))}return Is(t,r)?i:se}function Ts(t,r){var n=ba(t),i=Kr(t),a=i.typeParameters,o=vs(r),s=i.instantiations.get(o);return s||i.instantiations.set(o,s=Nu(n,fu(a,Ho(r,a,Wo(a),e.isInJSFile(t.valueDeclaration))))),s}function Cs(t){switch(t.kind){case 164:return t.typeName;case 211:var r=t.expression;if(e.isEntityNameExpression(r))return r}}function ks(e,t){return e&&gn(e,t)||re}function Es(t,r){var n=Ls(t);if(r===re)return se;var i=As(t,r,n);if(i)return i;var a=e.isInJSFile(t)&&r.valueDeclaration&&e.getJSDocEnumTag(r.valueDeclaration);if(a){var o=Ur(a);if(!gi(a,5))return se;var s=a.typeExpression?uu(a.typeExpression):se;return hi()||(s=se,Fr(t,e.Diagnostics.Enum_type_0_circularly_references_itself,ai(r))),o.resolvedEnumType=s}var c=Da(r);if(c)return Is(t,r)?262144&c.flags?ws(c,t):iu(c):se;if(!(67220415&r.flags&&Os(t)))return se;var u=Ns(t,r,n);return u||(ks(Cs(t),67897832),Qi(r))}function Ns(t,r,n){if(!gi(r,6))return se;var i=Wf(r),a=Qi(r),o=a.symbol&&a.symbol!==r&&!Gf(a)&&As(t,a.symbol,n);if(!hi())return Kr(r).resolvedJSDocType=se,Fr(t,e.Diagnostics.JSDoc_type_0_circularly_references_itself,ai(r)),se;if(o||i){var s=o&&i?xc([i,o]):o||i;return Kr(r).resolvedJSDocType=s}}function As(t,r,n){if(96&r.flags){if(r.valueDeclaration&&e.isBinaryExpression(r.valueDeclaration.parent)){var i=Ns(t,r,n);if(i)return i}return Ss(t,r,n)}return 524288&r.flags?function(t,r,n){var i=ba(r),a=Kr(r).typeParameters;if(a){var o=e.length(t.typeArguments),s=Wo(a);return oa.length?(Fr(t,s===a.length?e.Diagnostics.Generic_type_0_requires_1_type_argument_s:e.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments,ai(r),s,a.length),se):Ts(r,n)}return Is(t,r)?i:se}(t,r,n):16&r.flags&&Os(t)&&(r.members||e.getJSDocClassTag(r.valueDeclaration))?Hf(r):void 0}function Fs(e){return 170===e.kind&&1===e.elementTypes.length}function Ps(e,t,r){return Fs(t)&&Fs(r)?Ps(e,t.elementTypes[0],r.elementTypes[0]):Jc(uu(t))===e?uu(r):void 0}function ws(t,r){for(var n;r&&!e.isStatement(r)&&291!==r.kind;){var i=r.parent;if(175===i.kind&&r===i.trueType){var a=Ps(t,i.checkType,i.extendsType);a&&(n=e.append(n,a))}r=i}return n?function(e,t){var r=jn(33554432);return r.typeVariable=e,r.substitute=t,r}(t,xc(e.append(n,t))):t}function Os(e){return!!(2097152&e.flags)&&(164===e.kind||183===e.kind)}function Is(t,r){return!t.typeArguments||(Fr(t,e.Diagnostics.Type_0_is_not_generic,r?ai(r):t.typeName?e.declarationNameToString(t.typeName):"(anonymous)"),!1)}function Ms(t){var r=Ur(t);if(!r.resolvedType){var n=void 0,i=void 0,a=67897832;Os(t)&&(i=function(t){if(e.isIdentifier(t.typeName)){var r=t.typeArguments;switch(t.typeName.escapedText){case"String":return Is(t),pe;case"Number":return Is(t),fe;case"Boolean":return Is(t),be;case"Void":return Is(t),xe;case"Undefined":return Is(t),ue;case"Null":return Is(t),_e;case"Function":case"function":return Is(t),qe;case"Array":case"array":return r&&r.length?void 0:tt;case"Promise":case"promise":return r&&r.length?void 0:mm(ie);case"Object":if(r&&2===r.length){if(e.isJSDocIndexSignature(t)){var n=uu(r[0]),i=fs(uu(r[1]),!1);return Wn(void 0,E,e.emptyArray,e.emptyArray,n===pe?i:void 0,n===fe?i:void 0)}return ie}return Is(t),ie}}}(t),a|=67220415),i||(i=Es(t,n=ks(Cs(t),a))),r.resolvedSymbol=n,r.resolvedType=i}return r.resolvedType}function Ls(t){return e.map(t.typeArguments,uu)}function Rs(e){var t=Ur(e);return t.resolvedType||(t.resolvedType=iu(t_(tg(e.exprName)))),t.resolvedType}function Bs(t,r){function n(e){for(var t=0,r=e.declarations;t=r?16777216:0),""+c);l.type=u,o.push(l)}}}var _=[];for(c=r;c<=s;c++)_.push(ou(c));var d=wr(4,"length");d.type=n?fe:gc(_),o.push(d);var p=Kn(12);return p.typeParameters=a,p.outerTypeParameters=void 0,p.localTypeParameters=a,p.instantiations=e.createMap(),p.instantiations.set(vs(p.typeParameters),p),p.target=p,p.typeArguments=p.typeParameters,p.thisType=jn(262144),p.thisType.isThisType=!0,p.thisType.constraint=p,p.declaredProperties=o,p.declaredCallSignatures=e.emptyArray,p.declaredConstructSignatures=e.emptyArray,p.declaredStringIndexInfo=void 0,p.declaredNumberIndexInfo=void 0,p.minLength=r,p.hasRestElement=n,p.associatedNames=i,p}(t,r,n,i)),o}function sc(e,t,r,n){void 0===t&&(t=e.length),void 0===r&&(r=!1);var i=e.length;if(1===i&&r)return ic(e[0]);var a=oc(i,t,i>0&&r,n);return e.length?bs(a,e):a}function cc(t,r){var n=t.target;return n.hasRestElement&&(r=Math.min(r,xs(t)-1)),sc((t.typeArguments||e.emptyArray).slice(r),Math.max(0,n.minLength-r),n.hasRestElement,n.associatedNames&&n.associatedNames.slice(r))}function uc(e){return e.id}function lc(t,r){return e.binarySearch(t,r,uc,e.compareValues)>=0}function _c(t,r){var n=e.binarySearch(t,r,uc,e.compareValues);return n<0&&(t.splice(~n,0,r),!0)}function dc(t,r,n){var i=n.flags;if(1048576&i)return pc(t,r,n.types);if(!(131072&i||2097152&i&&function(e){for(var t=0,r=0,n=e.types;rt[a-1].id?~a:e.binarySearch(t,n,uc,e.compareValues);o<0&&t.splice(~o,0,n)}return r}function pc(e,t,r){for(var n=0,i=r;n0;)fc(t[--r],t)&&e.orderedRemoveItemAt(t,r)}function gc(t,r,n,i){if(void 0===r&&(r=1),0===t.length)return Se;if(1===t.length)return t[0];var a=[],o=pc(a,0,t);if(0!==r){if(3&o)return 1&o?268435456&o?oe:ie:ce;switch(r){case 1:8576&o|512&&function(t,r){for(var n=t.length;n>0;){var i=t[--n];(128&i.flags&&4&r||256&i.flags&&8&r||2048&i.flags&&64&r||8192&i.flags&&4096&r||au(i)&&lc(t,i.regularType))&&e.orderedRemoveItemAt(t,n)}}(a,o);break;case 2:mc(a)}if(0===a.length)return 65536&o?134217728&o?_e:de:32768&o?134217728&o?ue:le:Se}return vc(a,!(66994211&o),n,i)}function yc(t,r){return e.isIdentifierTypePredicate(t)?e.isIdentifierTypePredicate(r)&&t.parameterIndex===r.parameterIndex:!e.isIdentifierTypePredicate(r)}function vc(e,t,r,n){if(0===e.length)return Se;if(1===e.length)return e[0];var i=vs(e),a=X.get(i);return a||(a=jn(1048576|hs(e,98304)),X.set(i,a),a.types=e,a.primitiveTypesOnly=t,a.aliasSymbol=r,a.aliasTypeArguments=n),a}function hc(t,r,n){var i=n.flags;return 2097152&i?bc(t,r,n.types):(rl(n)?536870912&r||(r|=536870912,t.push(n)):(r|=-939524097&i,3&i?n===oe&&(r|=268435456):!O&&98304&i||e.contains(t,n)||t.push(n)),r)}function bc(e,t,r){for(var n=0,i=r;n0;){var i=t[--n];(4&i.flags&&128&r||8&i.flags&&256&r||64&i.flags&&2048&r||4096&i.flags&&8192&r)&&e.orderedRemoveItemAt(t,n)}}(i,a),536870912&a&&524288&a&&e.orderedRemoveItemAt(i,e.findIndex(i,rl)),0===i.length)return ce;if(1===i.length)return i[0];if(1048576&a){if(function(t){var r,n=e.findIndex(t,function(e){return!!(1048576&e.flags)&&e.primitiveTypesOnly});if(n<0)return!1;for(var i=n+1;i=0)return n&&id(t,function(e){return!e.target.hasRestElement})&&Fr(d=Pc(n),e.Diagnostics.Property_0_does_not_exist_on_type_1,e.unescapeLeadingUnderscores(s),si(t)),od(t,function(e){return Bl(e)||ue})}if(!(98304&r.flags)&&Im(r,12716)){if(131073&t.flags)return t;var l=Im(r,296)&&Mo(t,1)||Mo(t,0)||void 0;if(l)return n&&!Im(r,12)?Fr(d=Pc(n),e.Diagnostics.Type_0_cannot_be_used_as_an_index_type,si(r)):o&&l.isReadonly&&(e.isAssignmentTarget(o)||e.isDeleteTarget(o))&&Fr(o,e.Diagnostics.Index_signature_in_type_0_only_permits_reading,si(t)),l.type;if(131072&r.flags)return Se;if(Ac(t))return ie;if(o&&!Lm(t)){if(R&&!A.suppressImplicitAnyIndexErrors)if(void 0!==s&&Xp(s,t))Fr(o,e.Diagnostics.Property_0_is_a_static_member_of_type_1,s,si(t));else if(Lo(t,1))Fr(o.argumentExpression,e.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);else{var _=void 0;void 0!==s&&(_=$p(s,t))?void 0!==_&&Fr(o.argumentExpression,e.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2,s,si(t),_):Fr(o,e.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature,si(t))}return a}}if(Ac(t))return ie;if(n){var d=Pc(n);384&r.flags?Fr(d,e.Diagnostics.Property_0_does_not_exist_on_type_1,""+r.value,si(t)):12&r.flags?Fr(d,e.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1,si(t),si(r)):Fr(d,e.Diagnostics.Type_0_cannot_be_used_as_an_index_type,si(r))}return xi(r)?r:a}function Pc(e){return 190===e.kind?e.argumentExpression:180===e.kind?e.indexType:149===e.kind?e.expression:e}function wc(e){return Om(e,193200128)}function Oc(e){return Om(e,63176704)}function Ic(e){return 8388608&e.flags?function(e){if(e.simplified)return e.simplified===Re?e:e.simplified;e.simplified=Re;var t=Ic(e.objectType),r=Ic(e.indexType);if(1048576&r.flags)return e.simplified=od(r,function(e){return Ic(Rc(t,e))});if(!(63176704&r.flags)){var n=Mc(t,r);if(n)return e.simplified=n}if(so(t))return e.simplified=Lc(t,e);if(262144&t.flags){var i=mo(t);if(i&&so(i))return e.simplified=Lc(i,e)}return e.simplified=e}(e):e}function Mc(t,r){return 1048576&t.flags?od(t,function(e){return Ic(Rc(e,r))}):2097152&t.flags?xc(e.map(t.types,function(e){return Ic(Rc(e,r))})):void 0}function Lc(e,t){var r=fu([$a(e)],[t.indexType]),n=gu(e.mapper,r);return Nu(eo(e),n)}function Rc(e,t,r,n){if(void 0===n&&(n=r?se:ce),e===oe||t===oe)return oe;if(Oc(t)||(!r||180===r.kind)&&wc(e)){if(3&e.flags)return e;var i=e.id+","+t.id,a=Z.get(i);return a||Z.set(i,a=function(e,t){var r=jn(8388608);return r.objectType=e,r.indexType=t,r}(e,t)),a}var o=ko(e);if(1048576&t.flags&&!(16&t.flags)){for(var s=[],c=!1,u=0,l=t.types;u=i,n)}),o=io(r),s=4&o?0:8&o?xs(t)-(t.target.hasRestElement?1:0):i;return sc(a,s,t.target.hasRestElement,t.target.associatedNames)}(i,t,a):ku(t,a)}return i});return t.instantiating=!1,a}}return ku(t,r)}(n,g):ku(n,g),a.instantiations.set(f,m)}return m}return t}function Su(t,r){if(t.symbol&&t.symbol.declarations&&1===t.symbol.declarations.length){var n=t.symbol.declarations[0].parent;if(e.findAncestor(r,function(e){return 218===e.kind?"quit":e===n}))return!!e.forEachChild(r,function r(n){switch(n.kind){case 178:return!!t.isThisType;case 72:return!t.isThisType&&e.isPartOfTypeNode(n)&&function(e){return!(148===e.kind||164===e.parent.kind&&e.parent.typeArguments&&e===e.parent.typeName)}(n)&&uu(n)===t;case 167:return!0}return!!e.forEachChild(n,r)})}return!0}function Tu(e){var t=Za(e);if(4194304&t.flags){var r=t.type;if(262144&r.flags)return r}}function Cu(e,t,r,n){var i=gu(n,fu([$a(e)],[t])),a=Nu(eo(e.target||e),i),o=io(e);return O&&4&o&&!zu(ue,a)?Wl(a):O&&8&o&&r?z_(a,524288):a}function ku(e,t){var r=Kn(64|e.objectFlags,e.symbol);if(32&e.objectFlags){r.declaration=e.declaration;var n=$a(e),i=hu(n);r.typeParameter=i,t=gu(pu(n,i),t),i.mapper=t}return r.target=e,r.mapper=t,r.aliasSymbol=e.aliasSymbol,r.aliasTypeArguments=_u(e.aliasTypeArguments,t),r}function Eu(t,r){var n=t.root;if(n.outerTypeParameters){var i=e.map(n.outerTypeParameters,r),a=vs(i),o=n.instantiations.get(a);return o||(o=function(e,t){if(e.isDistributive){var r=e.checkType,n=t(r);if(r!==n&&1179648&n.flags)return od(n,function(n){return zc(e,yu(r,n,t))})}return zc(e,t)}(n,fu(n.outerTypeParameters,i)),n.instantiations.set(a,o)),o}return t}function Nu(e,t){if(!e||!t||t===N)return e;if(50===C)return se;C++;var r=function(e,t){var r=e.flags;if(262144&r)return t(e);if(524288&r){var n=e.objectFlags;if(16&n)return e.symbol&&14384&e.symbol.flags&&e.symbol.declarations?xu(e,t):e;if(32&n)return xu(e,t);if(4&n){var i=e.typeArguments,a=_u(i,t);return a!==i?bs(e.target,a):e}return e}if(1048576&r&&!(131068&r)){var o=e.types,s=_u(o,t);return s!==o?gc(s,1,e.aliasSymbol,_u(e.aliasTypeArguments,t)):e}if(2097152&r){var o=e.types,s=_u(o,t);return s!==o?xc(s,e.aliasSymbol,_u(e.aliasTypeArguments,t)):e}return 4194304&r?Ec(Nu(e.type,t)):8388608&r?Rc(Nu(e.objectType,t),Nu(e.indexType,t)):16777216&r?Eu(e,gu(e.mapper,t)):33554432&r?Nu(e.typeVariable,t):e}(e,t);return C--,r}function Au(e){return 262143&e.flags?e:e.wildcardInstantiation||(e.wildcardInstantiation=Nu(e,vu))}function Fu(e,t){return e&&fs(Nu(e.type,t),e.isReadonly,e.declaration)}function Pu(t){switch(e.Debug.assert(156!==t.kind||e.isObjectLiteralMethod(t)),t.kind){case 196:case 197:case 156:return wu(t);case 188:return e.some(t.properties,Pu);case 187:return e.some(t.elements,Pu);case 205:return Pu(t.whenTrue)||Pu(t.whenFalse);case 204:return 55===t.operatorToken.kind&&(Pu(t.left)||Pu(t.right));case 275:return Pu(t.initializer);case 195:return Pu(t.expression);case 268:return e.some(t.properties,Pu)||e.isJsxOpeningElement(t.parent)&&e.some(t.parent.parent.children,Pu);case 267:var r=t.initializer;return!!r&&Pu(r);case 270:var n=t.expression;return!!n&&Pu(n)}return!1}function wu(t){if(t.typeParameters)return!1;if(e.some(t.parameters,function(t){return!e.getEffectiveTypeAnnotationNode(t)}))return!0;if(197!==t.kind){var r=e.firstOrUndefined(t.parameters);if(!r||!e.parameterIsThisKeyword(r))return!0}return Ou(t)}function Ou(e){var t=e.body;return 218!==t.kind&&Pu(t)}function Iu(t){return(e.isInJSFile(t)&&e.isFunctionDeclaration(t)||sp(t)||e.isObjectLiteralMethod(t))&&wu(t)}function Mu(t){if(524288&t.flags){var r=co(t);if(r.constructSignatures.length||r.callSignatures.length){var n=Kn(16,t.symbol);return n.members=r.members,n.properties=r.properties,n.callSignatures=e.emptyArray,n.constructSignatures=e.emptyArray,n}}else if(2097152&t.flags)return xc(e.map(t.types,Mu));return t}function Lu(e,t){return al(e,t,Tr)}function Ru(e,t){return al(e,t,Tr)?-1:0}function Bu(e,t){return al(e,t,Dr)?-1:0}function ju(e,t){return al(e,t,br)?-1:0}function Ju(e,t){return al(e,t,br)}function zu(e,t){return al(e,t,Dr)}function Ku(t,r){return 1048576&t.flags?e.every(t.types,function(e){return Ku(e,r)}):1048576&r.flags?e.some(r.types,function(e){return Ku(t,e)}):58982400&t.flags?Ku(ho(t)||Fe,r):r===Ve?!!(67633152&t.flags):r===qe?!!(524288&t.flags)&&j_(t):ea(t,Zi(r))}function Uu(e,t){return al(e,t,Sr)}function Vu(e,t){return Uu(e,t)||Uu(t,e)}function qu(e,t,r,n,i,a){return sl(e,t,Dr,r,n,i,a)}function Wu(e,t,r,n,i,a){return Hu(e,t,Dr,r,n,i,a)}function Hu(e,t,r,n,i,a,o){return!!al(e,t,r)||(!n||!Yu(i,e,t,r,a))&&sl(e,t,r,n,a,o)}function Gu(t){return!!(16777216&t.flags||2097152&t.flags&&e.some(t.types,Gu))}function Yu(t,r,n,i,o){if(!t||Gu(n))return!1;if(!sl(r,n,i,void 0)&&function(t,r,n,i,a){for(var o=wo(r,0),s=wo(r,1),c=0,u=[s,o];cc)return 0;t.typeParameters&&t.typeParameters!==r.typeParameters&&(t=yf(t,r=us(r),void 0,s));var u=sm(t),l=_m(t),_=_m(r);if(l&&_&&u!==c)return 0;var d=r.declaration?r.declaration.kind:0,p=!n&&I&&156!==d&&155!==d&&157!==d,f=-1,m=$o(t);if(m&&m!==xe){var g=$o(r);if(g){if(!(b=!p&&s(m,g,!1)||s(g,m,a)))return a&&o(e.Diagnostics.The_this_types_of_each_signature_are_incompatible),0;f&=b}}for(var y=l||_?Math.min(u,c):Math.max(u,c),v=l||_?y-1:-1,h=0;h0||cv(r))&&!function(e,t,r){for(var n=0,i=po(e);n0&&N(ts(p[0]),n,!1)||m.length>0&&N(ts(m[0]),n,!1)?k(e.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it,si(r),si(n)):k(e.Diagnostics.Type_0_has_no_properties_in_common_with_type_1,si(r),si(n))}return 0}var g=0,y=u,v=!!c;if(1048576&r.flags?g=i===Sr?O(r,n,o&&!(131068&r.flags)):function(e,t,r){for(var n=-1,i=0,a=e.types;i0||wo(t,n=1).length>0)return e.find(r.types,function(e){return wo(e,n).length>0})}(t,r)||function(t,r){for(var n,i=0,a=0,o=r.types;a=i&&(n=s,i=u)}else!(131072&c.flags)&&1>=i&&(n=s,i=1)}return n}(t,r)||i[i.length-1],!0),0}function w(t,r){if(1048576&r.flags){var n=uo(t);if(n){var i=function(e,t){for(var r,n=0,i=e;n5?k(e.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more,si(t),si(r),e.map(_.slice(0,4),function(e){return ai(e)}).join(", "),_.length-4):k(e.Diagnostics.Type_0_is_missing_the_following_properties_from_type_1_Colon_2,si(t),si(r),e.map(_,function(e){return ai(e)}).join(", "))}return 0}if(b_(r))for(var p=0,f=po(t);p0&&e.every(r.properties,function(e){return!!(16777216&e.flags)})}return!!(2097152&t.flags)&&e.every(t.types,ul)}function ll(t,r,n){var i=bs(t,e.map(t.typeParameters,function(e){return e===r?n:e}));return i.objectFlags|=8192,i}function _l(t,r,n){void 0===t&&(t=e.emptyArray);var i=r.variances;if(!i){r.variances=e.emptyArray,i=[];for(var a=0,o=t;a":n+="-"+o.id}return n}function gl(e,t,r){if(r===Tr&&e.id>t.id){var n=e;e=t,t=n}if(fl(e)&&fl(t)){var i=[];return ml(e,i)+","+ml(t,i)}return e.id+","+t.id}function yl(t,r){if(!(6&e.getCheckFlags(t)))return r(t);for(var n=0,i=t.containingType.types;n=5&&524288&e.flags){var n=e.symbol;if(n)for(var i=0,a=0;a=5)return!0}}return!1}function Dl(t,r,n){if(t===r)return-1;var i=24&e.getDeclarationModifierFlagsFromSymbol(t);if(i!==(24&e.getDeclarationModifierFlagsFromSymbol(r)))return 0;if(i){if(Ey(t)!==Ey(r))return 0}else if((16777216&t.flags)!=(16777216&r.flags))return 0;return Nm(t)!==Nm(r)?0:n(Qi(t),Qi(r))}function xl(t,r,n,i,a,o){if(t===r)return-1;if(!function(e,t,r){var n=sm(e),i=sm(t),a=cm(e),o=cm(t),s=um(e),c=um(t);return n===i&&a===o&&s===c||!!(r&&a<=o)}(t,r,n))return 0;if(e.length(t.typeParameters)!==e.length(r.typeParameters))return 0;t=cs(t),r=cs(r);var s=-1;if(!i){var c=$o(t);if(c){var u=$o(r);if(u){if(!(d=o(c,u)))return 0;s&=d}}}for(var l=sm(r),_=0;_-1&&(Hr(a,a.name.escapedText,67897832,void 0,a.name.escapedText,!0)||a.name.originalKeywordKind&&e.isTypeNodeKind(a.name.originalKeywordKind))){var o="arg"+a.parent.parameters.indexOf(a);return void Pr(R,t,e.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1,o,e.declarationNameToString(a.name))}i=t.dotDotDotToken?R?e.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type:e.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage:R?e.Diagnostics.Parameter_0_implicitly_has_an_1_type:e.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;break;case 186:i=e.Diagnostics.Binding_element_0_implicitly_has_an_1_type;break;case 289:return void Fr(t,e.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type,n);case 239:case 156:case 155:case 158:case 159:case 196:case 197:if(R&&!t.name)return void Fr(t,e.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type,n);i=R?e.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type:e.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage;break;case 181:return void(R&&Fr(t,e.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type));default:i=R?e.Diagnostics.Variable_0_implicitly_has_an_1_type:e.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage}Pr(R,t,i,e.declarationNameToString(e.getNameOfDeclaration(t)),n)}}function i_(t,r){o&&R&&134217728&r.flags&&(function t(r){var n=!1;if(134217728&r.flags){if(1048576&r.flags)if(e.some(r.types,tl))n=!0;else for(var i=0,a=r.types;ie.target.minLength||!Bl(t)&&(!!Bl(e)||jl(t)1){var r=e.filter(t,b_);if(r.length){var n=t_(gc(r,2));return e.concatenate(e.filter(t,function(e){return!b_(e)}),[n])}}return t}(t.candidates),o=(n=t.typeParameter,!!(i=mo(n))&&Om(16777216&i.flags?go(i):i,4325372)),s=!o&&t.topLevel&&(t.isFixed||!l_(ts(r),t.typeParameter)),c=o?e.sameMap(a,iu):s?e.sameMap(a,Il):a;return t_(28&t.priority?gc(c,2):function(t){if(!O)return Sl(t);var r=e.filter(t,function(e){return!(98304&e.flags)});return r.length?ql(Sl(r),98304&zl(t)):gc(t,2)}(c))}function S_(e,t){var r=e.inferences[t],n=r.inferredType;if(!n){var i=e.signature;if(i){var a=r.candidates?x_(r,i):void 0;if(r.contraCandidates){var o=D_(r);n=!a||131072&a.flags||!Ju(a,o)?o:a}else if(a)n=a;else if(1&e.flags)n=Te;else{var s=To(r.typeParameter);n=s?Nu(s,gu(function(e,t){return function(r){return e.indexOf(r)>=t?Fe:r}}(e.signature.typeParameters,t),e)):T_(!!(2&e.flags))}}else n=g_(r);r.inferredType=n;var c=mo(r.typeParameter);if(c){var u=Nu(c,e);e.compareTypes(n,ja(u,n))||(r.inferredType=n=u)}}return n}function T_(e){return e?ie:Fe}function C_(e){for(var t=[],r=0;r=n&&c-1){var l=a.filter(function(e){return void 0!==e}),_=c=2||0==(34&r.flags)||274===r.valueDeclaration.parent.kind)){for(var n=e.getEnclosingBlockScopeContainer(r.valueDeclaration),i=function(t,r){return!!e.findAncestor(t,function(t){return t===r?"quit":e.isFunctionLike(t)})}(t.parent,n),a=n,o=!1;a&&!e.nodeStartsNewLexicalEnvironment(a);){if(e.isIterationStatement(a,!1)){o=!0;break}a=a.parent}if(o){if(i){var s=!0;if(e.isForStatement(n)&&e.getAncestor(r.valueDeclaration,238).parent===n){var c=function(t,r){return e.findAncestor(t,function(e){return e===r?"quit":e===r.initializer||e===r.condition||e===r.incrementor||e===r.statement})}(t.parent,n);if(c){var u=Ur(c);u.flags|=131072;var l=u.capturedBlockScopeBindings||(u.capturedBlockScopeBindings=[]);e.pushIfUnique(l,r),c===n.initializer&&(s=!1)}}s&&(Ur(a).flags|=65536)}225===n.kind&&e.getAncestor(r.valueDeclaration,238).parent===n&&function(t,r){for(var n=t;195===n.parent.kind;)n=n.parent;var i=!1;if(e.isAssignmentTarget(n))i=!0;else if(202===n.parent.kind||203===n.parent.kind){var a=n.parent;i=44===a.operator||45===a.operator}return!!i&&!!e.findAncestor(n,function(e){return e===r?"quit":e===r.statement})}(t,n)&&(Ur(r.valueDeclaration).flags|=4194304),Ur(r.valueDeclaration).flags|=524288}i&&(Ur(r.valueDeclaration).flags|=262144)}}(t,r);var o=Ed(Qi(i),t),s=e.getAssignmentTargetKind(t);if(s){if(!(3&i.flags||e.isInJSFile(t)&&512&i.flags))return Fr(t,e.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable,ai(r)),se;if(Nm(i))return 3&i.flags?Fr(t,e.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant,ai(r)):Fr(t,e.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property,ai(r)),se}var c=2097152&i.flags;if(3&i.flags){if(1===s)return o}else{if(!c)return o;a=e.find(r.declarations,p)}if(!a)return o;for(var u=151===e.getRootDeclaration(a).kind,l=Dd(a),_=Dd(t),d=_!==l,f=t.parent&&t.parent.parent&&e.isSpreadAssignment(t.parent)&&W_(t.parent.parent),m=134217728&r.flags;_!==l&&(196===_.kind||197===_.kind||e.isObjectLiteralOrClassExpressionMethod(_))&&(Td(i)||u&&!xd(i));)_=Dd(_);var g=u||c||d||f||m||o!==ae&&o!==rt&&(!O||0!=(3&o.flags)||N_(t)||257===t.parent.kind)||213===t.parent.kind||237===a.kind&&a.exclamationToken||4194304&a.flags,y=bd(t,o,g?u?function(e,t){return O&&151===t.kind&&t.initializer&&32768&Kl(e)&&!(32768&Kl(tg(t.initializer)))?z_(e,524288):e}(o,a):o:o===ae||o===rt?ue:Wl(o),_,!g);if(vd(t)||o!==ae&&o!==rt){if(!g&&!(32768&Kl(o))&&32768&Kl(y))return Fr(t,e.Diagnostics.Variable_0_is_used_before_being_assigned,ai(r)),o}else if(y===ae||y===rt)return R&&(Fr(e.getNameOfDeclaration(a),e.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined,ai(r),si(y)),Fr(t,e.Diagnostics.Variable_0_implicitly_has_an_1_type,ai(r),si(y))),ty(y);return s?Ol(y):y}function Fd(e,t){Ur(e).flags|=2,154===t.kind||157===t.kind?Ur(t.parent).flags|=4:Ur(t).flags|=4}function Pd(t){return e.isSuperCall(t)?t:e.isFunctionLike(t)?void 0:e.forEachChild(t,Pd)}function wd(e){var t=Ur(e);return void 0===t.hasSuperCall&&(t.superCall=Pd(e.body),t.hasSuperCall=!!t.superCall),t.superCall}function Od(e){return la(ba(wn(e)))===de}function Id(t,r,n){var i=r.parent;if(e.getEffectiveBaseTypeNode(i)&&!Od(i)){var a=wd(r);(!a||a.end>t.pos)&&Fr(t,n)}}function Md(t){var r=e.getThisContainer(t,!0),n=!1;switch(157===r.kind&&Id(t,r,e.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class),197===r.kind&&(r=e.getThisContainer(r,!1),n=!0),r.kind){case 244:Fr(t,e.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);break;case 243:Fr(t,e.Diagnostics.this_cannot_be_referenced_in_current_location);break;case 157:Rd(t,r)&&Fr(t,e.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);break;case 154:case 153:e.hasModifier(r,32)&&Fr(t,e.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);break;case 149:Fr(t,e.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name)}n&&F<2&&Fd(t,r);var i=Ld(t,r);if(!i&&B){var a=Fr(t,n&&279===r.kind?e.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any:e.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);e.isSourceFile(r)||Ld(r)&&Ar(a,e.createDiagnosticForNode(r,e.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container))}return i||ie}function Ld(t,r){void 0===r&&(r=e.getThisContainer(t,!1));var n=e.isInJSFile(t);if(e.isFunctionLike(r)&&(!Ud(t)||e.getThisParameter(r))){var i=function(t){return 196===t.kind&&e.isBinaryExpression(t.parent)&&3===e.getAssignmentDeclarationKind(t.parent)?t.parent.left.expression.expression:156===t.kind&&188===t.parent.kind&&e.isBinaryExpression(t.parent.parent)&&6===e.getAssignmentDeclarationKind(t.parent.parent)?t.parent.parent.left.expression:196===t.kind&&275===t.parent.kind&&188===t.parent.parent.kind&&e.isBinaryExpression(t.parent.parent.parent)&&6===e.getAssignmentDeclarationKind(t.parent.parent.parent)?t.parent.parent.parent.left.expression:196===t.kind&&e.isPropertyAssignment(t.parent)&&e.isIdentifier(t.parent.name)&&("value"===t.parent.name.escapedText||"get"===t.parent.name.escapedText||"set"===t.parent.name.escapedText)&&e.isObjectLiteralExpression(t.parent.parent)&&e.isCallExpression(t.parent.parent.parent)&&t.parent.parent.parent.arguments[2]===t.parent.parent&&9===e.getAssignmentDeclarationKind(t.parent.parent.parent)?t.parent.parent.parent.arguments[0].expression:e.isMethodDeclaration(t)&&e.isIdentifier(t.name)&&("value"===t.name.escapedText||"get"===t.name.escapedText||"set"===t.name.escapedText)&&e.isObjectLiteralExpression(t.parent)&&e.isCallExpression(t.parent.parent)&&t.parent.parent.arguments[2]===t.parent&&9===e.getAssignmentDeclarationKind(t.parent.parent)?t.parent.parent.arguments[0].expression:void 0}(r);if(n&&i){var a=tg(i).symbol;if(a&&a.members&&16&a.flags&&(o=qf(a)))return bd(t,o)}else if(n&&(196===r.kind||239===r.kind)&&e.getJSDocClassTag(r)){var o;if(o=qf(r.symbol))return bd(t,o)}var s=qi(r)||zd(r);if(s)return bd(t,s)}if(e.isClassLike(r.parent)){var c,u=wn(r.parent);return bd(t,c=e.hasModifier(r,32)?Qi(u):ba(u).thisType)}if(n&&(c=function(t){var r=e.getJSDocType(t);if(r&&289===r.kind){var n=r;if(n.parameters.length>0&&n.parameters[0].name&&"this"===n.parameters[0].name.escapedText)return uu(n.parameters[0].type)}var i=e.getJSDocThisTag(t);if(i&&i.typeExpression)return uu(i.typeExpression)}(r))&&c!==se)return bd(t,c)}function Rd(t,r){return!!e.findAncestor(t,function(e){return e===r?"quit":151===e.kind})}function Bd(t){var r=191===t.parent.kind&&t.parent.expression===t,n=e.getSuperContainer(t,!0),i=!1;if(!r)for(;n&&197===n.kind;)n=e.getSuperContainer(n,!0),i=F<2;var a=0;if(!function(t){return!!t&&(r?157===t.kind:!(!e.isClassLike(t.parent)&&188!==t.parent.kind)&&(e.hasModifier(t,32)?156===t.kind||155===t.kind||158===t.kind||159===t.kind:156===t.kind||155===t.kind||158===t.kind||159===t.kind||154===t.kind||153===t.kind||157===t.kind))}(n)){var o=e.findAncestor(t,function(e){return e===n?"quit":149===e.kind});return o&&149===o.kind?Fr(t,e.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name):r?Fr(t,e.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors):n&&n.parent&&(e.isClassLike(n.parent)||188===n.parent.kind)?Fr(t,e.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class):Fr(t,e.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions),se}if(r||157!==n.kind||Id(t,n,e.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class),a=e.hasModifier(n,32)||r?512:256,Ur(t).flags|=a,156===n.kind&&e.hasModifier(n,256)&&(e.isSuperProperty(t.parent)&&e.isAssignmentTarget(t.parent)?Ur(n).flags|=4096:Ur(n).flags|=2048),i&&Fd(t.parent,n),188===n.parent.kind)return F<2?(Fr(t,e.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher),se):ie;var s=n.parent;if(!e.getEffectiveBaseTypeNode(s))return Fr(t,e.Diagnostics.super_can_only_be_referenced_in_a_derived_class),se;var c=ba(wn(s)),u=c&&_a(c)[0];return u?157===n.kind&&Rd(t,n)?(Fr(t,e.Diagnostics.super_cannot_be_referenced_in_constructor_arguments),se):512===a?la(c):ja(u,c.thisType):se}function jd(t){return 4&e.getObjectFlags(t)&&t.target===et?t.typeArguments[0]:void 0}function Jd(t){return od(t,function(t){return 2097152&t.flags?e.forEach(t.types,jd):jd(t)})}function zd(t){if(197!==t.kind){if(Iu(t)){var r=lp(t);if(r){var n=r.thisParameter;if(n)return Qi(n)}}var i=e.isInJSFile(t);if(B||i){var a=function(e){return 156!==e.kind&&158!==e.kind&&159!==e.kind||188!==e.parent.kind?196===e.kind&&275===e.parent.kind?e.parent.parent:void 0:e.parent}(t);if(a){for(var o=tp(a),s=a,c=o;c;){var u=Jd(c);if(u)return Nu(u,np(a));if(275!==s.parent.kind)break;c=tp(s=s.parent.parent)}return o?Hl(o):Wm(a)}var l=t.parent;if(204===l.kind&&59===l.operatorToken.kind){var _=l.left;if(189===_.kind||190===_.kind){var d=_.expression;if(i&&e.isIdentifier(d)){var p=e.getSourceFileOfNode(l);if(p.commonJsModuleIndicator&&E_(d)===p.symbol)return}return Wm(d)}}}}}function Kd(t){var r=t.parent;if(Iu(r)){var n=e.getImmediatelyInvokedFunctionExpression(r);if(n&&n.arguments){var i=Cf(n),a=r.parameters.indexOf(t);if(t.dotDotDotToken)return hf(i,a,i.length,ie,void 0);var o=Ur(n),s=o.resolvedSignature;o.resolvedSignature=Et;var c=a=0}(r)?ts(r):void 0}function qd(e,t){var r=Cf(e).indexOf(t);return-1===r?void 0:Wd(e,r)}function Wd(t,r){var n=Ur(t).resolvedSignature===At?At:Kf(t);return e.isJsxOpeningLikeElement(t)&&0===r?ip(n,t):im(n,r)}function Hd(t){var r=t.parent,n=r.left,i=r.operatorToken,a=r.right;switch(i.kind){case 59:if(t!==a)return;var o=function(t){var r=e.getAssignmentDeclarationKind(t);switch(r){case 0:return!0;case 5:case 1:case 6:case 3:if(t.left.symbol){var n=t.left.symbol.valueDeclaration;if(!n)return!1;var i=t.left,a=e.getEffectiveTypeAnnotationNode(n);if(a)return uu(a);if(e.isIdentifier(i.expression)){var o=i.expression,s=Hr(o,o.escapedText,67220415,void 0,o.escapedText,!0);if(s){var c=e.getEffectiveTypeAnnotationNode(s.valueDeclaration);if(c){var u=Gd(uu(c),i.name.escapedText);return u||!1}return!1}}return!e.isInJSFile(n)}return!0;case 2:case 4:if(!t.symbol)return!0;if(t.symbol.valueDeclaration){var c=e.getEffectiveTypeAnnotationNode(t.symbol.valueDeclaration);if(c){var u=uu(c);if(u)return u}}if(2===r)return!1;var l=t.left;if(!e.isObjectLiteralMethod(e.getThisContainer(l.expression,!1)))return!1;var _=Md(l.expression);return _&&Gd(_,l.name.escapedText)||!1;case 7:case 8:case 9:return e.Debug.fail("Does not apply");default:return e.Debug.assertNever(r)}}(r);if(!o)return;return!0===o?Zm(n):o;case 55:var s=rp(r);return s||t!==a||e.isDefaultedExpandoInitializer(r)?s:Zm(n);case 54:case 27:return t===a?rp(r):void 0;default:return}}function Gd(e,t){return od(e,function(e){if(3670016&e.flags){var r=Fo(e,t);if(r)return Qi(r);if(Rl(e)){var n=Bl(e);if(n&&gp(t)&&+t>=0)return n}return gp(t)&&Yd(e,1)||Yd(e,0)}},!0)}function Yd(e,t){return od(e,function(e){return Io(e,t)},!0)}function Xd(e){var t=tp(e.parent);if(t){if(!Oa(e)){var r=Gd(t,wn(e).escapedName);if(r)return r}return fp(e.name)&&Yd(t,1)||Yd(t,0)}}function Qd(e,t){return e&&(Gd(e,""+t)||py(e,void 0,!1,!1,!1))}function $d(t){var r=t.parent;return e.isJsxAttributeLike(r)?rp(t):e.isJsxElement(r)?function(e){var t=tp(e.openingElement.tagName),r=Pp(Ap(e));return t&&!xi(t)&&r&&""!==r?Gd(t,r):void 0}(r):void 0}function Zd(t){if(e.isJsxAttribute(t)){var r=tp(t.parent);if(!r||xi(r))return;return Gd(r,t.name.escapedText)}return rp(t.parent)}function ep(e){switch(e.kind){case 10:case 8:case 9:case 14:case 102:case 87:case 96:case 72:case 141:return!0;case 189:case 195:return ep(e.expression);case 270:return!e.expression||ep(e.expression)}return!1}function tp(t){var r=rp(t);if((r=r&&od(r,ko))&&1048576&r.flags){if(e.isObjectLiteralExpression(t))return function(t,r){return cl(r,e.map(e.filter(t.properties,function(e){return!!e.symbol&&275===e.kind&&ep(e.initializer)&&M_(r,e.symbol.escapedName)}),function(e){return[function(){return tg(e.initializer)},e.symbol.escapedName]}),zu,r)}(t,r);if(e.isJsxAttributes(t))return function(t,r){return cl(r,e.map(e.filter(t.properties,function(e){return!!e.symbol&&267===e.kind&&M_(r,e.symbol.escapedName)&&(!e.initializer||ep(e.initializer))}),function(e){return[e.initializer?function(){return tg(e.initializer)}:function(){return ve},e.symbol.escapedName]}),zu,r)}(t,r)}return r}function rp(t){if(!(8388608&t.flags)){if(t.contextualType)return t.contextualType;var r=t.parent;switch(r.kind){case 237:case 151:case 154:case 153:case 186:return function(t){var r=t.parent;if(e.hasInitializer(r)&&t===r.initializer){var n=e.getEffectiveTypeAnnotationNode(r);if(n)return uu(n);if(151===r.kind){var i=Kd(r);if(i)return i}if(e.isBindingPattern(r.name))return Ri(r.name,!0,!1);if(e.isBindingPattern(r.parent)){var a=r.parent.parent,o=r.propertyName||r.name;if(186!==a.kind){var s=e.getEffectiveTypeAnnotationNode(a);if(s&&!e.isBindingPattern(o)){var c=e.getTextOfPropertyName(o);if(c)return Di(uu(s),c)}}}}}(t);case 197:case 230:return function(t){var r=e.getContainingFunction(t);if(r){var n=e.getFunctionFlags(r);if(1&n)return;var i=Vd(r);if(i){if(2&n){var a=xg(i);return a&&gc([a,gm(a)])}return i}}}(t);case 207:return function(t){var r=e.getContainingFunction(t);if(r){var n=e.getFunctionFlags(r),i=Vd(r);if(i)return t.asteriskToken?i:yy(i,0!=(2&n))}}(r);case 201:return function(e){var t=rp(e);if(t){var r=Cg(t);return r&&gc([r,gm(r)])}}(r);case 191:case 192:return qd(r,t);case 194:case 212:return uu(r.type);case 204:return Hd(t);case 275:case 276:return Xd(r);case 277:return tp(r.parent);case 187:var n=r;return Qd(tp(n),e.indexOfNode(n.elements,t));case 205:return function(e){var t=e.parent;return e===t.whenTrue||e===t.whenFalse?rp(t):void 0}(t);case 216:return e.Debug.assert(206===r.parent.kind),function(e,t){if(193===e.parent.kind)return qd(e.parent,t)}(r.parent,t);case 195:var i=e.isInJSFile(r)?e.getJSDocTypeTag(r):void 0;return i?uu(i.typeExpression.type):rp(r);case 270:return $d(r);case 267:case 269:return Zd(r);case 262:case 261:return function(t){return e.isJsxOpeningElement(t)&&t.parent.contextualType?t.parent.contextualType:Wd(t,0)}(r)}}}function np(t){var r=e.findAncestor(t,function(e){return!!e.contextualMapper});return r?r.contextualMapper:N}function ip(r,n){return 0!==Df(n)?function(e,r){var n=pm(e,Fe);n=ap(r,Ap(r),n);var i=Ep(t.IntrinsicAttributes,r);return i!==se&&(n=Ha(i,n)),n}(r,n):function(r,n){var i,a=Ap(n),o=(i=a,Fp(t.ElementAttributesPropertyNameContainer,i)),s=void 0===o?pm(r,Fe):""===o?ts(r):function(e,t){var r=ts(e);return xi(r)?r:Di(r,t)}(r,o);if(!s)return o&&e.length(n.attributes.properties)&&Fr(n,e.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property,e.unescapeLeadingUnderscores(o)),Fe;if(xi(s=ap(n,a,s)))return s;var c=s,u=Ep(t.IntrinsicClassAttributes,n);if(u!==se){var l=ia(u.symbol),_=ts(r);c=Ha(l?bs(u,Ho([_],l,Wo(l),e.isInJSFile(n))):u,c)}var d=Ep(t.IntrinsicAttributes,n);return d!==se&&(c=Ha(d,c)),c}(r,n)}function ap(r,n,i){var a,o=(a=n)&&qr(a.exports,t.LibraryManagedAttributes,67897832);if(o){var s=ba(o),c=function(e){if(Sp(e.tagName))return _s(jf(e,t=Op(e)));var t,r=Wm(e.tagName);return 128&r.flags?(t=wp(r,e))?_s(jf(e,t)):se:r}(r);if(e.length(s.typeParameters)>=2)return bs(s,u=Ho([c,i],s.typeParameters,2,e.isInJSFile(r)));if(e.length(s.aliasTypeArguments)>=2){var u=Ho([c,i],s.aliasTypeArguments,2,e.isInJSFile(r));return Ts(s.aliasSymbol,u)}}return i}function op(t,r){var n=wo(t,0);if(1===n.length){var i=n[0];if(!function(t,r){for(var n=0;n0&&208===i[a-1].kind,g=a-(m?1:0),y=void 0;if(c&&g>0)return(f=Ds(sc(s,g,m))).pattern=t,f;if(y=pp(s,u,m,a))return y;if(n)return sc(s,g,m)}return function(e,t){return void 0===t&&(t=1),ic(e.length?gc(e,t):O?Ce:le)}(s,2)}function pp(t,r,n,i){if(void 0===i&&(i=t.length),r&&nd(r,Nl)){var a=i-(n?1:0),o=r.pattern;if(!n&&o&&(185===o.kind||187===o.kind))for(var s=o.elements,c=i;c0&&(o=$c(o,P(),t.symbol,s,32768),a=[],n=e.createSymbolTable(),m=!1,g=!1,p=0),!Dp(x=tg(h.expression)))return Fr(h,e.Diagnostics.Spread_types_may_only_be_created_from_object_types),se;o=$c(o,x,t.symbol,s,32768),y=v+1;continue}e.Debug.assert(158===h.kind||159===h.kind),qy(h)}!D||8576&D.flags?n.set(b.escapedName,b):zu(D,Ee)&&(zu(D,fe)?g=!0:m=!0,i&&(f=!0)),a.push(b)}if(u)for(var E=0,N=po(c);E0&&(o=$c(o,P(),t.symbol,s,32768)),o):P();function P(){var r=m?vp(t.properties,y,a,0):void 0,o=g?vp(t.properties,y,a,1):void 0,c=Wn(t.symbol,n,e.emptyArray,e.emptyArray,r,o);return c.flags|=268435456|939524096&p,c.objectFlags|=128|J,d&&(c.objectFlags|=16384),f&&(c.objectFlags|=512),i&&(c.pattern=t),s|=939524096&c.flags,c}}function Dp(t){return!!(126615555&t.flags||117632&Kl(t)&&Dp(Ul(t))||3145728&t.flags&&e.every(t.types,Dp))}function xp(t){return!e.stringContains(t,"-")}function Sp(t){return 72===t.kind&&e.isIntrinsicJsxName(t.escapedText)}function Tp(e,t){return e.initializer?Ym(e.initializer,t):ve}function Cp(e,t){for(var r=[],n=0,i=e.children;n0&&(o=$c(o,T(),i.symbol,u,l),a=e.createSymbolTable()),xi(g=Wm(f.expression,r))&&(s=!0),Dp(g)?o=$c(o,g,i.symbol,u,l):n=n?xc([n,g]):g}s||a.size>0&&(o=$c(o,T(),i.symbol,u,l));var v=260===t.parent.kind?t.parent:void 0;if(v&&v.openingElement===t&&v.children.length>0){var h=Cp(v,r);if(!s&&_&&""!==_){c&&Fr(i,e.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten,e.unescapeLeadingUnderscores(_));var b=tp(t.attributes),D=b&&Gd(b,_),x=wr(33554436,_);x.type=1===h.length?h[0]:pp(h,D,!1)||ic(gc(h));var S=e.createSymbolTable();S.set(_,x),o=$c(o,Wn(i.symbol,S,e.emptyArray,e.emptyArray,void 0,void 0),i.symbol,u,l)}}return s?ie:n&&o!==Pe?xc([n,o]):n||(o===Pe?T():o);function T(){l|=J;var t=Wn(i.symbol,a,e.emptyArray,e.emptyArray,void 0,void 0);return t.flags|=268435456|u,t.objectFlags|=128|l,t}}(t.parent,r)}function Ep(e,t){var r=Ap(t),n=r&&En(r),i=n&&qr(n,e,67897832);return i?ba(i):se}function Np(r){var n=Ur(r);if(!n.resolvedSymbol){var i=Ep(t.IntrinsicElements,r);if(i!==se){if(!e.isIdentifier(r.tagName))return e.Debug.fail();var a=Fo(i,r.tagName.escapedText);return a?(n.jsxFlags|=1,n.resolvedSymbol=a):Lo(i,0)?(n.jsxFlags|=2,n.resolvedSymbol=i.symbol):(Fr(r,e.Diagnostics.Property_0_does_not_exist_on_type_1,e.idText(r.tagName),"JSX."+t.IntrinsicElements),n.resolvedSymbol=re)}return R&&Fr(r,e.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists,e.unescapeLeadingUnderscores(t.IntrinsicElements)),n.resolvedSymbol=re}return n.resolvedSymbol}function Ap(e){var r=e&&Ur(e);if(r&&r.jsxNamespace)return r.jsxNamespace;if(!r||!1!==r.jsxNamespace){var n=Nr(e),i=Hr(e,n,1920,void 0,n,!1);if(i){var a=qr(En(ln(i)),t.JSX,1920);if(a)return r&&(r.jsxNamespace=a),a;r&&(r.jsxNamespace=!1)}}return Js(t.JSX,1920,void 0)}function Fp(t,r){var n=r&&qr(r.exports,t,67897832),i=n&&ba(n),a=i&&po(i);if(a){if(0===a.length)return"";if(1===a.length)return a[0].escapedName;a.length>1&&Fr(n.declarations[0],e.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property,e.unescapeLeadingUnderscores(t))}}function Pp(e){return Fp(t.ElementChildrenAttributeNameContainer,e)}function wp(r,n){var i=Ep(t.IntrinsicElements,n);if(i!==se){var a=r.value,o=Fo(i,e.escapeLeadingUnderscores(a));if(o)return Qi(o);var s=Lo(i,0);return s||void 0}return ie}function Op(t){e.Debug.assert(Sp(t.tagName));var r=Ur(t);if(!r.resolvedJsxElementAttributesType){var n=Np(t);return 1&r.jsxFlags?r.resolvedJsxElementAttributesType=Qi(n):2&r.jsxFlags?r.resolvedJsxElementAttributesType=ms(n,0).type:r.resolvedJsxElementAttributesType=se}return r.resolvedJsxElementAttributesType}function Ip(e){var r=Ep(t.ElementClass,e);if(r!==se)return r}function Mp(e){return Ep(t.Element,e)}function Lp(e){var t=Mp(e);if(t)return gc([t,_e])}function Rp(t){var r,n=e.isJsxOpeningLikeElement(t);n&&function(t){Hv(t,t.typeArguments);for(var r=e.createUnderscoreEscapedMap(),n=0,i=t.attributes.properties;n=0)return _>=cm(n)&&(um(n)||_s)return!1;if(o||a>=c)return!0;for(var d=a;d=i&&r.length<=n}function gf(e){if(524288&e.flags){var t=co(e);if(1===t.callSignatures.length&&0===t.constructSignatures.length&&0===t.properties.length&&!t.stringIndexInfo&&!t.numberIndexInfo)return t.callSignatures[0]}}function yf(t,r,n,i){var a=o_(t.typeParameters,t,0,i);return a_(n?bu(r,n):r,t,function(e,t){y_(a.inferences,e,t)}),n||y_(a.inferences,ts(r),ts(t),8),is(t,C_(a),e.isInJSFile(r.declaration))}function vf(t,r,n,i,a){for(var o=0,s=a.inferences;o=n-1){var o=t[n-1];if(_f(o))return 215===o.kind?ic(o.type):nd(s=qm(o.expression,i,a),function(e){return!(63176705&e.flags||Tl(e)||Rl(e))})?ic(Lo(s,1)||se):s}for(var s,c=Lo(i,1)||ie,u=Om(c,4325372),l=[],_=-1,d=r;d0||e.isJsxOpeningElement(t)&&t.parent.children.length>0?[t.attributes]:e.emptyArray;var i=t.arguments||e.emptyArray,a=i.length;if(a&&_f(i[a-1])&&df(i)===a-1){var o=i[a-1],s=Wm(o.expression);if(Rl(s)){var c=s.typeArguments||e.emptyArray,u=s.target.hasRestElement?c.length-1:-1,l=e.map(c,function(e,t){return Tf(o,e,t===u)});return e.concatenate(i.slice(0,a-1),l)}}return i}function kf(t,r){switch(t.parent.kind){case 240:case 209:return 1;case 154:return 2;case 156:case 158:case 159:return 0===F||r.parameters.length<=2?2:3;case 151:return 3;default:return e.Debug.fail()}}function Ef(t,r,n){for(var i,a=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY,c=Number.POSITIVE_INFINITY,u=n.length,l=0,_=r;l<_.length;l++){var d=_[l],p=cm(d),f=sm(d);ps&&(s=p),u-1;if(u<=o&&v&&u--,i&&cm(i)>u&&i.declaration){var h=i.declaration.parameters[i.thisParameter?u+1:u];h&&(m=e.createDiagnosticForNode(h,e.isBindingPattern(h.name)?e.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided:e.Diagnostics.An_argument_for_0_was_not_provided,h.name?e.isBindingPattern(h.name)?void 0:e.idText(My(h.name)):u))}if(g||v){var b=g&&v?e.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more:g?e.Diagnostics.Expected_at_least_0_arguments_but_got_1:e.Diagnostics.Expected_0_arguments_but_got_1_or_more,D=e.createDiagnosticForNode(t,b,y,u);return m?Ar(D,m):D}if(a1&&(g=x(d,br,b)),g||(g=x(d,Dr,b)),g)return g;if(_)if(p)xf(t,y,p,Dr,void 0,!0);else if(f)ar.add(Ef(t,[f],y));else if(m)bf(m,t.typeArguments,!0,a);else{var D=e.filter(r,function(e){return mf(e,s)});0===D.length?ar.add(function(t,r,n){for(var i=1/0,a=-1/0,o=0,s=r;o0),i||1===r.length||r.some(function(e){return!!e.typeParameters})?function(t,r,n){var i=function(e,t){for(var r=-1,n=-1,i=0;i=t)return i;o>n&&(n=o,r=i)}return r}(r,void 0===V?n.length:V),a=r[i],o=a.typeParameters;if(!o)return a;var s=cf(t)?t.typeArguments:void 0,c=s?os(a,function(e,t,r){for(var n=e.map(av);n.length>t.length;)n.pop();for(;n.length=0&&Fr(t.arguments[i],e.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher)}var a=Up(t.expression);if(a===Te)return Ft;if((a=ko(a))===se)return lf(t);if(xi(a))return t.typeArguments&&Fr(t,e.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments),uf(t);var o=wo(a,1);if(o.length){if(!function(t,r){if(!r||!r.declaration)return!0;var n=r.declaration,i=e.getSelectedModifierFlags(n,24);if(!i)return!0;var a=e.getClassLikeDeclarationOfSymbol(n.parent.symbol),o=ba(n.parent.symbol);if(!tv(t,a)){var s=e.getContainingClass(t);if(s&&16&i){var c=av(s);if(function t(r,n){var i=_a(n);if(!e.length(i))return!1;var a=i[0];if(2097152&a.flags){for(var o=a.types,s=e.countWhere(o,aa),c=0,u=0,l=a.types;u0)return e.parameters.length-1+r}}return e.minArgumentCount}function um(e){if(e.hasRestParameter){var t=Qi(e.parameters[e.parameters.length-1]);return!Rl(t)||t.target.hasRestElement}return!1}function lm(e){if(e.hasRestParameter){var t=Qi(e.parameters[e.parameters.length-1]);return Rl(t)?function(e){var t=Bl(e);return t&&ic(t)}(t):t}}function _m(e){var t=lm(e);return!t||Tl(t)||xi(t)?void 0:t}function dm(e){return pm(e,Se)}function pm(e,t){return e.parameters.length>0?im(e,0):t}function fm(t,r){var n=Kr(t);if(!n.type){n.type=r;var i=t.valueDeclaration;72!==i.name.kind&&(n.type===Fe&&(n.type=Ri(i.name)),function t(r){for(var n=0,i=r.elements;n=2||A.noEmit||!e.hasRestParameter(t)||4194304&t.flags||e.nodeIsMissing(t.body)||e.forEach(t.parameters,function(t){t.name&&!e.isBindingPattern(t.name)&&t.name.escapedText===q.escapedName&&Fr(t,e.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters)})}(t);var n=e.getEffectiveReturnTypeNode(t);if(R&&!n)switch(t.kind){case 161:Fr(t,e.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);break;case 160:Fr(t,e.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type)}if(n){var i=e.getFunctionFlags(t);if(1==(5&i)){var a=uu(n);if(a===xe)Fr(n,e.Diagnostics.A_generator_cannot_have_a_void_type_annotation);else{var s=yy(a,0!=(2&i))||ie;qu(2&i?tc(s):nc(s),a,n)}}else 2==(3&i)&&function(t,r){var n=uu(r);if(F>=2){if(n===se)return;var i=Vs(!0);if(i!==Ie&&!$i(n,i))return void Fr(r,e.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type)}else{if(function(t){Eg(t&&e.getEntityNameFromTypeNode(t))}(r),n===se)return;var a=e.getEntityNameFromTypeNode(r);if(void 0===a)return void Fr(r,e.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value,si(n));var o=gn(a,67220415,!0),s=o?Qi(o):se;if(s===se)return void(72===a.kind&&"Promise"===a.escapedText&&Zi(n)===Vs(!1)?Fr(r,e.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option):Fr(r,e.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value,e.entityNameToString(a)));var c=_t||(_t=zs("PromiseConstructorLike",0,!0))||Fe;if(c===Fe)return void Fr(r,e.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value,e.entityNameToString(a));if(!qu(s,c,r,e.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value))return;var u=a&&My(a),l=qr(t.locals,u.escapedText,67220415);if(l)return void Fr(l.valueDeclaration,e.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions,e.idText(u),e.entityNameToString(a))}Tg(n,t,e.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)}(t,n)}162!==t.kind&&289!==t.kind&&Mg(t)}}function og(t){for(var r=e.createMap(),n=0,i=t.members;n0&&r.declarations[0]!==t)return}var n=ds(wn(t));if(n)for(var i=!1,a=!1,o=0,s=n.declarations;o=0)return void(r&&Fr(r,e.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method));ir.push(t.id);var l=Cg(u,r,n);if(ir.pop(),!l)return;return i.awaitedTypeOfType=l}var _=Di(t,"then");if(!(_&&wo(_,0).length>0))return i.awaitedTypeOfType=t;if(r){if(!n)return e.Debug.fail();Fr(r,n)}}function kg(t){var r=ts(Kf(t));if(!(1&r.flags)){var n,i,a=Rf(t);switch(t.parent.kind){case 240:n=gc([Qi(wn(t.parent)),xe]);break;case 151:n=xe,i=e.chainDiagnosticMessages(void 0,e.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);break;case 154:n=xe,i=e.chainDiagnosticMessages(void 0,e.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);break;case 156:case 158:case 159:n=gc([ec(av(t.parent)),xe]);break;default:return e.Debug.fail()}qu(r,n,t,a,function(){return i})}}function Eg(e){if(e){var t=My(e),r=2097152|(72===e.kind?67897832:1920),n=Hr(t,t.escapedText,r,void 0,void 0,!0);n&&2097152&n.flags&&Rn(n)&&!hv(_n(n))&&pn(n)}}function Ng(t){var r=Ag(t);r&&e.isEntityName(r)&&Eg(r)}function Ag(e){if(e)switch(e.kind){case 174:case 173:return Fg(e.types);case 175:return Fg([e.trueType,e.falseType]);case 177:return Ag(e.type);case 164:return e.typeName}}function Fg(t){for(var r,n=0,i=t;n=e.ModuleKind.ES2015||A.noEmit)&&(Yg(t,r,"require")||Yg(t,r,"exports"))&&(!e.isModuleDeclaration(t)||1===e.getModuleInstanceState(t))){var n=bi(t);279===n.kind&&e.isExternalOrCommonJsModule(n)&&Fr(r,e.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module,e.declarationNameToString(r),e.declarationNameToString(r))}}function Zg(t,r){if(!(F>=4||A.noEmit)&&Yg(t,r,"Promise")&&(!e.isModuleDeclaration(t)||1===e.getModuleInstanceState(t))){var n=bi(t);279===n.kind&&e.isExternalOrCommonJsModule(n)&&1024&n.flags&&Fr(r,e.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions,e.declarationNameToString(r),e.declarationNameToString(r))}}function ey(t){if(151===e.getRootDeclaration(t).kind){var r=e.getContainingFunction(t);!function n(i){if(!e.isTypeNode(i)&&!e.isDeclarationName(i)){if(189===i.kind)return n(i.expression);if(72!==i.kind)return e.forEachChild(i,n);var a=Hr(i,i.escapedText,69317567,void 0,void 0,!1);if(a&&a!==re&&a.valueDeclaration)if(a.valueDeclaration!==t){var o=e.getEnclosingBlockScopeContainer(a.valueDeclaration);if(o===r){if(151===a.valueDeclaration.kind||186===a.valueDeclaration.kind){if(a.valueDeclaration.pos1&&e.some(c.declarations,function(r){return r!==t&&e.isVariableLike(r)&&!iy(r,t)})&&Fr(t.name,e.Diagnostics.All_declarations_of_0_must_have_identical_modifiers,e.declarationNameToString(t.name))}else{var _=ty(Bi(t));u===se||_===se||Lu(u,_)||67108864&c.flags||ny(u,t,_),t.initializer&&Wu(Wm(t.initializer),_,t,t.initializer,void 0),iy(t,c.valueDeclaration)||Fr(t.name,e.Diagnostics.All_declarations_of_0_must_have_identical_modifiers,e.declarationNameToString(t.name))}154!==t.kind&&153!==t.kind&&(Dg(t),237!==t.kind&&186!==t.kind||function(t){if(0==(3&e.getCombinedNodeFlags(t))&&!e.isParameterDeclaration(t)&&(237!==t.kind||t.initializer)){var r=wn(t);if(1&r.flags){if(!e.isIdentifier(t.name))return e.Debug.fail();var n=Hr(t,t.name.escapedText,3,void 0,void 0,!1);if(n&&n!==r&&2&n.flags&&3&jp(n)){var i=e.getAncestor(n.valueDeclaration,238),a=219===i.parent.kind&&i.parent.parent?i.parent.parent:void 0;if(!a||!(218===a.kind&&e.isFunctionLike(a.parent)||245===a.kind||244===a.kind||279===a.kind)){var o=ai(n);Fr(t,e.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1,o,o)}}}}}(t),$g(t,t.name),Zg(t,t.name))}}}function ny(t,r,n){var i=e.getNameOfDeclaration(r);Fr(i,154===r.kind||153===r.kind?e.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2:e.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2,e.declarationNameToString(i),si(t),si(n))}function iy(t,r){return 151===t.kind&&237===r.kind||237===t.kind&&151===r.kind||e.hasQuestionToken(t)===e.hasQuestionToken(r)&&e.getSelectedModifierFlags(t,504)===e.getSelectedModifierFlags(r,504)}function ay(t){return function(t){if(226!==t.parent.parent.kind&&227!==t.parent.parent.kind)if(4194304&t.flags)oh(t);else if(!t.initializer){if(e.isBindingPattern(t.name)&&!e.isBindingPattern(t.parent))return _h(t,e.Diagnostics.A_destructuring_declaration_must_have_an_initializer);if(e.isVarConst(t))return _h(t,e.Diagnostics.const_declarations_must_be_initialized)}if(t.exclamationToken&&(219!==t.parent.parent.kind||!t.type||t.initializer||4194304&t.flags))return _h(t.exclamationToken,e.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);A.module===e.ModuleKind.ES2015||A.module===e.ModuleKind.ESNext||A.module===e.ModuleKind.System||A.noEmit||4194304&t.parent.parent.flags||!e.hasModifier(t.parent.parent,1)||function t(r){if(72===r.kind){if("__esModule"===e.idText(r))return _h(r,e.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules)}else for(var n=r.elements,i=0,a=n;i=1&&ay(t.declarations[0])}function _y(e,t){return dy(Up(e),e,!0,void 0!==t)}function dy(e,t,r,n){return xi(e)?e:py(e,t,r,n,!0)||ie}function py(t,r,n,i,a){if(t!==Se){var o=F>=2,s=!o&&A.downlevelIteration;if(o||s||i){var c=fy(t,o?r:void 0,i,!0,a);if(c||o)return c}var u=t,l=!1,_=!1;if(n){if(1048576&u.flags){var d=t.types,p=e.filter(d,function(e){return!(132&e.flags)});p!==d&&(u=gc(p,2))}else 132&u.flags&&(u=Se);if((_=u!==t)&&(F<1&&r&&(Fr(r,e.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher),l=!0),131072&u.flags))return pe}if(!kl(u)){if(r&&!l){var f=!!fy(t,void 0,i,!0,a);Fr(r,!n||_?s?e.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator:f?e.Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators:e.Diagnostics.Type_0_is_not_an_array_type:s?e.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator:f?e.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators:e.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type,si(u))}return _?pe:void 0}var m=Lo(u,1);return _&&m?132&m.flags?pe:gc([m,pe],2):m}my(r,t,i)}function fy(t,r,n,i,a){if(!xi(t))return od(t,function(t){var o=t;if(n){if(o.iteratedTypeOfAsyncIterable)return o.iteratedTypeOfAsyncIterable;if($i(t,Ws(!1))||$i(t,Gs(!1)))return o.iteratedTypeOfAsyncIterable=t.typeArguments[0]}if(i){if(o.iteratedTypeOfIterable)return n?o.iteratedTypeOfAsyncIterable=Cg(o.iteratedTypeOfIterable):o.iteratedTypeOfIterable;if($i(t,Ys(!1))||$i(t,Qs(!1)))return n?o.iteratedTypeOfAsyncIterable=Cg(t.typeArguments[0]):o.iteratedTypeOfIterable=t.typeArguments[0]}var s=n&&Di(t,e.getPropertyNameForKnownSymbolName("asyncIterator")),c=s||(i?Di(t,e.getPropertyNameForKnownSymbolName("iterator")):void 0);if(!xi(c)){var u=c?wo(c,0):void 0;if(e.some(u)){var l=gy(gc(e.map(u,ts),2),r,!!s);return a&&r&&l&&qu(t,s?function(e){return Zs(Ws(!0),[e])}(l):rc(l),r),l?n?o.iteratedTypeOfAsyncIterable=s?l:Cg(l):o.iteratedTypeOfIterable=l:void 0}r&&(my(r,t,n),r=void 0)}})}function my(t,r,n){Fr(t,n?e.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator:e.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator,si(r))}function gy(t,r,n){if(!xi(t)){var i=t;if(n?i.iteratedTypeOfAsyncIterator:i.iteratedTypeOfIterator)return n?i.iteratedTypeOfAsyncIterator:i.iteratedTypeOfIterator;if($i(t,(n?Hs:Xs)(!1)))return n?i.iteratedTypeOfAsyncIterator=t.typeArguments[0]:i.iteratedTypeOfIterator=t.typeArguments[0];var a=Di(t,"next");if(!xi(a)){var o=a?wo(a,0):e.emptyArray;if(0!==o.length){var s=gc(e.map(o,ts),2);if(!(xi(s)||n&&xi(s=xg(s,r,e.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property)))){var c=s&&Di(s,"value");if(c)return n?i.iteratedTypeOfAsyncIterator=c:i.iteratedTypeOfIterator=c;r&&Fr(r,n?e.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property:e.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property)}}else r&&Fr(r,n?e.Diagnostics.An_async_iterator_must_have_a_next_method:e.Diagnostics.An_iterator_must_have_a_next_method)}}}function yy(e,t){if(!xi(e))return fy(e,void 0,t,!t,!1)||gy(e,void 0,t)}function vy(t){dh(t)||function(t){for(var r=t;r;){if(e.isFunctionLike(r))return _h(t,e.Diagnostics.Jump_target_cannot_cross_function_boundary);switch(r.kind){case 233:if(t.label&&r.label.escapedText===t.label.escapedText){var n=228===t.kind&&!e.isIterationStatement(r.statement,!0);return!!n&&_h(t,e.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement)}break;case 232:if(229===t.kind&&!t.label)return!1;break;default:if(e.isIterationStatement(r,!1)&&!t.label)return!1}r=r.parent}if(t.label){var i=229===t.kind?e.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement:e.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;return _h(t,i)}var i=229===t.kind?e.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement:e.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;_h(t,i)}(t)}function hy(t,r){var n=2==(3&e.getFunctionFlags(t))?Sg(r):r;return!!n&&Om(n,16387)}function by(t){dh(t)||void 0===t.expression&&function(t,r,n,i,a){var o=e.getSourceFileOfNode(t);if(!ch(o)){var s=e.getSpanOfTokenAtPosition(o,t.pos);ar.add(e.createFileDiagnostic(o,e.textSpanEnd(s),0,r,n,i,a))}}(t,e.Diagnostics.Line_break_not_permitted_here),t.expression&&tg(t.expression)}function Dy(t){var r,n=ps(t.symbol,1),i=ps(t.symbol,0),a=Lo(t,0),o=Lo(t,1);if(a||o){e.forEach(uo(t),function(e){var r=Qi(e);p(e,r,t,i,a,0),p(e,r,t,n,o,1)});var s=t.symbol.valueDeclaration;if(1&e.getObjectFlags(t)&&e.isClassLike(s))for(var c=0,u=s.members;cn)return!1;for(var l=0;l1)return uh(o.types[1],e.Diagnostics.Classes_can_only_extend_a_single_class);r=!0}else{if(e.Debug.assert(109===o.token),n)return uh(o,e.Diagnostics.implements_clause_already_seen);n=!0}Yv(o)}})(t)||Vv(t.typeParameters,r)}(t),wg(t),t.name&&(xy(t.name,e.Diagnostics.Class_name_cannot_be_0),$g(t,t.name),Zg(t,t.name),4194304&t.flags||(r=t.name,1===F&&"Object"===r.escapedText&&P!==e.ModuleKind.ES2015&&P!==e.ModuleKind.ESNext&&Fr(r,e.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0,e.ModuleKind[P]))),Sy(e.getEffectiveTypeParameterDeclarations(t)),Dg(t);var n=wn(t),i=ba(n),a=ja(i),s=Qi(n);Ty(n),function(t){var r;!function(e){e[e.Getter=1]="Getter",e[e.Setter=2]="Setter",e[e.Method=4]="Method",e[e.Property=3]="Property"}(r||(r={}));for(var n=e.createUnderscoreEscapedMap(),i=e.createUnderscoreEscapedMap(),a=0,o=t.members;a>s;case 48:return a>>>s;case 46:return a<1&&!n&&_(t,!!A.preserveConstEnums||!!A.isolatedModules)){var s=function(t){for(var r=0,n=t.declarations;r1)for(var o=0,s=n;o=0)r.parameters[n.parameterIndex].dotDotDotToken?Fr(i,e.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter):qu(n.type,av(r.parameters[n.parameterIndex]),t.type,void 0,function(){return e.chainDiagnosticMessages(void 0,e.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type)});else if(i){for(var a=!1,o=0,s=r.parameters;o0),n.length>1&&Fr(n[1],e.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);var i=Og(t.class.expression),a=e.getClassExtendsHeritageElement(r);if(a){var o=Og(a.expression);o&&i.escapedText!==o.escapedText&&Fr(i,e.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause,e.idText(t.tagName),e.idText(i),e.idText(o))}}else Fr(r,e.Diagnostics.JSDoc_0_is_not_attached_to_a_class,e.idText(t.tagName))}(t);case 304:case 297:return function(t){t.typeExpression||Fr(t.name,e.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags),t.name&&xy(t.name,e.Diagnostics.Type_alias_name_cannot_be_0),Uy(t.typeExpression)}(t);case 303:return function(e){Uy(e.constraint);for(var t=0,r=e.typeParameters;t-1&&n0?s.statements[0].pos:s.end)-u,e.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement),n=!0}if(o&&271===s.kind){var l=tg(s.expression),_=wl(l),d=i;_&&a||(l=_?Ol(l):l,d=Ol(i)),zm(d,l)||$u(l,d,s.expression,void 0)}e.forEach(s.statements,Uy)}),t.caseBlock.locals&&Mg(t.caseBlock)}(t);case 233:return function(t){dh(t)||e.findAncestor(t.parent,function(r){return e.isFunctionLike(r)?"quit":233===r.kind&&r.label.escapedText===t.label.escapedText&&(_h(t.label,e.Diagnostics.Duplicate_label_0,e.getTextOfNode(t.label)),!0)}),Uy(t.statement)}(t);case 234:return by(t);case 235:return function(t){dh(t),Gg(t.tryBlock);var r=t.catchClause;if(r){if(r.variableDeclaration)if(r.variableDeclaration.type)uh(r.variableDeclaration.type,e.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation);else if(r.variableDeclaration.initializer)uh(r.variableDeclaration.initializer,e.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);else{var n=r.block.locals;n&&e.forEachKey(r.locals,function(t){var r=n.get(t);r&&0!=(2&r.flags)&&_h(r.valueDeclaration,e.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause,t)})}Gg(r.block)}t.finallyBlock&&Gg(t.finallyBlock)}(t);case 237:return ay(t);case 186:return oy(t);case 240:return function(t){t.name||e.hasModifier(t,512)||uh(t,e.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name),Cy(t),e.forEach(t.members,Uy),Mg(t)}(t);case 241:return Fy(t);case 242:return function(t){zv(t),xy(t.name,e.Diagnostics.Type_alias_name_cannot_be_0),Sy(t.typeParameters),Uy(t.type),Mg(t)}(t);case 243:return function(t){if(o){zv(t),xy(t.name,e.Diagnostics.Enum_name_cannot_be_0),$g(t,t.name),Zg(t,t.name),Dg(t),Py(t);var r=e.isEnumConst(t);A.isolatedModules&&r&&4194304&t.flags&&Fr(t.name,e.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided);var n=wn(t);if(t===e.getDeclarationOfKind(n,t.kind)){n.declarations.length>1&&e.forEach(n.declarations,function(t){e.isEnumDeclaration(t)&&e.isEnumConst(t)!==r&&Fr(e.getNameOfDeclaration(t),e.Diagnostics.Enum_declarations_must_all_be_const_or_non_const)});var i=!1;e.forEach(n.declarations,function(t){if(243!==t.kind)return!1;var r=t;if(!r.members.length)return!1;var n=r.members[0];n.initializer||(i?Fr(n.name,e.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element):i=!0)})}}}(t);case 244:return Oy(t);case 249:return function(t){if(!jy(t,e.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)&&(!zv(t)&&e.hasModifiers(t)&&uh(t,e.Diagnostics.An_import_declaration_cannot_have_modifiers),Ly(t))){var r=t.importClause;r&&(r.name&&By(r),r.namedBindings&&(251===r.namedBindings.kind?By(r.namedBindings):vn(t,t.moduleSpecifier)&&e.forEach(r.namedBindings.elements,By)))}}(t);case 248:return function(t){if(!jy(t,e.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)&&(zv(t),e.isInternalModuleImportEqualsDeclaration(t)||Ly(t)))if(By(t),e.hasModifier(t,1)&&dn(t),259!==t.moduleReference.kind){var r=_n(wn(t));if(r!==re){if(67220415&r.flags){var n=My(t.moduleReference);1920&gn(n,67221439).flags||Fr(n,e.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name,e.declarationNameToString(n))}67897832&r.flags&&xy(t.name,e.Diagnostics.Import_name_cannot_be_0)}}else P>=e.ModuleKind.ES2015&&!(4194304&t.flags)&&_h(t,e.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead)}(t);case 255:return function(t){if(!jy(t,e.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)&&(!zv(t)&&e.hasModifiers(t)&&uh(t,e.Diagnostics.An_export_declaration_cannot_have_modifiers),!t.moduleSpecifier||Ly(t)))if(t.exportClause){e.forEach(t.exportClause.elements,Jy);var r=245===t.parent.kind&&e.isAmbientModule(t.parent.parent),n=!r&&245===t.parent.kind&&!t.moduleSpecifier&&4194304&t.flags;279===t.parent.kind||r||n||Fr(t,e.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace)}else{var i=vn(t,t.moduleSpecifier);i&&Tn(i)&&Fr(t.moduleSpecifier,e.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk,ai(i)),P!==e.ModuleKind.System&&P!==e.ModuleKind.ES2015&&P!==e.ModuleKind.ESNext&&jv(t,32768)}}(t);case 254:return function(t){if(!jy(t,e.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)){var r=279===t.parent.kind?t.parent:t.parent.parent;244!==r.kind||e.isAmbientModule(r)?(!zv(t)&&e.hasModifiers(t)&&uh(t,e.Diagnostics.An_export_assignment_cannot_have_modifiers),72===t.expression.kind?(dn(t),e.getEmitDeclarations(A)&&mi(t.expression,!0)):Wm(t.expression),zy(r),4194304&t.flags&&!e.isEntityNameExpression(t.expression)&&_h(t.expression,e.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context),!t.isExportEquals||4194304&t.flags||(P>=e.ModuleKind.ES2015?_h(t,e.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead):P===e.ModuleKind.System&&_h(t,e.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system))):t.isExportEquals?Fr(t,e.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace):Fr(t,e.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module)}}(t);case 220:case 236:return void dh(t);case 258:return function(e){wg(e)}(t)}}}function Vy(t){e.isInJSFile(t)||_h(t,e.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments)}function qy(t){var r=Ur(e.getSourceFileOfNode(t));if(!(1&r.flags)){r.deferredNodes=r.deferredNodes||e.createMap();var n=""+u(t);r.deferredNodes.set(n,t)}}function Wy(t){var r=Ur(t);r.deferredNodes&&r.deferredNodes.forEach(function(t){switch(t.kind){case 196:case 197:case 156:case 155:!function(t){e.Debug.assert(156!==t.kind||e.isObjectLiteralMethod(t));var r=e.getFunctionFlags(t),n=Cm(t,r);if(0==(1&r)&&Sm(t,n),t.body)if(e.getEffectiveReturnTypeNode(t)||ts(Go(t)),218===t.body.kind)Uy(t.body);else{var i=tg(t.body);n&&Wu(2==(3&r)?Tg(i,t.body,e.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member):i,n,t.body,t.body)}}(t);break;case 158:case 159:lg(t);break;case 209:!function(t){e.forEach(t.members,Uy),Mg(t)}(t);break;case 261:!function(e){Rp(e)}(t);break;case 260:!function(e){Rp(e.openingElement),Sp(e.closingElement.tagName)?Np(e.closingElement):tg(e.closingElement.tagName),Cp(e)}(t)}})}function Hy(t){e.performance.mark("beforeCheck"),function(t){var r=Ur(t);if(!(1&r.flags)){if(e.skipTypeChecking(t,A))return;!function(t){4194304&t.flags&&function(t){for(var r=0,n=t.statements;r0?e.concatenate(o,a):a}return e.forEach(n.getSourceFiles(),Hy),ar.getDiagnostics()}(t)}finally{m=void 0}}function Qy(){if(!o)throw new Error("Trying to get diagnostics from a type checker that does not produce them.")}function $y(e){switch(e.kind){case 150:case 240:case 241:case 242:case 243:return!0;default:return!1}}function Zy(e){for(;148===e.parent.kind;)e=e.parent;return 164===e.parent.kind}function ev(t,r){for(var n;(t=e.getContainingClass(t))&&!(n=r(t)););return n}function tv(e,t){return!!ev(e,function(e){return e===t})}function rv(e){return void 0!==function(e){for(;148===e.parent.kind;)e=e.parent;return 248===e.parent.kind?e.parent.moduleReference===e?e.parent:void 0:254===e.parent.kind&&e.parent.expression===e?e.parent:void 0}(e)}function nv(t){if(e.isDeclarationName(t))return wn(t.parent);if(e.isInJSFile(t)&&189===t.parent.kind&&t.parent===t.parent.parent.left){var r=function(t){switch(e.getAssignmentDeclarationKind(t.parent.parent)){case 1:case 3:return wn(t.parent);case 4:case 2:case 5:return wn(t.parent.parent)}}(t);if(r)return r}if(254===t.parent.kind&&e.isEntityNameExpression(t)){var n=gn(t,70107135,!0);if(n&&n!==re)return n}else if(!e.isPropertyAccessExpression(t)&&rv(t)){var i=e.getAncestor(t,248);return e.Debug.assert(void 0!==i),fn(t,!0)}if(!e.isPropertyAccessExpression(t)){var a=function(t){for(var r=t.parent;e.isQualifiedName(r);)t=r,r=r.parent;if(r&&183===r.kind&&r.qualifier===t)return r}(t);if(a){uu(a);var o=Ur(t).resolvedSymbol;return o===re?void 0:o}}for(;e.isRightSideOfQualifiedNameOrPropertyAccess(t);)t=t.parent;if(function(e){for(;189===e.parent.kind;)e=e.parent;return 211===e.parent.kind}(t)){var s=0;211===t.parent.kind?(s=67897832,e.isExpressionWithTypeArgumentsInClassExtendsClause(t.parent)&&(s|=67220415)):s=1920,s|=2097152;var c=e.isEntityNameExpression(t)?gn(t,s):void 0;if(c)return c}if(299===t.parent.kind)return e.getParameterSymbolFromJSDoc(t.parent);if(150===t.parent.kind&&303===t.parent.parent.kind){e.Debug.assert(!e.isInJSFile(t));var u=e.getTypeParameterFromJsDoc(t.parent);return u&&u.symbol}if(e.isExpressionNode(t)){if(e.nodeIsMissing(t))return;if(72===t.kind){if(e.isJSXTagName(t)&&Sp(t)){var l=Np(t.parent);return l===re?void 0:l}return gn(t,67220415,!1,!0)}if(189===t.kind||148===t.kind){var _=Ur(t);return _.resolvedSymbol?_.resolvedSymbol:(189===t.kind?Wp(t):Hp(t),_.resolvedSymbol)}}else if(Zy(t))return gn(t,s=164===t.parent.kind?67897832:1920,!1,!0);return 163===t.parent.kind?gn(t,1):void 0}function iv(t){if(279===t.kind)return e.isExternalModule(t)?Pn(t.symbol):void 0;var r=t.parent,n=r.parent;if(!(8388608&t.flags)){if(d(t)){var i=wn(r);return e.isImportOrExportSpecifier(t.parent)&&t.parent.propertyName===t?hp(i):i}if(e.isLiteralComputedPropertyDeclarationName(t))return wn(r.parent);if(72===t.kind){if(rv(t))return nv(t);if(186===r.kind&&184===n.kind&&t===r.propertyName){var a=Fo(av(n),t.escapedText);if(a)return a}}switch(t.kind){case 72:case 189:case 148:return nv(t);case 100:var o=e.getThisContainer(t,!1);if(e.isFunctionLike(o)){var s=Go(o);if(s.thisParameter)return s.thisParameter}if(e.isInExpressionContext(t))return tg(t).symbol;case 178:return cu(t).symbol;case 98:return tg(t).symbol;case 124:var c=t.parent;return c&&157===c.kind?c.parent.symbol:void 0;case 10:case 14:if(e.isExternalModuleImportEqualsDeclaration(t.parent.parent)&&e.getExternalModuleImportEqualsDeclarationExpression(t.parent.parent)===t||(249===t.parent.kind||255===t.parent.kind)&&t.parent.moduleSpecifier===t||e.isInJSFile(t)&&e.isRequireCall(t.parent,!1)||e.isImportCall(t.parent)||e.isLiteralTypeNode(t.parent)&&e.isLiteralImportTypeNode(t.parent.parent)&&t.parent.parent.argument===t.parent)return vn(t,t);if(e.isCallExpression(r)&&e.isBindableObjectDefinePropertyCall(r)&&r.arguments[1]===t)return wn(r);case 8:var u=e.isElementAccessExpression(r)?r.argumentExpression===t?Zm(r.expression):void 0:e.isLiteralTypeNode(r)&&e.isIndexedAccessTypeNode(n)?uu(n.objectType):void 0;return u&&Fo(u,e.escapeLeadingUnderscores(t.text));case 80:case 90:case 37:case 76:return wn(t.parent);case 183:return e.isLiteralImportTypeNode(t)?iv(t.argument.literal):void 0;case 85:return e.isExportAssignment(t.parent)?e.Debug.assertDefined(t.parent.symbol):void 0;default:return}}}function av(t){if(8388608&t.flags)return se;var r,n,i=e.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(t),a=i&&pa(wn(i.class));if(e.isPartOfTypeNode(t)){var o=uu(t);return a?ja(o,a.thisType):o}if(e.isExpressionNode(t))return ov(t);if(a&&!i.isImplements){var s=e.firstOrUndefined(_a(a));return s?ja(s,a.thisType):se}if($y(t))return ba(n=wn(t));if(72===(r=t).kind&&$y(r.parent)&&r.parent.name===r)return(n=iv(t))?ba(n):se;if(e.isDeclaration(t))return Qi(n=wn(t));if(d(t))return(n=iv(t))?Qi(n):se;if(e.isBindingPattern(t))return Fi(t.parent,!0)||se;if(rv(t)&&(n=iv(t))){var c=ba(n);return c!==se?c:Qi(n)}return se}function ov(t){return e.isRightSideOfQualifiedNameOrPropertyAccess(t)&&(t=t.parent),iu(Zm(t))}function sv(t){t=ko(t);var r=e.createSymbolTable(po(t)),n=wo(t,0).length?We:wo(t,1).length?He:void 0;return n&&e.forEach(po(n),function(e){r.has(e.escapedName)||r.set(e.escapedName,e)}),Vn(r)}function cv(t){return e.typeHasCallOrConstructSignatures(t,H)}function uv(t){if(!e.isGeneratedIdentifier(t)){var r=e.getParseTreeNode(t,e.isIdentifier);if(r)return!(189===r.parent.kind&&r.parent.name===r)&&Iv(r)===q}return!1}function lv(t){var r=vn(t.parent,t);if(!r||e.isShorthandAmbientModuleSymbol(r))return!0;var n=Tn(r),i=Kr(r=xn(r));return void 0===i.exportsSomeValue&&(i.exportsSomeValue=n?!!(67220415&r.flags):e.forEachEntry(Nn(r),function(e){return(e=ln(e))&&!!(67220415&e.flags)})),i.exportsSomeValue}function _v(t,r){var n=e.getParseTreeNode(t,e.isIdentifier);if(n){var i=Iv(n,function(t){return e.isModuleOrEnumDeclaration(t.parent)&&t===t.parent.name}(n));if(i){if(1048576&i.flags){var a=Pn(i.exportSymbol);if(!r&&944&a.flags&&!(3&a.flags))return;i=a}var o=On(i);if(o){if(512&o.flags&&279===o.valueDeclaration.kind){var s=o.valueDeclaration;return s!==e.getSourceFileOfNode(n)?void 0:s}return e.findAncestor(n.parent,function(t){return e.isModuleOrEnumDeclaration(t)&&wn(t)===o})}}}}function dv(t){var r=e.getParseTreeNode(t,e.isIdentifier);if(r){var n=Iv(r);if(un(n,67220415))return tn(n)}}function pv(t){if(418&t.flags){var r=Kr(t);if(void 0===r.isDeclarationWithCollidingName){var n=e.getEnclosingBlockScopeContainer(t.valueDeclaration);if(e.isStatementWithLocals(n)){var i=Ur(t.valueDeclaration);if(Hr(n.parent,t.escapedName,67220415,void 0,void 0,!1))r.isDeclarationWithCollidingName=!0;else if(262144&i.flags){var a=524288&i.flags,o=e.isIterationStatement(n,!1),s=218===n.kind&&e.isIterationStatement(n.parent,!1);r.isDeclarationWithCollidingName=!(e.isBlockScopedContainerTopLevel(n)||a&&(o||s))}else r.isDeclarationWithCollidingName=!1}}return r.isDeclarationWithCollidingName}return!1}function fv(t){if(!e.isGeneratedIdentifier(t)){var r=e.getParseTreeNode(t,e.isIdentifier);if(r){var n=Iv(r);if(n&&pv(n))return n.valueDeclaration}}}function mv(t){var r=e.getParseTreeNode(t,e.isDeclaration);if(r){var n=wn(r);if(n)return pv(n)}return!1}function gv(t){switch(t.kind){case 248:case 250:case 251:case 253:case 257:return vv(wn(t)||re);case 255:var r=t.exportClause;return!!r&&e.some(r.elements,gv);case 254:return!t.expression||72!==t.expression.kind||vv(wn(t)||re)}return!1}function yv(t){var r=e.getParseTreeNode(t,e.isImportEqualsDeclaration);return!(void 0===r||279!==r.parent.kind||!e.isInternalModuleImportEqualsDeclaration(r))&&vv(wn(r))&&r.moduleReference&&!e.nodeIsMissing(r.moduleReference)}function vv(e){var t=_n(e);return t===re||!!(67220415&t.flags)&&(A.preserveConstEnums||!hv(t))}function hv(e){return Rm(e)||!!e.constEnumOnlyModule}function bv(t){if(e.nodeIsPresent(t.body)){if(e.isGetAccessor(t)||e.isSetAccessor(t))return!1;var r=Qo(wn(t));return r.length>1||1===r.length&&r[0].declaration!==t}return!1}function Dv(t){return!(!O||Ko(t)||e.isJSDocParameterTag(t)||!t.initializer||e.hasModifier(t,92))}function xv(t){return O&&Ko(t)&&!t.initializer&&e.hasModifier(t,92)}function Sv(t){var r=e.getParseTreeNode(t,e.isFunctionDeclaration);if(!r)return!1;var n=wn(r);return!!(n&&16&n.flags)&&!!e.forEachEntry(En(n),function(t){return 67220415&t.flags&&e.isPropertyAccessExpression(t.valueDeclaration)})}function Tv(t){var r=e.getParseTreeNode(t,e.isFunctionDeclaration);if(!r)return e.emptyArray;var n=wn(r);return n&&po(Qi(n))||e.emptyArray}function Cv(e){return Ur(e).flags||0}function kv(e){return Py(e.parent),Ur(e).enumMemberValue}function Ev(e){switch(e.kind){case 278:case 189:case 190:return!0}return!1}function Nv(t){if(278===t.kind)return kv(t);var r=Ur(t).resolvedSymbol;if(r&&8&r.flags){var n=r.valueDeclaration;if(e.isEnumConst(n.parent))return kv(n)}}function Av(t,r){var n=e.getParseTreeNode(t,e.isEntityName);if(!n)return e.TypeReferenceSerializationKind.Unknown;if(r&&!(r=e.getParseTreeNode(r)))return e.TypeReferenceSerializationKind.Unknown;var i=gn(n,67220415,!0,!1,r),a=gn(n,67897832,!0,!1,r);if(i&&i===a){var o=qs(!1);if(o&&i===o)return e.TypeReferenceSerializationKind.Promise;var s=Qi(i);if(s&&oa(s))return e.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue}if(!a)return e.TypeReferenceSerializationKind.Unknown;var c=ba(a);return c===se?e.TypeReferenceSerializationKind.Unknown:3&c.flags?e.TypeReferenceSerializationKind.ObjectType:Im(c,245760)?e.TypeReferenceSerializationKind.VoidNullableOrNeverType:Im(c,528)?e.TypeReferenceSerializationKind.BooleanType:Im(c,296)?e.TypeReferenceSerializationKind.NumberLikeType:Im(c,2112)?e.TypeReferenceSerializationKind.BigIntLikeType:Im(c,132)?e.TypeReferenceSerializationKind.StringLikeType:Rl(c)?e.TypeReferenceSerializationKind.ArrayLikeType:Im(c,12288)?e.TypeReferenceSerializationKind.ESSymbolType:function(e){return!!(524288&e.flags)&&wo(e,0).length>0}(c)?e.TypeReferenceSerializationKind.TypeWithCallSignature:Tl(c)?e.TypeReferenceSerializationKind.ArrayLikeType:e.TypeReferenceSerializationKind.ObjectType}function Fv(t,r,n,i,a){var o=e.getParseTreeNode(t,e.isVariableLikeOrAccessor);if(!o)return e.createToken(120);var s=wn(o),c=!s||133120&s.flags?se:Il(Qi(s));return 8192&c.flags&&c.symbol===s&&(n|=1048576),a&&(c=Wl(c)),K.typeToTypeNode(c,r,1024|n,i)}function Pv(t,r,n,i){var a=e.getParseTreeNode(t,e.isFunctionLike);if(!a)return e.createToken(120);var o=Go(a);return K.typeToTypeNode(ts(o),r,1024|n,i)}function wv(t,r,n,i){var a=e.getParseTreeNode(t,e.isExpression);if(!a)return e.createToken(120);var o=t_(ov(a));return K.typeToTypeNode(o,r,1024|n,i)}function Ov(t){return wt.has(e.escapeLeadingUnderscores(t))}function Iv(t,r){var n=Ur(t).resolvedSymbol;if(n)return n;var i=t;if(r){var a=t.parent;e.isDeclaration(a)&&t===a.name&&(i=bi(a))}return Hr(i,t.escapedText,70366143,void 0,void 0,!0)}function Mv(t){if(!e.isGeneratedIdentifier(t)){var r=e.getParseTreeNode(t,e.isIdentifier);if(r){var n=Iv(r);if(n)return Ln(n).valueDeclaration}}}function Lv(t){return!!(e.isDeclarationReadonly(t)||e.isVariableDeclaration(t)&&e.isVarConst(t))&&au(Qi(wn(t)))}function Rv(t,r){return function(t,r,n){return(1024&t.flags?K.symbolToExpression(t.symbol,67220415,r,void 0,n):t===ve?e.createTrue():t===ge&&e.createFalse())||e.createLiteral(t.value)}(Qi(wn(t)),t,r)}function Bv(t){var r=244===t.kind?e.tryCast(t.name,e.isStringLiteral):e.getExternalModuleName(t),n=hn(r,r,void 0);if(n)return e.getDeclarationOfKind(n,279)}function jv(t,r){if((g&r)!==r&&A.importHelpers){var n=e.getSourceFileOfNode(t);if(e.isEffectiveExternalModule(n,A)&&!(4194304&t.flags)){var i=(c=t,y||(y=bn(n,e.externalHelpersModuleNameText,e.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found,c)||re),y);if(i!==re)for(var a=r&~g,o=1;o<=65536;o<<=1)if(a&o){var s=Jv(o);qr(i.exports,e.escapeLeadingUnderscores(s),67220415)||Fr(t,e.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1,e.externalHelpersModuleNameText,s)}g|=r}}var c}function Jv(t){switch(t){case 1:return"__extends";case 2:return"__assign";case 4:return"__rest";case 8:return"__decorate";case 16:return"__metadata";case 32:return"__param";case 64:return"__awaiter";case 128:return"__generator";case 256:return"__values";case 512:return"__read";case 1024:return"__spread";case 2048:return"__await";case 4096:return"__asyncGenerator";case 8192:return"__asyncDelegator";case 16384:return"__asyncValues";case 32768:return"__exportStar";case 65536:return"__makeTemplateObject";default:return e.Debug.fail("Unrecognized helper")}}function zv(t){return function(t){if(!t.decorators)return!1;if(!e.nodeCanBeDecorated(t,t.parent,t.parent.parent))return 156!==t.kind||e.nodeIsPresent(t.body)?uh(t,e.Diagnostics.Decorators_are_not_valid_here):uh(t,e.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);if(158===t.kind||159===t.kind){var r=e.getAllAccessorDeclarations(t.parent.members,t);if(r.firstAccessor.decorators&&t===r.secondAccessor)return uh(t,e.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name)}return!1}(t)||function(t){var r,n,i,a,o=function(t){return!!t.modifiers&&(function(t){switch(t.kind){case 158:case 159:case 157:case 154:case 153:case 156:case 155:case 162:case 244:case 249:case 248:case 255:case 254:case 196:case 197:case 151:return!1;default:if(245===t.parent.kind||279===t.parent.kind)return!1;switch(t.kind){case 239:return Kv(t,121);case 240:return Kv(t,118);case 241:case 219:case 242:return!0;case 243:return Kv(t,77);default:return e.Debug.fail(),!1}}}(t)?uh(t,e.Diagnostics.Modifiers_cannot_appear_here):void 0)}(t);if(void 0!==o)return o;for(var s=0,c=0,u=t.modifiers;c1||e.modifiers[0].kind!==t}function Uv(t,r){return void 0===r&&(r=e.Diagnostics.Trailing_comma_not_allowed),!(!t||!t.hasTrailingComma)&&lh(t[0],t.end-",".length,",".length,r)}function Vv(t,r){if(t&&0===t.length){var n=t.pos-"<".length;return lh(r,n,e.skipTrivia(r.text,t.end)+">".length-n,e.Diagnostics.Type_parameter_list_cannot_be_empty)}return!1}function qv(t){if(F>=3){var r=t.body&&e.isBlock(t.body)&&e.findUseStrictPrologue(t.body.statements);if(r){var n=(a=t.parameters,e.filter(a,function(t){return!!t.initializer||e.isBindingPattern(t.name)||e.isRestParameter(t)}));if(e.length(n)){e.forEach(n,function(t){Ar(Fr(t,e.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive),e.createDiagnosticForNode(r,e.Diagnostics.use_strict_directive_used_here))});var i=n.map(function(t,r){return 0===r?e.createDiagnosticForNode(t,e.Diagnostics.Non_simple_parameter_declared_here):e.createDiagnosticForNode(t,e.Diagnostics.and_here)});return Ar.apply(void 0,[Fr(r,e.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(i)),!0}}}var a;return!1}function Wv(t){var r=e.getSourceFileOfNode(t);return zv(t)||Vv(t.typeParameters,r)||function(t){for(var r=!1,n=t.length,i=0;i".length-i,e.Diagnostics.Type_argument_list_cannot_be_empty)}return!1}(t,r)}function Gv(t){return function(t){if(t)for(var r=0,n=t;r1){var i=226===t.kind?e.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement:e.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;return uh(r.declarations[1],i)}var a=n[0];if(a.initializer){var i=226===t.kind?e.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer:e.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;return _h(a.name,i)}if(a.type)return _h(a,i=226===t.kind?e.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation:e.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation)}}return!1}function rh(t){if(t.parameters.length===(158===t.kind?1:2))return e.getThisParameter(t)}function nh(t,r){if(function(t){return e.isDynamicName(t)&&!Fa(t)}(t))return _h(t,r)}function ih(t){if(Wv(t))return!0;if(156===t.kind){if(188===t.parent.kind){if(t.modifiers&&(1!==t.modifiers.length||121!==e.first(t.modifiers).kind))return uh(t,e.Diagnostics.Modifiers_cannot_appear_here);if(Zv(t.questionToken,e.Diagnostics.An_object_member_cannot_be_declared_optional))return!0;if(eh(t.exclamationToken,e.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context))return!0;if(void 0===t.body)return lh(t,t.end-1,";".length,e.Diagnostics._0_expected,"{")}if($v(t))return!0}if(e.isClassLike(t.parent)){if(4194304&t.flags)return nh(t.name,e.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);if(156===t.kind&&!t.body)return nh(t.name,e.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)}else{if(241===t.parent.kind)return nh(t.name,e.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type);if(168===t.parent.kind)return nh(t.name,e.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)}}function ah(e){return 10===e.kind||8===e.kind||202===e.kind&&39===e.operator&&8===e.operand.kind}function oh(t){var r,n=t.initializer;if(n){var i=!(ah(n)||function(t){if((e.isPropertyAccessExpression(t)||e.isElementAccessExpression(t)&&ah(t.argumentExpression))&&e.isEntityNameExpression(t.expression))return!!(1024&Wm(t).flags)}(n)||102===n.kind||87===n.kind||(r=n,9===r.kind||202===r.kind&&39===r.operator&&9===r.operand.kind)),a=e.isDeclarationReadonly(t)||e.isVariableDeclaration(t)&&e.isVarConst(t);if(!a||t.type)return _h(n,e.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);if(i)return _h(n,e.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);if(!a||i)return _h(n,e.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts)}}function sh(t){var r=t.declarations;return!!Uv(t.declarations)||!t.declarations.length&&lh(t,r.pos,r.end-r.pos,e.Diagnostics.Variable_declaration_list_cannot_be_empty)}function ch(e){return e.parseDiagnostics.length>0}function uh(t,r,n,i,a){var o=e.getSourceFileOfNode(t);if(!ch(o)){var s=e.getSpanOfTokenAtPosition(o,t.pos);return ar.add(e.createFileDiagnostic(o,s.start,s.length,r,n,i,a)),!0}return!1}function lh(t,r,n,i,a,o,s){var c=e.getSourceFileOfNode(t);return!ch(c)&&(ar.add(e.createFileDiagnostic(c,r,n,i,a,o,s)),!0)}function _h(t,r,n,i,a){return!ch(e.getSourceFileOfNode(t))&&(ar.add(e.createDiagnosticForNode(t,r,n,i,a)),!0)}function dh(t){if(4194304&t.flags){if(e.isAccessor(t.parent))return Ur(t).hasReportedStatementInAmbientContext=!0;if(!Ur(t).hasReportedStatementInAmbientContext&&e.isFunctionLike(t.parent))return Ur(t).hasReportedStatementInAmbientContext=uh(t,e.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);if(218===t.parent.kind||245===t.parent.kind||279===t.parent.kind){var r=Ur(t.parent);if(!r.hasReportedStatementInAmbientContext)return r.hasReportedStatementInAmbientContext=uh(t,e.Diagnostics.Statements_are_not_allowed_in_ambient_contexts)}}return!1}function ph(t){if(32&t.numericLiteralFlags){var r=void 0;if(F>=1?r=e.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0:e.isChildOfNodeWithKind(t,182)?r=e.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0:e.isChildOfNodeWithKind(t,278)&&(r=e.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0),r){var n=e.isPrefixUnaryExpression(t.parent)&&39===t.parent.operator,i=(n?"-":"")+"0o"+t.text;return _h(n?t.parent:t,r,i)}}return!1}},function(e){e.JSX="JSX",e.IntrinsicElements="IntrinsicElements",e.ElementClass="ElementClass",e.ElementAttributesPropertyNameContainer="ElementAttributesProperty",e.ElementChildrenAttributeNameContainer="ElementChildrenAttribute",e.Element="Element",e.IntrinsicAttributes="IntrinsicAttributes",e.IntrinsicClassAttributes="IntrinsicClassAttributes",e.LibraryManagedAttributes="LibraryManagedAttributes"}(t||(t={}))}(c||(c={})),function(e){function t(t){var r=e.createNode(t,-1,-1);return r.flags|=8,r}function r(t,r){return t!==r&&(qt(t,r),jt(t,r),e.aggregateTransformFlags(t)),t}function n(t,r){if(t&&t!==e.emptyArray){if(e.isNodeArray(t))return t}else t=[];var n=t;return n.pos=-1,n.end=-1,n.hasTrailingComma=r,n}function i(e){if(void 0===e)return e;var r=t(e.kind);for(var n in r.flags|=e.flags,qt(r,e),e)!r.hasOwnProperty(n)&&e.hasOwnProperty(n)&&(r[n]=e[n]);return r}function a(t,r){if("number"==typeof t)return o(t+"");if("object"===f(t)&&"base10Value"in t)return s(e.pseudoBigIntToString(t)+"n");if("boolean"==typeof t)return t?m():g();if(e.isString(t)){var n=c(t);return r&&(n.singleQuote=!0),n}return i=t,(a=c(e.getTextOfIdentifierOrLiteral(i))).textSourceNode=i,a;var i,a}function o(e){var r=t(8);return r.text=e,r.numericLiteralFlags=0,r}function s(e){var r=t(9);return r.text=e,r}function c(e){var r=t(10);return r.text=e,r}function u(r,i){var a=t(72);return a.escapedText=e.escapeLeadingUnderscores(r),a.originalKeywordKind=r?e.stringToToken(r):0,a.autoGenerateFlags=0,a.autoGenerateId=0,i&&(a.typeArguments=n(i)),a}e.updateNode=r,e.createNodeArray=n,e.getSynthesizedClone=i,e.createLiteral=a,e.createNumericLiteral=o,e.createBigIntLiteral=s,e.createStringLiteral=c,e.createRegularExpressionLiteral=function(e){var r=t(13);return r.text=e,r},e.createIdentifier=u,e.updateIdentifier=function(t,n){return t.typeArguments!==n?r(u(e.idText(t),n),t):t};var l,_=0;function d(e){var t=u(e);return t.autoGenerateFlags=19,t.autoGenerateId=_,_++,t}function p(e){return t(e)}function m(){return t(102)}function g(){return t(87)}function y(e){return p(e)}function v(e,r){var n=t(148);return n.left=e,n.right=Lt(r),n}function h(r){var n=t(149);return n.expression=function(t){return e.isCommaSequence(t)?ce(t):t}(r),n}function b(e,r,n){var i=t(150);return i.name=Lt(e),i.constraint=r,i.default=n,i}function D(r,n,i,a,o,s,c){var u=t(151);return u.decorators=Rt(r),u.modifiers=Rt(n),u.dotDotDotToken=i,u.name=Lt(a),u.questionToken=o,u.type=s,u.initializer=c?e.parenthesizeExpressionForList(c):void 0,u}function x(r){var n=t(152);return n.expression=e.parenthesizeForAccess(r),n}function S(e,r,n,i,a){var o=t(153);return o.modifiers=Rt(e),o.name=Lt(r),o.questionToken=n,o.type=i,o.initializer=a,o}function T(e,r,n,i,a,o){var s=t(154);return s.decorators=Rt(e),s.modifiers=Rt(r),s.name=Lt(n),s.questionToken=void 0!==i&&56===i.kind?i:void 0,s.exclamationToken=void 0!==i&&52===i.kind?i:void 0,s.type=a,s.initializer=o,s}function C(e,t,r,n,i){var a=P(155,e,t,r);return a.name=Lt(n),a.questionToken=i,a}function k(e,r,i,a,o,s,c,u,l){var _=t(156);return _.decorators=Rt(e),_.modifiers=Rt(r),_.asteriskToken=i,_.name=Lt(a),_.questionToken=o,_.typeParameters=Rt(s),_.parameters=n(c),_.type=u,_.body=l,_}function E(e,r,i,a){var o=t(157);return o.decorators=Rt(e),o.modifiers=Rt(r),o.typeParameters=void 0,o.parameters=n(i),o.type=void 0,o.body=a,o}function N(e,r,i,a,o,s){var c=t(158);return c.decorators=Rt(e),c.modifiers=Rt(r),c.name=Lt(i),c.typeParameters=void 0,c.parameters=n(a),c.type=o,c.body=s,c}function A(e,r,i,a,o){var s=t(159);return s.decorators=Rt(e),s.modifiers=Rt(r),s.name=Lt(i),s.typeParameters=void 0,s.parameters=n(a),s.body=o,s}function F(e,r,i,a){var o=t(162);return o.decorators=Rt(e),o.modifiers=Rt(r),o.parameters=n(i),o.type=a,o}function P(e,r,n,i,a){var o=t(e);return o.typeParameters=Rt(r),o.parameters=Rt(n),o.type=i,o.typeArguments=Rt(a),o}function w(e,t,n,i){return e.typeParameters!==t||e.parameters!==n||e.type!==i?r(P(e.kind,t,n,i),e):e}function O(e,r){var n=t(163);return n.parameterName=Lt(e),n.type=r,n}function I(r,n){var i=t(164);return i.typeName=Lt(r),i.typeArguments=n&&e.parenthesizeTypeParameters(n),i}function M(e){var r=t(167);return r.exprName=e,r}function L(e){var r=t(168);return r.members=n(e),r}function R(r){var n=t(169);return n.elementType=e.parenthesizeArrayTypeMember(r),n}function B(e){var r=t(170);return r.elementTypes=n(e),r}function j(r){var n=t(171);return n.type=e.parenthesizeArrayTypeMember(r),n}function J(e){var r=t(172);return r.type=e,r}function z(r,n){var i=t(r);return i.types=e.parenthesizeElementTypeMembers(n),i}function K(e,t){return e.types!==t?r(z(e.kind,t),e):e}function U(r,n,i,a){var o=t(175);return o.checkType=e.parenthesizeConditionalTypeMember(r),o.extendsType=e.parenthesizeConditionalTypeMember(n),o.trueType=i,o.falseType=a,o}function V(e){var r=t(176);return r.typeParameter=e,r}function q(e,r,n,i){var a=t(183);return a.argument=e,a.qualifier=r,a.typeArguments=Rt(n),a.isTypeOf=i,a}function W(e){var r=t(177);return r.type=e,r}function H(r,n){var i=t(179);return i.operator="number"==typeof r?r:129,i.type=e.parenthesizeElementTypeMember("number"==typeof r?n:r),i}function G(r,n){var i=t(180);return i.objectType=e.parenthesizeElementTypeMember(r),i.indexType=n,i}function Y(e,r,n,i){var a=t(181);return a.readonlyToken=e,a.typeParameter=r,a.questionToken=n,a.type=i,a}function X(e){var r=t(182);return r.literal=e,r}function Q(e){var r=t(184);return r.elements=n(e),r}function $(e){var r=t(185);return r.elements=n(e),r}function Z(e,r,n,i){var a=t(186);return a.dotDotDotToken=e,a.propertyName=Lt(r),a.name=Lt(n),a.initializer=i,a}function ee(r,i){var a=t(187);return a.elements=e.parenthesizeListElements(n(r)),i&&(a.multiLine=!0),a}function te(e,r){var i=t(188);return i.properties=n(e),r&&(i.multiLine=!0),i}function re(r,n){var i=t(189);return i.expression=e.parenthesizeForAccess(r),i.name=Lt(n),Jt(i,131072),i}function ne(r,n){var i,o=t(190);return o.expression=e.parenthesizeForAccess(r),o.argumentExpression=(i=n,e.isString(i)||"number"==typeof i?a(i):i),o}function ie(r,i,a){var o=t(191);return o.expression=e.parenthesizeForAccess(r),o.typeArguments=Rt(i),o.arguments=e.parenthesizeListElements(n(a)),o}function ae(r,i,a){var o=t(192);return o.expression=e.parenthesizeForNew(r),o.typeArguments=Rt(i),o.arguments=a?e.parenthesizeListElements(n(a)):void 0,o}function oe(r,n,i){var a=t(193);return a.tag=e.parenthesizeForAccess(r),i?(a.typeArguments=Rt(n),a.template=i):(a.typeArguments=void 0,a.template=n),a}function se(r,n){var i=t(194);return i.type=r,i.expression=e.parenthesizePrefixOperand(n),i}function ce(e){var r=t(195);return r.expression=e,r}function ue(e,r,i,a,o,s,c){var u=t(196);return u.modifiers=Rt(e),u.asteriskToken=r,u.name=Lt(i),u.typeParameters=Rt(a),u.parameters=n(o),u.type=s,u.body=c,u}function le(r,i,a,o,s,c){var u=t(197);return u.modifiers=Rt(r),u.typeParameters=Rt(i),u.parameters=n(a),u.type=o,u.equalsGreaterThanToken=s||p(37),u.body=e.parenthesizeConciseBody(c),u}function _e(r){var n=t(198);return n.expression=e.parenthesizePrefixOperand(r),n}function de(r){var n=t(199);return n.expression=e.parenthesizePrefixOperand(r),n}function pe(r){var n=t(200);return n.expression=e.parenthesizePrefixOperand(r),n}function fe(r){var n=t(201);return n.expression=e.parenthesizePrefixOperand(r),n}function me(r,n){var i=t(202);return i.operator=r,i.operand=e.parenthesizePrefixOperand(n),i}function ge(r,n){var i=t(203);return i.operand=e.parenthesizePostfixOperand(r),i.operator=n,i}function ye(r,n,i){var a,o=t(204),s="number"==typeof(a=n)?p(a):a,c=s.kind;return o.left=e.parenthesizeBinaryOperand(c,r,!0,void 0),o.operatorToken=s,o.right=e.parenthesizeBinaryOperand(c,i,!1,o.left),o}function ve(r,n,i,a,o){var s=t(205);return s.condition=e.parenthesizeForConditionalHead(r),s.questionToken=o?n:p(56),s.whenTrue=e.parenthesizeSubexpressionOfConditionalExpression(o?i:n),s.colonToken=o?a:p(57),s.whenFalse=e.parenthesizeSubexpressionOfConditionalExpression(o||i),s}function he(e,r){var i=t(206);return i.head=e,i.templateSpans=n(r),i}function be(e,r){var n=t(207);return n.asteriskToken=e&&40===e.kind?e:void 0,n.expression=e&&40!==e.kind?e:r,n}function De(r){var n=t(208);return n.expression=e.parenthesizeExpressionForList(r),n}function xe(e,r,i,a,o){var s=t(209);return s.decorators=void 0,s.modifiers=Rt(e),s.name=Lt(r),s.typeParameters=Rt(i),s.heritageClauses=Rt(a),s.members=n(o),s}function Se(r,n){var i=t(211);return i.expression=e.parenthesizeForAccess(n),i.typeArguments=Rt(r),i}function Te(e,r){var n=t(212);return n.expression=e,n.type=r,n}function Ce(r){var n=t(213);return n.expression=e.parenthesizeForAccess(r),n}function ke(e,r){var n=t(214);return n.keywordToken=e,n.name=r,n}function Ee(e,r){var n=t(216);return n.expression=e,n.literal=r,n}function Ne(e,r){var i=t(218);return i.statements=n(e),r&&(i.multiLine=r),i}function Ae(r,n){var i=t(219);return i.decorators=void 0,i.modifiers=Rt(r),i.declarationList=e.isArray(n)?He(n):n,i}function Fe(r){var n=t(221);return n.expression=e.parenthesizeExpressionForExpressionStatement(r),n}function Pe(e,t){return e.expression!==t?r(Fe(t),e):e}function we(e,r,n){var i=t(222);return i.expression=e,i.thenStatement=r,i.elseStatement=n,i}function Oe(e,r){var n=t(223);return n.statement=e,n.expression=r,n}function Ie(e,r){var n=t(224);return n.expression=e,n.statement=r,n}function Me(e,r,n,i){var a=t(225);return a.initializer=e,a.condition=r,a.incrementor=n,a.statement=i,a}function Le(e,r,n){var i=t(226);return i.initializer=e,i.expression=r,i.statement=n,i}function Re(e,r,n,i){var a=t(227);return a.awaitModifier=e,a.initializer=r,a.expression=n,a.statement=i,a}function Be(e){var r=t(228);return r.label=Lt(e),r}function je(e){var r=t(229);return r.label=Lt(e),r}function Je(e){var r=t(230);return r.expression=e,r}function ze(e,r){var n=t(231);return n.expression=e,n.statement=r,n}function Ke(r,n){var i=t(232);return i.expression=e.parenthesizeExpressionForList(r),i.caseBlock=n,i}function Ue(e,r){var n=t(233);return n.label=Lt(e),n.statement=r,n}function Ve(e){var r=t(234);return r.expression=e,r}function qe(e,r,n){var i=t(235);return i.tryBlock=e,i.catchClause=r,i.finallyBlock=n,i}function We(r,n,i){var a=t(237);return a.name=Lt(r),a.type=n,a.initializer=void 0!==i?e.parenthesizeExpressionForList(i):void 0,a}function He(e,r){void 0===r&&(r=0);var i=t(238);return i.flags|=3&r,i.declarations=n(e),i}function Ge(e,r,i,a,o,s,c,u){var l=t(239);return l.decorators=Rt(e),l.modifiers=Rt(r),l.asteriskToken=i,l.name=Lt(a),l.typeParameters=Rt(o),l.parameters=n(s),l.type=c,l.body=u,l}function Ye(e,r,i,a,o,s){var c=t(240);return c.decorators=Rt(e),c.modifiers=Rt(r),c.name=Lt(i),c.typeParameters=Rt(a),c.heritageClauses=Rt(o),c.members=n(s),c}function Xe(e,r,i,a,o,s){var c=t(241);return c.decorators=Rt(e),c.modifiers=Rt(r),c.name=Lt(i),c.typeParameters=Rt(a),c.heritageClauses=Rt(o),c.members=n(s),c}function Qe(e,r,n,i,a){var o=t(242);return o.decorators=Rt(e),o.modifiers=Rt(r),o.name=Lt(n),o.typeParameters=Rt(i),o.type=a,o}function $e(e,r,i,a){var o=t(243);return o.decorators=Rt(e),o.modifiers=Rt(r),o.name=Lt(i),o.members=n(a),o}function Ze(e,r,n,i,a){void 0===a&&(a=0);var o=t(244);return o.flags|=532&a,o.decorators=Rt(e),o.modifiers=Rt(r),o.name=n,o.body=i,o}function et(e){var r=t(245);return r.statements=n(e),r}function tt(e){var r=t(246);return r.clauses=n(e),r}function rt(e){var r=t(247);return r.name=Lt(e),r}function nt(e,r,n,i){var a=t(248);return a.decorators=Rt(e),a.modifiers=Rt(r),a.name=Lt(n),a.moduleReference=i,a}function it(e,r,n,i){var a=t(249);return a.decorators=Rt(e),a.modifiers=Rt(r),a.importClause=n,a.moduleSpecifier=i,a}function at(e,r){var n=t(250);return n.name=e,n.namedBindings=r,n}function ot(e){var r=t(251);return r.name=e,r}function st(e){var r=t(252);return r.elements=n(e),r}function ct(e,r){var n=t(253);return n.propertyName=e,n.name=r,n}function ut(r,n,i,a){var o=t(254);return o.decorators=Rt(r),o.modifiers=Rt(n),o.isExportEquals=i,o.expression=i?e.parenthesizeBinaryOperand(59,a,!1,void 0):e.parenthesizeDefaultExpression(a),o}function lt(e,r,n,i){var a=t(255);return a.decorators=Rt(e),a.modifiers=Rt(r),a.exportClause=n,a.moduleSpecifier=i,a}function _t(e){var r=t(256);return r.elements=n(e),r}function dt(e,r){var n=t(257);return n.propertyName=Lt(e),n.name=Lt(r),n}function pt(e){var r=t(259);return r.expression=e,r}function ft(e,r){var n=t(e);return n.tagName=u(r),n}function mt(e,r,i){var a=t(260);return a.openingElement=e,a.children=n(r),a.closingElement=i,a}function gt(e,r,n){var i=t(261);return i.tagName=e,i.typeArguments=Rt(r),i.attributes=n,i}function yt(e,r,n){var i=t(262);return i.tagName=e,i.typeArguments=Rt(r),i.attributes=n,i}function vt(e){var r=t(263);return r.tagName=e,r}function ht(e,r,i){var a=t(264);return a.openingFragment=e,a.children=n(r),a.closingFragment=i,a}function bt(e,r){var n=t(267);return n.name=e,n.initializer=r,n}function Dt(e){var r=t(268);return r.properties=n(e),r}function xt(e){var r=t(269);return r.expression=e,r}function St(e,r){var n=t(270);return n.dotDotDotToken=e,n.expression=r,n}function Tt(r,i){var a=t(271);return a.expression=e.parenthesizeExpressionForList(r),a.statements=n(i),a}function Ct(e){var r=t(272);return r.statements=n(e),r}function kt(e,r){var i=t(273);return i.token=e,i.types=n(r),i}function Et(r,n){var i=t(274);return i.variableDeclaration=e.isString(r)?We(r):r,i.block=n,i}function Nt(r,n){var i=t(275);return i.name=Lt(r),i.questionToken=void 0,i.initializer=e.parenthesizeExpressionForList(n),i}function At(r,n){var i=t(276);return i.name=Lt(r),i.objectAssignmentInitializer=void 0!==n?e.parenthesizeExpressionForList(n):void 0,i}function Ft(r){var n=t(277);return n.expression=void 0!==r?e.parenthesizeExpressionForList(r):void 0,n}function Pt(r,n){var i=t(278);return i.name=Lt(r),i.initializer=n&&e.parenthesizeExpressionForList(n),i}function wt(e,r){var n=t(308);return n.expression=e,n.original=r,jt(n,r),n}function Ot(t){if(e.nodeIsSynthesized(t)&&!e.isParseTreeNode(t)&&!t.original&&!t.emitNode&&!t.id){if(309===t.kind)return t.elements;if(e.isBinaryExpression(t)&&27===t.operatorToken.kind)return[t.left,t.right]}return t}function It(r){var i=t(309);return i.elements=n(e.sameFlatMap(r,Ot)),i}function Mt(t,r){void 0===r&&(r=e.emptyArray);var n=e.createNode(280);return n.prepends=r,n.sourceFiles=t,n}function Lt(t){return e.isString(t)?u(t):t}function Rt(e){return e?n(e):void 0}function Bt(t){if(!t.emitNode){if(e.isParseTreeNode(t)){if(279===t.kind)return t.emitNode={annotatedNodes:[t]};Bt(e.getSourceFileOfNode(t)).annotatedNodes.push(t)}t.emitNode={}}return t.emitNode}function jt(e,t){return t&&(e.pos=t.pos,e.end=t.end),e}function Jt(e,t){return Bt(e).flags=t,e}function zt(e){var t=e.emitNode;return t&&t.leadingComments}function Kt(e,t){return Bt(e).leadingComments=t,e}function Ut(e){var t=e.emitNode;return t&&t.trailingComments}function Vt(e,t){return Bt(e).trailingComments=t,e}function qt(t,r){if(t.original=r,r){var n=r.emitNode;n&&(t.emitNode=function(t,r){var n=t.flags,i=t.leadingComments,a=t.trailingComments,o=t.commentRange,s=t.sourceMapRange,c=t.tokenSourceMapRanges,u=t.constantValue,l=t.helpers,_=t.startsOnNewLine;r||(r={});i&&(r.leadingComments=e.addRange(i.slice(),r.leadingComments));a&&(r.trailingComments=e.addRange(a.slice(),r.trailingComments));n&&(r.flags=n);o&&(r.commentRange=o);s&&(r.sourceMapRange=s);c&&(r.tokenSourceMapRanges=function(e,t){t||(t=[]);for(var r in e)t[r]=e[r];return t}(c,r.tokenSourceMapRanges));void 0!==u&&(r.constantValue=u);l&&(r.helpers=e.addRange(r.helpers,l));void 0!==_&&(r.startsOnNewLine=_);return r}(n,t.emitNode))}return t}e.createTempVariable=function(e,t){var r=u("");return r.autoGenerateFlags=1,r.autoGenerateId=_,_++,e&&e(r),t&&(r.autoGenerateFlags|=8),r},e.createLoopVariable=function(){var e=u("");return e.autoGenerateFlags=2,e.autoGenerateId=_,_++,e},e.createUniqueName=function(e){var t=u(e);return t.autoGenerateFlags=3,t.autoGenerateId=_,_++,t},e.createOptimisticUniqueName=d,e.createFileLevelUniqueName=function(e){var t=d(e);return t.autoGenerateFlags|=32,t},e.getGeneratedNameForNode=function(t,r){var n=u(t&&e.isIdentifier(t)?e.idText(t):"");return n.autoGenerateFlags=4|r,n.autoGenerateId=_,n.original=t,_++,n},e.createToken=p,e.createSuper=function(){return t(98)},e.createThis=function(){return t(100)},e.createNull=function(){return t(96)},e.createTrue=m,e.createFalse=g,e.createModifier=y,e.createModifiersFromModifierFlags=function(e){var t=[];return 1&e&&t.push(y(85)),2&e&&t.push(y(125)),512&e&&t.push(y(80)),2048&e&&t.push(y(77)),4&e&&t.push(y(115)),8&e&&t.push(y(113)),16&e&&t.push(y(114)),128&e&&t.push(y(118)),32&e&&t.push(y(116)),64&e&&t.push(y(133)),256&e&&t.push(y(121)),t},e.createQualifiedName=v,e.updateQualifiedName=function(e,t,n){return e.left!==t||e.right!==n?r(v(t,n),e):e},e.createComputedPropertyName=h,e.updateComputedPropertyName=function(e,t){return e.expression!==t?r(h(t),e):e},e.createTypeParameterDeclaration=b,e.updateTypeParameterDeclaration=function(e,t,n,i){return e.name!==t||e.constraint!==n||e.default!==i?r(b(t,n,i),e):e},e.createParameter=D,e.updateParameter=function(e,t,n,i,a,o,s,c){return e.decorators!==t||e.modifiers!==n||e.dotDotDotToken!==i||e.name!==a||e.questionToken!==o||e.type!==s||e.initializer!==c?r(D(t,n,i,a,o,s,c),e):e},e.createDecorator=x,e.updateDecorator=function(e,t){return e.expression!==t?r(x(t),e):e},e.createPropertySignature=S,e.updatePropertySignature=function(e,t,n,i,a,o){return e.modifiers!==t||e.name!==n||e.questionToken!==i||e.type!==a||e.initializer!==o?r(S(t,n,i,a,o),e):e},e.createProperty=T,e.updateProperty=function(e,t,n,i,a,o,s){return e.decorators!==t||e.modifiers!==n||e.name!==i||e.questionToken!==(void 0!==a&&56===a.kind?a:void 0)||e.exclamationToken!==(void 0!==a&&52===a.kind?a:void 0)||e.type!==o||e.initializer!==s?r(T(t,n,i,a,o,s),e):e},e.createMethodSignature=C,e.updateMethodSignature=function(e,t,n,i,a,o){return e.typeParameters!==t||e.parameters!==n||e.type!==i||e.name!==a||e.questionToken!==o?r(C(t,n,i,a,o),e):e},e.createMethod=k,e.updateMethod=function(e,t,n,i,a,o,s,c,u,l){return e.decorators!==t||e.modifiers!==n||e.asteriskToken!==i||e.name!==a||e.questionToken!==o||e.typeParameters!==s||e.parameters!==c||e.type!==u||e.body!==l?r(k(t,n,i,a,o,s,c,u,l),e):e},e.createConstructor=E,e.updateConstructor=function(e,t,n,i,a){return e.decorators!==t||e.modifiers!==n||e.parameters!==i||e.body!==a?r(E(t,n,i,a),e):e},e.createGetAccessor=N,e.updateGetAccessor=function(e,t,n,i,a,o,s){return e.decorators!==t||e.modifiers!==n||e.name!==i||e.parameters!==a||e.type!==o||e.body!==s?r(N(t,n,i,a,o,s),e):e},e.createSetAccessor=A,e.updateSetAccessor=function(e,t,n,i,a,o){return e.decorators!==t||e.modifiers!==n||e.name!==i||e.parameters!==a||e.body!==o?r(A(t,n,i,a,o),e):e},e.createCallSignature=function(e,t,r){return P(160,e,t,r)},e.updateCallSignature=function(e,t,r,n){return w(e,t,r,n)},e.createConstructSignature=function(e,t,r){return P(161,e,t,r)},e.updateConstructSignature=function(e,t,r,n){return w(e,t,r,n)},e.createIndexSignature=F,e.updateIndexSignature=function(e,t,n,i,a){return e.parameters!==i||e.type!==a||e.decorators!==t||e.modifiers!==n?r(F(t,n,i,a),e):e},e.createSignatureDeclaration=P,e.createKeywordTypeNode=function(e){return t(e)},e.createTypePredicateNode=O,e.updateTypePredicateNode=function(e,t,n){return e.parameterName!==t||e.type!==n?r(O(t,n),e):e},e.createTypeReferenceNode=I,e.updateTypeReferenceNode=function(e,t,n){return e.typeName!==t||e.typeArguments!==n?r(I(t,n),e):e},e.createFunctionTypeNode=function(e,t,r){return P(165,e,t,r)},e.updateFunctionTypeNode=function(e,t,r,n){return w(e,t,r,n)},e.createConstructorTypeNode=function(e,t,r){return P(166,e,t,r)},e.updateConstructorTypeNode=function(e,t,r,n){return w(e,t,r,n)},e.createTypeQueryNode=M,e.updateTypeQueryNode=function(e,t){return e.exprName!==t?r(M(t),e):e},e.createTypeLiteralNode=L,e.updateTypeLiteralNode=function(e,t){return e.members!==t?r(L(t),e):e},e.createArrayTypeNode=R,e.updateArrayTypeNode=function(e,t){return e.elementType!==t?r(R(t),e):e},e.createTupleTypeNode=B,e.updateTupleTypeNode=function(e,t){return e.elementTypes!==t?r(B(t),e):e},e.createOptionalTypeNode=j,e.updateOptionalTypeNode=function(e,t){return e.type!==t?r(j(t),e):e},e.createRestTypeNode=J,e.updateRestTypeNode=function(e,t){return e.type!==t?r(J(t),e):e},e.createUnionTypeNode=function(e){return z(173,e)},e.updateUnionTypeNode=function(e,t){return K(e,t)},e.createIntersectionTypeNode=function(e){return z(174,e)},e.updateIntersectionTypeNode=function(e,t){return K(e,t)},e.createUnionOrIntersectionTypeNode=z,e.createConditionalTypeNode=U,e.updateConditionalTypeNode=function(e,t,n,i,a){return e.checkType!==t||e.extendsType!==n||e.trueType!==i||e.falseType!==a?r(U(t,n,i,a),e):e},e.createInferTypeNode=V,e.updateInferTypeNode=function(e,t){return e.typeParameter!==t?r(V(t),e):e},e.createImportTypeNode=q,e.updateImportTypeNode=function(e,t,n,i,a){return e.argument!==t||e.qualifier!==n||e.typeArguments!==i||e.isTypeOf!==a?r(q(t,n,i,a),e):e},e.createParenthesizedType=W,e.updateParenthesizedType=function(e,t){return e.type!==t?r(W(t),e):e},e.createThisTypeNode=function(){return t(178)},e.createTypeOperatorNode=H,e.updateTypeOperatorNode=function(e,t){return e.type!==t?r(H(e.operator,t),e):e},e.createIndexedAccessTypeNode=G,e.updateIndexedAccessTypeNode=function(e,t,n){return e.objectType!==t||e.indexType!==n?r(G(t,n),e):e},e.createMappedTypeNode=Y,e.updateMappedTypeNode=function(e,t,n,i,a){return e.readonlyToken!==t||e.typeParameter!==n||e.questionToken!==i||e.type!==a?r(Y(t,n,i,a),e):e},e.createLiteralTypeNode=X,e.updateLiteralTypeNode=function(e,t){return e.literal!==t?r(X(t),e):e},e.createObjectBindingPattern=Q,e.updateObjectBindingPattern=function(e,t){return e.elements!==t?r(Q(t),e):e},e.createArrayBindingPattern=$,e.updateArrayBindingPattern=function(e,t){return e.elements!==t?r($(t),e):e},e.createBindingElement=Z,e.updateBindingElement=function(e,t,n,i,a){return e.propertyName!==n||e.dotDotDotToken!==t||e.name!==i||e.initializer!==a?r(Z(t,n,i,a),e):e},e.createArrayLiteral=ee,e.updateArrayLiteral=function(e,t){return e.elements!==t?r(ee(t,e.multiLine),e):e},e.createObjectLiteral=te,e.updateObjectLiteral=function(e,t){return e.properties!==t?r(te(t,e.multiLine),e):e},e.createPropertyAccess=re,e.updatePropertyAccess=function(t,n,i){return t.expression!==n||t.name!==i?r(Jt(re(n,i),e.getEmitFlags(t)),t):t},e.createElementAccess=ne,e.updateElementAccess=function(e,t,n){return e.expression!==t||e.argumentExpression!==n?r(ne(t,n),e):e},e.createCall=ie,e.updateCall=function(e,t,n,i){return e.expression!==t||e.typeArguments!==n||e.arguments!==i?r(ie(t,n,i),e):e},e.createNew=ae,e.updateNew=function(e,t,n,i){return e.expression!==t||e.typeArguments!==n||e.arguments!==i?r(ae(t,n,i),e):e},e.createTaggedTemplate=oe,e.updateTaggedTemplate=function(e,t,n,i){return e.tag!==t||(i?e.typeArguments!==n||e.template!==i:void 0!==e.typeArguments||e.template!==n)?r(oe(t,n,i),e):e},e.createTypeAssertion=se,e.updateTypeAssertion=function(e,t,n){return e.type!==t||e.expression!==n?r(se(t,n),e):e},e.createParen=ce,e.updateParen=function(e,t){return e.expression!==t?r(ce(t),e):e},e.createFunctionExpression=ue,e.updateFunctionExpression=function(e,t,n,i,a,o,s,c){return e.name!==i||e.modifiers!==t||e.asteriskToken!==n||e.typeParameters!==a||e.parameters!==o||e.type!==s||e.body!==c?r(ue(t,n,i,a,o,s,c),e):e},e.createArrowFunction=le,e.updateArrowFunction=function(e,t,n,i,a,o,s){return e.modifiers!==t||e.typeParameters!==n||e.parameters!==i||e.type!==a||e.equalsGreaterThanToken!==o||e.body!==s?r(le(t,n,i,a,o,s),e):e},e.createDelete=_e,e.updateDelete=function(e,t){return e.expression!==t?r(_e(t),e):e},e.createTypeOf=de,e.updateTypeOf=function(e,t){return e.expression!==t?r(de(t),e):e},e.createVoid=pe,e.updateVoid=function(e,t){return e.expression!==t?r(pe(t),e):e},e.createAwait=fe,e.updateAwait=function(e,t){return e.expression!==t?r(fe(t),e):e},e.createPrefix=me,e.updatePrefix=function(e,t){return e.operand!==t?r(me(e.operator,t),e):e},e.createPostfix=ge,e.updatePostfix=function(e,t){return e.operand!==t?r(ge(t,e.operator),e):e},e.createBinary=ye,e.updateBinary=function(e,t,n,i){return e.left!==t||e.right!==n?r(ye(t,i||e.operatorToken,n),e):e},e.createConditional=ve,e.updateConditional=function(e,t,n,i,a,o){return e.condition!==t||e.questionToken!==n||e.whenTrue!==i||e.colonToken!==a||e.whenFalse!==o?r(ve(t,n,i,a,o),e):e},e.createTemplateExpression=he,e.updateTemplateExpression=function(e,t,n){return e.head!==t||e.templateSpans!==n?r(he(t,n),e):e},e.createTemplateHead=function(e){var r=t(15);return r.text=e,r},e.createTemplateMiddle=function(e){var r=t(16);return r.text=e,r},e.createTemplateTail=function(e){var r=t(17);return r.text=e,r},e.createNoSubstitutionTemplateLiteral=function(e){var r=t(14);return r.text=e,r},e.createYield=be,e.updateYield=function(e,t,n){return e.expression!==n||e.asteriskToken!==t?r(be(t,n),e):e},e.createSpread=De,e.updateSpread=function(e,t){return e.expression!==t?r(De(t),e):e},e.createClassExpression=xe,e.updateClassExpression=function(e,t,n,i,a,o){return e.modifiers!==t||e.name!==n||e.typeParameters!==i||e.heritageClauses!==a||e.members!==o?r(xe(t,n,i,a,o),e):e},e.createOmittedExpression=function(){return t(210)},e.createExpressionWithTypeArguments=Se,e.updateExpressionWithTypeArguments=function(e,t,n){return e.typeArguments!==t||e.expression!==n?r(Se(t,n),e):e},e.createAsExpression=Te,e.updateAsExpression=function(e,t,n){return e.expression!==t||e.type!==n?r(Te(t,n),e):e},e.createNonNullExpression=Ce,e.updateNonNullExpression=function(e,t){return e.expression!==t?r(Ce(t),e):e},e.createMetaProperty=ke,e.updateMetaProperty=function(e,t){return e.name!==t?r(ke(e.keywordToken,t),e):e},e.createTemplateSpan=Ee,e.updateTemplateSpan=function(e,t,n){return e.expression!==t||e.literal!==n?r(Ee(t,n),e):e},e.createSemicolonClassElement=function(){return t(217)},e.createBlock=Ne,e.updateBlock=function(e,t){return e.statements!==t?r(Ne(t,e.multiLine),e):e},e.createVariableStatement=Ae,e.updateVariableStatement=function(e,t,n){return e.modifiers!==t||e.declarationList!==n?r(Ae(t,n),e):e},e.createEmptyStatement=function(){return t(220)},e.createExpressionStatement=Fe,e.updateExpressionStatement=Pe,e.createStatement=Fe,e.updateStatement=Pe,e.createIf=we,e.updateIf=function(e,t,n,i){return e.expression!==t||e.thenStatement!==n||e.elseStatement!==i?r(we(t,n,i),e):e},e.createDo=Oe,e.updateDo=function(e,t,n){return e.statement!==t||e.expression!==n?r(Oe(t,n),e):e},e.createWhile=Ie,e.updateWhile=function(e,t,n){return e.expression!==t||e.statement!==n?r(Ie(t,n),e):e},e.createFor=Me,e.updateFor=function(e,t,n,i,a){return e.initializer!==t||e.condition!==n||e.incrementor!==i||e.statement!==a?r(Me(t,n,i,a),e):e},e.createForIn=Le,e.updateForIn=function(e,t,n,i){return e.initializer!==t||e.expression!==n||e.statement!==i?r(Le(t,n,i),e):e},e.createForOf=Re,e.updateForOf=function(e,t,n,i,a){return e.awaitModifier!==t||e.initializer!==n||e.expression!==i||e.statement!==a?r(Re(t,n,i,a),e):e},e.createContinue=Be,e.updateContinue=function(e,t){return e.label!==t?r(Be(t),e):e},e.createBreak=je,e.updateBreak=function(e,t){return e.label!==t?r(je(t),e):e},e.createReturn=Je,e.updateReturn=function(e,t){return e.expression!==t?r(Je(t),e):e},e.createWith=ze,e.updateWith=function(e,t,n){return e.expression!==t||e.statement!==n?r(ze(t,n),e):e},e.createSwitch=Ke,e.updateSwitch=function(e,t,n){return e.expression!==t||e.caseBlock!==n?r(Ke(t,n),e):e},e.createLabel=Ue,e.updateLabel=function(e,t,n){return e.label!==t||e.statement!==n?r(Ue(t,n),e):e},e.createThrow=Ve,e.updateThrow=function(e,t){return e.expression!==t?r(Ve(t),e):e},e.createTry=qe,e.updateTry=function(e,t,n,i){return e.tryBlock!==t||e.catchClause!==n||e.finallyBlock!==i?r(qe(t,n,i),e):e},e.createDebuggerStatement=function(){return t(236)},e.createVariableDeclaration=We,e.updateVariableDeclaration=function(e,t,n,i){return e.name!==t||e.type!==n||e.initializer!==i?r(We(t,n,i),e):e},e.createVariableDeclarationList=He,e.updateVariableDeclarationList=function(e,t){return e.declarations!==t?r(He(t,e.flags),e):e},e.createFunctionDeclaration=Ge,e.updateFunctionDeclaration=function(e,t,n,i,a,o,s,c,u){return e.decorators!==t||e.modifiers!==n||e.asteriskToken!==i||e.name!==a||e.typeParameters!==o||e.parameters!==s||e.type!==c||e.body!==u?r(Ge(t,n,i,a,o,s,c,u),e):e},e.createClassDeclaration=Ye,e.updateClassDeclaration=function(e,t,n,i,a,o,s){return e.decorators!==t||e.modifiers!==n||e.name!==i||e.typeParameters!==a||e.heritageClauses!==o||e.members!==s?r(Ye(t,n,i,a,o,s),e):e},e.createInterfaceDeclaration=Xe,e.updateInterfaceDeclaration=function(e,t,n,i,a,o,s){return e.decorators!==t||e.modifiers!==n||e.name!==i||e.typeParameters!==a||e.heritageClauses!==o||e.members!==s?r(Xe(t,n,i,a,o,s),e):e},e.createTypeAliasDeclaration=Qe,e.updateTypeAliasDeclaration=function(e,t,n,i,a,o){return e.decorators!==t||e.modifiers!==n||e.name!==i||e.typeParameters!==a||e.type!==o?r(Qe(t,n,i,a,o),e):e},e.createEnumDeclaration=$e,e.updateEnumDeclaration=function(e,t,n,i,a){return e.decorators!==t||e.modifiers!==n||e.name!==i||e.members!==a?r($e(t,n,i,a),e):e},e.createModuleDeclaration=Ze,e.updateModuleDeclaration=function(e,t,n,i,a){return e.decorators!==t||e.modifiers!==n||e.name!==i||e.body!==a?r(Ze(t,n,i,a,e.flags),e):e},e.createModuleBlock=et,e.updateModuleBlock=function(e,t){return e.statements!==t?r(et(t),e):e},e.createCaseBlock=tt,e.updateCaseBlock=function(e,t){return e.clauses!==t?r(tt(t),e):e},e.createNamespaceExportDeclaration=rt,e.updateNamespaceExportDeclaration=function(e,t){return e.name!==t?r(rt(t),e):e},e.createImportEqualsDeclaration=nt,e.updateImportEqualsDeclaration=function(e,t,n,i,a){return e.decorators!==t||e.modifiers!==n||e.name!==i||e.moduleReference!==a?r(nt(t,n,i,a),e):e},e.createImportDeclaration=it,e.updateImportDeclaration=function(e,t,n,i,a){return e.decorators!==t||e.modifiers!==n||e.importClause!==i||e.moduleSpecifier!==a?r(it(t,n,i,a),e):e},e.createImportClause=at,e.updateImportClause=function(e,t,n){return e.name!==t||e.namedBindings!==n?r(at(t,n),e):e},e.createNamespaceImport=ot,e.updateNamespaceImport=function(e,t){return e.name!==t?r(ot(t),e):e},e.createNamedImports=st,e.updateNamedImports=function(e,t){return e.elements!==t?r(st(t),e):e},e.createImportSpecifier=ct,e.updateImportSpecifier=function(e,t,n){return e.propertyName!==t||e.name!==n?r(ct(t,n),e):e},e.createExportAssignment=ut,e.updateExportAssignment=function(e,t,n,i){return e.decorators!==t||e.modifiers!==n||e.expression!==i?r(ut(t,n,e.isExportEquals,i),e):e},e.createExportDeclaration=lt,e.updateExportDeclaration=function(e,t,n,i,a){return e.decorators!==t||e.modifiers!==n||e.exportClause!==i||e.moduleSpecifier!==a?r(lt(t,n,i,a),e):e},e.createNamedExports=_t,e.updateNamedExports=function(e,t){return e.elements!==t?r(_t(t),e):e},e.createExportSpecifier=dt,e.updateExportSpecifier=function(e,t,n){return e.propertyName!==t||e.name!==n?r(dt(t,n),e):e},e.createExternalModuleReference=pt,e.updateExternalModuleReference=function(e,t){return e.expression!==t?r(pt(t),e):e},e.createJSDocTypeExpression=function(e){var r=t(283);return r.type=e,r},e.createJSDocTypeTag=function(e,t){var r=ft(302,"type");return r.typeExpression=e,r.comment=t,r},e.createJSDocReturnTag=function(e,t){var r=ft(300,"returns");return r.typeExpression=e,r.comment=t,r},e.createJSDocParamTag=function(e,t,r,n){var i=ft(299,"param");return i.typeExpression=r,i.name=e,i.isBracketed=t,i.comment=n,i},e.createJSDocComment=function(e,r){var n=t(291);return n.comment=e,n.tags=r,n},e.createJsxElement=mt,e.updateJsxElement=function(e,t,n,i){return e.openingElement!==t||e.children!==n||e.closingElement!==i?r(mt(t,n,i),e):e},e.createJsxSelfClosingElement=gt,e.updateJsxSelfClosingElement=function(e,t,n,i){return e.tagName!==t||e.typeArguments!==n||e.attributes!==i?r(gt(t,n,i),e):e},e.createJsxOpeningElement=yt,e.updateJsxOpeningElement=function(e,t,n,i){return e.tagName!==t||e.typeArguments!==n||e.attributes!==i?r(yt(t,n,i),e):e},e.createJsxClosingElement=vt,e.updateJsxClosingElement=function(e,t){return e.tagName!==t?r(vt(t),e):e},e.createJsxFragment=ht,e.updateJsxFragment=function(e,t,n,i){return e.openingFragment!==t||e.children!==n||e.closingFragment!==i?r(ht(t,n,i),e):e},e.createJsxAttribute=bt,e.updateJsxAttribute=function(e,t,n){return e.name!==t||e.initializer!==n?r(bt(t,n),e):e},e.createJsxAttributes=Dt,e.updateJsxAttributes=function(e,t){return e.properties!==t?r(Dt(t),e):e},e.createJsxSpreadAttribute=xt,e.updateJsxSpreadAttribute=function(e,t){return e.expression!==t?r(xt(t),e):e},e.createJsxExpression=St,e.updateJsxExpression=function(e,t){return e.expression!==t?r(St(e.dotDotDotToken,t),e):e},e.createCaseClause=Tt,e.updateCaseClause=function(e,t,n){return e.expression!==t||e.statements!==n?r(Tt(t,n),e):e},e.createDefaultClause=Ct,e.updateDefaultClause=function(e,t){return e.statements!==t?r(Ct(t),e):e},e.createHeritageClause=kt,e.updateHeritageClause=function(e,t){return e.types!==t?r(kt(e.token,t),e):e},e.createCatchClause=Et,e.updateCatchClause=function(e,t,n){return e.variableDeclaration!==t||e.block!==n?r(Et(t,n),e):e},e.createPropertyAssignment=Nt,e.updatePropertyAssignment=function(e,t,n){return e.name!==t||e.initializer!==n?r(Nt(t,n),e):e},e.createShorthandPropertyAssignment=At,e.updateShorthandPropertyAssignment=function(e,t,n){return e.name!==t||e.objectAssignmentInitializer!==n?r(At(t,n),e):e},e.createSpreadAssignment=Ft,e.updateSpreadAssignment=function(e,t){return e.expression!==t?r(Ft(t),e):e},e.createEnumMember=Pt,e.updateEnumMember=function(e,t,n){return e.name!==t||e.initializer!==n?r(Pt(t,n),e):e},e.updateSourceFileNode=function(e,i,a,o,s,c,u){if(e.statements!==i||void 0!==a&&e.isDeclarationFile!==a||void 0!==o&&e.referencedFiles!==o||void 0!==s&&e.typeReferenceDirectives!==s||void 0!==u&&e.libReferenceDirectives!==u||void 0!==c&&e.hasNoDefaultLib!==c){var l=t(279);return l.flags|=e.flags,l.statements=n(i),l.endOfFileToken=e.endOfFileToken,l.fileName=e.fileName,l.path=e.path,l.text=e.text,l.isDeclarationFile=void 0===a?e.isDeclarationFile:a,l.referencedFiles=void 0===o?e.referencedFiles:o,l.typeReferenceDirectives=void 0===s?e.typeReferenceDirectives:s,l.hasNoDefaultLib=void 0===c?e.hasNoDefaultLib:c,l.libReferenceDirectives=void 0===u?e.libReferenceDirectives:u,void 0!==e.amdDependencies&&(l.amdDependencies=e.amdDependencies),void 0!==e.moduleName&&(l.moduleName=e.moduleName),void 0!==e.languageVariant&&(l.languageVariant=e.languageVariant),void 0!==e.renamedDependencies&&(l.renamedDependencies=e.renamedDependencies),void 0!==e.languageVersion&&(l.languageVersion=e.languageVersion),void 0!==e.scriptKind&&(l.scriptKind=e.scriptKind),void 0!==e.externalModuleIndicator&&(l.externalModuleIndicator=e.externalModuleIndicator),void 0!==e.commonJsModuleIndicator&&(l.commonJsModuleIndicator=e.commonJsModuleIndicator),void 0!==e.identifiers&&(l.identifiers=e.identifiers),void 0!==e.nodeCount&&(l.nodeCount=e.nodeCount),void 0!==e.identifierCount&&(l.identifierCount=e.identifierCount),void 0!==e.symbolCount&&(l.symbolCount=e.symbolCount),void 0!==e.parseDiagnostics&&(l.parseDiagnostics=e.parseDiagnostics),void 0!==e.bindDiagnostics&&(l.bindDiagnostics=e.bindDiagnostics),void 0!==e.bindSuggestionDiagnostics&&(l.bindSuggestionDiagnostics=e.bindSuggestionDiagnostics),void 0!==e.lineMap&&(l.lineMap=e.lineMap),void 0!==e.classifiableNames&&(l.classifiableNames=e.classifiableNames),void 0!==e.resolvedModules&&(l.resolvedModules=e.resolvedModules),void 0!==e.resolvedTypeReferenceDirectiveNames&&(l.resolvedTypeReferenceDirectiveNames=e.resolvedTypeReferenceDirectiveNames),void 0!==e.imports&&(l.imports=e.imports),void 0!==e.moduleAugmentations&&(l.moduleAugmentations=e.moduleAugmentations),void 0!==e.pragmas&&(l.pragmas=e.pragmas),void 0!==e.localJsxFactory&&(l.localJsxFactory=e.localJsxFactory),void 0!==e.localJsxNamespace&&(l.localJsxNamespace=e.localJsxNamespace),r(l,e)}return e},e.getMutableClone=function(e){var t=i(e);return t.pos=e.pos,t.end=e.end,t.parent=e.parent,t},e.createNotEmittedStatement=function(e){var r=t(307);return r.original=e,jt(r,e),r},e.createEndOfDeclarationMarker=function(e){var r=t(311);return r.emitNode={},r.original=e,r},e.createMergeDeclarationMarker=function(e){var r=t(310);return r.emitNode={},r.original=e,r},e.createPartiallyEmittedExpression=wt,e.updatePartiallyEmittedExpression=function(e,t){return e.expression!==t?r(wt(t,e.original),e):e},e.createCommaList=It,e.updateCommaList=function(e,t){return e.elements!==t?r(It(t),e):e},e.createBundle=Mt,e.createUnparsedSourceFile=function(t,r,n){var i=e.createNode(281);return i.text=t,i.sourceMapPath=r,i.sourceMapText=n,i},e.createInputFiles=function(t,r,n,i,a,o){var s=e.createNode(282);return s.javascriptText=t,s.javascriptMapPath=n,s.javascriptMapText=i,s.declarationText=r,s.declarationMapPath=a,s.declarationMapText=o,s},e.updateBundle=function(t,r,n){return void 0===n&&(n=e.emptyArray),t.sourceFiles!==r||t.prepends!==n?Mt(r,n):t},e.createImmediatelyInvokedFunctionExpression=function(e,t,r){return ie(ue(void 0,void 0,void 0,void 0,t?[t]:[],void 0,Ne(e,!0)),void 0,r?[r]:[])},e.createImmediatelyInvokedArrowFunction=function(e,t,r){return ie(le(void 0,void 0,t?[t]:[],void 0,void 0,Ne(e,!0)),void 0,r?[r]:[])},e.createComma=function(e,t){return ye(e,27,t)},e.createLessThan=function(e,t){return ye(e,28,t)},e.createAssignment=function(e,t){return ye(e,59,t)},e.createStrictEquality=function(e,t){return ye(e,35,t)},e.createStrictInequality=function(e,t){return ye(e,36,t)},e.createAdd=function(e,t){return ye(e,38,t)},e.createSubtract=function(e,t){return ye(e,39,t)},e.createPostfixIncrement=function(e){return ge(e,44)},e.createLogicalAnd=function(e,t){return ye(e,54,t)},e.createLogicalOr=function(e,t){return ye(e,55,t)},e.createLogicalNot=function(e){return me(52,e)},e.createVoidZero=function(){return pe(a(0))},e.createExportDefault=function(e){return ut(void 0,void 0,!1,e)},e.createExternalModuleExport=function(e){return lt(void 0,void 0,_t([dt(void 0,e)]))},e.disposeEmitNodes=function(t){var r=(t=e.getSourceFileOfNode(e.getParseTreeNode(t)))&&t.emitNode,n=r&&r.annotatedNodes;if(n)for(var i=0,a=n;i0&&(a[c-s]=u)}s>0&&(a.length-=s)}},e.compareEmitHelpers=function(t,r){return t===r?0:t.priority===r.priority?0:void 0===t.priority?1:void 0===r.priority?-1:e.compareValues(t.priority,r.priority)},e.setOriginalNode=qt}(c||(c={})),function(e){function t(t,r,n){if(e.isComputedPropertyName(r))return e.setTextRange(e.createElementAccess(t,r.expression),n);var i=e.setTextRange(e.isIdentifier(r)?e.createPropertyAccess(t,r):e.createElementAccess(t,r),r);return e.getOrCreateEmitNode(i).flags|=64,i}function r(t,r){var n=e.createIdentifier(t||"React");return n.flags&=-9,n.parent=e.getParseTreeNode(r),n}function n(t,n,i){return t?function t(n,i){if(e.isQualifiedName(n)){var a=t(n.left,i),o=e.createIdentifier(e.idText(n.right));return o.escapedText=n.right.escapedText,e.createPropertyAccess(a,o)}return r(e.idText(n),i)}(t,i):e.createPropertyAccess(r(n,i),"createElement")}function i(t){return e.setEmitFlags(e.createIdentifier(t),4098)}e.nullTransformationContext={enableEmitNotification:e.noop,enableSubstitution:e.noop,endLexicalEnvironment:function(){},getCompilerOptions:e.notImplemented,getEmitHost:e.notImplemented,getEmitResolver:e.notImplemented,hoistFunctionDeclaration:e.noop,hoistVariableDeclaration:e.noop,isEmitNotificationEnabled:e.notImplemented,isSubstitutionEnabled:e.notImplemented,onEmitNode:e.noop,onSubstituteNode:e.notImplemented,readEmitHelpers:e.notImplemented,requestEmitHelper:e.noop,resumeLexicalEnvironment:e.noop,startLexicalEnvironment:e.noop,suspendLexicalEnvironment:e.noop,addDiagnostic:e.noop},e.createTypeCheck=function(t,r){return"undefined"===r?e.createStrictEquality(t,e.createVoidZero()):e.createStrictEquality(e.createTypeOf(t),e.createLiteral(r))},e.createMemberAccessForPropertyName=t,e.createFunctionCall=function(t,r,n,i){return e.setTextRange(e.createCall(e.createPropertyAccess(t,"call"),void 0,[r].concat(n)),i)},e.createFunctionApply=function(t,r,n,i){return e.setTextRange(e.createCall(e.createPropertyAccess(t,"apply"),void 0,[r,n]),i)},e.createArraySlice=function(t,r){var n=[];return void 0!==r&&n.push("number"==typeof r?e.createLiteral(r):r),e.createCall(e.createPropertyAccess(t,"slice"),void 0,n)},e.createArrayConcat=function(t,r){return e.createCall(e.createPropertyAccess(t,"concat"),void 0,r)},e.createMathPow=function(t,r,n){return e.setTextRange(e.createCall(e.createPropertyAccess(e.createIdentifier("Math"),"pow"),void 0,[t,r]),n)},e.createExpressionForJsxElement=function(t,r,i,a,o,s,c){var u=[i];if(a&&u.push(a),o&&o.length>0)if(a||u.push(e.createNull()),o.length>1)for(var l=0,_=o;l<_.length;l++){var d=_[l];N(d),u.push(d)}else u.push(o[0]);return e.setTextRange(e.createCall(n(t,r,s),void 0,u),c)},e.createExpressionForJsxFragment=function(t,i,a,o,s){var c=[e.createPropertyAccess(r(i,o),"Fragment")];if(c.push(e.createNull()),a&&a.length>0)if(a.length>1)for(var u=0,l=a;u= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };'};e.createValuesHelper=function(t,r,n){return t.requestEmitHelper(a),e.setTextRange(e.createCall(i("__values"),void 0,[r]),n)};var o={name:"typescript:read",scoped:!1,text:'\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === "function" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i["return"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };'};e.createReadHelper=function(t,r,n,a){return t.requestEmitHelper(o),e.setTextRange(e.createCall(i("__read"),void 0,void 0!==n?[r,e.createLiteral(n)]:[r]),a)};var s={name:"typescript:spread",scoped:!1,text:"\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"};function c(t,r){var n=e.skipParentheses(t);switch(n.kind){case 72:return r;case 100:case 8:case 9:case 10:return!1;case 187:return 0!==n.elements.length;case 188:return n.properties.length>0;default:return!0}}function u(t){return e.isIdentifier(t)?e.createLiteral(t):e.isComputedPropertyName(t)?e.getMutableClone(t.expression):e.getMutableClone(t)}function l(e,t,r){return _(e,t,r,8192)}function _(t,r,n,i){void 0===i&&(i=0);var a=e.getNameOfDeclaration(t);if(a&&e.isIdentifier(a)&&!e.isGeneratedIdentifier(a)){var o=e.getMutableClone(a);return i|=e.getEmitFlags(a),n||(i|=48),r||(i|=1536),i&&e.setEmitFlags(o,i),o}return e.getGeneratedNameForNode(t)}function d(t,r,n,i){var a=e.createPropertyAccess(t,e.nodeIsSynthesized(r)?r:e.getSynthesizedClone(r));e.setTextRange(a,r);var o=0;return i||(o|=48),n||(o|=1536),o&&e.setEmitFlags(a,o),a}function p(t){return e.isStringLiteral(t.expression)&&"use strict"===t.expression.text}function f(t,r,n){e.Debug.assert(0===t.length,"Prologue directives should be at the first statement in the target statements array");for(var i=!1,a=0,o=r.length;ae.getOperatorPrecedence(204,27)?t:e.setTextRange(e.createParen(t),t)}function b(t){return 175===t.kind?e.createParenthesizedType(t):t}function D(t){switch(t.kind){case 173:case 174:case 165:case 166:return e.createParenthesizedType(t)}return b(t)}function x(e,t){for(;;){switch(e.kind){case 203:e=e.operand;continue;case 204:e=e.left;continue;case 205:e=e.condition;continue;case 193:e=e.tag;continue;case 191:if(t)return e;case 212:case 190:case 189:case 213:case 308:e=e.expression;continue}return e}}function S(e){return 204===e.kind&&27===e.operatorToken.kind||309===e.kind}function T(e,t){switch(void 0===t&&(t=7),e.kind){case 195:return 0!=(1&t);case 194:case 212:case 213:return 0!=(2&t);case 308:return 0!=(4&t)}return!1}function C(t,r){var n;void 0===r&&(r=7);do{n=t,1&r&&(t=e.skipParentheses(t)),2&r&&(t=k(t)),4&r&&(t=e.skipPartiallyEmittedExpressions(t))}while(n!==t);return t}function k(t){for(;e.isAssertionExpression(t)||213===t.kind;)t=t.expression;return t}function E(t,r,n){return void 0===n&&(n=7),t&&T(t,n)&&(!(195===(i=t).kind&&e.nodeIsSynthesized(i)&&e.nodeIsSynthesized(e.getSourceMapRange(i))&&e.nodeIsSynthesized(e.getCommentRange(i)))||e.some(e.getSyntheticLeadingComments(i))||e.some(e.getSyntheticTrailingComments(i)))?function(t,r){switch(t.kind){case 195:return e.updateParen(t,r);case 194:return e.updateTypeAssertion(t,t.type,r);case 212:return e.updateAsExpression(t,r,t.type);case 213:return e.updateNonNullExpression(t,r);case 308:return e.updatePartiallyEmittedExpression(t,r)}}(t,E(t.expression,r)):r;var i}function N(t){return e.setStartsOnNewLine(t,!0)}function A(t){var r=e.getOriginalNode(t,e.isSourceFile),n=r&&r.emitNode;return n&&n.externalHelpersModuleName}function F(t,r,n){if(t)return t.moduleName?e.createLiteral(t.moduleName):t.isDeclarationFile||!n.out&&!n.outFile?void 0:e.createLiteral(e.getExternalModuleNameFromPath(r,t.fileName))}function P(t){if(e.isDeclarationBindingElement(t))return t.name;if(!e.isObjectLiteralElementLike(t))return e.isAssignmentExpression(t,!0)?P(t.left):e.isSpreadElement(t)?P(t.expression):t;switch(t.kind){case 275:return P(t.initializer);case 276:return t.name;case 277:return P(t.expression)}}function w(e){var t=e.kind;return 10===t||8===t}function O(t){if(e.isBindingElement(t)){if(t.dotDotDotToken)return e.Debug.assertNode(t.name,e.isIdentifier),e.setOriginalNode(e.setTextRange(e.createSpread(t.name),t),t);var r=B(t.name);return t.initializer?e.setOriginalNode(e.setTextRange(e.createAssignment(r,t.initializer),t),t):r}return e.Debug.assertNode(t,e.isExpression),t}function I(t){if(e.isBindingElement(t)){if(t.dotDotDotToken)return e.Debug.assertNode(t.name,e.isIdentifier),e.setOriginalNode(e.setTextRange(e.createSpreadAssignment(t.name),t),t);if(t.propertyName){var r=B(t.name);return e.setOriginalNode(e.setTextRange(e.createPropertyAssignment(t.propertyName,t.initializer?e.createAssignment(r,t.initializer):r),t),t)}return e.Debug.assertNode(t.name,e.isIdentifier),e.setOriginalNode(e.setTextRange(e.createShorthandPropertyAssignment(t.name,t.initializer),t),t)}return e.Debug.assertNode(t,e.isObjectLiteralElementLike),t}function M(e){switch(e.kind){case 185:case 187:return R(e);case 184:case 188:return L(e)}}function L(t){return e.isObjectBindingPattern(t)?e.setOriginalNode(e.setTextRange(e.createObjectLiteral(e.map(t.elements,I)),t),t):(e.Debug.assertNode(t,e.isObjectLiteralExpression),t)}function R(t){return e.isArrayBindingPattern(t)?e.setOriginalNode(e.setTextRange(e.createArrayLiteral(e.map(t.elements,O)),t),t):(e.Debug.assertNode(t,e.isArrayLiteralExpression),t)}function B(t){return e.isBindingPattern(t)?M(t):(e.Debug.assertNode(t,e.isExpression),t)}e.createSpreadHelper=function(t,r,n){return t.requestEmitHelper(o),t.requestEmitHelper(s),e.setTextRange(e.createCall(i("__spread"),void 0,r),n)},e.createForOfBindingStatement=function(t,r){if(e.isVariableDeclarationList(t)){var n=e.first(t.declarations),i=e.updateVariableDeclaration(n,n.name,void 0,r);return e.setTextRange(e.createVariableStatement(void 0,e.updateVariableDeclarationList(t,[i])),t)}var a=e.setTextRange(e.createAssignment(t,r),t);return e.setTextRange(e.createStatement(a),t)},e.insertLeadingStatement=function(t,r){return e.isBlock(t)?e.updateBlock(t,e.setTextRange(e.createNodeArray([r].concat(t.statements)),t.statements)):e.createBlock(e.createNodeArray([t,r]),!0)},e.restoreEnclosingLabel=function t(r,n,i){if(!n)return r;var a=e.updateLabel(n,n.label,233===n.statement.kind?t(r,n.statement):r);return i&&i(n),a},e.createCallBinding=function(t,r,n,i){void 0===i&&(i=!1);var a,o,s=C(t,7);if(e.isSuperProperty(s))a=e.createThis(),o=s;else if(98===s.kind)a=e.createThis(),o=n<2?e.setTextRange(e.createIdentifier("_super"),s):s;else if(4096&e.getEmitFlags(s))a=e.createVoidZero(),o=v(s);else switch(s.kind){case 189:c(s.expression,i)?(a=e.createTempVariable(r),o=e.createPropertyAccess(e.setTextRange(e.createAssignment(a,s.expression),s.expression),s.name),e.setTextRange(o,s)):(a=s.expression,o=s);break;case 190:c(s.expression,i)?(a=e.createTempVariable(r),o=e.createElementAccess(e.setTextRange(e.createAssignment(a,s.expression),s.expression),s.argumentExpression),e.setTextRange(o,s)):(a=s.expression,o=s);break;default:a=e.createVoidZero(),o=v(t)}return{target:o,thisArg:a}},e.inlineExpressions=function(t){return t.length>10?e.createCommaList(t):e.reduceLeft(t,e.createComma)},e.createExpressionFromEntityName=function t(r){if(e.isQualifiedName(r)){var n=t(r.left),i=e.getMutableClone(r.right);return e.setTextRange(e.createPropertyAccess(n,i),r)}return e.getMutableClone(r)},e.createExpressionForPropertyName=u,e.createExpressionForObjectLiteralElementLike=function(r,n,i){switch(n.kind){case 158:case 159:return function(t,r,n,i){var a=e.getAllAccessorDeclarations(t,r),o=a.firstAccessor,s=a.getAccessor,c=a.setAccessor;if(r===o){var l=[];if(s){var _=e.createFunctionExpression(s.modifiers,void 0,void 0,void 0,s.parameters,void 0,s.body);e.setTextRange(_,s),e.setOriginalNode(_,s);var d=e.createPropertyAssignment("get",_);l.push(d)}if(c){var p=e.createFunctionExpression(c.modifiers,void 0,void 0,void 0,c.parameters,void 0,c.body);e.setTextRange(p,c),e.setOriginalNode(p,c);var f=e.createPropertyAssignment("set",p);l.push(f)}l.push(e.createPropertyAssignment("enumerable",e.createTrue())),l.push(e.createPropertyAssignment("configurable",e.createTrue()));var m=e.setTextRange(e.createCall(e.createPropertyAccess(e.createIdentifier("Object"),"defineProperty"),void 0,[n,u(r.name),e.createObjectLiteral(l,i)]),o);return e.aggregateTransformFlags(m)}}(r.properties,n,i,!!r.multiLine);case 275:return function(r,n){return e.aggregateTransformFlags(e.setOriginalNode(e.setTextRange(e.createAssignment(t(n,r.name,r.name),r.initializer),r),r))}(n,i);case 276:return function(r,n){return e.aggregateTransformFlags(e.setOriginalNode(e.setTextRange(e.createAssignment(t(n,r.name,r.name),e.getSynthesizedClone(r.name)),r),r))}(n,i);case 156:return function(r,n){return e.aggregateTransformFlags(e.setOriginalNode(e.setTextRange(e.createAssignment(t(n,r.name,r.name),e.setOriginalNode(e.setTextRange(e.createFunctionExpression(r.modifiers,r.asteriskToken,void 0,void 0,r.parameters,void 0,r.body),r),r)),r),r))}(n,i)}},e.getInternalName=function(e,t,r){return _(e,t,r,49152)},e.isInternalName=function(t){return 0!=(32768&e.getEmitFlags(t))},e.getLocalName=function(e,t,r){return _(e,t,r,16384)},e.isLocalName=function(t){return 0!=(16384&e.getEmitFlags(t))},e.getExportName=l,e.isExportName=function(t){return 0!=(8192&e.getEmitFlags(t))},e.getDeclarationName=function(e,t,r){return _(e,t,r)},e.getExternalModuleOrNamespaceExportName=function(t,r,n,i){return t&&e.hasModifier(r,1)?d(t,_(r),n,i):l(r,n,i)},e.getNamespaceMemberName=d,e.convertToFunctionBody=function(t,r){return e.isBlock(t)?t:e.setTextRange(e.createBlock([e.setTextRange(e.createReturn(t),t)],r),t)},e.convertFunctionDeclarationToExpression=function(t){if(!t.body)return e.Debug.fail();var r=e.createFunctionExpression(t.modifiers,t.asteriskToken,t.name,t.typeParameters,t.parameters,t.type,t.body);return e.setOriginalNode(r,t),e.setTextRange(r,t),e.getStartsOnNewLine(t)&&e.setStartsOnNewLine(r,!0),e.aggregateTransformFlags(r),r},e.addPrologue=function(e,t,r,n){return m(e,t,f(e,t,r),n)},e.addStandardPrologue=f,e.addCustomPrologue=m,e.findUseStrictPrologue=g,e.startsWithUseStrict=function(t){var r=e.firstOrUndefined(t);return void 0!==r&&e.isPrologueDirective(r)&&p(r)},e.ensureUseStrict=function(t){return g(t)?t:e.setTextRange(e.createNodeArray([N(e.createStatement(e.createLiteral("use strict")))].concat(t)),t)},e.parenthesizeBinaryOperand=function(t,r,n,i){return 195===e.skipPartiallyEmittedExpressions(r).kind?r:function(t,r,n,i){var a=e.getOperatorPrecedence(204,t),o=e.getOperatorAssociativity(204,t),s=e.skipPartiallyEmittedExpressions(r);if(!n&&197===r.kind&&a>4)return!0;var c=e.getExpressionPrecedence(s);switch(e.compareValues(c,a)){case-1:return!(!n&&1===o&&207===r.kind);case 1:return!1;case 0:if(n)return 1===o;if(e.isBinaryExpression(s)&&s.operatorToken.kind===t){if(function(e){return 40===e||50===e||49===e||51===e}(t))return!1;if(38===t){var u=i?y(i):0;if(e.isLiteralKind(u)&&u===y(s))return!1}}var l=e.getExpressionAssociativity(s);return 0===l}}(t,r,n,i)?e.createParen(r):r},e.parenthesizeForConditionalHead=function(t){var r=e.getOperatorPrecedence(205,56),n=e.skipPartiallyEmittedExpressions(t),i=e.getExpressionPrecedence(n);return-1===e.compareValues(i,r)?e.createParen(t):t},e.parenthesizeSubexpressionOfConditionalExpression=function(t){return S(e.skipPartiallyEmittedExpressions(t))?e.createParen(t):t},e.parenthesizeDefaultExpression=function(t){var r=e.skipPartiallyEmittedExpressions(t),n=S(r);if(!n)switch(x(r,!1).kind){case 209:case 196:n=!0}return n?e.createParen(t):t},e.parenthesizeForNew=function(t){var r=x(t,!0);switch(r.kind){case 191:return e.createParen(t);case 192:return r.arguments?t:e.createParen(t)}return v(t)},e.parenthesizeForAccess=v,e.parenthesizePostfixOperand=function(t){return e.isLeftHandSideExpression(t)?t:e.setTextRange(e.createParen(t),t)},e.parenthesizePrefixOperand=function(t){return e.isUnaryExpression(t)?t:e.setTextRange(e.createParen(t),t)},e.parenthesizeListElements=function(t){for(var r,n=0;ns-i)&&(a=s-i),(i>0||a0&&d<=147||178===d)return s;switch(d){case 72:return e.updateIdentifier(s,l(s.typeArguments,c,t));case 148:return e.updateQualifiedName(s,r(s.left,c,e.isEntityName),r(s.right,c,e.isIdentifier));case 149:return e.updateComputedPropertyName(s,r(s.expression,c,e.isExpression));case 150:return e.updateTypeParameterDeclaration(s,r(s.name,c,e.isIdentifier),r(s.constraint,c,e.isTypeNode),r(s.default,c,e.isTypeNode));case 151:return e.updateParameter(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.dotDotDotToken,_,e.isToken),r(s.name,c,e.isBindingName),r(s.questionToken,_,e.isToken),r(s.type,c,e.isTypeNode),r(s.initializer,c,e.isExpression));case 152:return e.updateDecorator(s,r(s.expression,c,e.isExpression));case 153:return e.updatePropertySignature(s,l(s.modifiers,c,e.isToken),r(s.name,c,e.isPropertyName),r(s.questionToken,_,e.isToken),r(s.type,c,e.isTypeNode),r(s.initializer,c,e.isExpression));case 154:return e.updateProperty(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.name,c,e.isPropertyName),r(s.questionToken,_,e.isToken),r(s.type,c,e.isTypeNode),r(s.initializer,c,e.isExpression));case 155:return e.updateMethodSignature(s,l(s.typeParameters,c,e.isTypeParameterDeclaration),l(s.parameters,c,e.isParameterDeclaration),r(s.type,c,e.isTypeNode),r(s.name,c,e.isPropertyName),r(s.questionToken,_,e.isToken));case 156:return e.updateMethod(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.asteriskToken,_,e.isToken),r(s.name,c,e.isPropertyName),r(s.questionToken,_,e.isToken),l(s.typeParameters,c,e.isTypeParameterDeclaration),a(s.parameters,c,u,l),r(s.type,c,e.isTypeNode),o(s.body,c,u));case 157:return e.updateConstructor(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),a(s.parameters,c,u,l),o(s.body,c,u));case 158:return e.updateGetAccessor(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.name,c,e.isPropertyName),a(s.parameters,c,u,l),r(s.type,c,e.isTypeNode),o(s.body,c,u));case 159:return e.updateSetAccessor(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.name,c,e.isPropertyName),a(s.parameters,c,u,l),o(s.body,c,u));case 160:return e.updateCallSignature(s,l(s.typeParameters,c,e.isTypeParameterDeclaration),l(s.parameters,c,e.isParameterDeclaration),r(s.type,c,e.isTypeNode));case 161:return e.updateConstructSignature(s,l(s.typeParameters,c,e.isTypeParameterDeclaration),l(s.parameters,c,e.isParameterDeclaration),r(s.type,c,e.isTypeNode));case 162:return e.updateIndexSignature(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),l(s.parameters,c,e.isParameterDeclaration),r(s.type,c,e.isTypeNode));case 163:return e.updateTypePredicateNode(s,r(s.parameterName,c),r(s.type,c,e.isTypeNode));case 164:return e.updateTypeReferenceNode(s,r(s.typeName,c,e.isEntityName),l(s.typeArguments,c,e.isTypeNode));case 165:return e.updateFunctionTypeNode(s,l(s.typeParameters,c,e.isTypeParameterDeclaration),l(s.parameters,c,e.isParameterDeclaration),r(s.type,c,e.isTypeNode));case 166:return e.updateConstructorTypeNode(s,l(s.typeParameters,c,e.isTypeParameterDeclaration),l(s.parameters,c,e.isParameterDeclaration),r(s.type,c,e.isTypeNode));case 167:return e.updateTypeQueryNode(s,r(s.exprName,c,e.isEntityName));case 168:return e.updateTypeLiteralNode(s,l(s.members,c,e.isTypeElement));case 169:return e.updateArrayTypeNode(s,r(s.elementType,c,e.isTypeNode));case 170:return e.updateTupleTypeNode(s,l(s.elementTypes,c,e.isTypeNode));case 171:return e.updateOptionalTypeNode(s,r(s.type,c,e.isTypeNode));case 172:return e.updateRestTypeNode(s,r(s.type,c,e.isTypeNode));case 173:return e.updateUnionTypeNode(s,l(s.types,c,e.isTypeNode));case 174:return e.updateIntersectionTypeNode(s,l(s.types,c,e.isTypeNode));case 175:return e.updateConditionalTypeNode(s,r(s.checkType,c,e.isTypeNode),r(s.extendsType,c,e.isTypeNode),r(s.trueType,c,e.isTypeNode),r(s.falseType,c,e.isTypeNode));case 176:return e.updateInferTypeNode(s,r(s.typeParameter,c,e.isTypeParameterDeclaration));case 183:return e.updateImportTypeNode(s,r(s.argument,c,e.isTypeNode),r(s.qualifier,c,e.isEntityName),n(s.typeArguments,c,e.isTypeNode),s.isTypeOf);case 177:return e.updateParenthesizedType(s,r(s.type,c,e.isTypeNode));case 179:return e.updateTypeOperatorNode(s,r(s.type,c,e.isTypeNode));case 180:return e.updateIndexedAccessTypeNode(s,r(s.objectType,c,e.isTypeNode),r(s.indexType,c,e.isTypeNode));case 181:return e.updateMappedTypeNode(s,r(s.readonlyToken,_,e.isToken),r(s.typeParameter,c,e.isTypeParameterDeclaration),r(s.questionToken,_,e.isToken),r(s.type,c,e.isTypeNode));case 182:return e.updateLiteralTypeNode(s,r(s.literal,c,e.isExpression));case 184:return e.updateObjectBindingPattern(s,l(s.elements,c,e.isBindingElement));case 185:return e.updateArrayBindingPattern(s,l(s.elements,c,e.isArrayBindingElement));case 186:return e.updateBindingElement(s,r(s.dotDotDotToken,_,e.isToken),r(s.propertyName,c,e.isPropertyName),r(s.name,c,e.isBindingName),r(s.initializer,c,e.isExpression));case 187:return e.updateArrayLiteral(s,l(s.elements,c,e.isExpression));case 188:return e.updateObjectLiteral(s,l(s.properties,c,e.isObjectLiteralElementLike));case 189:return e.updatePropertyAccess(s,r(s.expression,c,e.isExpression),r(s.name,c,e.isIdentifier));case 190:return e.updateElementAccess(s,r(s.expression,c,e.isExpression),r(s.argumentExpression,c,e.isExpression));case 191:return e.updateCall(s,r(s.expression,c,e.isExpression),l(s.typeArguments,c,e.isTypeNode),l(s.arguments,c,e.isExpression));case 192:return e.updateNew(s,r(s.expression,c,e.isExpression),l(s.typeArguments,c,e.isTypeNode),l(s.arguments,c,e.isExpression));case 193:return e.updateTaggedTemplate(s,r(s.tag,c,e.isExpression),n(s.typeArguments,c,e.isExpression),r(s.template,c,e.isTemplateLiteral));case 194:return e.updateTypeAssertion(s,r(s.type,c,e.isTypeNode),r(s.expression,c,e.isExpression));case 195:return e.updateParen(s,r(s.expression,c,e.isExpression));case 196:return e.updateFunctionExpression(s,l(s.modifiers,c,e.isModifier),r(s.asteriskToken,_,e.isToken),r(s.name,c,e.isIdentifier),l(s.typeParameters,c,e.isTypeParameterDeclaration),a(s.parameters,c,u,l),r(s.type,c,e.isTypeNode),o(s.body,c,u));case 197:return e.updateArrowFunction(s,l(s.modifiers,c,e.isModifier),l(s.typeParameters,c,e.isTypeParameterDeclaration),a(s.parameters,c,u,l),r(s.type,c,e.isTypeNode),r(s.equalsGreaterThanToken,c,e.isToken),o(s.body,c,u));case 198:return e.updateDelete(s,r(s.expression,c,e.isExpression));case 199:return e.updateTypeOf(s,r(s.expression,c,e.isExpression));case 200:return e.updateVoid(s,r(s.expression,c,e.isExpression));case 201:return e.updateAwait(s,r(s.expression,c,e.isExpression));case 202:return e.updatePrefix(s,r(s.operand,c,e.isExpression));case 203:return e.updatePostfix(s,r(s.operand,c,e.isExpression));case 204:return e.updateBinary(s,r(s.left,c,e.isExpression),r(s.right,c,e.isExpression),r(s.operatorToken,c,e.isToken));case 205:return e.updateConditional(s,r(s.condition,c,e.isExpression),r(s.questionToken,c,e.isToken),r(s.whenTrue,c,e.isExpression),r(s.colonToken,c,e.isToken),r(s.whenFalse,c,e.isExpression));case 206:return e.updateTemplateExpression(s,r(s.head,c,e.isTemplateHead),l(s.templateSpans,c,e.isTemplateSpan));case 207:return e.updateYield(s,r(s.asteriskToken,_,e.isToken),r(s.expression,c,e.isExpression));case 208:return e.updateSpread(s,r(s.expression,c,e.isExpression));case 209:return e.updateClassExpression(s,l(s.modifiers,c,e.isModifier),r(s.name,c,e.isIdentifier),l(s.typeParameters,c,e.isTypeParameterDeclaration),l(s.heritageClauses,c,e.isHeritageClause),l(s.members,c,e.isClassElement));case 211:return e.updateExpressionWithTypeArguments(s,l(s.typeArguments,c,e.isTypeNode),r(s.expression,c,e.isExpression));case 212:return e.updateAsExpression(s,r(s.expression,c,e.isExpression),r(s.type,c,e.isTypeNode));case 213:return e.updateNonNullExpression(s,r(s.expression,c,e.isExpression));case 214:return e.updateMetaProperty(s,r(s.name,c,e.isIdentifier));case 216:return e.updateTemplateSpan(s,r(s.expression,c,e.isExpression),r(s.literal,c,e.isTemplateMiddleOrTemplateTail));case 218:return e.updateBlock(s,l(s.statements,c,e.isStatement));case 219:return e.updateVariableStatement(s,l(s.modifiers,c,e.isModifier),r(s.declarationList,c,e.isVariableDeclarationList));case 221:return e.updateExpressionStatement(s,r(s.expression,c,e.isExpression));case 222:return e.updateIf(s,r(s.expression,c,e.isExpression),r(s.thenStatement,c,e.isStatement,e.liftToBlock),r(s.elseStatement,c,e.isStatement,e.liftToBlock));case 223:return e.updateDo(s,r(s.statement,c,e.isStatement,e.liftToBlock),r(s.expression,c,e.isExpression));case 224:return e.updateWhile(s,r(s.expression,c,e.isExpression),r(s.statement,c,e.isStatement,e.liftToBlock));case 225:return e.updateFor(s,r(s.initializer,c,e.isForInitializer),r(s.condition,c,e.isExpression),r(s.incrementor,c,e.isExpression),r(s.statement,c,e.isStatement,e.liftToBlock));case 226:return e.updateForIn(s,r(s.initializer,c,e.isForInitializer),r(s.expression,c,e.isExpression),r(s.statement,c,e.isStatement,e.liftToBlock));case 227:return e.updateForOf(s,r(s.awaitModifier,c,e.isToken),r(s.initializer,c,e.isForInitializer),r(s.expression,c,e.isExpression),r(s.statement,c,e.isStatement,e.liftToBlock));case 228:return e.updateContinue(s,r(s.label,c,e.isIdentifier));case 229:return e.updateBreak(s,r(s.label,c,e.isIdentifier));case 230:return e.updateReturn(s,r(s.expression,c,e.isExpression));case 231:return e.updateWith(s,r(s.expression,c,e.isExpression),r(s.statement,c,e.isStatement,e.liftToBlock));case 232:return e.updateSwitch(s,r(s.expression,c,e.isExpression),r(s.caseBlock,c,e.isCaseBlock));case 233:return e.updateLabel(s,r(s.label,c,e.isIdentifier),r(s.statement,c,e.isStatement,e.liftToBlock));case 234:return e.updateThrow(s,r(s.expression,c,e.isExpression));case 235:return e.updateTry(s,r(s.tryBlock,c,e.isBlock),r(s.catchClause,c,e.isCatchClause),r(s.finallyBlock,c,e.isBlock));case 237:return e.updateVariableDeclaration(s,r(s.name,c,e.isBindingName),r(s.type,c,e.isTypeNode),r(s.initializer,c,e.isExpression));case 238:return e.updateVariableDeclarationList(s,l(s.declarations,c,e.isVariableDeclaration));case 239:return e.updateFunctionDeclaration(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.asteriskToken,_,e.isToken),r(s.name,c,e.isIdentifier),l(s.typeParameters,c,e.isTypeParameterDeclaration),a(s.parameters,c,u,l),r(s.type,c,e.isTypeNode),o(s.body,c,u));case 240:return e.updateClassDeclaration(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.name,c,e.isIdentifier),l(s.typeParameters,c,e.isTypeParameterDeclaration),l(s.heritageClauses,c,e.isHeritageClause),l(s.members,c,e.isClassElement));case 241:return e.updateInterfaceDeclaration(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.name,c,e.isIdentifier),l(s.typeParameters,c,e.isTypeParameterDeclaration),l(s.heritageClauses,c,e.isHeritageClause),l(s.members,c,e.isTypeElement));case 242:return e.updateTypeAliasDeclaration(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.name,c,e.isIdentifier),l(s.typeParameters,c,e.isTypeParameterDeclaration),r(s.type,c,e.isTypeNode));case 243:return e.updateEnumDeclaration(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.name,c,e.isIdentifier),l(s.members,c,e.isEnumMember));case 244:return e.updateModuleDeclaration(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.name,c,e.isIdentifier),r(s.body,c,e.isModuleBody));case 245:return e.updateModuleBlock(s,l(s.statements,c,e.isStatement));case 246:return e.updateCaseBlock(s,l(s.clauses,c,e.isCaseOrDefaultClause));case 247:return e.updateNamespaceExportDeclaration(s,r(s.name,c,e.isIdentifier));case 248:return e.updateImportEqualsDeclaration(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.name,c,e.isIdentifier),r(s.moduleReference,c,e.isModuleReference));case 249:return e.updateImportDeclaration(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.importClause,c,e.isImportClause),r(s.moduleSpecifier,c,e.isExpression));case 250:return e.updateImportClause(s,r(s.name,c,e.isIdentifier),r(s.namedBindings,c,e.isNamedImportBindings));case 251:return e.updateNamespaceImport(s,r(s.name,c,e.isIdentifier));case 252:return e.updateNamedImports(s,l(s.elements,c,e.isImportSpecifier));case 253:return e.updateImportSpecifier(s,r(s.propertyName,c,e.isIdentifier),r(s.name,c,e.isIdentifier));case 254:return e.updateExportAssignment(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.expression,c,e.isExpression));case 255:return e.updateExportDeclaration(s,l(s.decorators,c,e.isDecorator),l(s.modifiers,c,e.isModifier),r(s.exportClause,c,e.isNamedExports),r(s.moduleSpecifier,c,e.isExpression));case 256:return e.updateNamedExports(s,l(s.elements,c,e.isExportSpecifier));case 257:return e.updateExportSpecifier(s,r(s.propertyName,c,e.isIdentifier),r(s.name,c,e.isIdentifier));case 259:return e.updateExternalModuleReference(s,r(s.expression,c,e.isExpression));case 260:return e.updateJsxElement(s,r(s.openingElement,c,e.isJsxOpeningElement),l(s.children,c,e.isJsxChild),r(s.closingElement,c,e.isJsxClosingElement));case 261:return e.updateJsxSelfClosingElement(s,r(s.tagName,c,e.isJsxTagNameExpression),l(s.typeArguments,c,e.isTypeNode),r(s.attributes,c,e.isJsxAttributes));case 262:return e.updateJsxOpeningElement(s,r(s.tagName,c,e.isJsxTagNameExpression),l(s.typeArguments,c,e.isTypeNode),r(s.attributes,c,e.isJsxAttributes));case 263:return e.updateJsxClosingElement(s,r(s.tagName,c,e.isJsxTagNameExpression));case 264:return e.updateJsxFragment(s,r(s.openingFragment,c,e.isJsxOpeningFragment),l(s.children,c,e.isJsxChild),r(s.closingFragment,c,e.isJsxClosingFragment));case 267:return e.updateJsxAttribute(s,r(s.name,c,e.isIdentifier),r(s.initializer,c,e.isStringLiteralOrJsxExpression));case 268:return e.updateJsxAttributes(s,l(s.properties,c,e.isJsxAttributeLike));case 269:return e.updateJsxSpreadAttribute(s,r(s.expression,c,e.isExpression));case 270:return e.updateJsxExpression(s,r(s.expression,c,e.isExpression));case 271:return e.updateCaseClause(s,r(s.expression,c,e.isExpression),l(s.statements,c,e.isStatement));case 272:return e.updateDefaultClause(s,l(s.statements,c,e.isStatement));case 273:return e.updateHeritageClause(s,l(s.types,c,e.isExpressionWithTypeArguments));case 274:return e.updateCatchClause(s,r(s.variableDeclaration,c,e.isVariableDeclaration),r(s.block,c,e.isBlock));case 275:return e.updatePropertyAssignment(s,r(s.name,c,e.isPropertyName),r(s.initializer,c,e.isExpression));case 276:return e.updateShorthandPropertyAssignment(s,r(s.name,c,e.isIdentifier),r(s.objectAssignmentInitializer,c,e.isExpression));case 277:return e.updateSpreadAssignment(s,r(s.expression,c,e.isExpression));case 278:return e.updateEnumMember(s,r(s.name,c,e.isPropertyName),r(s.initializer,c,e.isExpression));case 279:return e.updateSourceFileNode(s,i(s.statements,c,u));case 308:return e.updatePartiallyEmittedExpression(s,r(s.expression,c,e.isExpression));case 309:return e.updateCommaList(s,l(s.elements,c,e.isExpression));default:return s}}}}(c||(c={})),function(e){function t(e,t,r){return e?t(r,e):r}function r(e,t,r){return e?t(r,e):r}function n(n,i,a,o){if(void 0===n)return i;var s=o?r:e.reduceLeft,c=o||a,u=n.kind;if(u>0&&u<=147)return i;if(u>=163&&u<=182)return i;var l=i;switch(n.kind){case 217:case 220:case 210:case 236:case 307:break;case 148:l=t(n.left,a,l),l=t(n.right,a,l);break;case 149:l=t(n.expression,a,l);break;case 151:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.name,a,l),l=t(n.type,a,l),l=t(n.initializer,a,l);break;case 152:l=t(n.expression,a,l);break;case 153:l=s(n.modifiers,c,l),l=t(n.name,a,l),l=t(n.questionToken,a,l),l=t(n.type,a,l),l=t(n.initializer,a,l);break;case 154:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.name,a,l),l=t(n.type,a,l),l=t(n.initializer,a,l);break;case 156:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.name,a,l),l=s(n.typeParameters,c,l),l=s(n.parameters,c,l),l=t(n.type,a,l),l=t(n.body,a,l);break;case 157:l=s(n.modifiers,c,l),l=s(n.parameters,c,l),l=t(n.body,a,l);break;case 158:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.name,a,l),l=s(n.parameters,c,l),l=t(n.type,a,l),l=t(n.body,a,l);break;case 159:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.name,a,l),l=s(n.parameters,c,l),l=t(n.body,a,l);break;case 184:case 185:l=s(n.elements,c,l);break;case 186:l=t(n.propertyName,a,l),l=t(n.name,a,l),l=t(n.initializer,a,l);break;case 187:l=s(n.elements,c,l);break;case 188:l=s(n.properties,c,l);break;case 189:l=t(n.expression,a,l),l=t(n.name,a,l);break;case 190:l=t(n.expression,a,l),l=t(n.argumentExpression,a,l);break;case 191:case 192:l=t(n.expression,a,l),l=s(n.typeArguments,c,l),l=s(n.arguments,c,l);break;case 193:l=t(n.tag,a,l),l=s(n.typeArguments,c,l),l=t(n.template,a,l);break;case 194:l=t(n.type,a,l),l=t(n.expression,a,l);break;case 196:l=s(n.modifiers,c,l),l=t(n.name,a,l),l=s(n.typeParameters,c,l),l=s(n.parameters,c,l),l=t(n.type,a,l),l=t(n.body,a,l);break;case 197:l=s(n.modifiers,c,l),l=s(n.typeParameters,c,l),l=s(n.parameters,c,l),l=t(n.type,a,l),l=t(n.body,a,l);break;case 195:case 198:case 199:case 200:case 201:case 207:case 208:case 213:l=t(n.expression,a,l);break;case 202:case 203:l=t(n.operand,a,l);break;case 204:l=t(n.left,a,l),l=t(n.right,a,l);break;case 205:l=t(n.condition,a,l),l=t(n.whenTrue,a,l),l=t(n.whenFalse,a,l);break;case 206:l=t(n.head,a,l),l=s(n.templateSpans,c,l);break;case 209:l=s(n.modifiers,c,l),l=t(n.name,a,l),l=s(n.typeParameters,c,l),l=s(n.heritageClauses,c,l),l=s(n.members,c,l);break;case 211:l=t(n.expression,a,l),l=s(n.typeArguments,c,l);break;case 212:l=t(n.expression,a,l),l=t(n.type,a,l);break;case 216:l=t(n.expression,a,l),l=t(n.literal,a,l);break;case 218:l=s(n.statements,c,l);break;case 219:l=s(n.modifiers,c,l),l=t(n.declarationList,a,l);break;case 221:l=t(n.expression,a,l);break;case 222:l=t(n.expression,a,l),l=t(n.thenStatement,a,l),l=t(n.elseStatement,a,l);break;case 223:l=t(n.statement,a,l),l=t(n.expression,a,l);break;case 224:case 231:l=t(n.expression,a,l),l=t(n.statement,a,l);break;case 225:l=t(n.initializer,a,l),l=t(n.condition,a,l),l=t(n.incrementor,a,l),l=t(n.statement,a,l);break;case 226:case 227:l=t(n.initializer,a,l),l=t(n.expression,a,l),l=t(n.statement,a,l);break;case 230:case 234:l=t(n.expression,a,l);break;case 232:l=t(n.expression,a,l),l=t(n.caseBlock,a,l);break;case 233:l=t(n.label,a,l),l=t(n.statement,a,l);break;case 235:l=t(n.tryBlock,a,l),l=t(n.catchClause,a,l),l=t(n.finallyBlock,a,l);break;case 237:l=t(n.name,a,l),l=t(n.type,a,l),l=t(n.initializer,a,l);break;case 238:l=s(n.declarations,c,l);break;case 239:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.name,a,l),l=s(n.typeParameters,c,l),l=s(n.parameters,c,l),l=t(n.type,a,l),l=t(n.body,a,l);break;case 240:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.name,a,l),l=s(n.typeParameters,c,l),l=s(n.heritageClauses,c,l),l=s(n.members,c,l);break;case 243:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.name,a,l),l=s(n.members,c,l);break;case 244:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.name,a,l),l=t(n.body,a,l);break;case 245:l=s(n.statements,c,l);break;case 246:l=s(n.clauses,c,l);break;case 248:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.name,a,l),l=t(n.moduleReference,a,l);break;case 249:l=s(n.decorators,c,l),l=s(n.modifiers,c,l),l=t(n.importClause,a,l),l=t(n.moduleSpecifier,a,l);break;case 250:l=t(n.name,a,l),l=t(n.namedBindings,a,l);break;case 251:l=t(n.name,a,l);break;case 252:case 256:l=s(n.elements,c,l);break;case 253:case 257:l=t(n.propertyName,a,l),l=t(n.name,a,l);break;case 254:l=e.reduceLeft(n.decorators,a,l),l=e.reduceLeft(n.modifiers,a,l),l=t(n.expression,a,l);break;case 255:l=e.reduceLeft(n.decorators,a,l),l=e.reduceLeft(n.modifiers,a,l),l=t(n.exportClause,a,l),l=t(n.moduleSpecifier,a,l);break;case 259:l=t(n.expression,a,l);break;case 260:l=t(n.openingElement,a,l),l=e.reduceLeft(n.children,a,l),l=t(n.closingElement,a,l);break;case 264:l=t(n.openingFragment,a,l),l=e.reduceLeft(n.children,a,l),l=t(n.closingFragment,a,l);break;case 261:case 262:l=t(n.tagName,a,l),l=s(n.typeArguments,a,l),l=t(n.attributes,a,l);break;case 268:l=s(n.properties,c,l);break;case 263:l=t(n.tagName,a,l);break;case 267:l=t(n.name,a,l),l=t(n.initializer,a,l);break;case 269:case 270:l=t(n.expression,a,l);break;case 271:l=t(n.expression,a,l);case 272:l=s(n.statements,c,l);break;case 273:l=s(n.types,c,l);break;case 274:l=t(n.variableDeclaration,a,l),l=t(n.block,a,l);break;case 275:l=t(n.name,a,l),l=t(n.initializer,a,l);break;case 276:l=t(n.name,a,l),l=t(n.objectAssignmentInitializer,a,l);break;case 277:l=t(n.expression,a,l);break;case 278:l=t(n.name,a,l),l=t(n.initializer,a,l);break;case 279:l=s(n.statements,c,l);break;case 308:l=t(n.expression,a,l);break;case 309:l=s(n.elements,c,l)}return l}function i(t){if(void 0===t)return 0;if(536870912&t.transformFlags)return t.transformFlags&~e.getTransformFlagsSubtreeExclusions(t.kind);var r=function(t){if(e.hasModifier(t,2)||e.isTypeNode(t)&&211!==t.kind)return 0;return n(t,0,a,o)}(t);return e.computeTransformFlagsForNode(t,r)}function a(e,t){return e|i(t)}function o(e,t){return e|function(e){if(void 0===e)return 0;for(var t=0,r=0,n=0,a=e;n=C,"generatedLine cannot backtrack"),e.Debug.assert(r>=0,"generatedCharacter cannot be negative"),_();for(var s,c=[],u=a(n.mappings),l=u.next(),p=l.value,f=l.done;!f;o=u.next(),p=o.value,f=o.done,o){var m=void 0,g=void 0,y=void 0,v=void 0;if(void 0!==p.sourceIndex){if(void 0===(m=c[p.sourceIndex])){var h=n.sources[p.sourceIndex],b=n.sourceRoot?e.combinePaths(n.sourceRoot,h):h,D=e.combinePaths(e.getDirectoryPath(i),b);c[p.sourceIndex]=m=I(D),n.sourcesContent&&"string"==typeof n.sourcesContent[p.sourceIndex]&&M(m,n.sourcesContent[p.sourceIndex])}g=p.sourceLine,y=p.sourceCharacter,n.names&&void 0!==p.nameIndex&&(s||(s=[]),void 0===(v=s[p.nameIndex])&&(s[p.nameIndex]=v=L(n.names[p.nameIndex])))}var x=p.generatedLine+t,S=0===p.generatedLine?p.generatedCharacter+r:p.generatedCharacter;R(x,S,m,g,y,v)}d()},toJSON:j,toString:function(){return JSON.stringify(j())}};function I(r){_();var n=e.getRelativePathToDirectoryOrUrl(i,r,t.getCurrentDirectory(),t.getCanonicalFileName,!0),a=m.get(n);return void 0===a&&(a=f.length,f.push(n),p.push(r),m.set(n,a)),d(),a}function M(e,t){if(_(),null!==t){for(c||(c=[]);c.length=C,"generatedLine cannot backtrack"),e.Debug.assert(r>=0,"generatedCharacter cannot be negative"),e.Debug.assert(void 0===n||n>=0,"sourceIndex cannot be negative"),e.Debug.assert(void 0===i||i>=0,"sourceLine cannot be negative"),e.Debug.assert(void 0===a||a>=0,"sourceCharacter cannot be negative"),_(),(function(e,t){return!P||C!==e||k!==t}(t,r)||function(e,t,r){return void 0!==e&&void 0!==t&&void 0!==r&&E===e&&(N>t||N===t&&A>r)}(n,i,a))&&(B(),C=t,k=r,w=!1,O=!1,P=!0),void 0!==n&&void 0!==i&&void 0!==a&&(E=n,N=i,A=a,w=!0,void 0!==o&&(F=o,O=!0)),d()}function B(){if(P&&(!T||v!==C||h!==k||b!==E||D!==N||x!==A||S!==F)){if(_(),v=e.length)return d("Error in decoding base64VLQFormatDecode, past the mapping string"),-1;var o=(t=e.charCodeAt(n))>=65&&t<=90?t-65:t>=97&&t<=122?t-97+26:t>=48&&t<=57?t-48+52:43===t?62:47===t?63:-1;if(-1===o)return d("Invalid character in VLQ"),-1;r=0!=(32&o),a|=(31&o)<>=1:a=-(a>>=1),a}}function o(e){return void 0!==e.sourceIndex&&void 0!==e.sourceLine&&void 0!==e.sourceCharacter}function s(t){t<0?t=1+(-t<<1):t<<=1;var r,n="";do{var i=31&t;(t>>=5)>0&&(i|=32),n+=String.fromCharCode((r=i)>=0&&r<26?65+r:r>=26&&r<52?97+r-26:r>=52&&r<62?48+r-52:62===r?43:63===r?47:e.Debug.fail(r+": not a base64 value"))}while(t>0);return n}function c(e){return void 0!==e.sourceIndex&&void 0!==e.sourcePosition}function u(e,t){return e.generatedPosition===t.generatedPosition&&e.sourceIndex===t.sourceIndex&&e.sourcePosition===t.sourcePosition}function l(t,r){return e.compareValues(t.sourceIndex,r.sourceIndex)}function _(t,r){return e.compareValues(t.generatedPosition,r.generatedPosition)}function d(e){return e.sourcePosition}function p(e){return e.generatedPosition}e.tryGetSourceMappingURL=function(n,i){void 0===i&&(i=e.computeLineStarts(n));for(var a=i.length-1;a>=0;a--){var o=n.substring(i[a],i[a+1]),s=t.exec(o);if(s)return s[1];if(!o.match(r))break}},e.isRawSourceMap=i,e.tryParseRawSourceMap=function(e){try{var t=JSON.parse(e);if(i(t))return t}catch(e){}},e.decodeMappings=a,e.sameMapping=function(e,t){return e===t||e.generatedLine===t.generatedLine&&e.generatedCharacter===t.generatedCharacter&&e.sourceIndex===t.sourceIndex&&e.sourceLine===t.sourceLine&&e.sourceCharacter===t.sourceCharacter&&e.nameIndex===t.nameIndex},e.isSourceMapping=o,e.createDocumentPositionMapper=function(t,r,n){var i,s,f,m=e.getDirectoryPath(n),g=r.sourceRoot?e.getNormalizedAbsolutePath(r.sourceRoot,m):m,y=e.getNormalizedAbsolutePath(r.file,m),v=t.getCanonicalFileName(y),h=t.getSourceFileLike(v),b=r.sources.map(function(t){return e.getNormalizedAbsolutePath(t,g)}),D=b.map(function(e){return t.getCanonicalFileName(e)}),x=e.createMapFromEntries(D.map(function(e,t){return[e,t]}));return{getSourcePosition:function(t){var r=k();if(!e.some(r))return t;var n=e.binarySearchKey(r,t.pos,p,e.compareValues);n<0&&(n=~n);var i=r[n];return void 0!==i&&c(i)?{fileName:b[i.sourceIndex],pos:i.sourcePosition}:t},getGeneratedPosition:function(r){var n=x.get(t.getCanonicalFileName(r.fileName));if(void 0===n)return r;var i=C(n);if(!e.some(i))return r;var a=e.binarySearchKey(i,r.pos,d,e.compareValues);a<0&&(a=~a);var o=i[a];return void 0===o||o.sourceIndex!==n?r:{fileName:y,pos:o.generatedPosition}}};function S(n){var i,a,s=void 0!==h?e.getPositionOfLineAndCharacterWithEdits(h,n.generatedLine,n.generatedCharacter):-1;if(o(n)){var c=D[n.sourceIndex],u=t.getSourceFileLike(c);i=r.sources[n.sourceIndex],a=void 0!==u?e.getPositionOfLineAndCharacterWithEdits(u,n.sourceLine,n.sourceCharacter):-1}return{generatedPosition:s,source:i,sourceIndex:n.sourceIndex,sourcePosition:a,nameIndex:n.nameIndex}}function T(){if(void 0===i){var n=a(r.mappings),o=e.arrayFrom(n,S);void 0!==n.error?(t.log&&t.log("Encountered error while decoding sourcemap: "+n.error),i=e.emptyArray):i=o}return i}function C(t){if(void 0===f){for(var r=[],n=0,i=T();n0&&i!==n.elements.length||!!(n.elements.length-i)&&e.isDefaultImport(t)}function i(t){return!n(t)&&(e.isDefaultImport(t)||!!t.importClause&&e.isNamedImports(t.importClause.namedBindings)&&function(t){return!!t&&!!e.isNamedImports(t)&&e.some(t.elements,r)}(t.importClause.namedBindings))}function a(t,r,n){if(e.isBindingPattern(t.name))for(var i=0,o=t.name.elements;i=1)||393216&g.transformFlags||393216&e.getTargetOfBindingOrAssignmentElement(g).transformFlags||e.isComputedPropertyName(v)){u&&(t.emitBindingOrAssignment(t.createObjectBindingOrAssignmentPattern(u),s,c,o),u=void 0);var y=n(t,s,v);e.isComputedPropertyName(v)&&(l=e.append(l,y.argumentExpression)),r(t,g,y,g)}else u=e.append(u,g)}}u&&t.emitBindingOrAssignment(t.createObjectBindingOrAssignmentPattern(u),s,c,o)}(t,a,l,o,s):e.isArrayBindingOrAssignmentPattern(l)?function(t,n,a,o,s){var c,u,l=e.getElementsOfBindingOrAssignmentPattern(a),_=l.length;if(t.level<1&&t.downlevelIteration)o=i(t,e.createReadHelper(t.context,o,_>0&&e.getRestIndicatorOfBindingOrAssignmentElement(l[_-1])?void 0:_,s),!1,s);else if(1!==_&&(t.level<1||0===_)||e.every(l,e.isOmittedExpression)){var d=!e.isDeclarationBindingElement(n)||0!==_;o=i(t,o,d,s)}for(var p=0;p<_;p++){var f=l[p];if(t.level>=1)if(262144&f.transformFlags){var m=e.createTempVariable(void 0);t.hoistTempVariables&&t.context.hoistVariableDeclaration(m),u=e.append(u,[m,f]),c=e.append(c,t.createArrayBindingOrAssignmentElement(m))}else c=e.append(c,f);else{if(e.isOmittedExpression(f))continue;if(e.getRestIndicatorOfBindingOrAssignmentElement(f)){if(p===_-1){var g=e.createArraySlice(o,p);r(t,f,g,f)}}else{var g=e.createElementAccess(o,p);r(t,f,g,f)}}}c&&t.emitBindingOrAssignment(t.createArrayBindingOrAssignmentPattern(c),o,s,a);if(u)for(var y=0,v=u;y0)return!0;var r=e.getFirstConstructorWithBody(t);return!!r&&e.forEach(r.parameters,J)}(t)&&(n|=2),e.childIsDecorated(t)&&(n|=4),Le(t)?n|=8:function(t){return Re(t)&&e.hasModifier(t,512)}(t)?n|=32:Be(t)&&(n|=16),S<=1&&7&n&&(n|=128),n}(n,o);128&s&&t.startLexicalEnvironment();var c=n.name||(5&s?e.getGeneratedNameForNode(n):void 0),u=2&s?function(t,r,n){var i=e.moveRangePastDecorators(t),a=function(t){if(16777216&b.getNodeCheckFlags(t)){qe();var r=e.createUniqueName(t.name&&!e.isGeneratedIdentifier(t.name)?e.idText(t.name):"default");return p[e.getOriginalNodeId(t)]=r,h(r),r}}(t),o=e.getLocalName(t,!1,!0),s=e.visitNodes(t.heritageClauses,A,e.isHeritageClause),c=z(t,0!=(64&n)),u=e.createClassExpression(void 0,r,void 0,s,c);e.setOriginalNode(u,t),e.setTextRange(u,i);var l=e.createVariableStatement(void 0,e.createVariableDeclarationList([e.createVariableDeclaration(o,void 0,a?e.createAssignment(a,u):u)],1));return e.setOriginalNode(l,t),e.setTextRange(l,i),e.setCommentRange(l,t),l}(n,c,s):function(t,r,n){var i=128&n?void 0:e.visitNodes(t.modifiers,R,e.isModifier),a=e.createClassDeclaration(void 0,i,r,void 0,e.visitNodes(t.heritageClauses,A,e.isHeritageClause),z(t,0!=(64&n))),o=e.getEmitFlags(t);return 1&n&&(o|=32),e.setTextRange(a,t),e.setOriginalNode(a,t),e.setEmitFlags(a,o),a}(n,c,s),l=[u];if(e.some(m)&&l.push(e.createExpressionStatement(e.inlineExpressions(m))),m=a,1&s&&G(l,o,128&s?e.getInternalName(n):e.getLocalName(n)),te(l,n,!1),te(l,n,!0),function(r,n){var a=function(r){var n=function(t){var r=t.decorators,n=$(e.getFirstConstructorWithBody(t));if(r||n)return{decorators:r,parameters:n}}(r),a=ee(r,r,n);if(a){var o=p&&p[e.getOriginalNodeId(r)],s=e.getLocalName(r,!1,!0),c=i(t,a,s),u=e.createAssignment(s,o?e.createAssignment(o,c):c);return e.setEmitFlags(u,1536),e.setSourceMapRange(u,e.moveRangePastDecorators(r)),u}}(n);a&&r.push(e.setOriginalNode(e.createExpressionStatement(a),n))}(l,n),128&s){var _=e.createTokenRange(e.skipTrivia(r.text,n.members.end),19),d=e.getInternalName(n),f=e.createPartiallyEmittedExpression(d);f.end=_.end,e.setEmitFlags(f,1536);var g=e.createReturn(f);g.pos=_.pos,e.setEmitFlags(g,1920),l.push(g),e.addStatementsAfterPrologue(l,t.endLexicalEnvironment());var y=e.createImmediatelyInvokedArrowFunction(l);e.setEmitFlags(y,33554432);var v=e.createVariableStatement(void 0,e.createVariableDeclarationList([e.createVariableDeclaration(e.getLocalName(n,!1,!1),void 0,y)]));e.setOriginalNode(v,n),e.setCommentRange(v,n),e.setSourceMapRange(v,e.moveRangePastDecorators(n)),e.startOnNewLine(v),l=[v]}return 8&s?Je(l,n):(128&s||2&s)&&(32&s?l.push(e.createExportDefault(e.getLocalName(n,!1,!0))):16&s&&l.push(e.createExternalModuleExport(e.getLocalName(n,!1,!0)))),l.length>1&&(l.push(e.createEndOfDeclarationMarker(n)),e.setEmitFlags(u,4194304|e.getEmitFlags(u))),e.singleOrMany(l)}(n);case 209:return function(t){var r=m;m=void 0;var n=V(t,!0),i=e.visitNodes(t.heritageClauses,A,e.isHeritageClause),a=z(t,e.some(i,function(e){return 86===e.token})),o=e.createClassExpression(void 0,t.name,void 0,i,a);if(e.setOriginalNode(o,t),e.setTextRange(o,t),e.some(n)||e.some(m)){var s=[],c=16777216&b.getNodeCheckFlags(t),u=e.createTempVariable(h,!!c);if(c){qe();var l=e.getSynthesizedClone(u);l.autoGenerateFlags&=-9,p[e.getOriginalNodeId(t)]=l}return e.setEmitFlags(o,65536|e.getEmitFlags(o)),s.push(e.startOnNewLine(e.createAssignment(u,o))),e.addRange(s,e.map(m,e.startOnNewLine)),m=r,e.addRange(s,function(t,r){for(var n=[],i=0,a=t;i=e.ModuleKind.ES2015)&&!e.isJsonSourceFile(r);return e.updateSourceFileNode(r,e.visitLexicalEnvironment(r.statements,P,t,0,n))}function J(e){return void 0!==e.decorators&&e.decorators.length>0}function z(r,n){var i=[],a=function(r,n){var i=e.getFirstConstructorWithBody(r),a=e.forEach(r.members,W),o=i&&4096&i.transformFlags&&e.forEach(i.parameters,K);if(!a&&!o)return e.visitEachChild(i,A,t);var s=function(r){return e.visitParameterList(r&&r.parameters,A,t)||[]}(i),c=function(t,r,n){var i=[],a=0;if(y(),r){a=function(t,r){if(t.body){var n=t.body.statements,i=e.addPrologue(r,n,!1,A);if(i===n.length)return i;var a=n[i];return 221===a.kind&&e.isSuperCall(a.expression)?(r.push(e.visitNode(a,A,e.isStatement)),i+1):i}return 0}(r,i);var o=function(t){return e.filter(t.parameters,K)}(r);e.addRange(i,e.map(o,U))}else n&&i.push(e.createExpressionStatement(e.createCall(e.createSuper(),void 0,[e.createSpread(e.createIdentifier("arguments"))])));var s=V(t,!1);return G(i,s,e.createThis()),r&&e.addRange(i,e.visitNodes(r.body.statements,A,e.isStatement,a)),i=e.mergeLexicalEnvironment(i,v()),e.setTextRange(e.createBlock(e.setTextRange(e.createNodeArray(i),r?r.body.statements:t.members),!0),r?r.body:void 0)}(r,i,n);return e.startOnNewLine(e.setOriginalNode(e.setTextRange(e.createConstructor(void 0,void 0,s,c),i||r),i))}(r,n);return a&&i.push(a),e.addRange(i,e.visitNodes(r.members,M,e.isClassElement)),e.setTextRange(e.createNodeArray(i),r.members)}function K(t){return e.hasModifier(t,92)&&e.isIdentifier(t.name)}function U(t){e.Debug.assert(e.isIdentifier(t.name));var r=t.name,n=e.getMutableClone(r);e.setEmitFlags(n,1584);var i=e.getMutableClone(r);return e.setEmitFlags(i,1536),e.startOnNewLine(e.setEmitFlags(e.setTextRange(e.createExpressionStatement(e.createAssignment(e.setTextRange(e.createPropertyAccess(e.createThis(),n),t.name),i)),e.moveRangePos(t,-1)),1536))}function V(t,r){return e.filter(t.members,r?q:W)}function q(e){return H(e,!0)}function W(e){return H(e,!1)}function H(t,r){return 154===t.kind&&r===e.hasModifier(t,32)&&void 0!==t.initializer}function G(t,r,n){for(var i=0,a=r;i0?154===n.kind?e.createVoidZero():e.createNull():void 0,u=i(t,a,o,s,c,e.moveRangePastDecorators(n));return e.setEmitFlags(u,1536),u}}function ne(t){return e.visitNode(t.expression,A,e.isExpression)}function ie(r,n){var i;if(r){i=[];for(var a=0,o=r;a= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };'};function o(t,r,n){return t.requestEmitHelper(s),e.createCall(e.getHelperName("__metadata"),void 0,[e.createLiteral(r),n])}var s={name:"typescript:metadata",scoped:!1,priority:3,text:'\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);\n };'};function c(t,r,n,i){return t.requestEmitHelper(u),e.setTextRange(e.createCall(e.getHelperName("__param"),void 0,[e.createLiteral(n),r]),i)}var u={name:"typescript:param",scoped:!1,priority:4,text:"\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };"}}(c||(c={})),function(e){var t;function r(t,r,n){var i=0!=(4096&t.getNodeCheckFlags(r)),a=[];return n.forEach(function(t,r){var n=e.unescapeLeadingUnderscores(r),o=[];o.push(e.createPropertyAssignment("get",e.createArrowFunction(void 0,void 0,[],void 0,void 0,e.createPropertyAccess(e.createSuper(),n)))),i&&o.push(e.createPropertyAssignment("set",e.createArrowFunction(void 0,void 0,[e.createParameter(void 0,void 0,void 0,"v",void 0,void 0,void 0)],void 0,void 0,e.createAssignment(e.createPropertyAccess(e.createSuper(),n),e.createIdentifier("v"))))),a.push(e.createPropertyAssignment(n,e.createObjectLiteral(o)))}),e.createVariableStatement(void 0,e.createVariableDeclarationList([e.createVariableDeclaration(e.createFileLevelUniqueName("_super"),void 0,e.createCall(e.createPropertyAccess(e.createIdentifier("Object"),"create"),void 0,[e.createNull(),e.createObjectLiteral(a,!0)]))],2))}!function(e){e[e.AsyncMethodsWithSuper=1]="AsyncMethodsWithSuper"}(t||(t={})),e.transformES2017=function(t){var n,a,o,s,c=t.resumeLexicalEnvironment,u=t.endLexicalEnvironment,l=t.hoistVariableDeclaration,_=t.getEmitResolver(),d=t.getCompilerOptions(),p=e.getEmitScriptTarget(d),f=0,m=[],g=t.onEmitNode,y=t.onSubstituteNode;return t.onEmitNode=function(t,r,i){if(1&n&&function(e){var t=e.kind;return 240===t||157===t||156===t||158===t||159===t}(r)){var a=6144&_.getNodeCheckFlags(r);if(a!==f){var o=f;return f=a,g(t,r,i),void(f=o)}}else if(n&&m[e.getNodeId(r)]){var o=f;return f=0,g(t,r,i),void(f=o)}g(t,r,i)},t.onSubstituteNode=function(t,r){return r=y(t,r),1===t&&f?function(t){switch(t.kind){case 189:return N(t);case 190:return A(t);case 191:return function(t){var r=t.expression;if(e.isSuperProperty(r)){var n=e.isPropertyAccessExpression(r)?N(r):A(r);return e.createCall(e.createPropertyAccess(n,"call"),void 0,[e.createThis()].concat(t.arguments))}return t}(t)}return t}(r):r},e.chainBundle(function(r){if(r.isDeclarationFile)return r;var n=e.visitEachChild(r,v,t);return e.addEmitHelpers(n,t.readEmitHelpers()),n});function v(r){if(0==(16&r.transformFlags))return r;switch(r.kind){case 121:return;case 201:return function(t){return e.setOriginalNode(e.setTextRange(e.createYield(void 0,e.visitNode(t.expression,v,e.isExpression)),t),t)}(r);case 156:return function(r){return e.updateMethod(r,void 0,e.visitNodes(r.modifiers,v,e.isModifier),r.asteriskToken,r.name,void 0,void 0,e.visitParameterList(r.parameters,v,t),void 0,2&e.getFunctionFlags(r)?k(r):e.visitFunctionBody(r.body,v,t))}(r);case 239:return function(r){return e.updateFunctionDeclaration(r,void 0,e.visitNodes(r.modifiers,v,e.isModifier),r.asteriskToken,r.name,void 0,e.visitParameterList(r.parameters,v,t),void 0,2&e.getFunctionFlags(r)?k(r):e.visitFunctionBody(r.body,v,t))}(r);case 196:return function(r){return e.updateFunctionExpression(r,e.visitNodes(r.modifiers,v,e.isModifier),r.asteriskToken,r.name,void 0,e.visitParameterList(r.parameters,v,t),void 0,2&e.getFunctionFlags(r)?k(r):e.visitFunctionBody(r.body,v,t))}(r);case 197:return function(r){return e.updateArrowFunction(r,e.visitNodes(r.modifiers,v,e.isModifier),void 0,e.visitParameterList(r.parameters,v,t),void 0,r.equalsGreaterThanToken,2&e.getFunctionFlags(r)?k(r):e.visitFunctionBody(r.body,v,t))}(r);case 189:return o&&e.isPropertyAccessExpression(r)&&98===r.expression.kind&&o.set(r.name.escapedText,!0),e.visitEachChild(r,v,t);case 190:return o&&98===r.expression.kind&&(s=!0),e.visitEachChild(r,v,t);default:return e.visitEachChild(r,v,t)}}function h(r){if(e.isNodeWithPossibleHoistedDeclaration(r))switch(r.kind){case 219:return function(r){if(D(r.declarationList)){var n=x(r.declarationList,!1);return n?e.createExpressionStatement(n):void 0}return e.visitEachChild(r,v,t)}(r);case 225:return function(t){var r=t.initializer;return e.updateFor(t,D(r)?x(r,!1):e.visitNode(t.initializer,v,e.isForInitializer),e.visitNode(t.condition,v,e.isExpression),e.visitNode(t.incrementor,v,e.isExpression),e.visitNode(t.statement,h,e.isStatement,e.liftToBlock))}(r);case 226:return function(t){return e.updateForIn(t,D(t.initializer)?x(t.initializer,!0):e.visitNode(t.initializer,v,e.isForInitializer),e.visitNode(t.expression,v,e.isExpression),e.visitNode(t.statement,h,e.isStatement,e.liftToBlock))}(r);case 227:return function(t){return e.updateForOf(t,e.visitNode(t.awaitModifier,v,e.isToken),D(t.initializer)?x(t.initializer,!0):e.visitNode(t.initializer,v,e.isForInitializer),e.visitNode(t.expression,v,e.isExpression),e.visitNode(t.statement,h,e.isStatement,e.liftToBlock))}(r);case 274:return function(r){var n,i=e.createUnderscoreEscapedMap();if(b(r.variableDeclaration,i),i.forEach(function(t,r){a.has(r)&&(n||(n=e.cloneMap(a)),n.delete(r))}),n){var o=a;a=n;var s=e.visitEachChild(r,h,t);return a=o,s}return e.visitEachChild(r,h,t)}(r);case 218:case 232:case 246:case 271:case 272:case 235:case 223:case 224:case 222:case 231:case 233:return e.visitEachChild(r,h,t);default:return e.Debug.assertNever(r,"Unhandled node.")}return v(r)}function b(t,r){var n=t.name;if(e.isIdentifier(n))r.set(n.escapedText,!0);else for(var i=0,a=n.elements;i=2&&6144&_.getNodeCheckFlags(l);if(P){0==(1&n)&&(n|=1,t.enableSubstitution(191),t.enableSubstitution(189),t.enableSubstitution(190),t.enableEmitNotification(240),t.enableEmitNotification(156),t.enableEmitNotification(158),t.enableEmitNotification(159),t.enableEmitNotification(157),t.enableEmitNotification(219));var w=r(_,l,o);m[e.getNodeId(w)]=!0,e.addStatementsAfterPrologue(A,[w])}var O=e.createBlock(A,!0);e.setTextRange(O,l.body),P&&s&&(4096&_.getNodeCheckFlags(l)?e.addEmitHelper(O,e.advancedAsyncSuperHelper):2048&_.getNodeCheckFlags(l)&&e.addEmitHelper(O,e.asyncSuperHelper)),S=O}return a=h,o=T,s=C,S}function E(t,r){return e.isBlock(t)?e.updateBlock(t,e.visitNodes(t.statements,h,e.isStatement,r)):e.convertToFunctionBody(e.visitNode(t,h,e.isConciseBody))}function N(t){return 98===t.expression.kind?e.setTextRange(e.createPropertyAccess(e.createFileLevelUniqueName("_super"),t.name),t):t}function A(t){return 98===t.expression.kind?(r=t.argumentExpression,n=t,4096&f?e.setTextRange(e.createPropertyAccess(e.createCall(e.createFileLevelUniqueName("_superIndex"),void 0,[r]),"value"),n):e.setTextRange(e.createCall(e.createFileLevelUniqueName("_superIndex"),void 0,[r]),n)):t;var r,n}},e.createSuperAccessVariableStatement=r;var n={name:"typescript:awaiter",scoped:!1,priority:5,text:'\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };'};function i(t,r,i,a){t.requestEmitHelper(n);var o=e.createFunctionExpression(void 0,e.createToken(40),void 0,void 0,[],void 0,a);return(o.emitNode||(o.emitNode={})).flags|=786432,e.createCall(e.getHelperName("__awaiter"),void 0,[e.createThis(),r?e.createIdentifier("arguments"):e.createVoidZero(),i?e.createExpressionFromEntityName(i):e.createVoidZero(),o])}e.asyncSuperHelper={name:"typescript:async-super",scoped:!0,text:e.helperString(o(["\n const "," = name => super[name];"],["\n const "," = name => super[name];"]),"_superIndex")},e.advancedAsyncSuperHelper={name:"typescript:advanced-async-super",scoped:!0,text:e.helperString(o(["\n const "," = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"],["\n const "," = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]),"_superIndex")}}(c||(c={})),function(e){var t;!function(e){e[e.AsyncMethodsWithSuper=1]="AsyncMethodsWithSuper"}(t||(t={})),e.transformESNext=function(t){var r=t.resumeLexicalEnvironment,c=t.endLexicalEnvironment,l=t.hoistVariableDeclaration,_=t.getEmitResolver(),d=t.getCompilerOptions(),p=e.getEmitScriptTarget(d),f=t.onEmitNode;t.onEmitNode=function(t,r,n){if(1&m&&function(e){var t=e.kind;return 240===t||157===t||156===t||158===t||159===t}(r)){var i=6144&_.getNodeCheckFlags(r);if(i!==b){var a=b;return b=i,f(t,r,n),void(b=a)}}else if(m&&D[e.getNodeId(r)]){var a=b;return b=0,f(t,r,n),void(b=a)}f(t,r,n)};var m,g,y=t.onSubstituteNode;t.onSubstituteNode=function(t,r){return r=y(t,r),1===t&&b?function(t){switch(t.kind){case 189:return P(t);case 190:return w(t);case 191:return function(t){var r=t.expression;if(e.isSuperProperty(r)){var n=e.isPropertyAccessExpression(r)?P(r):w(r);return e.createCall(e.createPropertyAccess(n,"call"),void 0,[e.createThis()].concat(t.arguments))}return t}(t)}return t}(r):r};var v,h,b=0,D=[];return e.chainBundle(function(r){if(r.isDeclarationFile)return r;var n=e.visitEachChild(r,x,t);return e.addEmitHelpers(n,t.readEmitHelpers()),n});function x(e){return C(e,!1)}function S(e){return C(e,!0)}function T(e){if(121!==e.kind)return e}function C(r,o){if(0==(8&r.transformFlags))return r;switch(r.kind){case 201:return function(r){return 2&g&&1&g?e.setOriginalNode(e.setTextRange(e.createYield(a(t,e.visitNode(r.expression,x,e.isExpression))),r),r):e.visitEachChild(r,x,t)}(r);case 207:return function(r){if(2&g&&1&g){if(r.asteriskToken){var n=e.visitNode(r.expression,x,e.isExpression);return e.setOriginalNode(e.setTextRange(e.createYield(a(t,e.updateYield(r,r.asteriskToken,function(t,r,n){return t.requestEmitHelper(i),t.requestEmitHelper(s),e.setTextRange(e.createCall(e.getHelperName("__asyncDelegator"),void 0,[r]),n)}(t,u(t,n,n),n)))),r),r)}return e.setOriginalNode(e.setTextRange(e.createYield(E(r.expression?e.visitNode(r.expression,x,e.isExpression):e.createVoidZero())),r),r)}return e.visitEachChild(r,x,t)}(r);case 230:return function(r){return 2&g&&1&g?e.updateReturn(r,E(r.expression?e.visitNode(r.expression,x,e.isExpression):e.createVoidZero())):e.visitEachChild(r,x,t)}(r);case 233:return function(r){if(2&g){var n=e.unwrapInnermostStatementOfLabel(r);return 227===n.kind&&n.awaitModifier?k(n,r):e.restoreEnclosingLabel(e.visitEachChild(n,x,t),r)}return e.visitEachChild(r,x,t)}(r);case 188:return function(r){if(262144&r.transformFlags){var i=function(t){for(var r,n=[],i=0,a=t;i=2&&6144&_.getNodeCheckFlags(n);if(f){0==(1&m)&&(m|=1,t.enableSubstitution(191),t.enableSubstitution(189),t.enableSubstitution(190),t.enableEmitNotification(240),t.enableEmitNotification(156),t.enableEmitNotification(158),t.enableEmitNotification(159),t.enableEmitNotification(157),t.enableEmitNotification(219));var g=e.createSuperAccessVariableStatement(_,n,v);D[e.getNodeId(g)]=!0,e.addStatementsAfterPrologue(a,[g])}a.push(d),e.addStatementsAfterPrologue(a,c());var y=e.updateBlock(n.body,a);return f&&h&&(4096&_.getNodeCheckFlags(n)?e.addEmitHelper(y,e.advancedAsyncSuperHelper):2048&_.getNodeCheckFlags(n)&&e.addEmitHelper(y,e.asyncSuperHelper)),v=u,h=l,y}function A(t){r();var n=0,i=[],a=e.visitNode(t.body,x,e.isConciseBody);e.isBlock(a)&&(n=e.addPrologue(i,a.statements,!1,x)),e.addRange(i,F(void 0,t));var o=c();if(n>0||e.some(i)||e.some(o)){var s=e.convertToFunctionBody(a,!0);return e.addStatementsAfterPrologue(i,o),e.addRange(i,s.statements.slice(n)),e.updateBlock(s,e.setTextRange(e.createNodeArray(i),s.statements))}return a}function F(r,n){for(var i=0,a=n.parameters;i=2?e.createCall(e.createPropertyAccess(e.createIdentifier("Object"),"assign"),void 0,n):(t.requestEmitHelper(r),e.createCall(e.getHelperName("__assign"),void 0,n))}e.createAssignHelper=n;var i={name:"typescript:await",scoped:!1,text:"\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"};function a(t,r){return t.requestEmitHelper(i),e.createCall(e.getHelperName("__await"),void 0,[r])}var o={name:"typescript:asyncGenerator",scoped:!1,text:'\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume("next", value); }\n function reject(value) { resume("throw", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };'};var s={name:"typescript:asyncDelegator",scoped:!1,text:'\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }\n };'};var c={name:"typescript:asyncValues",scoped:!1,text:'\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };'};function u(t,r,n){return t.requestEmitHelper(c),e.setTextRange(e.createCall(e.getHelperName("__asyncValues"),void 0,[r]),n)}}(c||(c={})),function(e){e.transformJsx=function(r){var n,i=r.getCompilerOptions();return e.chainBundle(function(t){if(t.isDeclarationFile)return t;n=t;var i=e.visitEachChild(t,a,r);return e.addEmitHelpers(i,r.readEmitHelpers()),i});function a(t){return 4&t.transformFlags?function(t){switch(t.kind){case 260:return s(t,!1);case 261:return c(t,!1);case 264:return u(t,!1);case 270:return m(t);default:return e.visitEachChild(t,a,r)}}(t):t}function o(t){switch(t.kind){case 11:return function(t){var r=function(t){for(var r,n=0,i=-1,a=0;a=t.end)return!1;for(var i=e.getEnclosingBlockScopeContainer(t);n;){if(n===i||n===t)return!1;if(e.isClassElement(n)&&n.parent===t)return!0;n=n.parent}return!1}(r,t)))return e.setTextRange(e.getGeneratedNameForNode(e.getNameOfDeclaration(r)),t)}return t}(t);case 100:return function(t){return 1&u&&16&i?e.setTextRange(e.createFileLevelUniqueName("_this"),t):t}(t)}return t}(r):e.isIdentifier(r)?function(t){if(2&u&&!e.isInternalName(t)){var r=e.getParseTreeNode(t,e.isIdentifier);if(r&&function(e){switch(e.parent.kind){case 186:case 240:case 243:case 237:return e.parent.name===e&&m.isDeclarationWithCollidingName(e.parent)}return!1}(r))return e.setTextRange(e.getGeneratedNameForNode(r),t)}return t}(r):r},e.chainBundle(function(o){if(o.isDeclarationFile)return o;r=o,n=o.text;var s=function(t){var r=v(3968,64),n=[];l();var i=e.addStandardPrologue(n,t.statements,!1);return O(n,t),i=e.addCustomPrologue(n,t.statements,i,x),e.addRange(n,e.visitNodes(t.statements,x,e.isStatement,i)),a&&n.push(e.createVariableStatement(void 0,e.createVariableDeclarationList(a))),e.addStatementsAfterPrologue(n,d()),h(r,0,0),e.updateSourceFileNode(t,e.setTextRange(e.createNodeArray(n),t.statements))}(o);return e.addEmitHelpers(s,t.readEmitHelpers()),r=void 0,n=void 0,a=void 0,i=0,s});function v(e,t){var r=i;return i=16383&(i&~e|t),r}function h(e,t,r){i=-16384&(i&~t|r)|e}function b(e){return 0!=(4096&i)&&230===e.kind&&!e.expression}function D(t){return 0!=(128&t.transformFlags)||void 0!==o||4096&i&&(e.isStatement(t)||218===t.kind)||e.isIterationStatement(t,!1)&&ce(t)||0!=(33554432&e.getEmitFlags(t))}function x(n){return D(n)?function(n){switch(n.kind){case 116:return;case 240:return function(t){var r=e.createVariableDeclaration(e.getLocalName(t,!0),void 0,k(t));e.setOriginalNode(r,t);var n=[],i=e.createVariableStatement(void 0,e.createVariableDeclarationList([r]));if(e.setOriginalNode(i,t),e.setTextRange(i,t),e.startOnNewLine(i),n.push(i),e.hasModifier(t,1)){var a=e.hasModifier(t,512)?e.createExportDefault(e.getLocalName(t)):e.createExternalModuleExport(e.getLocalName(t));e.setOriginalNode(a,i),n.push(a)}var o=e.getEmitFlags(t);return 0==(4194304&o)&&(n.push(e.createEndOfDeclarationMarker(t)),e.setEmitFlags(i,4194304|o)),e.singleOrMany(n)}(n);case 209:return function(e){return k(e)}(n);case 151:return function(t){return t.dotDotDotToken?void 0:e.isBindingPattern(t.name)?e.setOriginalNode(e.setTextRange(e.createParameter(void 0,void 0,void 0,e.getGeneratedNameForNode(t),void 0,void 0,void 0),t),t):t.initializer?e.setOriginalNode(e.setTextRange(e.createParameter(void 0,void 0,void 0,t.name,void 0,void 0,void 0),t),t):t}(n);case 239:return function(r){var n=o;o=void 0;var a=v(16286,65),s=e.visitParameterList(r.parameters,x,t),c=64&r.transformFlags?z(r):K(r),u=16384&i?e.getLocalName(r):r.name;return h(a,49152,0),o=n,e.updateFunctionDeclaration(r,void 0,e.visitNodes(r.modifiers,x,e.isModifier),r.asteriskToken,u,void 0,s,void 0,c)}(n);case 197:return function(r){8192&r.transformFlags&&Fe();var n=o;o=void 0;var i=v(16256,66),a=e.createFunctionExpression(void 0,void 0,void 0,void 0,e.visitParameterList(r.parameters,x,t),void 0,z(r));return e.setTextRange(a,r),e.setOriginalNode(a,r),e.setEmitFlags(a,8),h(i,0,0),o=n,a}(n);case 196:return function(r){var n=262144&e.getEmitFlags(r)?v(16278,69):v(16286,65),a=o;o=void 0;var s=e.visitParameterList(r.parameters,x,t),c=64&r.transformFlags?z(r):K(r),u=16384&i?e.getLocalName(r):r.name;return h(n,49152,0),o=a,e.updateFunctionExpression(r,void 0,r.asteriskToken,u,void 0,s,void 0,c)}(n);case 237:return H(n);case 72:return function(t){return o?e.isGeneratedIdentifier(t)?t:"arguments"===t.escapedText&&m.isArgumentsLocalBinding(t)?o.argumentsName||(o.argumentsName=e.createUniqueName("arguments")):t:t}(n);case 238:return function(r){if(64&r.transformFlags){3&r.flags&&Ae();var n=e.flatMap(r.declarations,1&r.flags?W:H),i=e.createVariableDeclarationList(n);return e.setOriginalNode(i,r),e.setTextRange(i,r),e.setCommentRange(i,r),2097152&r.transformFlags&&(e.isBindingPattern(r.declarations[0].name)||e.isBindingPattern(e.last(r.declarations).name))&&e.setSourceMapRange(i,function(t){for(var r=-1,n=-1,i=0,a=t;i=0,"statementOffset not initialized correctly!"));var c=!!n&&96!==e.skipOuterExpressions(n.expression).kind,u=function(t,r,n,i,a){if(!n)return r&&O(t,r),0;if(!r)return t.push(e.createReturn(N())),2;if(i)return I(t,r,N()),Fe(),1;var o,s,c,u=r.body.statements;if(a0?r.push(e.setEmitFlags(e.createVariableStatement(void 0,e.createVariableDeclarationList(e.flattenDestructuringBinding(n,x,t,0,o))),1048576)):a&&r.push(e.setEmitFlags(e.createExpressionStatement(e.createAssignment(o,e.visitNode(a,x,e.isExpression))),1048576))}function P(t,r,n,i){i=e.visitNode(i,x,e.isExpression);var a=e.createIf(e.createTypeCheck(e.getSynthesizedClone(n),"undefined"),e.setEmitFlags(e.setTextRange(e.createBlock([e.createExpressionStatement(e.setEmitFlags(e.setTextRange(e.createAssignment(e.setEmitFlags(e.getMutableClone(n),48),e.setEmitFlags(i,1584|e.getEmitFlags(i))),r),1536))]),r),1953));e.startOnNewLine(a),e.setTextRange(a,r),e.setEmitFlags(a,1050528),t.push(a)}function w(t,r,n){var i=e.lastOrUndefined(r.parameters);if(function(e,t){return e&&e.dotDotDotToken&&72===e.name.kind&&!t}(i,n)){var a=e.getMutableClone(i.name);e.setEmitFlags(a,48);var o=e.getSynthesizedClone(i.name),s=r.parameters.length-1,c=e.createLoopVariable();t.push(e.setEmitFlags(e.setTextRange(e.createVariableStatement(void 0,e.createVariableDeclarationList([e.createVariableDeclaration(a,void 0,e.createArrayLiteral([]))])),i),1048576));var u=e.createFor(e.setTextRange(e.createVariableDeclarationList([e.createVariableDeclaration(c,void 0,e.createLiteral(s))]),i),e.setTextRange(e.createLessThan(c,e.createPropertyAccess(e.createIdentifier("arguments"),"length")),i),e.setTextRange(e.createPostfixIncrement(c),i),e.createBlock([e.startOnNewLine(e.setTextRange(e.createExpressionStatement(e.createAssignment(e.createElementAccess(o,0===s?c:e.createSubtract(c,e.createLiteral(s))),e.createElementAccess(e.createIdentifier("arguments"),c))),i))]));e.setEmitFlags(u,1048576),e.startOnNewLine(u),t.push(u)}}function O(t,r){16384&r.transformFlags&&197!==r.kind&&I(t,r,e.createThis())}function I(t,r,n){Fe();var i=e.createVariableStatement(void 0,e.createVariableDeclarationList([e.createVariableDeclaration(e.createFileLevelUniqueName("_this"),void 0,n)]));e.setEmitFlags(i,1050112),e.setSourceMapRange(i,r),t.push(i)}function M(t,r,n){if(16384&i){var a=void 0;switch(r.kind){case 197:return t;case 156:case 158:case 159:a=e.createVoidZero();break;case 157:a=e.createPropertyAccess(e.setEmitFlags(e.createThis(),4),"constructor");break;case 239:case 196:a=e.createConditional(e.createLogicalAnd(e.setEmitFlags(e.createThis(),4),e.createBinary(e.setEmitFlags(e.createThis(),4),94,e.getLocalName(r))),e.createPropertyAccess(e.setEmitFlags(e.createThis(),4),"constructor"),e.createVoidZero());break;default:return e.Debug.failBadSyntaxKind(r)}var o=e.createVariableStatement(void 0,e.createVariableDeclarationList([e.createVariableDeclaration(e.createFileLevelUniqueName("_newTarget"),void 0,a)]));if(n)return[o].concat(t);t.unshift(o)}return t}function L(t){return e.setTextRange(e.createEmptyStatement(),t)}function R(t,r,n){var a=v(0,0),o=e.getCommentRange(r),s=e.getSourceMapRange(r),c=e.createMemberAccessForPropertyName(t,e.visitNode(r.name,x,e.isPropertyName),r.name),u=J(r,r,void 0,n);e.setEmitFlags(u,1536),e.setSourceMapRange(u,s);var l=e.setTextRange(e.createExpressionStatement(e.createAssignment(c,u)),r);return e.setOriginalNode(l,r),e.setCommentRange(l,o),e.setEmitFlags(l,48),h(a,49152,49152&i?16384:0),l}function B(t,r,n){var i=e.createExpressionStatement(j(t,r,n,!1));return e.setEmitFlags(i,1536),e.setSourceMapRange(i,e.getSourceMapRange(r.firstAccessor)),i}function j(t,r,n,a){var o=r.firstAccessor,s=r.getAccessor,c=r.setAccessor,u=v(0,0),l=e.getMutableClone(t);e.setEmitFlags(l,1568),e.setSourceMapRange(l,o.name);var _=e.createExpressionForPropertyName(e.visitNode(o.name,x,e.isPropertyName));e.setEmitFlags(_,1552),e.setSourceMapRange(_,o.name);var d=[];if(s){var p=J(s,void 0,void 0,n);e.setSourceMapRange(p,e.getSourceMapRange(s)),e.setEmitFlags(p,512);var f=e.createPropertyAssignment("get",p);e.setCommentRange(f,e.getCommentRange(s)),d.push(f)}if(c){var m=J(c,void 0,void 0,n);e.setSourceMapRange(m,e.getSourceMapRange(c)),e.setEmitFlags(m,512);var g=e.createPropertyAssignment("set",m);e.setCommentRange(g,e.getCommentRange(c)),d.push(g)}d.push(e.createPropertyAssignment("enumerable",e.createTrue()),e.createPropertyAssignment("configurable",e.createTrue()));var y=e.createCall(e.createPropertyAccess(e.createIdentifier("Object"),"defineProperty"),void 0,[l,_,e.createObjectLiteral(d,!0)]);return a&&e.startOnNewLine(y),h(u,49152,49152&i?16384:0),y}function J(r,n,a,s){var c=o;o=void 0;var u=s&&e.isClassLike(s)&&!e.hasModifier(r,32)?v(16286,73):v(16286,65),l=e.visitParameterList(r.parameters,x,t),_=z(r);return 16384&i&&!a&&(239===r.kind||196===r.kind)&&(a=e.getGeneratedNameForNode(r)),h(u,49152,0),o=c,e.setOriginalNode(e.setTextRange(e.createFunctionExpression(void 0,r.asteriskToken,a,void 0,l,void 0,_),n),r)}function z(n){var i,a,o,s=!1,c=!1,u=[],l=[],d=n.body;if(_(),e.isBlock(d)&&(o=e.addStandardPrologue(u,d.statements,!1)),O(u,n),A(u,n),w(u,n,!1),e.isBlock(d))o=e.addCustomPrologue(u,d.statements,o,x),i=d.statements,e.addRange(l,e.visitNodes(d.statements,x,e.isStatement,o)),!s&&d.multiLine&&(s=!0);else{e.Debug.assert(197===n.kind),i=e.moveRangeEnd(d,-1);var p=n.equalsGreaterThanToken;e.nodeIsSynthesized(p)||e.nodeIsSynthesized(d)||(e.rangeEndIsOnSameLineAsRangeStart(p,d,r)?c=!0:s=!0);var f=e.visitNode(d,x,e.isExpression),m=e.createReturn(f);e.setTextRange(m,d),e.moveSyntheticComments(m,d),e.setEmitFlags(m,1440),l.push(m),a=d}var g=t.endLexicalEnvironment();e.addStatementsAfterPrologue(l,g),M(l,n,!1),(e.some(u)||e.some(g))&&(s=!0);var y=e.createBlock(e.setTextRange(e.createNodeArray(u.concat(l)),i),s);return e.setTextRange(y,n.body),!s&&c&&e.setEmitFlags(y,1),a&&e.setTokenSourceMapRange(y,19,a),e.setOriginalNode(y,n.body),y}function K(r){var n=e.visitFunctionBody(r.body,S,t);return e.updateBlock(n,e.setTextRange(e.createNodeArray(M(n.statements,r,!0)),n.statements))}function U(r,n){if(n)return e.visitEachChild(r,x,t);var a=256&i?v(4032,512):v(3904,128),o=e.visitEachChild(r,x,t);return h(a,0,0),o}function V(r,n){if(!n)switch(r.expression.kind){case 195:return e.updateParen(r,V(r.expression,!1));case 204:return e.updateParen(r,q(r.expression,!1))}return e.visitEachChild(r,x,t)}function q(r,n){return e.isDestructuringAssignment(r)?e.flattenDestructuringAssignment(r,x,t,0,n):e.visitEachChild(r,x,t)}function W(r){var n=r.name;if(e.isBindingPattern(n))return H(r);if(!r.initializer&&function(e){var t=m.getNodeCheckFlags(e),r=262144&t,n=524288&t;return!(0!=(64&i)||r&&n&&0!=(512&i))&&0==(2048&i)&&(!m.isDeclarationWithCollidingName(e)||n&&!r&&0==(3072&i))}(r)){var a=e.getMutableClone(r);return a.initializer=e.createVoidZero(),a}return e.visitEachChild(r,x,t)}function H(r){var n,i=v(32,0);return n=e.isBindingPattern(r.name)?e.flattenDestructuringBinding(r,x,t,0,void 0,0!=(32&i)):e.visitEachChild(r,x,t),h(i,0,0),n}function G(t){o.labels.set(e.idText(t.label),!0)}function Y(t){o.labels.set(e.idText(t.label),!1)}function X(r,n,a,s,c){var u=v(r,n),_=function(r,n,a){if(!ce(r)){var s=void 0;o&&(s=o.allowedNonLabeledJumps,o.allowedNonLabeledJumps=6);var c=a?a(r,n,void 0):e.restoreEnclosingLabel(e.visitEachChild(r,x,t),n,o&&Y);return o&&(o.allowedNonLabeledJumps=s),c}var u=function(t){var r;switch(t.kind){case 225:case 226:case 227:var n=t.initializer;n&&238===n.kind&&(r=n)}var i=[],a=[];if(r&&3&e.getCombinedNodeFlags(r))for(var s=oe(t),c=0,u=r.declarations;c=73&&r<=108)return e.setTextRange(e.createLiteral(t),t)}}}(c||(c={})),function(e){var t,r,n,i,a;!function(e){e[e.Nop=0]="Nop",e[e.Statement=1]="Statement",e[e.Assign=2]="Assign",e[e.Break=3]="Break",e[e.BreakWhenTrue=4]="BreakWhenTrue",e[e.BreakWhenFalse=5]="BreakWhenFalse",e[e.Yield=6]="Yield",e[e.YieldStar=7]="YieldStar",e[e.Return=8]="Return",e[e.Throw=9]="Throw",e[e.Endfinally=10]="Endfinally"}(t||(t={})),function(e){e[e.Open=0]="Open",e[e.Close=1]="Close"}(r||(r={})),function(e){e[e.Exception=0]="Exception",e[e.With=1]="With",e[e.Switch=2]="Switch",e[e.Loop=3]="Loop",e[e.Labeled=4]="Labeled"}(n||(n={})),function(e){e[e.Try=0]="Try",e[e.Catch=1]="Catch",e[e.Finally=2]="Finally",e[e.Done=3]="Done"}(i||(i={})),function(e){e[e.Next=0]="Next",e[e.Throw=1]="Throw",e[e.Return=2]="Return",e[e.Break=3]="Break",e[e.Yield=4]="Yield",e[e.YieldStar=5]="YieldStar",e[e.Catch=6]="Catch",e[e.Endfinally=7]="Endfinally"}(a||(a={})),e.transformGenerators=function(t){var r,n,i,a,s,c,u,l,_,d,p=t.resumeLexicalEnvironment,f=t.endLexicalEnvironment,m=t.hoistFunctionDeclaration,g=t.hoistVariableDeclaration,y=t.getCompilerOptions(),v=e.getEmitScriptTarget(y),h=t.getEmitResolver(),b=t.onSubstituteNode;t.onSubstituteNode=function(t,i){return i=b(t,i),1===t?function(t){return e.isIdentifier(t)?function(t){if(!e.isGeneratedIdentifier(t)&&r&&r.has(e.idText(t))){var i=e.getOriginalNode(t);if(e.isIdentifier(i)&&i.parent){var a=h.getReferencedValueDeclaration(i);if(a){var o=n[e.getOriginalNodeId(a)];if(o){var s=e.getMutableClone(o);return e.setSourceMapRange(s,t),e.setCommentRange(s,t),s}}}}return t}(t):t}(i):i};var D,x,S,T,C,k,E,N,A,F,P,w,O=1,I=0,M=0;return e.chainBundle(function(r){if(r.isDeclarationFile||0==(512&r.transformFlags))return r;var n=e.visitEachChild(r,L,t);return e.addEmitHelpers(n,t.readEmitHelpers()),n});function L(r){var n=r.transformFlags;return a?function(r){switch(r.kind){case 223:case 224:return function(r){return a?(ne(),r=e.visitEachChild(r,L,t),ae(),r):e.visitEachChild(r,L,t)}(r);case 232:return function(r){return a&&Z({kind:2,isScript:!0,breakLabel:-1}),r=e.visitEachChild(r,L,t),a&&oe(),r}(r);case 233:return function(r){return a&&Z({kind:4,isScript:!0,labelText:e.idText(r.label),breakLabel:-1}),r=e.visitEachChild(r,L,t),a&&se(),r}(r);default:return R(r)}}(r):i?R(r):256&n?function(t){switch(t.kind){case 239:return B(t);case 196:return j(t);default:return e.Debug.failBadSyntaxKind(t)}}(r):512&n?e.visitEachChild(r,L,t):r}function R(r){switch(r.kind){case 239:return B(r);case 196:return j(r);case 158:case 159:return function(r){var n=i,o=a;return i=!1,a=!1,r=e.visitEachChild(r,L,t),i=n,a=o,r}(r);case 219:return function(t){if(4194304&t.transformFlags)q(t.declarationList);else{if(1048576&e.getEmitFlags(t))return t;for(var r=0,n=t.declarationList.declarations;r0?e.inlineExpressions(e.map(c,W)):void 0,e.visitNode(r.condition,L,e.isExpression),e.visitNode(r.incrementor,L,e.isExpression),e.visitNode(r.statement,L,e.isStatement,e.liftToBlock))}else r=e.visitEachChild(r,L,t);return a&&ae(),r}(r);case 226:return function(r){a&&ne();var n=r.initializer;if(e.isVariableDeclarationList(n)){for(var i=0,o=n.declarations;i0)return ge(n,r)}return e.visitEachChild(r,L,t)}(r);case 228:return function(r){if(a){var n=pe(r.label&&e.idText(r.label));if(n>0)return ge(n,r)}return e.visitEachChild(r,L,t)}(r);case 230:return function(t){return r=e.visitNode(t.expression,L,e.isExpression),n=t,e.setTextRange(e.createReturn(e.createArrayLiteral(r?[me(2),r]:[me(2)])),n);var r,n}(r);default:return 4194304&r.transformFlags?function(r){switch(r.kind){case 204:return function(r){var n=e.getExpressionAssociativity(r);switch(n){case 0:return function(r){if(H(r.right)){if(e.isLogicalOperator(r.operatorToken.kind))return function(t){var r=Q(),n=X();return he(n,e.visitNode(t.left,L,e.isExpression),t.left),54===t.operatorToken.kind?xe(r,n,t.left):De(r,n,t.left),he(n,e.visitNode(t.right,L,e.isExpression),t.right),$(r),n}(r);if(27===r.operatorToken.kind)return function(t){var r=[];return n(t.left),n(t.right),e.inlineExpressions(r);function n(t){e.isBinaryExpression(t)&&27===t.operatorToken.kind?(n(t.left),n(t.right)):(H(t)&&r.length>0&&(Se(1,[e.createExpressionStatement(e.inlineExpressions(r))]),r=[]),r.push(e.visitNode(t,L,e.isExpression)))}}(r);var n=e.getMutableClone(r);return n.left=Y(e.visitNode(r.left,L,e.isExpression)),n.right=e.visitNode(r.right,L,e.isExpression),n}return e.visitEachChild(r,L,t)}(r);case 1:return function(r){var n,i=r.left,a=r.right;if(H(a)){var o=void 0;switch(i.kind){case 189:o=e.updatePropertyAccess(i,Y(e.visitNode(i.expression,L,e.isLeftHandSideExpression)),i.name);break;case 190:o=e.updateElementAccess(i,Y(e.visitNode(i.expression,L,e.isLeftHandSideExpression)),Y(e.visitNode(i.argumentExpression,L,e.isExpression)));break;default:o=e.visitNode(i,L,e.isExpression)}var s=r.operatorToken.kind;return(n=s)>=60&&n<=71?e.setTextRange(e.createAssignment(o,e.setTextRange(e.createBinary(Y(o),function(e){switch(e){case 60:return 38;case 61:return 39;case 62:return 40;case 63:return 41;case 64:return 42;case 65:return 43;case 66:return 46;case 67:return 47;case 68:return 48;case 69:return 49;case 70:return 50;case 71:return 51}}(s),e.visitNode(a,L,e.isExpression)),r)),r):e.updateBinary(r,o,e.visitNode(a,L,e.isExpression))}return e.visitEachChild(r,L,t)}(r);default:return e.Debug.assertNever(n)}}(r);case 205:return function(r){if(H(r.whenTrue)||H(r.whenFalse)){var n=Q(),i=Q(),a=X();return xe(n,e.visitNode(r.condition,L,e.isExpression),r.condition),he(a,e.visitNode(r.whenTrue,L,e.isExpression),r.whenTrue),be(i),$(n),he(a,e.visitNode(r.whenFalse,L,e.isExpression),r.whenFalse),$(i),a}return e.visitEachChild(r,L,t)}(r);case 207:return function(r){var n,i=Q(),a=e.visitNode(r.expression,L,e.isExpression);if(r.asteriskToken){var o=0==(8388608&e.getEmitFlags(r.expression))?e.createValuesHelper(t,a,r):a;!function(e,t){Se(7,[e],t)}(o,r)}else!function(e,t){Se(6,[e],t)}(a,r);return $(i),n=r,e.setTextRange(e.createCall(e.createPropertyAccess(T,"sent"),void 0,[]),n)}(r);case 187:return function(e){return z(e.elements,void 0,void 0,e.multiLine)}(r);case 188:return function(t){var r=t.properties,n=t.multiLine,i=G(r),a=X();he(a,e.createObjectLiteral(e.visitNodes(r,L,e.isObjectLiteralElementLike,0,i),n));var o=e.reduceLeft(r,function(r,i){H(i)&&r.length>0&&(ve(e.createExpressionStatement(e.inlineExpressions(r))),r=[]);var o=e.createExpressionForObjectLiteralElementLike(t,i,a),s=e.visitNode(o,L,e.isExpression);return s&&(n&&e.startOnNewLine(s),r.push(s)),r},[],i);return o.push(n?e.startOnNewLine(e.getMutableClone(a)):a),e.inlineExpressions(o)}(r);case 190:return function(r){if(H(r.argumentExpression)){var n=e.getMutableClone(r);return n.expression=Y(e.visitNode(r.expression,L,e.isLeftHandSideExpression)),n.argumentExpression=e.visitNode(r.argumentExpression,L,e.isExpression),n}return e.visitEachChild(r,L,t)}(r);case 191:return function(r){if(!e.isImportCall(r)&&e.forEach(r.arguments,H)){var n=e.createCallBinding(r.expression,g,v,!0),i=n.target,a=n.thisArg;return e.setOriginalNode(e.createFunctionApply(Y(e.visitNode(i,L,e.isLeftHandSideExpression)),a,z(r.arguments),r),r)}return e.visitEachChild(r,L,t)}(r);case 192:return function(r){if(e.forEach(r.arguments,H)){var n=e.createCallBinding(e.createPropertyAccess(r.expression,"bind"),g),i=n.target,a=n.thisArg;return e.setOriginalNode(e.setTextRange(e.createNew(e.createFunctionApply(Y(e.visitNode(i,L,e.isExpression)),a,z(r.arguments,e.createVoidZero())),void 0,[]),r),r)}return e.visitEachChild(r,L,t)}(r);default:return e.visitEachChild(r,L,t)}}(r):8389120&r.transformFlags?e.visitEachChild(r,L,t):r}}function B(r){if(r.asteriskToken)r=e.setOriginalNode(e.setTextRange(e.createFunctionDeclaration(void 0,r.modifiers,void 0,r.name,void 0,e.visitParameterList(r.parameters,L,t),void 0,J(r.body)),r),r);else{var n=i,o=a;i=!1,a=!1,r=e.visitEachChild(r,L,t),i=n,a=o}return i?void m(r):r}function j(r){if(r.asteriskToken)r=e.setOriginalNode(e.setTextRange(e.createFunctionExpression(void 0,void 0,r.name,void 0,e.visitParameterList(r.parameters,L,t),void 0,J(r.body)),r),r);else{var n=i,o=a;i=!1,a=!1,r=e.visitEachChild(r,L,t),i=n,a=o}return r}function J(t){var r=[],n=i,o=a,m=s,g=c,y=u,v=l,h=_,b=d,C=O,k=D,E=x,N=S,A=T;i=!0,a=!1,s=void 0,c=void 0,u=void 0,l=void 0,_=void 0,d=void 0,O=1,D=void 0,x=void 0,S=void 0,T=e.createTempVariable(void 0),p();var F=e.addPrologue(r,t.statements,!1,L);K(t.statements,F);var P=Te();return e.addStatementsAfterPrologue(r,f()),r.push(e.createReturn(P)),i=n,a=o,s=m,c=g,u=y,l=v,_=h,d=b,O=C,D=k,x=E,S=N,T=A,e.setTextRange(e.createBlock(r,t.multiLine),t)}function z(t,r,n,i){var a,o=G(t);if(o>0){a=X();var s=e.visitNodes(t,L,e.isExpression,0,o);he(a,e.createArrayLiteral(r?[r].concat(s):s)),r=void 0}var c=e.reduceLeft(t,function(t,n){if(H(n)&&t.length>0){var o=void 0!==a;a||(a=X()),he(a,o?e.createArrayConcat(a,[e.createArrayLiteral(t,i)]):e.createArrayLiteral(r?[r].concat(t):t,i)),r=void 0,t=[]}return t.push(e.visitNode(n,L,e.isExpression)),t},[],o);return a?e.createArrayConcat(a,[e.createArrayLiteral(c,i)]):e.setTextRange(e.createArrayLiteral(r?[r].concat(c):c,i),n)}function K(e,t){void 0===t&&(t=0);for(var r=e.length,n=t;n0?be(r,t):ve(t)}(i);case 229:return function(t){var r=de(t.label?e.idText(t.label):void 0);r>0?be(r,t):ve(t)}(i);case 230:return function(t){Se(8,[e.visitNode(t.expression,L,e.isExpression)],t)}(i);case 231:return function(t){var r,n,i;H(t)?(r=Y(e.visitNode(t.expression,L,e.isExpression)),n=Q(),i=Q(),$(n),Z({kind:1,expression:r,startLabel:n,endLabel:i}),U(t.statement),e.Debug.assert(1===re()),$(ee().endLabel)):ve(e.visitNode(t,L,e.isStatement))}(i);case 232:return function(t){if(H(t.caseBlock)){for(var r=t.caseBlock,n=r.clauses.length,i=(Z({kind:2,isScript:!1,breakLabel:p=Q()}),p),a=Y(e.visitNode(t.expression,L,e.isExpression)),o=[],s=-1,c=0;c0)break;_.push(e.createCaseClause(e.visitNode(u.expression,L,e.isExpression),[ge(o[c],u.expression)]))}else d++}_.length&&(ve(e.createSwitch(a,e.createCaseBlock(_))),l+=_.length,_=[]),d>0&&(l+=d,d=0)}be(s>=0?o[s]:i);for(var c=0;c0);l++)u.push(W(i));u.length&&(ve(e.createExpressionStatement(e.inlineExpressions(u))),c+=u.length,u=[])}}function W(t){return e.setSourceMapRange(e.createAssignment(e.setSourceMapRange(e.getSynthesizedClone(t.name),t.name),e.visitNode(t.initializer,L,e.isExpression)),t)}function H(e){return!!e&&0!=(4194304&e.transformFlags)}function G(e){for(var t=e.length,r=0;r=0;r--){var n=l[r];if(!ue(n))break;if(n.labelText===e)return!0}return!1}function de(e){if(l)if(e)for(var t=l.length-1;t>=0;t--){if(ue(r=l[t])&&r.labelText===e)return r.breakLabel;if(ce(r)&&_e(e,t-1))return r.breakLabel}else for(t=l.length-1;t>=0;t--){var r;if(ce(r=l[t]))return r.breakLabel}return 0}function pe(e){if(l)if(e){for(var t=l.length-1;t>=0;t--)if(le(r=l[t])&&_e(e,t-1))return r.continueLabel}else for(t=l.length-1;t>=0;t--){var r;if(le(r=l[t]))return r.continueLabel}return 0}function fe(t){if(void 0!==t&&t>0){void 0===d&&(d=[]);var r=e.createLiteral(-1);return void 0===d[t]?d[t]=[r]:d[t].push(r),r}return e.createOmittedExpression()}function me(t){var r=e.createLiteral(t);return e.addSyntheticTrailingComment(r,3,function(e){switch(e){case 2:return"return";case 3:return"break";case 4:return"yield";case 5:return"yield*";case 7:return"endfinally";default:return}}(t)),r}function ge(t,r){return e.Debug.assertLessThan(0,t,"Invalid label"),e.setTextRange(e.createReturn(e.createArrayLiteral([me(3),fe(t)])),r)}function ye(){Se(0)}function ve(e){e?Se(1,[e]):ye()}function he(e,t,r){Se(2,[e,t],r)}function be(e,t){Se(3,[e],t)}function De(e,t,r){Se(4,[e,t],r)}function xe(e,t,r){Se(5,[e,t],r)}function Se(e,t,r){void 0===D&&(D=[],x=[],S=[]),void 0===_&&$(Q());var n=D.length;D[n]=e,x[n]=t,S[n]=r}function Te(){I=0,M=0,C=void 0,k=!1,E=!1,N=void 0,A=void 0,F=void 0,P=void 0,w=void 0;var r=function(){if(D){for(var t=0;t0)),524288))}function Ce(e){(function(e){if(!E)return!0;if(!_||!d)return!1;for(var t=0;t<_.length;t++)if(_[t]===e&&d[t])return!0;return!1})(e)&&(Ee(e),w=void 0,Fe(void 0,void 0)),A&&N&&ke(!1),function(){if(void 0!==d&&void 0!==C)for(var e=0;e=0;r--){var n=w[r];A=[e.createWith(n.expression,e.createBlock(A))]}if(P){var i=P.startLabel,a=P.catchLabel,o=P.finallyLabel,s=P.endLabel;A.unshift(e.createExpressionStatement(e.createCall(e.createPropertyAccess(e.createPropertyAccess(T,"trys"),"push"),void 0,[e.createArrayLiteral([fe(i),fe(a),fe(o),fe(s)])]))),P=void 0}t&&A.push(e.createExpressionStatement(e.createAssignment(e.createPropertyAccess(T,"label"),e.createLiteral(M+1))))}N.push(e.createCaseClause(e.createLiteral(M),A||[])),A=void 0}function Ee(e){if(_)for(var t=0;t<_.length;t++)_[t]===e&&(A&&(ke(!k),k=!1,E=!1,M++),void 0===C&&(C=[]),void 0===C[M]?C[M]=[t]:C[M].push(t))}function Ne(t){if(Ee(t),function(e){if(s)for(;I 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };'}}(c||(c={})),function(e){e.transformModule=function(a){var o=a.startLexicalEnvironment,s=a.endLexicalEnvironment,c=a.hoistVariableDeclaration,u=a.getCompilerOptions(),l=a.getEmitResolver(),_=a.getEmitHost(),d=e.getEmitScriptTarget(u),p=e.getEmitModuleKind(u),f=a.onSubstituteNode,m=a.onEmitNode;a.onSubstituteNode=function(t,r){return(r=f(t,r)).id&&v[r.id]?r:1===t?function(t){switch(t.kind){case 72:return Y(t);case 204:return function(t){if(e.isAssignmentOperator(t.operatorToken.kind)&&e.isIdentifier(t.left)&&!e.isGeneratedIdentifier(t.left)&&!e.isLocalName(t.left)&&!e.isDeclarationNameOfEnumOrNamespace(t.left)){var r=X(t.left);if(r){for(var n=t,i=0,a=r;i=2?2:0)),t),t))}else n&&e.isDefaultImport(t)&&(r=e.append(r,e.createVariableStatement(void 0,e.createVariableDeclarationList([e.setOriginalNode(e.setTextRange(e.createVariableDeclaration(e.getSynthesizedClone(n.name),void 0,e.getGeneratedNameForNode(t)),t),t)],d>=2?2:0))));if(B(t)){var a=e.getOriginalNodeId(t);D[a]=j(D[a],t)}else r=j(r,t);return e.singleOrMany(r)}(t);case 248:return function(t){var r;if(e.Debug.assert(e.isExternalModuleImportEqualsDeclaration(t),"import= for internal module references should be handled in an earlier transformer."),p!==e.ModuleKind.AMD?r=e.hasModifier(t,1)?e.append(r,e.setOriginalNode(e.setTextRange(e.createExpressionStatement(H(t.name,M(t))),t),t)):e.append(r,e.setOriginalNode(e.setTextRange(e.createVariableStatement(void 0,e.createVariableDeclarationList([e.createVariableDeclaration(e.getSynthesizedClone(t.name),void 0,M(t))],d>=2?2:0)),t),t)):e.hasModifier(t,1)&&(r=e.append(r,e.setOriginalNode(e.setTextRange(e.createExpressionStatement(H(e.getExportName(t),e.getLocalName(t))),t),t))),B(t)){var n=e.getOriginalNodeId(t);D[n]=J(D[n],t)}else r=J(r,t);return e.singleOrMany(r)}(t);case 255:return function(t){if(t.moduleSpecifier){var r=e.getGeneratedNameForNode(t);if(t.exportClause){var n=[];p!==e.ModuleKind.AMD&&n.push(e.setOriginalNode(e.setTextRange(e.createVariableStatement(void 0,e.createVariableDeclarationList([e.createVariableDeclaration(r,void 0,M(t))])),t),t));for(var i=0,o=t.exportClause.elements;i(e.isExportName(r)?1:0);return!1}(t.left)?e.flattenDestructuringAssignment(t,P,a,0,!1,L):e.visitEachChild(t,P,a)}(t):e.visitEachChild(t,P,a):t}function w(t,r){var i,o=e.createUniqueName("resolve"),s=e.createUniqueName("reject"),c=[e.createParameter(void 0,void 0,void 0,o),e.createParameter(void 0,void 0,void 0,s)],l=e.createBlock([e.createExpressionStatement(e.createCall(e.createIdentifier("require"),void 0,[e.createArrayLiteral([t||e.createOmittedExpression()]),o,s]))]);d>=2?i=e.createArrowFunction(void 0,void 0,c,void 0,void 0,l):(i=e.createFunctionExpression(void 0,void 0,void 0,void 0,c,void 0,l),r&&e.setEmitFlags(i,8));var _=e.createNew(e.createIdentifier("Promise"),void 0,[i]);return u.esModuleInterop?(a.requestEmitHelper(n),e.createCall(e.createPropertyAccess(_,e.createIdentifier("then")),void 0,[e.getHelperName("__importStar")])):_}function O(t,r){var i,o=e.createCall(e.createPropertyAccess(e.createIdentifier("Promise"),"resolve"),void 0,[]),s=e.createCall(e.createIdentifier("require"),void 0,t?[t]:[]);return u.esModuleInterop&&(a.requestEmitHelper(n),s=e.createCall(e.getHelperName("__importStar"),void 0,[s])),d>=2?i=e.createArrowFunction(void 0,void 0,[],void 0,void 0,s):(i=e.createFunctionExpression(void 0,void 0,void 0,void 0,[],void 0,e.createBlock([e.createReturn(s)])),r&&e.setEmitFlags(i,8)),e.createCall(e.createPropertyAccess(o,"then"),void 0,[i])}function I(t,r){return!u.esModuleInterop||67108864&e.getEmitFlags(t)?r:e.getImportNeedsImportStarHelper(t)?(a.requestEmitHelper(n),e.createCall(e.getHelperName("__importStar"),void 0,[r])):e.getImportNeedsImportDefaultHelper(t)?(a.requestEmitHelper(i),e.createCall(e.getHelperName("__importDefault"),void 0,[r])):r}function M(t){var r=e.getExternalModuleNameLiteral(t,g,_,l,u),n=[];return r&&n.push(r),e.createCall(e.createIdentifier("require"),void 0,n)}function L(t,r,n){var i=X(t);if(i){for(var a=e.isExportName(t)?r:e.createAssignment(t,r),o=0,s=i;o1){var i=n.slice(1),a=e.guessIndentation(i);r=[n[0]].concat(e.map(i,function(e){return e.slice(a)})).join(E)}e.addSyntheticLeadingComment(o,t.kind,r,t.hasTrailingNewLine)}},u=0,l=s;u0?e.parameters[0].type:void 0}e.transformDeclarations=r}(c||(c={})),function(e){var t,r;function n(e,t){return t}function i(e,t,r){r(e,t)}!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Completed=2]="Completed",e[e.Disposed=3]="Disposed"}(t||(t={})),function(e){e[e.Substitution=1]="Substitution",e[e.EmitNotifications=2]="EmitNotifications"}(r||(r={})),e.getTransformers=function(t,r){var n=t.jsx,i=e.getEmitScriptTarget(t),a=e.getEmitModuleKind(t),o=[];return e.addRange(o,r&&r.before),o.push(e.transformTypeScript),2===n&&o.push(e.transformJsx),i<6&&o.push(e.transformESNext),i<4&&o.push(e.transformES2017),i<3&&o.push(e.transformES2016),i<2&&(o.push(e.transformES2015),o.push(e.transformGenerators)),o.push(function(t){switch(t){case e.ModuleKind.ESNext:case e.ModuleKind.ES2015:return e.transformES2015Module;case e.ModuleKind.System:return e.transformSystemModule;default:return e.transformModule}}(a)),i<1&&o.push(e.transformES5),e.addRange(o,r&&r.after),o},e.noEmitSubstitution=n,e.noEmitNotification=i,e.transformNodes=function(t,r,a,o,s,c){for(var u,l,_,d=new Array(312),p=[],f=[],m=0,g=!1,y=n,v=i,h=0,b=[],D={getCompilerOptions:function(){return a},getEmitResolver:function(){return t},getEmitHost:function(){return r},startLexicalEnvironment:function(){e.Debug.assert(h>0,"Cannot modify the lexical environment during initialization."),e.Debug.assert(h<2,"Cannot modify the lexical environment after transformation has completed."),e.Debug.assert(!g,"Lexical environment is suspended."),p[m]=u,f[m]=l,m++,u=void 0,l=void 0},suspendLexicalEnvironment:function(){e.Debug.assert(h>0,"Cannot modify the lexical environment during initialization."),e.Debug.assert(h<2,"Cannot modify the lexical environment after transformation has completed."),e.Debug.assert(!g,"Lexical environment is already suspended."),g=!0},resumeLexicalEnvironment:function(){e.Debug.assert(h>0,"Cannot modify the lexical environment during initialization."),e.Debug.assert(h<2,"Cannot modify the lexical environment after transformation has completed."),e.Debug.assert(g,"Lexical environment is not suspended."),g=!1},endLexicalEnvironment:function(){var t;if(e.Debug.assert(h>0,"Cannot modify the lexical environment during initialization."),e.Debug.assert(h<2,"Cannot modify the lexical environment after transformation has completed."),e.Debug.assert(!g,"Lexical environment is suspended."),(u||l)&&(l&&(t=l.slice()),u)){var r=e.createVariableStatement(void 0,e.createVariableDeclarationList(u));t?t.push(r):t=[r]}return u=p[--m],l=f[m],0===m&&(p=[],f=[]),t},hoistVariableDeclaration:function(t){e.Debug.assert(h>0,"Cannot modify the lexical environment during initialization."),e.Debug.assert(h<2,"Cannot modify the lexical environment after transformation has completed.");var r=e.setEmitFlags(e.createVariableDeclaration(t),64);u?u.push(r):u=[r]},hoistFunctionDeclaration:function(t){e.Debug.assert(h>0,"Cannot modify the lexical environment during initialization."),e.Debug.assert(h<2,"Cannot modify the lexical environment after transformation has completed."),l?l.push(t):l=[t]},requestEmitHelper:function(t){e.Debug.assert(h>0,"Cannot modify the transformation context during initialization."),e.Debug.assert(h<2,"Cannot modify the transformation context after transformation has completed."),e.Debug.assert(!t.scoped,"Cannot request a scoped emit helper."),_=e.append(_,t)},readEmitHelpers:function(){e.Debug.assert(h>0,"Cannot modify the transformation context during initialization."),e.Debug.assert(h<2,"Cannot modify the transformation context after transformation has completed.");var t=_;return _=void 0,t},enableSubstitution:function(t){e.Debug.assert(h<2,"Cannot modify the transformation context after transformation has completed."),d[t]|=1},enableEmitNotification:function(t){e.Debug.assert(h<2,"Cannot modify the transformation context after transformation has completed."),d[t]|=2},isSubstitutionEnabled:E,isEmitNotificationEnabled:N,get onSubstituteNode(){return y},set onSubstituteNode(t){e.Debug.assert(h<1,"Cannot modify transformation hooks after initialization has completed."),e.Debug.assert(void 0!==t,"Value must not be 'undefined'"),y=t},get onEmitNode(){return v},set onEmitNode(t){e.Debug.assert(h<1,"Cannot modify transformation hooks after initialization has completed."),e.Debug.assert(void 0!==t,"Value must not be 'undefined'"),v=t},addDiagnostic:function(e){b.push(e)}},x=0,S=o;x"],e[8192]=["[","]"],e}(),a={pos:-1,end:-1};function o(t,r,n,i){void 0===i&&(i=!1);var a=e.isArray(n)?n:e.getSourceFilesToEmit(t,n),o=t.getCompilerOptions();if(o.outFile||o.out){if(a.length){var c=e.createBundle(a,t.getPrependNodes());if(_=r(s(c,t,i),c))return _}}else for(var u=0,l=a;u"),_t(),ne(e.type),Ot(e)}(i);case 289:return function(e){st("function"),$e(e,e.parameters),at(":"),ne(e.type)}(i);case 166:return function(e){wt(e),st("new"),_t(),Qe(e,e.typeParameters),$e(e,e.parameters),_t(),at("=>"),_t(),ne(e.type),Ot(e)}(i);case 167:return function(e){st("typeof"),_t(),ne(e.exprName)}(i);case 168:return function(t){at("{");var r=1&e.getEmitFlags(t)?768:32897;et(t,t.members,524288|r),at("}")}(i);case 169:return function(e){ne(e.elementType),at("["),at("]")}(i);case 170:return function(e){at("["),et(e,e.elementTypes,528),at("]")}(i);case 171:return function(e){ne(e.type),at("?")}(i);case 173:return function(e){et(e,e.types,516)}(i);case 174:return function(e){et(e,e.types,520)}(i);case 175:return function(e){ne(e.checkType),_t(),st("extends"),_t(),ne(e.extendsType),_t(),at("?"),_t(),ne(e.trueType),_t(),at(":"),_t(),ne(e.falseType)}(i);case 176:return function(e){st("infer"),_t(),ne(e.typeParameter)}(i);case 177:return function(e){at("("),ne(e.type),at(")")}(i);case 211:return function(e){ae(e.expression),Xe(e,e.typeArguments)}(i);case 178:return void st("this");case 179:return function(e){vt(e.operator,st),_t(),ne(e.type)}(i);case 180:return function(e){ne(e.objectType),at("["),ne(e.indexType),at("]")}(i);case 181:return function(t){var r=e.getEmitFlags(t);at("{"),1&r?_t():(pt(),ft());t.readonlyToken&&(ne(t.readonlyToken),133!==t.readonlyToken.kind&&st("readonly"),_t());at("["),oe(0,t.typeParameter)(3,t.typeParameter),at("]"),t.questionToken&&(ne(t.questionToken),56!==t.questionToken.kind&&at("?"));at(":"),_t(),ne(t.type),ot(),1&r?_t():(pt(),mt());at("}")}(i);case 182:return function(e){ae(e.literal)}(i);case 183:return function(e){e.isTypeOf&&(st("typeof"),_t());st("import"),at("("),ne(e.argument),at(")"),e.qualifier&&(at("."),ne(e.qualifier));Xe(e,e.typeArguments)}(i);case 284:return void at("*");case 285:return void at("?");case 286:return function(e){at("?"),ne(e.type)}(i);case 287:return function(e){at("!"),ne(e.type)}(i);case 288:return function(e){ne(e.type),at("=")}(i);case 172:case 290:return function(e){at("..."),ne(e.type)}(i);case 184:return function(e){at("{"),et(e,e.elements,525136),at("}")}(i);case 185:return function(e){at("["),et(e,e.elements,524880),at("]")}(i);case 186:return function(e){ne(e.dotDotDotToken),e.propertyName&&(ne(e.propertyName),at(":"),_t());ne(e.name),qe(e.initializer,e.name.end,e)}(i);case 216:return function(e){ae(e.expression),ne(e.literal)}(i);case 217:return void ot();case 218:return function(e){me(e,!e.multiLine&&Nt(e))}(i);case 219:return function(e){Ue(e,e.modifiers),ne(e.declarationList),ot()}(i);case 220:return ge(!1);case 221:return function(t){ae(t.expression),(!e.isJsonSourceFile(n)||e.nodeIsSynthesized(t.expression))&&ot()}(i);case 222:return function(e){var t=he(91,e.pos,st,e);_t(),he(20,t,at,e),ae(e.expression),he(21,e.expression.end,at,e),Ge(e,e.thenStatement),e.elseStatement&&(ht(e),he(83,e.thenStatement.end,st,e),222===e.elseStatement.kind?(_t(),ne(e.elseStatement)):Ge(e,e.elseStatement))}(i);case 223:return function(t){he(82,t.pos,st,t),Ge(t,t.statement),e.isBlock(t.statement)?_t():ht(t);ye(t,t.statement.end),at(";")}(i);case 224:return function(e){ye(e,e.pos),Ge(e,e.statement)}(i);case 225:return function(e){var t=he(89,e.pos,st,e);_t();var r=he(20,t,at,e);ve(e.initializer),r=he(26,e.initializer?e.initializer.end:r,at,e),He(e.condition),r=he(26,e.condition?e.condition.end:r,at,e),He(e.incrementor),he(21,e.incrementor?e.incrementor.end:r,at,e),Ge(e,e.statement)}(i);case 226:return function(e){var t=he(89,e.pos,st,e);_t(),he(20,t,at,e),ve(e.initializer),_t(),he(93,e.initializer.end,st,e),_t(),ae(e.expression),he(21,e.expression.end,at,e),Ge(e,e.statement)}(i);case 227:return function(e){var t=he(89,e.pos,st,e);_t(),function(e){e&&(ne(e),_t())}(e.awaitModifier),he(20,t,at,e),ve(e.initializer),_t(),he(147,e.initializer.end,st,e),_t(),ae(e.expression),he(21,e.expression.end,at,e),Ge(e,e.statement)}(i);case 228:return function(e){he(78,e.pos,st,e),We(e.label),ot()}(i);case 229:return function(e){he(73,e.pos,st,e),We(e.label),ot()}(i);case 230:return function(e){he(97,e.pos,st,e),He(e.expression),ot()}(i);case 231:return function(e){var t=he(108,e.pos,st,e);_t(),he(20,t,at,e),ae(e.expression),he(21,e.expression.end,at,e),Ge(e,e.statement)}(i);case 232:return function(e){var t=he(99,e.pos,st,e);_t(),he(20,t,at,e),ae(e.expression),he(21,e.expression.end,at,e),_t(),ne(e.caseBlock)}(i);case 233:return function(e){ne(e.label),he(57,e.label.end,at,e),_t(),ne(e.statement)}(i);case 234:return function(e){he(101,e.pos,st,e),He(e.expression),ot()}(i);case 235:return function(e){he(103,e.pos,st,e),_t(),ne(e.tryBlock),e.catchClause&&(ht(e),ne(e.catchClause));e.finallyBlock&&(ht(e),he(88,(e.catchClause||e.tryBlock).end,st,e),_t(),ne(e.finallyBlock))}(i);case 236:return function(e){gt(79,e.pos,st),ot()}(i);case 237:return function(e){ne(e.name),Ve(e.type),qe(e.initializer,e.type?e.type.end:e.name.end,e)}(i);case 238:return function(t){st(e.isLet(t)?"let":e.isVarConst(t)?"const":"var"),_t(),et(t,t.declarations,528)}(i);case 239:return function(e){be(e)}(i);case 240:return function(e){Ee(e)}(i);case 241:return function(e){Ye(e,e.decorators),Ue(e,e.modifiers),st("interface"),_t(),ne(e.name),Qe(e,e.typeParameters),et(e,e.heritageClauses,512),_t(),at("{"),et(e,e.members,129),at("}")}(i);case 242:return function(e){Ye(e,e.decorators),Ue(e,e.modifiers),st("type"),_t(),ne(e.name),Qe(e,e.typeParameters),_t(),at("="),_t(),ne(e.type),ot()}(i);case 243:return function(e){Ue(e,e.modifiers),st("enum"),_t(),ne(e.name),_t(),at("{"),et(e,e.members,145),at("}")}(i);case 244:return function(e){Ue(e,e.modifiers),512&~e.flags&&(st(16&e.flags?"namespace":"module"),_t());ne(e.name);var t=e.body;if(!t)return ot();for(;244===t.kind;)at("."),ne(t.name),t=t.body;_t(),ne(t)}(i);case 245:return function(t){wt(t),e.forEach(t.statements,Mt),me(t,Nt(t)),Ot(t)}(i);case 246:return function(e){he(18,e.pos,at,e),et(e,e.clauses,129),he(19,e.clauses.end,at,e,!0)}(i);case 247:return function(e){var t=he(85,e.pos,st,e);_t(),t=he(119,t,st,e),_t(),t=he(131,t,st,e),_t(),ne(e.name),ot()}(i);case 248:return function(e){Ue(e,e.modifiers),he(92,e.modifiers?e.modifiers.end:e.pos,st,e),_t(),ne(e.name),_t(),he(59,e.name.end,at,e),_t(),function(e){72===e.kind?ae(e):ne(e)}(e.moduleReference),ot()}(i);case 249:return function(e){Ue(e,e.modifiers),he(92,e.modifiers?e.modifiers.end:e.pos,st,e),_t(),e.importClause&&(ne(e.importClause),_t(),he(144,e.importClause.end,st,e),_t());ae(e.moduleSpecifier),ot()}(i);case 250:return function(e){ne(e.name),e.name&&e.namedBindings&&(he(27,e.name.end,at,e),_t());ne(e.namedBindings)}(i);case 251:return function(e){var t=he(40,e.pos,at,e);_t(),he(119,t,st,e),_t(),ne(e.name)}(i);case 252:return function(e){Ne(e)}(i);case 253:return function(e){Ae(e)}(i);case 254:return function(e){var t=he(85,e.pos,st,e);_t(),e.isExportEquals?he(59,t,ct,e):he(80,t,st,e);_t(),ae(e.expression),ot()}(i);case 255:return function(e){var t=he(85,e.pos,st,e);_t(),e.exportClause?ne(e.exportClause):t=he(40,t,at,e);if(e.moduleSpecifier){_t();var r=e.exportClause?e.exportClause.end:t;he(144,r,st,e),_t(),ae(e.moduleSpecifier)}ot()}(i);case 256:return function(e){Ne(e)}(i);case 257:return function(e){Ae(e)}(i);case 258:return;case 259:return function(e){st("require"),at("("),ae(e.expression),at(")")}(i);case 11:return function(e){p.writeLiteral(Ft(e,!0))}(i);case 262:case 265:return function(t){at("<"),e.isJsxOpeningElement(t)&&(Fe(t.tagName),t.attributes.properties&&t.attributes.properties.length>0&&_t(),ne(t.attributes));at(">")}(i);case 263:case 266:return function(t){at("")}(i);case 267:return function(e){ne(e.name),function(e,t,r,n){r&&(t(e),n(r))}("=",at,e.initializer,ne)}(i);case 268:return function(e){et(e,e.properties,262656)}(i);case 269:return function(e){at("{..."),ae(e.expression),at("}")}(i);case 270:return function(e){e.expression&&(at("{"),ne(e.dotDotDotToken),ae(e.expression),at("}"))}(i);case 271:return function(e){he(74,e.pos,st,e),_t(),ae(e.expression),Pe(e,e.statements,e.expression.end)}(i);case 272:return function(e){var t=he(80,e.pos,st,e);Pe(e,e.statements,t)}(i);case 273:return function(e){_t(),vt(e.token,st),_t(),et(e,e.types,528)}(i);case 274:return function(e){var t=he(75,e.pos,st,e);_t(),e.variableDeclaration&&(he(20,t,at,e),ne(e.variableDeclaration),he(21,e.variableDeclaration.end,at,e),_t());ne(e.block)}(i);case 275:return function(t){ne(t.name),at(":"),_t();var r=t.initializer;if(rr&&0==(512&e.getEmitFlags(r))){var n=e.getCommentRange(r);rr(n.pos)}ae(r)}(i);case 276:return function(e){ne(e.name),e.objectAssignmentInitializer&&(_t(),at("="),_t(),ae(e.objectAssignmentInitializer))}(i);case 277:return function(e){e.expression&&(he(25,e.pos,at,e),ae(e.expression))}(i);case 278:return function(e){ne(e.name),qe(e.initializer,e.name.end,e)}(i);case 299:case 305:return function(e){Ie(e.tagName),Le(e.typeExpression),_t(),e.isBracketed&&at("[");ne(e.name),e.isBracketed&&at("]");Me(e.comment)}(i);case 300:case 302:case 301:case 298:return Ie((a=i).tagName),Le(a.typeExpression),void Me(a.comment);case 295:return function(e){Ie(e.tagName),_t(),at("{"),ne(e.class),at("}"),Me(e.comment)}(i);case 303:return function(e){Ie(e.tagName),Le(e.constraint),_t(),et(e,e.typeParameters,528),Me(e.comment)}(i);case 304:return function(e){Ie(e.tagName),e.typeExpression&&(283===e.typeExpression.kind?Le(e.typeExpression):(_t(),at("{"),O("Object"),e.typeExpression.isArrayType&&(at("["),at("]")),at("}")));e.fullName&&(_t(),ne(e.fullName));Me(e.comment),e.typeExpression&&292===e.typeExpression.kind&&we(e.typeExpression)}(i);case 297:return function(e){Ie(e.tagName),e.name&&(_t(),ne(e.name));Me(e.comment),Oe(e.typeExpression)}(i);case 293:return Oe(i);case 292:return we(i);case 296:case 294:return function(e){Ie(e.tagName),Me(e.comment)}(i);case 291:return function(e){if(O("/**"),e.comment)for(var t=e.comment.split(/\r\n?|\n/g),r=0,n=t;r=1&&!e.isJsonSourceFile(n)?64:0;et(t,t.properties,526226|a|i),r&&mt()}(i);case 189:return function(r){var i=!1,a=!1;if(!(131072&e.getEmitFlags(r))){var o=r.expression.end,s=e.skipTrivia(n.text,r.expression.end)+1,c=e.createToken(24);c.pos=o,c.end=s,i=Et(r,r.expression,c),a=Et(r,c,r.name)}ae(r.expression),Dt(i,!1),!i&&function(r){if(r=e.skipPartiallyEmittedExpressions(r),e.isNumericLiteral(r)){var n=Pt(r,!0);return!r.numericLiteralFlags&&!e.stringContains(n,e.tokenToString(24))}if(e.isPropertyAccessExpression(r)||e.isElementAccessExpression(r)){var i=e.getConstantValue(r);return"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&t.removeComments}}(r.expression)&&at(".");he(24,r.expression.end,at,r),Dt(a,!1),ne(r.name),xt(i,a)}(i);case 190:return function(e){ae(e.expression),he(22,e.expression.end,at,e),ae(e.argumentExpression),he(23,e.argumentExpression.end,at,e)}(i);case 191:return function(e){ae(e.expression),Xe(e,e.typeArguments),tt(e,e.arguments,2576)}(i);case 192:return function(e){he(95,e.pos,st,e),_t(),ae(e.expression),Xe(e,e.typeArguments),tt(e,e.arguments,18960)}(i);case 193:return function(e){ae(e.tag),Xe(e,e.typeArguments),_t(),ae(e.template)}(i);case 194:return function(e){at("<"),ne(e.type),at(">"),ae(e.expression)}(i);case 195:return function(e){var t=he(20,e.pos,at,e);ae(e.expression),he(21,e.expression?e.expression.end:t,at,e)}(i);case 196:return function(e){Rt(e.name),be(e)}(i);case 197:return function(e){Ye(e,e.decorators),Ue(e,e.modifiers),xe(e,fe)}(i);case 198:return function(e){he(81,e.pos,st,e),_t(),ae(e.expression)}(i);case 199:return function(e){he(104,e.pos,st,e),_t(),ae(e.expression)}(i);case 200:return function(e){he(106,e.pos,st,e),_t(),ae(e.expression)}(i);case 201:return function(e){he(122,e.pos,st,e),_t(),ae(e.expression)}(i);case 202:return function(e){vt(e.operator,ct),function(e){var t=e.operand;return 202===t.kind&&(38===e.operator&&(38===t.operator||44===t.operator)||39===e.operator&&(39===t.operator||45===t.operator))}(e)&&_t();ae(e.operand)}(i);case 203:return function(e){ae(e.operand),vt(e.operator,ct)}(i);case 204:return function(e){var t=27!==e.operatorToken.kind,r=Et(e,e.left,e.operatorToken),n=Et(e,e.operatorToken,e.right);ae(e.left),Dt(r,t),er(e.operatorToken.pos),yt(e.operatorToken,93===e.operatorToken.kind?st:ct),rr(e.operatorToken.end,!0),Dt(n,!0),ae(e.right),xt(r,n)}(i);case 205:return function(e){var t=Et(e,e.condition,e.questionToken),r=Et(e,e.questionToken,e.whenTrue),n=Et(e,e.whenTrue,e.colonToken),i=Et(e,e.colonToken,e.whenFalse);ae(e.condition),Dt(t,!0),ne(e.questionToken),Dt(r,!0),ae(e.whenTrue),xt(t,r),Dt(n,!0),ne(e.colonToken),Dt(i,!0),ae(e.whenFalse),xt(n,i)}(i);case 206:return function(e){ne(e.head),et(e,e.templateSpans,262144)}(i);case 207:return function(e){he(117,e.pos,st,e),ne(e.asteriskToken),He(e.expression)}(i);case 208:return function(e){he(25,e.pos,at,e),ae(e.expression)}(i);case 209:return function(e){Rt(e.name),Ee(e)}(i);case 210:return;case 212:return function(e){ae(e.expression),e.type&&(_t(),st("as"),_t(),ne(e.type))}(i);case 213:return function(e){ae(e.expression),ct("!")}(i);case 214:return function(e){gt(e.keywordToken,e.pos,at),at("."),ne(e.name)}(i);case 260:return function(e){ne(e.openingElement),et(e,e.children,262144),ne(e.closingElement)}(i);case 261:return function(e){at("<"),Fe(e.tagName),_t(),ne(e.attributes),at("/>")}(i);case 264:return function(e){ne(e.openingFragment),et(e,e.children,262144),ne(e.closingFragment)}(i);case 308:return function(e){ae(e.expression)}(i);case 309:return function(e){tt(e,e.elements,528)}(i)}}function le(e,t){se(1,t)(e,T(e,t))}function _e(r){var i=!1,a=280===r.kind?r:void 0;if(!a||P!==e.ModuleKind.None){for(var o=a?a.sourceFiles.length:1,s=0;s'),pt()),n&&n.moduleName&&(lt('/// '),pt()),n&&n.amdDependencies)for(var a=0,o=n.amdDependencies;a'):lt('/// '),pt()}for(var c=0,u=t;c'),pt()}for(var l=0,_=r;l<_.length;l++){lt('/// '),pt()}for(var d=0,p=i;d'),pt()}}function Be(t){var r=t.statements;wt(t),e.forEach(t.statements,Mt),_e(t);var n=e.findIndex(r,function(t){return!e.isPrologueDirective(t)});!function(e){e.isDeclarationFile&&Re(e.hasNoDefaultLib,e.referencedFiles,e.typeReferenceDirectives,e.libReferenceDirectives)}(t),et(t,r,1,-1===n?r.length:n),Ot(t)}function je(t,r,n){for(var i=0;i0)&&pt(),ne(a),n&&n.set(a.expression.text,!0))}return t.length}function Je(t){if(e.isSourceFile(t))Z(t),je(t.statements);else{for(var r=e.createMap(),n=0,i=t.sourceFiles;n=n.length||0===s;if(u&&32768&a)return C&&C(n),void(k&&k(n));if(15360&a&&(at(function(e){return i[15360&e][0]}(a)),u&&!c&&rr(n.pos,!0)),C&&C(n),u)1&a?pt():256&a&&!(524288&a)&&_t();else{var l=0==(262144&a),_=l;St(r,n,a)?(pt(),_=!1):256&a&&_t(),128&a&&ft();for(var d=void 0,p=!1,f=0;f=0&&lr(u,i);i=a(r,n,i),c&&(i=c.end);0==(256&s)&&i>=0&&lr(u,i);return i}(i,t,n,r,vt)}function yt(t,r){E&&E(t),r(e.tokenToString(t.kind)),N&&N(t)}function vt(t,r,n){var i=e.tokenToString(t);return r(i),n<0?n:n+i.length}function ht(t){1&e.getEmitFlags(t)?_t():pt()}function bt(t){for(var r=t.split(/\r\n?|\n/g),n=e.guessIndentation(r),i=0,a=r;i0||o>0)&&a!==o&&(c||Xt(a,s),(!c||a>=0&&0!=(512&n))&&(L=a),(!u||o>=0&&0!=(1024&n))&&(R=o,238===r.kind&&(B=o))),e.forEach(e.getSyntheticLeadingComments(r),Wt),U();var p=se(2,r);2048&n?(J=!0,p(t,r),J=!1):p(t,r),K(),e.forEach(e.getSyntheticTrailingComments(r),Ht),(a>0||o>0)&&a!==o&&(L=l,R=_,B=d,!u&&s&&function(e){ar(e,tr)}(o)),U()}function Wt(e){2===e.kind&&p.writeLine(),Gt(e),e.hasTrailingNewLine||2===e.kind?p.writeLine():p.writeSpace(" ")}function Ht(e){p.isAtStartOfLine()||p.writeSpace(" "),Gt(e),e.hasTrailingNewLine&&p.writeLine()}function Gt(t){var r=function(e){return 3===e.kind?"/*"+e.text+"*/":"//"+e.text}(t),n=3===t.kind?e.computeLineStarts(r):void 0;e.writeCommentRange(r,n,p,0,r.length,F)}function Yt(t,r,i){K();var a,o,s=r.pos,c=r.end,u=e.getEmitFlags(t),l=J||c<0||0!=(1024&u);s<0||0!=(512&u)||(a=r,(o=e.emitDetachedComments(n.text,re(),p,or,a,F,J))&&(h?h.push(o):h=[o])),U(),2048&u&&!J?(J=!0,i(t),J=!1):i(t),K(),l||(Xt(r.end,!0),j&&!p.isAtStartOfLine()&&p.writeLine()),U()}function Xt(e,t){j=!1,t?ir(e,Zt):0===e&&ir(e,Qt)}function Qt(t,r,i,a,o){(function(t,r){return e.isRecognizedTripleSlashComment(n.text,t,r)})(t,r)&&Zt(t,r,i,a,o)}function $t(r,n){return!t.onlyPrintJsDocStyle||(e.isJSDocLikeText(r,n)||e.isPinnedComment(r,n))}function Zt(t,r,i,a,o){$t(n.text,t)&&(j||(e.emitNewLineBeforeLeadingCommentOfPosition(re(),p,o,t),j=!0),ur(t),e.writeCommentRange(n.text,re(),p,t,r,F),ur(r),a?p.writeLine():3===i&&p.writeSpace(" "))}function er(e){J||-1===e||Xt(e,!0)}function tr(t,r,i,a){$t(n.text,t)&&(p.isAtStartOfLine()||p.writeSpace(" "),ur(t),e.writeCommentRange(n.text,re(),p,t,r,F),ur(r),a&&p.writeLine())}function rr(e,t){J||(K(),ar(e,t?tr:nr),U())}function nr(t,r,i,a){ur(t),e.writeCommentRange(n.text,re(),p,t,r,F),ur(r),a?p.writeLine():p.writeSpace(" ")}function ir(t,r){!n||-1!==L&&t===L||(function(t){return void 0!==h&&e.last(h).nodePos===t}(t)?function(t){var r=e.last(h).detachedCommentEndPos;h.length-1?h.pop():h=void 0;e.forEachLeadingCommentRange(n.text,r,t,r)}(r):e.forEachLeadingCommentRange(n.text,t,r,t))}function ar(t,r){n&&(-1===R||t!==R&&t!==B)&&e.forEachTrailingCommentRange(n.text,t,r)}function or(t,r,i,a,o,s){$t(n.text,a)&&(ur(a),e.writeCommentRange(t,r,i,a,o,s),ur(o))}function sr(t,r){var n=se(3,r);if(e.isUnparsedSource(r)&&void 0!==r.sourceMapText){var i=e.tryParseRawSourceMap(r.sourceMapText);i&&g.appendSourceMap(p.getLine(),p.getColumn(),i,r.sourceMapPath),n(t,r)}else{var a=e.getSourceMapRange(r),o=a.pos,s=a.end,c=a.source,u=void 0===c?y:c,l=e.getEmitFlags(r);307!==r.kind&&0==(16&l)&&o>=0&&lr(u,cr(u,o)),64&l?(I=!0,n(t,r),I=!1):n(t,r),307!==r.kind&&0==(32&l)&&s>=0&&lr(u,s)}}function cr(t,r){return t.skipTrivia?t.skipTrivia(r):e.skipTrivia(y.text,r)}function ur(t){if(!(I||e.positionIsSynthesized(t)||dr(y))){var r=e.getLineAndCharacterOfPosition(n,t),i=r.line,a=r.character;g.addMapping(p.getLine(),p.getColumn(),M,i,a,void 0)}}function lr(e,t){if(e!==y){var r=y;_r(e),ur(t),_r(r)}else ur(t)}function _r(e){I||(y=e,dr(e)||(M=g.addSource(e.fileName),t.inlineSources&&g.setSourceContent(M,e.text)))}function dr(t){return e.fileExtensionIs(t.fileName,".json")}}e.forEachEmittedFile=o,e.getOutputPathsFor=s,e.getOutputExtension=u,e.emitFiles=function(t,r,n,i,a,s){var c,u=r.getCompilerOptions(),_=u.sourceMap||u.inlineSourceMap||e.getAreDeclarationMapsEnabled(u)?[]:void 0,d=u.listEmittedFiles?[]:void 0,p=e.createDiagnosticCollection(),f=e.getNewLineCharacter(u,function(){return r.getNewLine()}),m=e.createTextWriter(f),g=e.performance.createTimer("printTime","beforePrint","afterPrint"),y=g.enter,v=g.exit,h={originalOffset:-1,totalLength:-1},b=!1;return y(),o(r,function(n,o){var _=n.jsFilePath,f=n.sourceMapFilePath,m=n.declarationFilePath,g=n.declarationMapPath,y=n.bundleInfoPath;(function(n,o,s,c){if(!i&&o)if(o&&r.isEmitBlocked(o)||u.noEmit)b=!0;else{var _=e.transformNodes(t,r,u,[n],a,!1),d=l({removeComments:u.removeComments,newLine:u.newLine,noEmitHelpers:u.noEmitHelpers,module:u.module,target:u.target,sourceMap:u.sourceMap,inlineSourceMap:u.inlineSourceMap,inlineSources:u.inlineSources,extendedDiagnostics:u.extendedDiagnostics},{hasGlobalName:t.hasGlobalName,onEmitNode:_.emitNodeWithNotification,substituteNode:_.substituteNode});e.Debug.assert(1===_.transformed.length,"Should only see one output from the transform"),x(o,s,_.transformed[0],c,d,u),_.dispose()}})(o,_,f,y),function(n,a,o){if(a&&!e.isInJSFile(n)){var _=e.isSourceFile(n)?[n]:n.sourceFiles,d=e.filter(_,e.isSourceFileNotJS),f=u.outFile||u.out?[e.createBundle(d,e.isSourceFile(n)?void 0:n.prepends)]:d;i&&!e.getEmitDeclarations(u)&&d.forEach(D);var m=e.transformNodes(t,r,u,f,e.concatenate([e.transformDeclarations],s),!1);if(e.length(m.diagnostics))for(var g=0,y=m.diagnostics;ge.getRootLength(t)&&!function(e){return!!a.has(e)||!!n.directoryExists(e)&&(a.set(e,!0),!0)}(t)&&(o(e.getDirectoryPath(t)),l.createDirectory?l.createDirectory(t):n.createDirectory(t))}function s(){return e.getDirectoryPath(e.normalizePath(n.getExecutingFilePath()))}var c=e.getNewLineCharacter(t,function(){return n.newLine}),u=n.realpath&&function(e){return n.realpath(e)},l={getSourceFile:function(t,n,i){var a;try{e.performance.mark("beforeIORead"),a=l.readFile(t),e.performance.mark("afterIORead"),e.performance.measure("I/O Read","beforeIORead","afterIORead")}catch(e){i&&i(e.message),a=""}return void 0!==a?e.createSourceFile(t,a,n,r):void 0},getDefaultLibLocation:s,getDefaultLibFileName:function(t){return e.combinePaths(s(),e.getDefaultLibFileName(t))},writeFile:function(r,a,s,c){try{e.performance.mark("beforeIOWrite"),o(e.getDirectoryPath(e.normalizePath(r))),e.isWatchSet(t)&&n.createHash&&n.getModifiedTime?function(t,r,a){i||(i=e.createMap());var o=n.createHash(r),s=n.getModifiedTime(t);if(s){var c=i.get(t);if(c&&c.byteOrderMark===a&&c.hash===o&&c.mtime.getTime()===s.getTime())return}n.writeFile(t,r,a);var u=n.getModifiedTime(t)||e.missingFileModifiedTime;i.set(t,{hash:o,byteOrderMark:a,mtime:u})}(r,a,s):n.writeFile(r,a,s),e.performance.mark("afterIOWrite"),e.performance.measure("I/O Write","beforeIOWrite","afterIOWrite")}catch(e){c&&c(e.message)}},getCurrentDirectory:e.memoize(function(){return n.getCurrentDirectory()}),useCaseSensitiveFileNames:function(){return n.useCaseSensitiveFileNames},getCanonicalFileName:function(e){return n.useCaseSensitiveFileNames?e:e.toLowerCase()},getNewLine:function(){return c},fileExists:function(e){return n.fileExists(e)},readFile:function(e){return n.readFile(e)},trace:function(e){return n.write(e+c)},directoryExists:function(e){return n.directoryExists(e)},getEnvironmentVariable:function(e){return n.getEnvironmentVariable?n.getEnvironmentVariable(e):""},getDirectories:function(e){return n.getDirectories(e)},realpath:u,readDirectory:function(e,t,r,i,a){return n.readDirectory(e,t,r,i,a)},createDirectory:function(e){return n.createDirectory(e)}};return l}function c(t,r){var n=e.diagnosticCategoryName(t)+" TS"+t.code+": "+D(t.messageText,r.getNewLine())+r.getNewLine();if(t.file){var i=e.getLineAndCharacterOfPosition(t.file,t.start),a=i.line,o=i.character,s=t.file.fileName;return e.convertToRelativePath(s,r.getCurrentDirectory(),function(e){return r.getCanonicalFileName(e)})+"("+(a+1)+","+(o+1)+"): "+n}return n}e.findConfigFile=function(t,r,n){return void 0===n&&(n="tsconfig.json"),e.forEachAncestorDirectory(t,function(t){var i=e.combinePaths(t,n);return r(i)?i:void 0})},e.resolveTripleslashReference=n,e.computeCommonSourceDirectoryOfFilenames=a,e.createCompilerHost=o,e.createCompilerHostWorker=s,e.changeCompilerHostToUseCache=function(t,r,n){var i=t.readFile,a=t.fileExists,o=t.directoryExists,s=t.createDirectory,c=t.writeFile,u=t.getSourceFile,l=e.createMap(),_=e.createMap(),d=e.createMap(),p=e.createMap(),f=function(e,r){var n=i.call(t,r);return l.set(e,n||!1),n};return t.readFile=function(n){var a=r(n),o=l.get(a);return void 0!==o?o:e.fileExtensionIs(n,".json")?f(a,n):i.call(t,n)},n&&(t.getSourceFile=function(n,i,a,o){var s=r(n),c=p.get(s);if(c)return c;var l=u.call(t,n,i,a,o);return l&&(e.isDeclarationFileName(n)||e.fileExtensionIs(n,".json"))&&p.set(s,l),l}),t.fileExists=function(e){var n=r(e),i=_.get(n);if(void 0!==i)return i;var o=a.call(t,e);return _.set(n,!!o),o},t.writeFile=function(e,i,a,o,s){var u=r(e);_.delete(u);var d=l.get(u);if(d&&d!==i)l.delete(u),p.delete(u);else if(n){var f=p.get(u);f&&f.text!==i&&p.delete(u)}c.call(t,e,i,a,o,s)},o&&s&&(t.directoryExists=function(e){var n=r(e),i=d.get(n);if(void 0!==i)return i;var a=o.call(t,e);return d.set(n,!!a),a},t.createDirectory=function(e){var n=r(e);d.delete(n),s.call(t,e)}),{originalReadFile:i,originalFileExists:a,originalDirectoryExists:o,originalCreateDirectory:s,originalWriteFile:c,originalGetSourceFile:u,readFileWithCache:function(e){var t=r(e),n=l.get(t);return void 0!==n?n||void 0:f(t,e)}}},e.getPreEmitDiagnostics=function(t,r,n){var i=t.getConfigFileParsingDiagnostics().concat(t.getOptionsDiagnostics(n),t.getSyntacticDiagnostics(r,n),t.getGlobalDiagnostics(n),t.getSemanticDiagnostics(r,n));return e.getEmitDeclarations(t.getCompilerOptions())&&e.addRange(i,t.getDeclarationDiagnostics(r,n)),e.sortAndDeduplicateDiagnostics(i)},e.formatDiagnostics=function(e,t){for(var r="",n=0,i=e;n=4,D=(m+1+"").length;b&&(D=Math.max(d.length,D));for(var x="",S=c;S<=m;S++){x+=o.getNewLine(),b&&c+10||s.length>0)return{diagnostics:e.concatenate(c,s),sourceMaps:void 0,emittedFiles:void 0,emitSkipped:!0}}}var u=Le().getEmitResolver(N.outFile||N.out?void 0:r,i);e.performance.mark("beforeEmit");var l=a?[]:e.getTransformers(N,o),_=e.emitFiles(u,Oe(n),r,a,l,o&&o.afterDeclarations);return e.performance.mark("afterEmit"),e.performance.measure("Emit","beforeEmit","afterEmit"),_}(_,t,r,n,i,a)})},getCurrentDirectory:function(){return Q},getNodeCount:function(){return Le().getNodeCount()},getIdentifierCount:function(){return Le().getIdentifierCount()},getSymbolCount:function(){return Le().getSymbolCount()},getTypeCount:function(){return Le().getTypeCount()},getFileProcessingDiagnostics:function(){return L},getResolvedTypeReferenceDirectives:function(){return M},isSourceFileFromExternalLibrary:Me,isSourceFileDefaultLibrary:function(t){if(t.hasNoDefaultLib)return!0;if(!N.noLib)return!1;var r=q.useCaseSensitiveFileNames()?e.equateStringsCaseSensitive:e.equateStringsCaseInsensitive;return N.lib?e.some(N.lib,function(n){return r(t.fileName,e.combinePaths(Y,n))}):r(t.fileName,G())},dropDiagnosticsProducingTypeChecker:function(){y=void 0},getSourceFileFromReference:function(e,t){return tt(n(t.fileName,e.fileName),function(e){return _e.get(Fe(e))})},getLibFileFromReference:function(t){var r=t.fileName.toLocaleLowerCase(),n=e.libMap.get(r);if(n)return je(e.combinePaths(Y,n))},sourceFileToPackageName:ue,redirectTargetsMap:le,isEmittedFile:function(t){if(N.noEmit)return!1;var r=Fe(t);if(Je(r))return!1;var n=N.outFile||N.out;if(n)return Ft(r,n)||Ft(r,e.removeFileExtension(n)+".d.ts");if(N.declarationDir&&e.containsPath(N.declarationDir,r,Q,!q.useCaseSensitiveFileNames()))return!0;if(N.outDir)return e.containsPath(N.outDir,r,Q,!q.useCaseSensitiveFileNames());if(e.fileExtensionIsOneOf(r,e.supportedJSExtensions)||e.fileExtensionIs(r,".d.ts")){var i=e.removeFileExtension(r);return!!Je(i+".ts")||!!Je(i+".tsx")}return!1},getConfigFileParsingDiagnostics:function(){return A||e.emptyArray},getResolvedModuleWithFailedLookupLocationsFromCache:function(t,r){return K&&e.resolveModuleNameFromCache(t,r,K)},getProjectReferences:function(){return F},getResolvedProjectReferences:function(){return ae},getProjectReferenceRedirect:ot,getResolvedProjectReferenceToRedirect:st,getResolvedProjectReferenceByPath:lt,forEachResolvedProjectReference:ct},function(){if(N.strictPropertyInitialization&&!e.getStrictOptionValue(N,"strictNullChecks")&&St(e.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1,"strictPropertyInitialization","strictNullChecks"),N.isolatedModules&&(e.getEmitDeclarations(N)&&St(e.Diagnostics.Option_0_cannot_be_specified_with_option_1,C(N),"isolatedModules"),N.noEmitOnError&&St(e.Diagnostics.Option_0_cannot_be_specified_with_option_1,"noEmitOnError","isolatedModules"),N.out&&St(e.Diagnostics.Option_0_cannot_be_specified_with_option_1,"out","isolatedModules"),N.outFile&&St(e.Diagnostics.Option_0_cannot_be_specified_with_option_1,"outFile","isolatedModules")),N.inlineSourceMap&&(N.sourceMap&&St(e.Diagnostics.Option_0_cannot_be_specified_with_option_1,"sourceMap","inlineSourceMap"),N.mapRoot&&St(e.Diagnostics.Option_0_cannot_be_specified_with_option_1,"mapRoot","inlineSourceMap")),N.paths&&void 0===N.baseUrl&&St(e.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option,"paths"),N.composite&&!1===N.declaration&&St(e.Diagnostics.Composite_projects_may_not_disable_declaration_emit,"declaration"),ut(F,ae,function(t,r,n){var i=(n?n.commandLine.projectReferences:F)[r],a=n&&n.sourceFile;if(t){var o=t.commandLine.options;if(!o.composite){var s=n?n.commandLine.fileNames:D;s.length&&Ct(a,r,e.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true,i.path)}if(i.prepend){var c=o.outFile||o.out;c?q.fileExists(c)||Ct(a,r,e.Diagnostics.Output_file_0_from_project_1_does_not_exist,c,i.path):Ct(a,r,e.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set,i.path)}}else Ct(a,r,e.Diagnostics.File_0_not_found,i.path)}),N.composite){var t=m.filter(function(e){return!e.isDeclarationFile});if(D.length1})&&St(e.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files,"outDir")}if(!N.noEmit&&N.allowJs&&e.getEmitDeclarations(N)&&St(e.Diagnostics.Option_0_cannot_be_specified_with_option_1,"allowJs",C(N)),N.checkJs&&!N.allowJs&&X.add(e.createCompilerDiagnostic(e.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1,"checkJs","allowJs")),N.emitDeclarationOnly&&(e.getEmitDeclarations(N)||St(e.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2,"emitDeclarationOnly","declaration","composite"),N.noEmit&&St(e.Diagnostics.Option_0_cannot_be_specified_with_option_1,"emitDeclarationOnly","noEmit")),N.emitDecoratorMetadata&&!N.experimentalDecorators&&St(e.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1,"emitDecoratorMetadata","experimentalDecorators"),N.jsxFactory?(N.reactNamespace&&St(e.Diagnostics.Option_0_cannot_be_specified_with_option_1,"reactNamespace","jsxFactory"),e.parseIsolatedEntityName(N.jsxFactory,_)||Tt("jsxFactory",e.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name,N.jsxFactory)):N.reactNamespace&&!e.isIdentifierText(N.reactNamespace,_)&&Tt("reactNamespace",e.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier,N.reactNamespace),!N.noEmit&&!N.suppressOutputPathCheck){var h=Oe(),b=e.createMap();e.forEachEmittedFile(h,function(e){N.emitDeclarationOnly||x(e.jsFilePath,b),x(e.declarationFilePath,b)})}function x(t,r){if(t){var n,i=Fe(t);_e.has(i)&&(N.configFilePath||(n=e.chainDiagnosticMessages(void 0,e.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig)),n=e.chainDiagnosticMessages(n,e.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file,t),At(t,e.createCompilerDiagnosticFromMessageChain(n)));var a=q.useCaseSensitiveFileNames()?i:i.toLocaleLowerCase();r.has(a)?At(t,e.createCompilerDiagnostic(e.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files,t)):r.set(a,!0)}}}(),e.performance.mark("afterProgram"),e.performance.measure("Program","beforeProgram","afterProgram"),_;function Ae(t){if(e.containsPath(Y,t.fileName,!1)){var r=e.getBaseFileName(t.fileName);if("lib.d.ts"===r||"lib.es6.d.ts"===r)return 0;var n=e.removeSuffix(e.removePrefix(r,"lib."),".d.ts"),i=e.libs.indexOf(n);if(-1!==i)return i+1}return e.libs.length+2}function Fe(t){return e.toPath(t,Q,gt)}function Pe(){if(void 0===g){var t=e.filter(m,function(t){return e.sourceFileMayBeEmitted(t,N,Me)});N.rootDir&&vt(t,N.rootDir)?g=e.getNormalizedAbsolutePath(N.rootDir,Q):N.composite&&N.configFilePath?vt(t,g=e.getDirectoryPath(e.normalizeSlashes(N.configFilePath))):(r=t,g=a(e.mapDefined(r,function(e){return e.isDeclarationFile?void 0:e.fileName}),Q,gt)),g&&g[g.length-1]!==e.directorySeparator&&(g+=e.directorySeparator)}var r;return g}function we(t,r,n){if(0===fe&&!n.ambientModuleNames.length)return U(t,r,void 0,st(n.originalFileName));var i,a,o,s=P&&P.getSourceFile(r);if(s!==n&&n.resolvedModules){for(var c=[],u=0,l=t;u0;){var s=n.text.slice(a[o-1],a[o]),c=r.exec(s);if(!c)return!0;if(c[3])return!1;o--}return!0}function He(e,t){return Ye(e,t,I,Ge)}function Ge(t,r){return Ue(function(){var n=Le().getEmitResolver(t,r);return e.getDeclarationDiagnostics(Oe(e.noop),n,t)})}function Ye(t,r,n,i){var a=t?n.perFile&&n.perFile.get(t.path):n.allDiagnostics;if(a)return a;var o=i(t,r)||e.emptyArray;return t?(n.perFile||(n.perFile=e.createMap()),n.perFile.set(t.path,o)):n.allDiagnostics=o,o}function Xe(e,t){return e.isDeclarationFile?[]:He(e,t)}function Qe(t,r,n){rt(e.normalizePath(t),r,n,void 0)}function $e(e,t){return e.fileName===t.fileName}function Ze(e,t){return 72===e.kind?72===t.kind&&e.escapedText===t.escapedText:10===t.kind&&e.text===t.text}function et(t){if(!t.imports){var r,n,i,a=e.isSourceFileJS(t),o=e.isExternalModule(t);if(N.importHelpers&&(N.isolatedModules||o)&&!t.isDeclarationFile){var s=e.createLiteral(e.externalHelpersModuleNameText),c=e.createImportDeclaration(void 0,void 0,void 0,s);e.addEmitFlags(c,67108864),s.parent=c,c.parent=t,r=[s]}for(var u=0,l=t.statements;u0),Object.defineProperties(o,{id:{get:function(){return this.redirectInfo.redirectTarget.id},set:function(e){this.redirectInfo.redirectTarget.id=e}},symbol:{get:function(){return this.redirectInfo.redirectTarget.symbol},set:function(e){this.redirectInfo.redirectTarget.symbol=e}}}),o}(h,y,t,r,Fe(t),l);return le.add(h.path,t),at(b,r,u),ue.set(r,c.name),p.push(b),b}y&&(ce.set(v,y),ue.set(r,c.name))}if(at(y,r,u),y){if(J.set(r,B>0),y.path=r,y.resolvedPath=Fe(t),y.originalFileName=l,q.useCaseSensitiveFileNames()){var D=r.toLowerCase(),x=de.get(D);x?nt(t,x.fileName,a,o,s):de.set(D,y)}H=H||y.hasNoDefaultLib&&!i,N.noResolve||(_t(y,n),dt(y)),ft(y),yt(y),n?d.push(y):p.push(y)}return y}function at(e,t,r){_e.set(t,e),r&&_e.set(r,e)}function ot(t){if(ae&&ae.length&&!e.fileExtensionIs(t,".d.ts")&&e.fileExtensionIsOneOf(t,e.supportedTSExtensions)){var r=st(t);if(r){var n=r.commandLine.options.outFile||r.commandLine.options.out;return n?e.changeExtension(n,".d.ts"):e.getOutputDeclarationFileName(t,r.commandLine)}}}function st(t){void 0===se&&(se=e.createMap(),ct(function(e,t){e&&Fe(N.configFilePath)!==t&&e.commandLine.fileNames.forEach(function(e){return se.set(Fe(e),t)})}));var r=se.get(Fe(t));return r&<(r)}function ct(e){return ut(F,ae,function(t,r,n){var i=Fe(T((n?n.commandLine.projectReferences:F)[r]));return e(t,i)})}function ut(t,r,n,i){var a;return function t(r,n,i,o,s){if(s){var c=s(r,i);if(c)return c}return e.forEach(n,function(r,n){if(!e.contains(a,r)){var c=o(r,n,i);if(c)return c;if(r)return(a||(a=[])).push(r),t(r.commandLine.projectReferences,r.references,r,o,s)}})}(t,r,void 0,n,i)}function lt(e){if(oe)return oe.get(e)||void 0}function _t(t,r){e.forEach(t.referencedFiles,function(e){rt(n(e.fileName,t.originalFileName),r,!1,void 0,t,e.pos,e.end)})}function dt(t){var r=e.map(t.typeReferenceDirectives,function(e){return e.fileName.toLocaleLowerCase()});if(r)for(var n=V(r,t.originalFileName,st(t.originalFileName)),i=0;iR,_=u&&!k(N,a)&&!N.noResolve&&ir&&(X.add(e.createDiagnosticForNodeInSourceFile(N.configFile,p.elements[r],n,i,a,o)),s=!1)}}s&&X.add(e.createCompilerDiagnostic(n,i,a,o))}function Dt(t,r,n,i){for(var a=!0,o=0,s=xt();or?X.add(e.createDiagnosticForNodeInSourceFile(t||N.configFile,o.elements[r],n,i,a)):X.add(e.createCompilerDiagnostic(n,i,a))}function kt(t,r,n,i,a,o,s){var c=Et();(!c||!Nt(c,t,r,n,i,a,o,s))&&X.add(e.createCompilerDiagnostic(i,a,o,s))}function Et(){if(void 0===z){z=null;var t=e.getTsConfigObjectLiteralExpression(N.configFile);if(t)for(var r=0,n=e.getPropertyAssignment(t,"compilerOptions");r0)for(var s=t.getTypeChecker(),c=0,u=r.imports;c0)for(var d=0,p=r.referencedFiles;d1&&x(D)}return o;function x(t){for(var n=0,i=t.declarations;n0?(l=s(p.outputFiles[0].text),c&&l!==_&&function(t,n,i){if(!n)return void i.set(t.path,!1);var a;n.forEach(function(t){var n;(n=r(t))&&(a||(a=e.createMap()),a.set(n,!0))}),i.set(t.path,a||!1)}(i,p.exportedModulesFromDeclarationEmit,c)):l=_}return a.set(i.path,l),!_||l!==_}function u(t,r){if(!t.allFileNames){var n=r.getSourceFiles();t.allFileNames=n===e.emptyArray?e.emptyArray:n.map(function(e){return e.fileName})}return t.allFileNames}function l(t,r){return e.arrayFrom(e.mapDefinedIterator(t.referencedMap.entries(),function(e){var t=e[0];return e[1].has(r)?t:void 0}))}function _(t){return function(t){return e.some(t.moduleAugmentations,function(t){return e.isGlobalScopeAugmentation(t.parent)})}(t)||!e.isExternalModule(t)&&!function(t){for(var r=0,n=t.statements;r0;){var m=f.pop();if(!p.has(m)){var g=r.getSourceFileByPath(m);p.set(m,g),g&&c(t,r,g,i,a,o,s)&&f.push.apply(f,l(t,m))}}return e.arrayFrom(e.mapDefinedIterator(p.values(),function(e){return e}))}:function(e,t,r){var n=t.getCompilerOptions();return n&&(n.out||n.outFile)?[r]:d(e,t,r)})(t,r,f,p,i,a,u);return o||s(t,p),m},t.updateSignaturesFromCache=s,t.updateExportedFilesMapFromCache=function(t,r){r&&(e.Debug.assert(!!t.exportedModulesMap),r.forEach(function(e,r){e?t.exportedModulesMap.set(r,e):t.exportedModulesMap.delete(r)}))},t.getAllDependencies=function(t,r,n){var i,a=r.getCompilerOptions();if(a.outFile||a.out)return u(t,r);if(!t.referencedMap||_(n))return u(t,r);for(var o=e.createMap(),s=[n.path];s.length;){var c=s.pop();if(!o.has(c)){o.set(c,!0);var l=t.referencedMap.get(c);if(l)for(var d=l.keys(),p=d.next(),f=p.value,m=p.done;!m;f=(i=d.next()).value,m=i.done,i)s.push(f)}}return e.arrayFrom(e.mapDefinedIterator(o.keys(),function(e){var t=r.getSourceFileByPath(e);return t?t.fileName:e}))}}(e.BuilderState||(e.BuilderState={}))}(c||(c={})),function(e){function t(t,r,n){var i=e.BuilderState.create(t,r,n);i.program=t;var a=t.getCompilerOptions();a.outFile||a.out||(i.semanticDiagnosticsPerFile=e.createMap()),i.changedFilesSet=e.createMap();var o=e.BuilderState.canReuseOldState(i.referencedMap,n),s=o?n.program.getCompilerOptions():void 0,c=o&&n.semanticDiagnosticsPerFile&&!!i.semanticDiagnosticsPerFile&&!e.compilerOptionsAffectSemanticDiagnostics(a,s);o&&(n.currentChangedFilePath||e.Debug.assert(!(n.affectedFiles||n.currentAffectedFilesSignatures&&n.currentAffectedFilesSignatures.size),"Cannot reuse if only few affected files of currentChangedFile were iterated"),c&&e.Debug.assert(!e.forEachKey(n.changedFilesSet,function(e){return n.semanticDiagnosticsPerFile.has(e)}),"Semantic diagnostics shouldnt be available for changed files"),e.copyEntries(n.changedFilesSet,i.changedFilesSet));var u=i.referencedMap,l=o?n.referencedMap:void 0,_=c&&!a.skipLibCheck==!s.skipLibCheck,d=_&&!a.skipDefaultLibCheck==!s.skipDefaultLibCheck;return i.fileInfos.forEach(function(t,r){var a,s,p,f;if(!o||!(a=n.fileInfos.get(r))||a.version!==t.version||(p=s=u&&u.get(r),f=l&&l.get(r),p!==f&&(void 0===p||void 0===f||p.size!==f.size||e.forEachKey(p,function(e){return!f.has(e)})))||s&&e.forEachKey(s,function(e){return!i.fileInfos.has(e)&&n.fileInfos.has(e)}))i.changedFilesSet.set(r,!0);else if(c){var m=i.program.getSourceFileByPath(r);if(m.isDeclarationFile&&!_)return;if(m.hasNoDefaultLib&&!d)return;var g=n.semanticDiagnosticsPerFile.get(r);g&&(i.semanticDiagnosticsPerFile.set(r,g),i.semanticDiagnosticsFromOldState||(i.semanticDiagnosticsFromOldState=e.createMap()),i.semanticDiagnosticsFromOldState.set(r,!0))}}),i}function r(t,r){e.Debug.assert(!r||!t.affectedFiles||t.affectedFiles[t.affectedFilesIndex-1]!==r||!t.semanticDiagnosticsPerFile.has(r.path))}function n(t,r,n){for(;;){var a=t.affectedFiles;if(a){for(var o=t.seenAffectedFiles,s=t.affectedFilesIndex;s0;a--)if(0===(i=t.indexOf(e.directorySeparator,i)+1))return!1;return!0}function I(t,r){if(k(x,r)){t=e.isRootedDiskPath(t)?e.normalizePath(t):e.getNormalizedAbsolutePath(t,l()),e.Debug.assert(t.length===r.length,"FailedLookup: "+t+" failedLookupLocationPath: "+r);var n=r.indexOf(e.directorySeparator,x.length+1);return-1!==n?{dir:t.substr(0,n),dirPath:r.substr(0,n)}:{dir:D,dirPath:x,nonRecursive:!1}}return M(e.getDirectoryPath(e.getNormalizedAbsolutePath(t,l())),e.getDirectoryPath(r))}function M(t,r){for(;e.pathContainsNodeModules(r);)t=e.getDirectoryPath(t),r=e.getDirectoryPath(r);if(P(r))return O(e.getDirectoryPath(r))?{dir:t,dirPath:r}:void 0;var n,i,a=!0;if(void 0!==x)for(;!k(r,x);){var o=e.getDirectoryPath(r);if(o===r)break;a=!1,n=r,i=t,r=o,t=e.getDirectoryPath(t)}return O(r)?{dir:i||t,dirPath:n||r,nonRecursive:a}:void 0}function L(t){return e.fileExtensionIsOneOf(t,v)}function R(t,r){r.failedLookupLocations&&r.failedLookupLocations.length&&(r.refCount?r.refCount++:(r.refCount=1,e.isExternalModuleNameRelative(t)?B(r):u.add(t,r)))}function B(t){e.Debug.assert(!!t.refCount);for(var n=!1,i=0,a=t.failedLookupLocations;i1),h.set(s,l-1))),u===x?n=!0:U(u)}}n&&U(x)}}function U(e){b.get(e).refCount--}function V(e,t){var r=e.get(t);r&&(r.forEach(K),e.delete(t))}function q(e){V(d,e),V(g,e)}function W(t,r,n){var i=e.createMap();t.forEach(function(t,a){var s=e.getDirectoryPath(a),c=i.get(s);c||(c=e.createMap(),i.set(s,c)),t.forEach(function(t,i){c.has(i)||(c.set(i,!0),!t.isInvalidated&&r(t,n)&&(t.isInvalidated=!0,(o||(o=e.createMap())).set(a,!0)))})})}function H(t){var n;n=r.maxNumberOfFilesToIterateForInvalidation||e.maxNumberOfFilesToIterateForInvalidation,d.size>n||g.size>n?c=!0:(W(d,t,T),W(g,t,C))}function G(n,i){var a;if(i)a=function(e){return k(n,r.toPath(e))};else{if(t(n))return!1;var s=e.getDirectoryPath(n);if(w(n)||P(n)||w(s)||P(s))a=function(t){return r.toPath(t)===n||e.startsWith(r.toPath(t),n)};else{if(!L(n)&&!h.has(n))return!1;if(e.isEmittedFileOfProgram(r.getCurrentProgram(),n))return!1;a=function(e){return r.toPath(e)===n}}}var u=o&&o.size;return H(function(t){return e.some(t.failedLookupLocations,a)}),c||o&&o.size!==u}function Y(){e.clearMap(S,e.closeFileWatcher)}function X(e,t){return r.watchTypeRootsDirectory(t,function(n){var i=r.toPath(n);_&&_.addOrDeleteFileOrDirectory(n,i),r.onChangedAutomaticTypeDirectiveNames();var a=function(e,t){if(!c){if(k(x,t))return x;var r=M(e,t);return r&&b.has(r.dirPath)?r.dirPath:void 0}}(t,e);a&&G(i,a===i)&&r.onInvalidatedResolution()},1)}function Q(t){var n=e.getDirectoryPath(e.getDirectoryPath(t)),i=r.toPath(n);return i===x||O(i)}}}(c||(c={})),function(e){!function(t){var r,n;function i(t,r,n){var i=t.importModuleSpecifierPreference,a=t.importModuleSpecifierEnding;return{relativePreference:"relative"===i?0:"non-relative"===i?1:2,ending:function(){switch(a){case"minimal":return 0;case"index":return 1;case"js":return 2;default:return t=n.imports,e.firstDefined(t,function(t){var r=t.text;return e.pathIsRelative(r)?e.hasJSOrJsonFileExtension(r):void 0})?2:e.getEmitModuleResolutionKind(r)!==e.ModuleResolutionKind.NodeJs?1:0}var t}()}}function a(t,r,n,i,a,c,u){var l=o(r,i),_=d(a,r,n,l.getCanonicalFileName,i,c);return e.firstDefined(_,function(e){return f(e,l,i,t)})||s(n,l,t,u)}function o(t,r){return{getCanonicalFileName:e.createGetCanonicalFileName(!r.useCaseSensitiveFileNames||r.useCaseSensitiveFileNames()),sourceDirectory:e.getDirectoryPath(t)}}function s(t,r,n,i){var a=r.getCanonicalFileName,o=r.sourceDirectory,s=i.ending,u=i.relativePreference,l=n.baseUrl,_=n.paths,d=n.rootDirs,f=d&&function(t,r,n,i){var a=m(r,t,i);if(void 0===a)return;var o=m(n,t,i),s=void 0!==o?e.ensurePathIsNonModuleName(e.getRelativePathFromDirectory(o,a,i)):a;return e.removeFileExtension(s)}(d,t,o,a)||g(e.ensurePathIsNonModuleName(e.getRelativePathFromDirectory(o,t,a)),s,n);if(!l||0===u)return f;var h=y(t,l,a);if(!h)return f;var b=g(h,s,n),D=_&&p(e.removeFileExtension(h),b,_),x=void 0===D?b:D;return 1===u?x:(2!==u&&e.Debug.assertNever(u),v(x)||c(f)=l.length+_.length&&e.startsWith(r,l)&&e.endsWith(r,_)||!_&&r===e.removeTrailingDirectorySeparator(l)){var d=r.substr(l.length,r.length-_.length);return i.replace("*",d)}}else if(c===r||c===t)return i}}function f(t,r,n,i){var a=r.getCanonicalFileName,o=r.sourceDirectory;if(n.fileExists&&n.readFile){var s=function(t){var r,n=0,i=0,a=0;!function(e){e[e.BeforeNodeModules=0]="BeforeNodeModules",e[e.NodeModules=1]="NodeModules",e[e.Scope=2]="Scope",e[e.PackageContent=3]="PackageContent"}(r||(r={}));var o=0,s=0,c=0;for(;s>=0;)switch(o=s,s=t.indexOf("/",o+1),c){case 0:t.indexOf(e.nodeModulesPathPart,o)===o&&(n=o,i=s,c=1);break;case 1:case 2:1===c&&"@"===t.charAt(o+1)?c=2:(a=s,c=3);break;case 3:c=t.indexOf(e.nodeModulesPathPart,o)===o?1:3}return c>1?{topLevelNodeModulesIndex:n,topLevelPackageNameIndex:i,packageRootIndex:a,fileNameIndex:o}:void 0}(t);if(s){var c=t.substring(0,s.packageRootIndex),u=e.combinePaths(c,"package.json"),l=n.fileExists(u)?JSON.parse(n.readFile(u)):void 0,_=l&&l.typesVersions?e.getPackageJsonTypesVersionsPaths(l.typesVersions):void 0;if(_){var d=t.slice(s.packageRootIndex+1),f=p(e.removeFileExtension(d),g(d,0,i),_.paths);void 0!==f&&(t=e.combinePaths(t.slice(0,s.packageRootIndex),f))}var m=function(t){if(l){var r=l.typings||l.types||l.main;if(r){var i=e.toPath(r,c,a);if(e.removeFileExtension(i)===e.removeFileExtension(a(t)))return c}}var o=e.removeFileExtension(t);if("/index"===a(o.substring(s.fileNameIndex))&&!function(t,r){if(!t.fileExists)return;for(var n=0,i=e.getSupportedExtensions({allowJs:!0},[{extension:"node",isMixedContent:!1},{extension:"json",isMixedContent:!1,scriptKind:6}]);n0?e.ExitStatus.DiagnosticsPresent_OutputsSkipped:s.length>0?e.ExitStatus.DiagnosticsPresent_OutputsGenerated:e.ExitStatus.Success}e.createDiagnosticReporter=r,e.screenStartingMessageCodes=[e.Diagnostics.Starting_compilation_in_watch_mode.code,e.Diagnostics.File_change_detected_Starting_incremental_compilation.code],e.createWatchStatusReporter=i,e.parseConfigFileWithSystem=function(t,r,n,i){var a=n;a.onUnRecoverableConfigFileDiagnostic=function(t){return _(e.sys,i,t)};var o=e.getParsedCommandLineOfConfigFile(t,r,a);return a.onUnRecoverableConfigFileDiagnostic=void 0,o},e.getErrorCountForSummary=a,e.getWatchErrorSummaryDiagnosticMessage=o,e.getErrorSummaryText=function(t,r){if(0===t)return"";var n=e.createCompilerDiagnostic(1===t?e.Diagnostics.Found_1_error:e.Diagnostics.Found_0_errors,t);return""+r+e.flattenDiagnosticMessageText(n.messageText,r)+r+r},e.emitFilesAndReportErrors=s;var c={close:e.noop};function u(t,r){return void 0===t&&(t=e.sys),{onWatchStatusChange:r||i(t),watchFile:t.watchFile?function(e,r,n){return t.watchFile(e,r,n)}:function(){return c},watchDirectory:t.watchDirectory?function(e,r,n){return t.watchDirectory(e,r,n)}:function(){return c},setTimeout:t.setTimeout?function(e,r){for(var n,i=[],a=2;ae.getRootLength(n)&&!r.directoryExists(n)){var i=e.getDirectoryPath(n);t(i),r.createDirectory(n)}}(e.getDirectoryPath(e.normalizePath(t))),r.writeFile(t,n,i),e.performance.mark("afterIOWrite"),e.performance.measure("I/O Write","beforeIOWrite","afterIOWrite")}catch(e){a&&a(e.message)}},getCurrentDirectory:g,useCaseSensitiveFileNames:function(){return f},getCanonicalFileName:B,getNewLine:function(){return F},fileExists:Y,readFile:y,trace:P,directoryExists:N.directoryExists&&function(e){return N.directoryExists(e)},getDirectories:N.getDirectories&&function(e){return N.getDirectories(e)},realpath:r.realpath&&function(e){return r.realpath(e)},getEnvironmentVariable:r.getEnvironmentVariable?function(e){return r.getEnvironmentVariable(e)}:function(){return""},onReleaseOldSourceFile:function(e,t,r){var n=_.get(e.resolvedPath);n&&(H(n)?(c||(c=[])).push(e.path):n.sourceFile===e&&(n.fileWatcher&&n.fileWatcher.close(),_.delete(e.resolvedPath),r||J.removeResolutionsOfFile(e.path)))},createHash:r.createHash&&function(e){return r.createHash(e)},toPath:W,getCompilationSettings:function(){return S},watchDirectoryOfFailedLookupLocation:function(e,t,n){return R(r,e,t,n,"Failed Lookup Locations")},watchTypeRootsDirectory:function(e,t,n){return R(r,e,t,n,"Type roots")},getCachedDirectoryStructureHost:function(){return E},onInvalidatedResolution:ee,onChangedAutomaticTypeDirectiveNames:function(){p=!0,ee()},maxNumberOfFilesToIterateForInvalidation:r.maxNumberOfFilesToIterateForInvalidation,getCurrentProgram:U,writeLog:O,readDirectory:function(e,t,r,n,i){return N.readDirectory(e,t,r,n,i)}},J=e.createResolutionCache(j,v?e.getDirectoryPath(e.getNormalizedAbsolutePath(v,m)):m,!1);j.resolveModuleNames=r.resolveModuleNames?function(e,t,n,i){return r.resolveModuleNames(e,t,n,i)}:function(e,t,r,n){return J.resolveModuleNames(e,t,r,n)},j.resolveTypeReferenceDirectives=r.resolveTypeReferenceDirectives?function(e,t,n){return r.resolveTypeReferenceDirectives(e,t,n)}:function(e,t,r){return J.resolveTypeReferenceDirectives(e,t,r)};var z=!!r.resolveModuleNames||!!r.resolveTypeReferenceDirectives;return V(),ce(),v?{getCurrentProgram:K,getProgram:V}:{getCurrentProgram:K,getProgram:V,updateRootFileNames:function(t){e.Debug.assert(!v,"Cannot update root file names with config file watch mode"),x=t,ee()}};function K(){return n}function U(){return n&&n.getProgram()}function V(){O("Synchronizing program");var t=U();d&&(F=q(),t&&e.changesAffectModuleResolution(t.getCompilerOptions(),S)&&J.clear());var i=J.createHasInvalidatedResolution(z);return e.isProgramUptoDate(U(),x,S,$,Y,i,p,T)?k&&(n=D(void 0,void 0,j,n,l,T),k=!1):function(t,r){w!==e.WatchLogLevel.None&&(O("CreatingProgramWith::"),O(" roots: "+JSON.stringify(x)),O(" options: "+JSON.stringify(S)));var i=d||!t;if(d=!1,k=!1,J.startCachingPerDirectoryResolution(),j.hasInvalidatedResolution=r,j.hasChangedAutomaticTypeDirectiveNames=p,n=D(x,S,j,n,l,T),J.finishCachingPerDirectoryResolution(),e.updateMissingFilePathsWatch(n.getProgram(),a||(a=e.createMap()),oe),i&&J.updateTypeRootsWatch(),c){for(var o=0,s=c;oe?t:e}function d(t){return e.fileExtensionIs(t,".d.ts")}function p(t,r){return function(n){var i=r?"["+e.formatColorAndReset((new Date).toLocaleTimeString(),e.ForegroundColorEscapeSequences.Grey)+"] ":(new Date).toLocaleTimeString()+" - ";i+=""+e.flattenDiagnosticMessageText(n.messageText,t.newLine)+(t.newLine+t.newLine),t.write(i)}}function f(t,r,n){void 0===t&&(t=e.sys);var i=e.createCompilerHostWorker({},void 0,t);return i.getModifiedTime=t.getModifiedTime?function(e){return t.getModifiedTime(e)}:function(){},i.setModifiedTime=t.setModifiedTime?function(e,r){return t.setModifiedTime(e,r)}:e.noop,i.deleteFile=t.deleteFile?function(e){return t.deleteFile(e)}:e.noop,i.reportDiagnostic=r||e.createDiagnosticReporter(t),i.reportSolutionBuilderStatus=n||p(t),i}function m(t){var r={};return e.commonOptionsWithBuild.forEach(function(e){r[e.name]=t[e.name]}),r}function g(t){return e.fileExtensionIs(t,".json")?t:e.combinePaths(t,"tsconfig.json")}function y(t){if(t.options.outFile||t.options.out)return function(t){var r=t.options.outFile||t.options.out;if(!r)return e.Debug.fail("outFile must be set");var n=[];if(n.push(r),t.options.sourceMap&&n.push(r+".map"),e.getEmitDeclarations(t.options)){var i=e.changeExtension(r,".d.ts");n.push(i),t.options.declarationMap&&n.push(i+".map")}return n}(t);for(var r=[],n=0,i=t.fileNames;no&&(a=l,o=p)}var f=y(t);if(0===f.length)return{type:r.ContainerOnly};for(var m,g="(none)",v=i,h="(none)",b=n,D=n,x=!1,S=0,T=f;Sb&&(b=N,h=C),d(C)){var A=k.getValue(C);if(void 0!==A)D=_(A,D);else{var F=c.getModifiedTime(C)||e.missingFileModifiedTime;D=_(D,F)}}}var P,w=!1,O=!1;if(t.projectReferences){E.setValue(t.options.configFilePath,{type:r.ComputingUpstream});for(var I=0,M=t.projectReferences;I4)return a(r.has(e),n);r.add(e),n.push(t);var o=i();return n.pop(),r.delete(e),o}));var r,n}function i(t,r,n){return n(r,t,function(){if("function"==typeof r)return function(t,r,n){var a=function(t,r){var n=t.prototype;return"object"!==f(n)||null===n?e.emptyArray:e.mapDefined(c(n),function(e){var t=e.key,n=e.value;return"constructor"===t?void 0:i(t,n,r)})}(t,n),o=e.flatMap(c(t),function(e){var t=e.key,r=e.value;return i(t,r,n)}),s=e.cast(Function.prototype.toString.call(t),e.isString),l=e.stringContains(s,"{ [native code] }")?function(t){return e.tryCast(u(t,"length"),e.isNumber)||0}(t):s;return{kind:2,name:r,source:l,namespaceMembers:o,prototypeMembers:a}}(r,t,n);if("object"===f(r)){var o=function(t,r,n){return e.isArray(r)?{name:t,kind:1,inner:r.length&&i("element",e.first(r),n)||_(t)}:e.forEachEntry(a(),function(e,n){return r instanceof e?{kind:0,name:t,typeName:n}:void 0})}(t,r,n);if(void 0!==o)return o;var s=c(r),d=Object.getPrototypeOf(r)!==Object.prototype,p=e.flatMap(s,function(e){return i(e.key,e.value,n)});return{kind:3,name:t,hasNontrivialPrototype:d,members:p}}return{kind:0,name:t,typeName:l(r)?"any":f(r)}},function(e,r){return _(t," "+(e?"Circular reference":"Too-deep object hierarchy")+" from "+r.join("."))})}!function(e){e[e.Const=0]="Const",e[e.Array=1]="Array",e[e.FunctionOrClass=2]="FunctionOrClass",e[e.Object=3]="Object"}(e.ValueKind||(e.ValueKind={})),e.inspectModule=function(r){return t(e.removeFileExtension(e.getBaseFileName(r)),function(e){try{return n()}catch(e){return}}())},e.inspectValue=t;var a=e.memoize(function(){for(var t=e.createMap(),n=0,i=c(r);n=0},t.findArgument=function(t){var r=e.sys.args.indexOf(t);return r>=0&&rn?3:46===e.charCodeAt(0)?4:95===e.charCodeAt(0)?5:/^@[^/]+\/[^/]+$/.test(e)?1:encodeURIComponent(e)!==e?6:0:2},t.renderPackageNameValidationFailure=function(t,r){switch(t){case 2:return"Package name '"+r+"' cannot be empty";case 3:return"Package name '"+r+"' should be less than "+n+" characters";case 4:return"Package name '"+r+"' cannot start with '.'";case 5:return"Package name '"+r+"' cannot start with '_'";case 1:return"Package '"+r+"' is scoped and currently is not supported";case 6:return"Package name '"+r+"' contains non URI safe characters";case 0:return e.Debug.fail();default:throw e.Debug.assertNever(t)}}}(e.JsTyping||(e.JsTyping={}))}(c||(c={})),function(e){var t;function r(e){return{indentSize:4,tabSize:4,newLineCharacter:e||"\n",convertTabsToSpaces:!0,indentStyle:t.Smart,insertSpaceAfterConstructor:!1,insertSpaceAfterCommaDelimiter:!0,insertSpaceAfterSemicolonInForStatements:!0,insertSpaceBeforeAndAfterBinaryOperators:!0,insertSpaceAfterKeywordsInControlFlowStatements:!0,insertSpaceAfterFunctionKeywordForAnonymousFunctions:!1,insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis:!1,insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets:!1,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0,insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces:!1,insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces:!1,insertSpaceBeforeFunctionParenthesis:!1,placeOpenBraceOnNewLineForFunctions:!1,placeOpenBraceOnNewLineForControlBlocks:!1}}!function(e){var t=function(){function e(e){this.text=e}return e.prototype.getText=function(e,t){return 0===e&&t===this.text.length?this.text:this.text.substring(e,t)},e.prototype.getLength=function(){return this.text.length},e.prototype.getChangeRange=function(){},e}();e.fromString=function(e){return new t(e)}}(e.ScriptSnapshot||(e.ScriptSnapshot={})),e.emptyOptions={},function(e){e.none="none",e.definition="definition",e.reference="reference",e.writtenReference="writtenReference"}(e.HighlightSpanKind||(e.HighlightSpanKind={})),function(e){e[e.None=0]="None",e[e.Block=1]="Block",e[e.Smart=2]="Smart"}(t=e.IndentStyle||(e.IndentStyle={})),e.getDefaultFormatCodeSettings=r,e.testFormatSettings=r("\n"),function(e){e[e.aliasName=0]="aliasName",e[e.className=1]="className",e[e.enumName=2]="enumName",e[e.fieldName=3]="fieldName",e[e.interfaceName=4]="interfaceName",e[e.keyword=5]="keyword",e[e.lineBreak=6]="lineBreak",e[e.numericLiteral=7]="numericLiteral",e[e.stringLiteral=8]="stringLiteral",e[e.localName=9]="localName",e[e.methodName=10]="methodName",e[e.moduleName=11]="moduleName",e[e.operator=12]="operator",e[e.parameterName=13]="parameterName",e[e.propertyName=14]="propertyName",e[e.punctuation=15]="punctuation",e[e.space=16]="space",e[e.text=17]="text",e[e.typeParameterName=18]="typeParameterName",e[e.enumMemberName=19]="enumMemberName",e[e.functionName=20]="functionName",e[e.regularExpressionLiteral=21]="regularExpressionLiteral"}(e.SymbolDisplayPartKind||(e.SymbolDisplayPartKind={})),function(e){e.Comment="comment",e.Region="region",e.Code="code",e.Imports="imports"}(e.OutliningSpanKind||(e.OutliningSpanKind={})),function(e){e[e.JavaScript=0]="JavaScript",e[e.SourceMap=1]="SourceMap",e[e.Declaration=2]="Declaration"}(e.OutputFileType||(e.OutputFileType={})),function(e){e[e.None=0]="None",e[e.InMultiLineCommentTrivia=1]="InMultiLineCommentTrivia",e[e.InSingleQuoteStringLiteral=2]="InSingleQuoteStringLiteral",e[e.InDoubleQuoteStringLiteral=3]="InDoubleQuoteStringLiteral",e[e.InTemplateHeadOrNoSubstitutionTemplate=4]="InTemplateHeadOrNoSubstitutionTemplate",e[e.InTemplateMiddleOrTail=5]="InTemplateMiddleOrTail",e[e.InTemplateSubstitutionPosition=6]="InTemplateSubstitutionPosition"}(e.EndOfLineState||(e.EndOfLineState={})),function(e){e[e.Punctuation=0]="Punctuation",e[e.Keyword=1]="Keyword",e[e.Operator=2]="Operator",e[e.Comment=3]="Comment",e[e.Whitespace=4]="Whitespace",e[e.Identifier=5]="Identifier",e[e.NumberLiteral=6]="NumberLiteral",e[e.BigIntLiteral=7]="BigIntLiteral",e[e.StringLiteral=8]="StringLiteral",e[e.RegExpLiteral=9]="RegExpLiteral"}(e.TokenClass||(e.TokenClass={})),function(e){e.unknown="",e.warning="warning",e.keyword="keyword",e.scriptElement="script",e.moduleElement="module",e.classElement="class",e.localClassElement="local class",e.interfaceElement="interface",e.typeElement="type",e.enumElement="enum",e.enumMemberElement="enum member",e.variableElement="var",e.localVariableElement="local var",e.functionElement="function",e.localFunctionElement="local function",e.memberFunctionElement="method",e.memberGetAccessorElement="getter",e.memberSetAccessorElement="setter",e.memberVariableElement="property",e.constructorImplementationElement="constructor",e.callSignatureElement="call",e.indexSignatureElement="index",e.constructSignatureElement="construct",e.parameterElement="parameter",e.typeParameterElement="type parameter",e.primitiveType="primitive type",e.label="label",e.alias="alias",e.constElement="const",e.letElement="let",e.directory="directory",e.externalModuleName="external module name",e.jsxAttribute="JSX attribute",e.string="string"}(e.ScriptElementKind||(e.ScriptElementKind={})),function(e){e.none="",e.publicMemberModifier="public",e.privateMemberModifier="private",e.protectedMemberModifier="protected",e.exportedModifier="export",e.ambientModifier="declare",e.staticModifier="static",e.abstractModifier="abstract",e.optionalModifier="optional",e.dtsModifier=".d.ts",e.tsModifier=".ts",e.tsxModifier=".tsx",e.jsModifier=".js",e.jsxModifier=".jsx",e.jsonModifier=".json"}(e.ScriptElementKindModifier||(e.ScriptElementKindModifier={})),function(e){e.comment="comment",e.identifier="identifier",e.keyword="keyword",e.numericLiteral="number",e.bigintLiteral="bigint",e.operator="operator",e.stringLiteral="string",e.whiteSpace="whitespace",e.text="text",e.punctuation="punctuation",e.className="class name",e.enumName="enum name",e.interfaceName="interface name",e.moduleName="module name",e.typeParameterName="type parameter name",e.typeAliasName="type alias name",e.parameterName="parameter name",e.docCommentTagName="doc comment tag name",e.jsxOpenTagName="jsx open tag name",e.jsxCloseTagName="jsx close tag name",e.jsxSelfClosingTagName="jsx self closing tag name",e.jsxAttribute="jsx attribute",e.jsxText="jsx text",e.jsxAttributeStringLiteralValue="jsx attribute string literal value"}(e.ClassificationTypeNames||(e.ClassificationTypeNames={})),function(e){e[e.comment=1]="comment",e[e.identifier=2]="identifier",e[e.keyword=3]="keyword",e[e.numericLiteral=4]="numericLiteral",e[e.operator=5]="operator",e[e.stringLiteral=6]="stringLiteral",e[e.regularExpressionLiteral=7]="regularExpressionLiteral",e[e.whiteSpace=8]="whiteSpace",e[e.text=9]="text",e[e.punctuation=10]="punctuation",e[e.className=11]="className",e[e.enumName=12]="enumName",e[e.interfaceName=13]="interfaceName",e[e.moduleName=14]="moduleName",e[e.typeParameterName=15]="typeParameterName",e[e.typeAliasName=16]="typeAliasName",e[e.parameterName=17]="parameterName",e[e.docCommentTagName=18]="docCommentTagName",e[e.jsxOpenTagName=19]="jsxOpenTagName",e[e.jsxCloseTagName=20]="jsxCloseTagName",e[e.jsxSelfClosingTagName=21]="jsxSelfClosingTagName",e[e.jsxAttribute=22]="jsxAttribute",e[e.jsxText=23]="jsxText",e[e.jsxAttributeStringLiteralValue=24]="jsxAttributeStringLiteralValue",e[e.bigintLiteral=25]="bigintLiteral"}(e.ClassificationType||(e.ClassificationType={}))}(c||(c={})),function(e){function t(t){switch(t.kind){case 237:return e.isInJSFile(t)&&e.getJSDocEnumTag(t)?7:1;case 151:case 186:case 154:case 153:case 275:case 276:case 156:case 155:case 157:case 158:case 159:case 239:case 196:case 197:case 274:case 267:return 1;case 150:case 241:case 242:case 168:return 2;case 304:return void 0===t.name?3:2;case 278:case 240:return 3;case 244:return e.isAmbientModule(t)?5:1===e.getModuleInstanceState(t)?5:4;case 243:case 252:case 253:case 248:case 249:case 254:case 255:return 7;case 279:return 5}return 7}function r(t){for(;148===t.parent.kind;)t=t.parent;return e.isInternalModuleImportEqualsDeclaration(t.parent)&&t.parent.moduleReference===t}function n(e,t){var r=i(e);return!!r&&!!r.parent&&t(r.parent)&&r.parent.expression===r}function i(e){return s(e)?e.parent:e}function a(t){return 72===t.kind&&e.isBreakOrContinueStatement(t.parent)&&t.parent.label===t}function o(t){return 72===t.kind&&e.isLabeledStatement(t.parent)&&t.parent.label===t}function s(e){return e&&e.parent&&189===e.parent.kind&&e.parent.name===e}e.scanner=e.createScanner(6,!0),function(e){e[e.None=0]="None",e[e.Value=1]="Value",e[e.Type=2]="Type",e[e.Namespace=4]="Namespace",e[e.All=7]="All"}(e.SemanticMeaning||(e.SemanticMeaning={})),e.getMeaningFromDeclaration=t,e.getMeaningFromLocation=function(n){return 279===n.kind?1:254===n.parent.kind||259===n.parent.kind?7:r(n)?function(t){var r=148===t.kind?t:e.isQualifiedName(t.parent)&&t.parent.right===t?t.parent:void 0;return r&&248===r.parent.kind?7:4}(n):e.isDeclarationName(n)?t(n.parent):function(t){switch(e.isRightSideOfQualifiedNameOrPropertyAccess(t)&&(t=t.parent),t.kind){case 100:return!e.isExpressionNode(t);case 178:return!0}switch(t.parent.kind){case 164:return!0;case 183:return!t.parent.isTypeOf;case 211:return!e.isExpressionWithTypeArgumentsInClassExtendsClause(t.parent)}return!1}(n)?2:function(e){return function(e){var t=e,r=!0;if(148===t.parent.kind){for(;t.parent&&148===t.parent.kind;)t=t.parent;r=t.right===e}return 164===t.parent.kind&&!r}(e)||function(e){var t=e,r=!0;if(189===t.parent.kind){for(;t.parent&&189===t.parent.kind;)t=t.parent;r=t.name===e}if(!r&&211===t.parent.kind&&273===t.parent.parent.kind){var n=t.parent.parent.parent;return 240===n.kind&&109===t.parent.parent.token||241===n.kind&&86===t.parent.parent.token}return!1}(e)}(n)?4:e.isTypeParameterDeclaration(n.parent)?(e.Debug.assert(e.isJSDocTemplateTag(n.parent.parent)),2):e.isLiteralTypeNode(n.parent)?3:1},e.isInRightSideOfInternalImportEqualsDeclaration=r,e.isCallExpressionTarget=function(t){return n(t,e.isCallExpression)},e.isNewExpressionTarget=function(t){return n(t,e.isNewExpression)},e.isCallOrNewExpressionTarget=function(t){return n(t,e.isCallOrNewExpression)},e.climbPastPropertyAccess=i,e.getTargetLabel=function(e,t){for(;e;){if(233===e.kind&&e.label.escapedText===t)return e.label;e=e.parent}},e.hasPropertyAccessExpressionWithName=function(t,r){return!!e.isPropertyAccessExpression(t.expression)&&t.expression.name.text===r},e.isJumpStatementTarget=a,e.isLabelOfLabeledStatement=o,e.isLabelName=function(e){return o(e)||a(e)},e.isTagName=function(t){return e.isJSDocTag(t.parent)&&t.parent.tagName===t},e.isRightSideOfQualifiedName=function(e){return 148===e.parent.kind&&e.parent.right===e},e.isRightSideOfPropertyAccess=s,e.isNameOfModuleDeclaration=function(e){return 244===e.parent.kind&&e.parent.name===e},e.isNameOfFunctionDeclaration=function(t){return 72===t.kind&&e.isFunctionLike(t.parent)&&t.parent.name===t},e.isLiteralNameOfPropertyDeclarationOrIndexAccess=function(t){switch(t.parent.kind){case 154:case 153:case 275:case 278:case 156:case 155:case 158:case 159:case 244:return e.getNameOfDeclaration(t.parent)===t;case 190:return t.parent.argumentExpression===t;case 149:return!0;case 182:return 180===t.parent.parent.kind;default:return!1}},e.isExpressionOfExternalModuleImportEqualsDeclaration=function(t){return e.isExternalModuleImportEqualsDeclaration(t.parent.parent)&&e.getExternalModuleImportEqualsDeclarationExpression(t.parent.parent)===t},e.getContainerNode=function(t){for(e.isJSDocTypeAlias(t)&&(t=t.parent.parent);;){if(!(t=t.parent))return;switch(t.kind){case 279:case 156:case 155:case 239:case 196:case 158:case 159:case 240:case 241:case 243:case 244:return t}}},e.getNodeKind=function t(r){switch(r.kind){case 279:return e.isExternalModule(r)?"module":"script";case 244:return"module";case 240:case 209:return"class";case 241:return"interface";case 242:case 297:case 304:return"type";case 243:return"enum";case 237:return o(r);case 186:return o(e.getRootDeclaration(r));case 197:case 239:case 196:return"function";case 158:return"getter";case 159:return"setter";case 156:case 155:return"method";case 154:case 153:return"property";case 162:return"index";case 161:return"construct";case 160:return"call";case 157:return"constructor";case 150:return"type parameter";case 278:return"enum member";case 151:return e.hasModifier(r,92)?"property":"parameter";case 248:case 253:case 257:case 251:return"alias";case 204:var n=e.getAssignmentDeclarationKind(r),i=r.right;switch(n){case 7:case 8:case 9:case 0:return"";case 1:case 2:var a=t(i);return""===a?"const":a;case 3:return e.isFunctionExpression(i)?"method":"property";case 4:return"property";case 5:return e.isFunctionExpression(i)?"method":"property";case 6:return"local class";default:return e.assertType(n),""}case 72:return e.isImportClause(r.parent)?"alias":"";default:return""}function o(t){return e.isVarConst(t)?"const":e.isLet(t)?"let":"var"}},e.isThis=function(t){switch(t.kind){case 100:return!0;case 72:return e.identifierIsThisKeyword(t)&&151===t.parent.kind;default:return!1}};var c=/^\/\/\/\s*=r.end}function d(e,t,r,n){return Math.max(e,r)t)break;var u=c.getEnd();if(t=t||!A(u,r)||T(u);if(_){var d=S(s,c,r);return d&&x(d,r)}return a(u)}}e.Debug.assert(void 0!==n||279===o.kind||1===o.kind||e.isJSDocCommentContainingNode(o));var p=S(s,s.length,r);return p&&x(p,r)}(n||r);return e.Debug.assert(!(a&&T(a))),a}function D(t){return e.isToken(t)&&!T(t)}function x(e,t){if(D(e))return e;var r=e.getChildren(t),n=S(r,r.length,t);return n&&x(n,t)}function S(t,r,n){for(var i=r-1;i>=0;i--){if(T(t[i]))e.Debug.assert(i>0,"`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");else if(A(t[i],n))return t[i]}}function T(t){return e.isJsxText(t)&&t.containsOnlyWhiteSpaces}function C(e,t,r){for(var n=e.kind,i=0;;){var a=b(e.getFullStart(),r);if(!a)return;if((e=a).kind===t){if(0===i)return e;i--}else e.kind===n&&i++}}function k(t,r,n){var i=n.getTypeAtLocation(t);return(e.isNewExpression(t.parent)?i.getConstructSignatures():i.getCallSignatures()).filter(function(e){return!!e.typeParameters&&e.typeParameters.length>=r})}function E(t,r){for(var n=t,i=0,a=0;n;){switch(n.kind){case 28:if(!(n=b(n.getFullStart(),r))||!e.isIdentifier(n))return;if(!i)return e.isDeclarationName(n)?void 0:{called:n,nTypeArguments:a};i--;break;case 48:i=3;break;case 47:i=2;break;case 30:i++;break;case 19:if(!(n=C(n,18,r)))return;break;case 21:if(!(n=C(n,20,r)))return;break;case 23:if(!(n=C(n,22,r)))return;break;case 27:a++;break;case 37:case 72:case 10:case 8:case 9:case 102:case 87:case 104:case 86:case 129:case 24:case 50:case 56:case 57:break;default:if(e.isTypeNode(n))break;return}n=b(n.getFullStart(),r)}}function N(t,r,n){return e.formatting.getRangeOfEnclosingComment(t,r,void 0,n)}function A(e,t){return 1===e.kind?!!e.jsDoc:0!==e.getWidth(t)}function F(e,t,r){var n=N(e,t,void 0);return!!n&&r===c.test(e.text.substring(n.pos,n.end))}function P(e,t){return{span:e,newText:t}}function w(e){return!!e.useCaseSensitiveFileNames&&e.useCaseSensitiveFileNames()}function O(t,r,n,i){return e.createImportDeclaration(void 0,void 0,t||r?e.createImportClause(t,r&&r.length?e.createNamedImports(r):void 0):void 0,"string"==typeof n?I(n,i):n)}function I(t,r){return e.createLiteral(t,0===r)}function M(t,r){return e.isStringDoubleQuoted(t,r)?1:0}function L(t){return"default"!==t.escapedName?t.escapedName:e.firstDefined(t.declarations,function(t){var r=e.getNameOfDeclaration(t);return r&&72===r.kind?r.escapedText:void 0})}function R(t,r,n,i){var a=e.createMap();return function t(o){if(!(96&o.flags&&e.addToSeen(a,e.getSymbolId(o))))return;return e.firstDefined(o.declarations,function(a){return e.firstDefined(e.getAllSuperTypeNodes(a),function(a){var o=n.getTypeAtLocation(a),s=o&&o.symbol&&n.getPropertyOfType(o,r);return o&&s&&(e.firstDefined(n.getRootSymbols(s),i)||t(o.symbol))})})}(t)}function B(t,r,n){return e.textSpanContainsPosition(t,r.getStart(n))&&r.getEnd()<=e.textSpanEnd(t)}function j(e,t){return!!e&&!!t&&e.start===t.start&&e.length===t.length}e.getLineStartPositionForPosition=function(t,r){return e.getLineStarts(r)[r.getLineAndCharacterOfPosition(t).line]},e.rangeContainsRange=u,e.rangeContainsRangeExclusive=function(e,t){return l(e,t.pos)&&l(e,t.end)},e.rangeContainsPosition=function(e,t){return e.pos<=t&&t<=e.end},e.rangeContainsPositionExclusive=l,e.startEndContainsRange=_,e.rangeContainsStartEnd=function(e,t,r){return e.pos<=t&&e.end>=r},e.rangeOverlapsWithStartEnd=function(e,t,r){return d(e.pos,e.end,t,r)},e.nodeOverlapsWithStartEnd=function(e,t,r,n){return d(e.getStart(t),e.end,r,n)},e.startEndOverlapsWithStartEnd=d,e.positionBelongsToNode=function(t,r,n){return e.Debug.assert(t.pos<=r),rn.getStart(t)&&rt.end||e.pos===t.end;return i&&A(e,n)?r(e):void 0})}(r)},e.findPrecedingToken=b,e.isInString=function(t,r,n){if(void 0===n&&(n=b(r,t)),n&&e.isStringTextContainingNode(n)){var i=n.getStart(t),a=n.getEnd();if(in.getStart(t)},e.isInJSXText=function(t,r){var n=v(t,r);return!!e.isJsxText(n)||!(18!==n.kind||!e.isJsxExpression(n.parent)||!e.isJsxElement(n.parent.parent))||!(28!==n.kind||!e.isJsxOpeningLikeElement(n.parent)||!e.isJsxElement(n.parent.parent))},e.findPrecedingMatchingToken=C,e.isPossiblyTypeArgumentPosition=function t(r,n,i){var a=E(r,n);return void 0!==a&&(e.isPartOfTypeNode(a.called)||0!==k(a.called,a.nTypeArguments,i).length||t(a.called,n,i))},e.getPossibleGenericSignatures=k,e.getPossibleTypeArgumentsInfo=E,e.isInComment=N,e.hasDocComment=function(t,r){var n=v(t,r);return!!e.findAncestor(n,e.isJSDoc)},e.getNodeModifiers=function(t){var r=e.isDeclaration(t)?e.getCombinedModifierFlags(t):0,n=[];return 8&r&&n.push("private"),16&r&&n.push("protected"),4&r&&n.push("public"),32&r&&n.push("static"),128&r&&n.push("abstract"),1&r&&n.push("export"),4194304&t.flags&&n.push("declare"),n.length>0?n.join(","):""},e.getTypeArgumentOrTypeParameterList=function(t){return 164===t.kind||191===t.kind?t.typeArguments:e.isFunctionLike(t)||240===t.kind||241===t.kind?t.typeParameters:void 0},e.isComment=function(e){return 2===e||3===e},e.isStringOrRegularExpressionOrTemplateLiteral=function(t){return!(10!==t&&13!==t&&!e.isTemplateLiteralKind(t))},e.isPunctuation=function(e){return 18<=e&&e<=71},e.isInsideTemplateLiteral=function(t,r,n){return e.isTemplateLiteralKind(t.kind)&&t.getStart(n)=2||!!e.noEmit},e.hostUsesCaseSensitiveFileNames=w,e.hostGetCanonicalFileName=function(t){return e.createGetCanonicalFileName(w(t))},e.makeImportIfNecessary=function(e,t,r,n){return e||t&&t.length?O(e,t,r,n):void 0},e.makeImport=O,e.makeStringLiteral=I,function(e){e[e.Single=0]="Single",e[e.Double=1]="Double"}(e.QuotePreference||(e.QuotePreference={})),e.quotePreferenceFromString=M,e.getQuotePreference=function(t,r){if(r.quotePreference)return"single"===r.quotePreference?0:1;var n=t.imports&&e.find(t.imports,e.isStringLiteral);return n?M(n,t):1},e.getQuoteFromPreference=function(t){switch(t){case 0:return"'";case 1:return'"';default:return e.Debug.assertNever(t)}},e.symbolNameNoDefault=function(t){var r=L(t);return void 0===r?void 0:e.unescapeLeadingUnderscores(r)},e.symbolEscapedNameNoDefault=L,e.isObjectBindingElementWithoutPropertyName=function(t){return e.isBindingElement(t)&&e.isObjectBindingPattern(t.parent)&&e.isIdentifier(t.name)&&!t.propertyName},e.getPropertySymbolFromBindingElement=function(e,t){var r=e.getTypeAtLocation(t.parent);return r&&e.getPropertyOfType(r,t.name.text)},e.getPropertySymbolsFromBaseTypes=R,e.isMemberSymbolInBaseType=function(e,t){return R(e.parent,e.name,t,function(e){return!0})||!1},e.getParentNodeInSpan=function(t,r,n){if(t)for(;t.parent;){if(e.isSourceFile(t.parent)||!B(n,t.parent,r))return t;t=t.parent}},e.findModifier=function(t,r){return t.modifiers&&e.find(t.modifiers,function(e){return e.kind===r})},e.insertImport=function(t,r,n){var i=e.findLast(r.statements,e.isAnyImportSyntax);i?t.insertNodeAfter(r,i,n):t.insertNodeAtTopOfFile(r,n,!0)},e.textSpansEqual=j,e.documentSpansEqual=function(e,t){return e.fileName===t.fileName&&j(e.textSpan,t.textSpan)}}(c||(c={})),function(e){function t(e){return e.declarations&&e.declarations.length>0&&151===e.declarations[0].kind}e.isFirstDeclarationOfSymbolParameter=t;var r=function(){var t,r,a,o,s=10*e.defaultMaximumTruncationLength;d();var u=function(t){return _(t,e.SymbolDisplayPartKind.text)};return{displayParts:function(){var r=t.length&&t[t.length-1].text;return o>s&&r&&"..."!==r&&(e.isWhiteSpaceLike(r.charCodeAt(r.length-1))||t.push(i(" ",e.SymbolDisplayPartKind.space)),t.push(i("...",e.SymbolDisplayPartKind.punctuation))),t},writeKeyword:function(t){return _(t,e.SymbolDisplayPartKind.keyword)},writeOperator:function(t){return _(t,e.SymbolDisplayPartKind.operator)},writePunctuation:function(t){return _(t,e.SymbolDisplayPartKind.punctuation)},writeTrailingSemicolon:function(t){return _(t,e.SymbolDisplayPartKind.punctuation)},writeSpace:function(t){return _(t,e.SymbolDisplayPartKind.space)},writeStringLiteral:function(t){return _(t,e.SymbolDisplayPartKind.stringLiteral)},writeParameter:function(t){return _(t,e.SymbolDisplayPartKind.parameterName)},writeProperty:function(t){return _(t,e.SymbolDisplayPartKind.propertyName)},writeLiteral:function(t){return _(t,e.SymbolDisplayPartKind.stringLiteral)},writeSymbol:function(e,r){if(o>s)return;l(),o+=e.length,t.push(n(e,r))},writeLine:function(){if(o>s)return;o+=1,t.push(c()),r=!0},write:u,writeComment:u,getText:function(){return""},getTextPos:function(){return 0},getColumn:function(){return 0},getLine:function(){return 0},isAtStartOfLine:function(){return!1},rawWrite:e.notImplemented,getIndent:function(){return a},increaseIndent:function(){a++},decreaseIndent:function(){a--},clear:d,trackSymbol:e.noop,reportInaccessibleThisError:e.noop,reportInaccessibleUniqueSymbolError:e.noop,reportPrivateInBaseOfClassExpression:e.noop};function l(){if(!(o>s)&&r){var n=e.getIndentString(a);n&&(o+=n.length,t.push(i(n,e.SymbolDisplayPartKind.space))),r=!1}}function _(e,r){o>s||(l(),o+=e.length,t.push(i(e,r)))}function d(){t=[],r=!0,a=0,o=0}}();function n(r,n){return i(r,function(r){var n=r.flags;if(3&n)return t(r)?e.SymbolDisplayPartKind.parameterName:e.SymbolDisplayPartKind.localName;if(4&n)return e.SymbolDisplayPartKind.propertyName;if(32768&n)return e.SymbolDisplayPartKind.propertyName;if(65536&n)return e.SymbolDisplayPartKind.propertyName;if(8&n)return e.SymbolDisplayPartKind.enumMemberName;if(16&n)return e.SymbolDisplayPartKind.functionName;if(32&n)return e.SymbolDisplayPartKind.className;if(64&n)return e.SymbolDisplayPartKind.interfaceName;if(384&n)return e.SymbolDisplayPartKind.enumName;if(1536&n)return e.SymbolDisplayPartKind.moduleName;if(8192&n)return e.SymbolDisplayPartKind.methodName;if(262144&n)return e.SymbolDisplayPartKind.typeParameterName;if(524288&n)return e.SymbolDisplayPartKind.aliasName;if(2097152&n)return e.SymbolDisplayPartKind.aliasName;return e.SymbolDisplayPartKind.text}(n))}function i(t,r){return{text:t,kind:e.SymbolDisplayPartKind[r]}}function a(t){return i(e.tokenToString(t),e.SymbolDisplayPartKind.keyword)}function o(t){return i(t,e.SymbolDisplayPartKind.text)}e.symbolPart=n,e.displayPart=i,e.spacePart=function(){return i(" ",e.SymbolDisplayPartKind.space)},e.keywordPart=a,e.punctuationPart=function(t){return i(e.tokenToString(t),e.SymbolDisplayPartKind.punctuation)},e.operatorPart=function(t){return i(e.tokenToString(t),e.SymbolDisplayPartKind.operator)},e.textOrKeywordPart=function(t){var r=e.stringToToken(t);return void 0===r?o(t):a(r)},e.textPart=o;var s="\r\n";function c(){return i("\n",e.SymbolDisplayPartKind.lineBreak)}function u(e){try{return e(r),r.displayParts()}finally{r.clear()}}function l(e){var t=e.length;return t>=2&&e.charCodeAt(0)===e.charCodeAt(t-1)&&_(e)?e.substring(1,t-1):e}function _(t){return e.isSingleOrDoubleQuote(t.charCodeAt(0))}function d(t,r){return e.ensureScriptKind(t,r&&r.getScriptKind&&r.getScriptKind(t))}function p(e,t){void 0===t&&(t=!0);var r=e&&m(e);return r&&!t&&g(r),r}function f(t,r,n,i,a){var o;if(void 0===r&&(r=!0),e.isIdentifier(t)&&n&&i){var s=i.getSymbolAtLocation(t),c=s&&n.get(String(e.getSymbolId(s)));c&&(o=e.createIdentifier(c.text))}return o||(o=m(t,n,i,a)),o&&!r&&g(o),a&&o&&a(t,o),o}function m(t,r,n,i){var a=r||n||i?e.visitEachChild(t,function(e){return f(e,!0,r,n,i)},e.nullTransformationContext):e.visitEachChild(t,p,e.nullTransformationContext);if(a===t){var o=e.getSynthesizedClone(t);return e.isStringLiteral(o)?o.textSourceNode=t:e.isNumericLiteral(o)&&(o.numericLiteralFlags=t.numericLiteralFlags),e.setTextRange(o,t)}return a.parent=void 0,a}function g(e){y(e),v(e)}function y(e){h(e,512,b)}function v(t){h(t,1024,e.getLastChild)}function h(t,r,n){e.addEmitFlags(t,r);var i=n(t);i&&h(i,r,n)}function b(e){return e.forEachChild(function(e){return e})}function D(t,r){if(e.startsWith(t,r))return 0;var n=t.indexOf(" "+r);return-1===n&&(n=t.indexOf("."+r)),-1===n&&(n=t.indexOf('"'+r)),-1===n?-1:n+1}function x(e){switch(e){case 35:case 33:case 36:case 34:return!0;default:return!1}}function S(e,t){return t.getTypeAtLocation(e.parent.parent.expression)}e.getNewLineOrDefaultFromHost=function(e,t){return t&&t.newLineCharacter||e.getNewLine&&e.getNewLine()||s},e.lineBreakPart=c,e.mapToDisplayParts=u,e.typeToDisplayParts=function(e,t,r,n){return void 0===n&&(n=0),u(function(i){e.writeType(t,r,17408|n,i)})},e.symbolToDisplayParts=function(e,t,r,n,i){return void 0===i&&(i=0),u(function(a){e.writeSymbol(t,r,n,8|i,a)})},e.signatureToDisplayParts=function(e,t,r,n){return void 0===n&&(n=0),n|=25632,u(function(i){e.writeSignature(t,r,n,void 0,i)})},e.isImportOrExportSpecifierName=function(t){return!!t.parent&&e.isImportOrExportSpecifier(t.parent)&&t.parent.propertyName===t},e.stripQuotes=l,e.startsWithQuote=_,e.scriptKindIs=function(t,r){for(var n=[],i=2;i-1&&e.isWhiteSpaceSingleLine(t.charCodeAt(r));)r-=1;return r+1},e.getSynthesizedDeepClone=p,e.getSynthesizedDeepCloneWithRenames=f,e.getSynthesizedDeepClones=function(t,r){return void 0===r&&(r=!0),t&&e.createNodeArray(t.map(function(e){return p(e,r)}),t.hasTrailingComma)},e.suppressLeadingAndTrailingTrivia=g,e.suppressLeadingTrivia=y,e.suppressTrailingTrivia=v,e.getUniqueName=function(t,r){for(var n=t,i=1;!e.isFileLevelUniqueName(r,n);i++)n=t+"_"+i;return n},e.getRenameLocation=function(t,r,n,i){for(var a=0,o=-1,s=0,c=t;s=0),o},e.copyComments=function(t,r,n,i,a){e.forEachLeadingCommentRange(n.text,t.pos,function(t,o,s,c){3===s?(t+=2,o-=2):t+=2,e.addSyntheticLeadingComment(r,i||s,n.text.slice(t,o),void 0!==a?a:c)})},e.getContextualTypeFromParent=function(e,t){var r=e.parent;switch(r.kind){case 192:return t.getContextualType(r);case 204:var n=r,i=n.left,a=n.operatorToken,o=n.right;return x(a.kind)?t.getTypeAtLocation(e===o?i:o):t.getContextualType(e);case 271:return r.expression===e?S(r,t):void 0;default:return t.getContextualType(e)}},e.quote=function(t,r){if(/^\d+$/.test(t))return t;var n=JSON.stringify(t);switch(r.quotePreference){case void 0:case"double":return n;case"single":return"'"+l(n).replace("'","\\'").replace('\\"','"')+"'";default:return e.Debug.assertNever(r.quotePreference)}},e.isEqualityOperatorKind=x,e.isStringLiteralOrTemplate=function(e){switch(e.kind){case 10:case 14:case 206:case 193:return!0;default:return!1}},e.hasIndexSignature=function(e){return!!e.getStringIndexType()||!!e.getNumberIndexType()},e.getSwitchedType=S}(c||(c={})),function(e){e.createClassifier=function(){var o=e.createScanner(6,!1);function s(i,s,c){var u=0,l=0,_=[],d=function(t){switch(t){case 3:return{prefix:'"\\\n'};case 2:return{prefix:"'\\\n"};case 1:return{prefix:"/*\n"};case 4:return{prefix:"`\n"};case 5:return{prefix:"}\n",pushTemplate:!0};case 6:return{prefix:"",pushTemplate:!0};case 0:return{prefix:""};default:return e.Debug.assertNever(t)}}(s),p=d.prefix,f=d.pushTemplate;i=p+i;var m=p.length;f&&_.push(15),o.setText(i);var g=0,y=[],v=0;do{u=o.scan(),e.isTrivia(u)||(D(),l=u);var h=o.getTextPos();if(n(o.getTokenPos(),h,m,a(u),y),h>=i.length){var b=r(o,u,e.lastOrUndefined(_));void 0!==b&&(g=b)}}while(1!==u);function D(){switch(u){case 42:case 64:t[l]||13!==o.reScanSlashToken()||(u=13);break;case 28:72===l&&v++;break;case 30:v>0&&v--;break;case 120:case 138:case 135:case 123:case 139:v>0&&!c&&(u=72);break;case 15:_.push(u);break;case 18:_.length>0&&_.push(u);break;case 19:if(_.length>0){var r=e.lastOrUndefined(_);15===r?17===(u=o.reScanTemplateToken())?_.pop():e.Debug.assertEqual(u,16,"Should have been a template middle."):(e.Debug.assertEqual(r,18,"Should have been an open brace"),_.pop())}break;default:if(!e.isKeyword(u))break;24===l?u=72:e.isKeyword(l)&&e.isKeyword(u)&&!function(t,r){if(!e.isAccessibilityModifier(t))return!0;switch(r){case 126:case 137:case 124:case 116:return!0;default:return!1}}(l,u)&&(u=72)}}return{endOfLineState:g,spans:y}}return{getClassificationsForLine:function(t,r,n){return function(t,r){for(var n=[],a=t.spans,o=0,s=0;s=0){var _=c-o;_>0&&n.push({length:_,classification:e.TokenClass.Whitespace})}n.push({length:u,classification:i(l)}),o=c+u}var d=r.length-o;return d>0&&n.push({length:d,classification:e.TokenClass.Whitespace}),{entries:n,finalLexState:t.endOfLineState}}(s(t,r,n),t)},getEncodedLexicalClassifications:s}};var t=e.arrayToNumericMap([72,10,8,9,13,100,44,45,21,23,19,102,87],function(e){return e},function(){return!0});function r(t,r,n){switch(r){case 10:if(!t.isUnterminated())return;for(var i=t.getTokenText(),a=i.length-1,o=0;92===i.charCodeAt(a-o);)o++;if(0==(1&o))return;return 34===i.charCodeAt(0)?3:2;case 3:return t.isUnterminated()?1:void 0;default:if(e.isTemplateLiteralKind(r)){if(!t.isUnterminated())return;switch(r){case 17:return 5;case 14:return 4;default:return e.Debug.fail("Only 'NoSubstitutionTemplateLiteral's and 'TemplateTail's can be unterminated; got SyntaxKind #"+r)}}return 15===n?6:void 0}}function n(e,t,r,n,i){if(8!==n){0===e&&r>0&&(e+=r);var a=t-e;a>0&&i.push(e-r,a,n)}}function i(t){switch(t){case 1:return e.TokenClass.Comment;case 3:return e.TokenClass.Keyword;case 4:return e.TokenClass.NumberLiteral;case 25:return e.TokenClass.BigIntLiteral;case 5:return e.TokenClass.Operator;case 6:return e.TokenClass.StringLiteral;case 8:return e.TokenClass.Whitespace;case 10:return e.TokenClass.Punctuation;case 2:case 11:case 12:case 13:case 14:case 15:case 16:case 9:case 17:return e.TokenClass.Identifier;default:return}}function a(t){if(e.isKeyword(t))return 3;if(function(e){switch(e){case 40:case 42:case 43:case 38:case 39:case 46:case 47:case 48:case 28:case 30:case 31:case 32:case 94:case 93:case 119:case 33:case 34:case 35:case 36:case 49:case 51:case 50:case 54:case 55:case 70:case 69:case 71:case 66:case 67:case 68:case 60:case 61:case 62:case 64:case 65:case 59:case 27:return!0;default:return!1}}(t)||function(e){switch(e){case 38:case 39:case 53:case 52:case 44:case 45:return!0;default:return!1}}(t))return 5;if(t>=18&&t<=71)return 10;switch(t){case 8:return 4;case 9:return 25;case 10:return 6;case 13:return 7;case 7:case 3:case 2:return 1;case 5:case 4:return 8;case 72:default:return e.isTemplateLiteralKind(t)?6:2}}function o(e,t){switch(t){case 244:case 240:case 241:case 239:e.throwIfCancellationRequested()}}function s(t,r,n,i,a){var s=[];return n.forEachChild(function c(u){if(u&&e.textSpanIntersectsWith(a,u.pos,u.getFullWidth())){if(o(r,u.kind),e.isIdentifier(u)&&!e.nodeIsMissing(u)&&i.has(u.escapedText)){var l=t.getSymbolAtLocation(u),_=l&&function t(r,n,i){var a=r.getFlags();return 0==(2885600&a)?void 0:32&a?11:384&a?12:524288&a?16:1536&a?4&n||1&n&&function(t){return e.some(t.declarations,function(t){return e.isModuleDeclaration(t)&&1===e.getModuleInstanceState(t)})}(r)?14:void 0:2097152&a?t(i.getAliasedSymbol(r),n,i):2&n?64&a?13:262144&a?15:void 0:void 0}(l,e.getMeaningFromLocation(u),t);_&&function(e,t,r){s.push(e),s.push(t-e),s.push(r)}(u.getStart(n),u.getEnd(),_)}u.forEachChild(c)}}),{spans:s,endOfLineState:0}}function c(e){switch(e){case 1:return"comment";case 2:return"identifier";case 3:return"keyword";case 4:return"number";case 25:return"bigint";case 5:return"operator";case 6:return"string";case 8:return"whitespace";case 9:return"text";case 10:return"punctuation";case 11:return"class name";case 12:return"enum name";case 13:return"interface name";case 14:return"module name";case 15:return"type parameter name";case 16:return"type alias name";case 17:return"parameter name";case 18:return"doc comment tag name";case 19:return"jsx open tag name";case 20:return"jsx close tag name";case 21:return"jsx self closing tag name";case 22:return"jsx attribute";case 23:return"jsx text";case 24:return"jsx attribute string literal value";default:return}}function u(t){e.Debug.assert(t.spans.length%3==0);for(var r=t.spans,n=[],i=0;i=0),a>0){var o=n||y(t.kind,t);o&&l(i,a,o)}return!0}function y(t,r){if(e.isKeyword(t))return 3;if((28===t||30===t)&&r&&e.getTypeArgumentOrTypeParameterList(r.parent))return 10;if(e.isPunctuation(t)){if(r){var n=r.parent;if(59===t&&(237===n.kind||154===n.kind||151===n.kind||267===n.kind))return 5;if(204===n.kind||202===n.kind||203===n.kind||205===n.kind)return 5}return 10}if(8===t)return 4;if(9===t)return 25;if(10===t)return 267===r.parent.kind?24:6;if(13===t)return 6;if(e.isTemplateLiteralKind(t))return 6;if(11===t)return 23;if(72===t){if(r)switch(r.parent.kind){case 240:return r.parent.name===r?11:void 0;case 150:return r.parent.name===r?15:void 0;case 241:return r.parent.name===r?13:void 0;case 243:return r.parent.name===r?12:void 0;case 244:return r.parent.name===r?14:void 0;case 151:return r.parent.name===r?e.isThisIdentifier(r)?3:17:void 0}return 2}}function v(n){if(n&&e.decodedTextSpanIntersectsWith(i,a,n.pos,n.getFullWidth())){o(t,n.kind);for(var s=0,c=n.getChildren(r);se.parameters.length)){var a=r.getParameterType(e,t.argumentIndex);return n=n||!!(4&a.flags),c(a,i)}}),isNewIdentifier:n}}(y,i):v()}case 249:case 255:case 259:return{kind:0,paths:d(t,r,a,o,i)};default:return v()}function v(){return{kind:2,types:c(e.getContextualTypeFromParent(r,i)),isNewIdentifier:!1}}}function s(t){return t&&{kind:1,symbols:t.getApparentProperties(),hasIndexSignature:e.hasIndexSignature(t)}}function c(t,r){return void 0===r&&(r=e.createMap()),t?(t=e.skipConstraint(t)).isUnion()?e.flatMap(t.types,function(e){return c(e,r)}):!t.isStringLiteral()||1024&t.flags||!e.addToSeen(r,t.value)?e.emptyArray:[t]:e.emptyArray}function u(e,t,r){return{name:e,kind:t,extension:r}}function l(e){return u(e,"directory",void 0)}function _(t,r,n){var i=function(t,r){var n=Math.max(t.lastIndexOf(e.directorySeparator),t.lastIndexOf("\\")),i=-1!==n?n+1:0,a=t.length-i;return 0===a||e.isIdentifierText(t.substr(i,a),6)?void 0:e.createTextSpan(r+i,a)}(t,r);return n.map(function(e){return{name:e.name,kind:e.kind,extension:e.extension,span:i}})}function d(t,r,n,i,a){return _(r.text,r.getStart(t)+1,function(t,r,n,i,a){var o=e.normalizeSlashes(r.text),s=t.path,c=e.getDirectoryPath(s);return function(e){if(e&&e.length>=2&&46===e.charCodeAt(0)){var t=e.length>=3&&46===e.charCodeAt(1)?2:1,r=e.charCodeAt(t);return 47===r||92===r}return!1}(o)||!n.baseUrl&&(e.isRootedDiskPath(o)||e.isUrl(o))?function(t,r,n,i,a){var o=p(n);return n.rootDirs?function(t,r,n,i,a,o,s){var c=a.project||o.getCurrentDirectory(),u=!(o.useCaseSensitiveFileNames&&o.useCaseSensitiveFileNames()),l=function(t,r,n,i){t=t.map(function(t){return e.normalizePath(e.isRootedDiskPath(t)?t:e.combinePaths(r,t))});var a=e.firstDefined(t,function(t){return e.containsPath(t,n,r,i)?n.substr(t.length):void 0});return e.deduplicate(t.map(function(t){return e.combinePaths(t,a)}).concat([n]),e.equateStringsCaseSensitive,e.compareStringsCaseSensitive)}(t,c,n,u);return e.flatMap(l,function(e){return m(r,e,i,o,s)})}(n.rootDirs,t,r,o,n,i,a):m(t,r,o,i,a)}(o,c,n,i,s):function(t,r,n,i,a){var o=n.baseUrl,s=n.paths,c=[],l=p(n);if(o){var _=n.project||i.getCurrentDirectory(),d=e.normalizePath(e.combinePaths(_,o));m(t,d,l,i,void 0,c),s&&g(c,t,d,l.extensions,s,i)}for(var f=y(t),v=0,D=function(t,r,n){var i=n.getAmbientModules().map(function(t){return e.stripQuotes(t.name)}).filter(function(r){return e.startsWith(r,t)});if(void 0!==r){var a=e.ensureTrailingDirectorySeparator(r);return i.map(function(t){return e.removePrefix(t,a)})}return i}(t,f,a);v=e.pos&&r<=e.end});if(s){var c=t.text.slice(s.pos,r),u=D.exec(c);if(u){var l=u[1],d=u[2],f=u[3],g=e.getDirectoryPath(t.path),v="path"===d?m(f,g,p(n,!0),i,t.path):"types"===d?h(i,n,g,y(f),p(n)):e.Debug.fail();return _(f,s.pos+l.length,v)}}}(r,i,c,u);return f&&n(f)}if(e.isInString(r,i,a))return a&&e.isStringLiteralLike(a)?function(r,i,a,o,s){if(void 0!==r)switch(r.kind){case 0:return n(r.paths);case 1:var c=[];return t.getCompletionEntriesFromSymbols(r.symbols,c,i,i,a,6,o,4,s),{isGlobalCompletion:!1,isMemberCompletion:!0,isNewIdentifierLocation:r.hasIndexSignature,entries:c};case 2:var c=r.types.map(function(e){return{name:e.value,kindModifiers:"",kind:"string",sortText:"0"}});return{isGlobalCompletion:!1,isMemberCompletion:!1,isNewIdentifierLocation:r.isNewIdentifier,entries:c};default:return e.Debug.assertNever(r)}}(o(r,a,i,s,c,u),r,s,l,d):void 0},r.getStringLiteralCompletionDetails=function(r,n,a,s,c,u,l,_){if(s&&e.isStringLiteralLike(s)){var d=o(n,s,a,c,u,l);return d&&function(r,n,a,o,s,c){switch(a.kind){case 0:var u=e.find(a.paths,function(e){return e.name===r});return u&&t.createCompletionDetails(r,i(u.extension),u.kind,[e.textPart(r)]);case 1:var u=e.find(a.symbols,function(e){return e.name===r});return u&&t.createCompletionDetailsForSymbol(u,s,o,n,c);case 2:return e.find(a.types,function(e){return e.value===r})?t.createCompletionDetails(r,"","type",[e.textPart(r)]):void 0;default:return e.Debug.assertNever(a)}}(r,s,d,n,c,_)}},function(e){e[e.Paths=0]="Paths",e[e.Properties=1]="Properties",e[e.Types=2]="Types"}(a||(a={}));var D=/^(\/\/\/\s*"),kind:"class",kindModifiers:void 0,sortText:"0"};return{isGlobalCompletion:!1,isMemberCompletion:!0,isNewIdentifierLocation:!1,entries:[S]}}var N=[];if(s(t,n)){var A=m(c,N,p,t,r,n.target,i,u,o,f,b,h,v);!function(t,r,n,i,a){e.getNameTable(t).forEach(function(t,o){if(t!==r){var s=e.unescapeLeadingUnderscores(o);e.addToSeen(n,s)&&e.isIdentifierText(s,i)&&a.push({name:s,kind:"warning",kindModifiers:"",sortText:"1"})}})}(t,p.pos,A,n.target,N)}else{if((!c||0===c.length)&&0===g)return;m(c,N,p,t,r,n.target,i,u,o,f,b,h,v)}if(0!==g)for(var F=e.arrayToSet(N,function(e){return e.name}),P=0,w=function(t){return T[t]||(T[t]=C().filter(function(r){var n=e.stringToToken(r.name);switch(t){case 0:return!1;case 1:return 121===n||122;case 2:return E(n);case 3:return k(n);case 4:return e.isParameterPropertyModifier(n);case 5:return function(t){return 121===t||122===t||!e.isContextualKeyword(t)&&!E(t)}(n);case 6:return e.isTypeKeyword(n);default:return e.Debug.assertNever(t)}}))}(g);P=t.pos;case 24:return 185===n;case 57:return 186===n;case 22:return 185===n;case 20:return 274===n||re(n);case 18:return 243===n;case 28:return 240===n||209===n||241===n||242===n||e.isFunctionLikeKind(n);case 116:return 154===n&&!e.isClassLike(r.parent);case 25:return 151===n||!!r.parent&&185===r.parent.kind;case 115:case 113:case 114:return 151===n&&!e.isConstructorDeclaration(r.parent);case 119:return 253===n||257===n||251===n;case 126:case 137:return!P(t);case 76:case 84:case 110:case 90:case 105:case 92:case 111:case 77:case 117:case 140:return!0;case 40:return e.isFunctionLike(t.parent)&&!e.isMethodDeclaration(t.parent)}if(E(N(t))&&P(t))return!1;if(te(t)&&(!e.isIdentifier(t)||e.isParameterPropertyModifier(N(t))||ne(t)))return!1;switch(N(t)){case 118:case 76:case 77:case 125:case 84:case 90:case 110:case 111:case 113:case 114:case 115:case 116:case 105:case 117:return!0;case 121:return e.isPropertyDeclaration(t.parent)}return e.isDeclarationName(t)&&!e.isJsxAttribute(t.parent)&&!(e.isClassLike(t.parent)&&(t!==g||a>g.end))}(t)||function(e){if(8===e.kind){var t=e.getFullText();return"."===t.charAt(t.length-1)}return!1}(t)||function(e){if(11===e.kind)return!0;if(30===e.kind&&e.parent){if(262===e.parent.kind)return!0;if(263===e.parent.kind||261===e.parent.kind)return!!e.parent.parent&&260===e.parent.parent.kind}return!1}(t);return r("getCompletionsAtPosition: isCompletionListBlocker: "+(e.timestamp()-n)),i}(v))return void r("Returning an empty list because completion was requested in an invalid position.");var M=v.parent;if(24===v.kind)switch(S=!0,M.kind){case 189:x=(b=M).expression;break;case 148:x=M.left;break;case 244:x=M.name;break;case 183:case 214:x=M;break;default:return}else if(1===n.languageVariant){if(M&&189===M.kind&&(v=M,M=M.parent),l.parent===I)switch(l.kind){case 30:260!==l.parent.kind&&262!==l.parent.kind||(I=l);break;case 42:261===l.parent.kind&&(I=l)}switch(M.kind){case 263:42===v.kind&&(C=!0,I=v);break;case 204:if(!w(M))break;case 261:case 260:case 262:28===v.kind&&(T=!0,I=v);break;case 267:switch(g.kind){case 59:O=!0;break;case 72:M!==g.parent&&!M.initializer&&e.findChildOfKind(M,59,n)&&(O=g)}}}}var L=e.timestamp(),R=5,B=!1,j=0,J=[],z=[];if(S)!function(){R=2;var t=e.isLiteralImportTypeNode(x),r=d||t&&!x.isTypeOf||e.isPartOfTypeNode(x.parent),i=e.isInRightSideOfInternalImportEqualsDeclaration(x)||!r&&e.isPossiblyTypeArgumentPosition(v,n,c);if(e.isEntityName(x)||t){var a=e.isModuleDeclaration(x.parent);a&&(B=!0);var o=c.getSymbolAtLocation(x);if(o&&1920&(o=e.skipAlias(o,c)).flags){for(var s=e.Debug.assertEachDefined(c.getExportsOfModule(o),"getExportsOfModule() should all be defined"),u=function(e){return c.isValidPropertyAccess(t?x:x.parent,e.name)},l=function(e){return Z(e)},_=a?function(e){return!!(1920&e.flags)&&!e.declarations.every(function(e){return e.parent===x.parent})}:i?function(e){return l(e)||u(e)}:r?l:u,p=0,f=s;p0&&(J=function(t,r){if(0===r.length)return t;for(var n=e.createUnderscoreEscapedMap(),i=0,a=r;i=0&&!c(r,n[a],107);a--);return e.forEach(i(t.statement),function(e){o(t,e)&&c(r,e.getFirstToken(),73,78)}),r}function l(e){var t=s(e);if(t)switch(t.kind){case 225:case 226:case 227:case 223:case 224:return u(t);case 232:return _(t)}}function _(t){var r=[];return c(r,t.getFirstToken(),99),e.forEach(t.caseBlock.clauses,function(n){c(r,n.getFirstToken(),74,80),e.forEach(i(n),function(e){o(t,e)&&c(r,e.getFirstToken(),73)})}),r}function d(t,r){var n=[];(c(n,t.getFirstToken(),103),t.catchClause&&c(n,t.catchClause.getFirstToken(),75),t.finallyBlock)&&c(n,e.findChildOfKind(t,88,r),88);return n}function p(t,r){var i=function(t){for(var r=t;r.parent;){var n=r.parent;if(e.isFunctionBlock(n)||279===n.kind)return n;if(e.isTryStatement(n)&&n.tryBlock===r&&n.catchClause)return r;r=n}}(t);if(i){var a=[];return e.forEach(n(i),function(t){a.push(e.findChildOfKind(t,101,r))}),e.isFunctionBlock(i)&&e.forEachReturnStatement(i,function(t){a.push(e.findChildOfKind(t,97,r))}),a}}function f(t,r){var i=e.getContainingFunction(t);if(i){var a=[];return e.forEachReturnStatement(e.cast(i.body,e.isBlock),function(t){a.push(e.findChildOfKind(t,97,r))}),e.forEach(n(i.body),function(t){a.push(e.findChildOfKind(t,101,r))}),a}}function m(t){var r=e.getContainingFunction(t);if(r){var n=[];return r.modifiers&&r.modifiers.forEach(function(e){c(n,e,121)}),e.forEachChild(r,function(t){g(t,function(t){e.isAwaitExpression(t)&&c(n,t.getFirstToken(),122)})}),n}}function g(t,r){r(t),e.isFunctionLike(t)||e.isClassLike(t)||e.isInterfaceDeclaration(t)||e.isModuleDeclaration(t)||e.isTypeAliasDeclaration(t)||e.isTypeNode(t)||e.forEachChild(t,function(e){return g(e,r)})}t.getDocumentHighlights=function(t,n,i,a,o){var s=e.getTouchingPropertyName(i,a);if(s.parent&&(e.isJsxOpeningElement(s.parent)&&s.parent.tagName===s||e.isJsxClosingElement(s.parent))){var y=s.parent.parent,v=[y.openingElement,y.closingElement].map(function(e){return r(e.tagName,i)});return[{fileName:i.fileName,highlightSpans:v}]}return function(t,r,n,i,a){var o=e.arrayToSet(a,function(e){return e.fileName}),s=e.FindAllReferences.getReferenceEntriesForNode(t,r,n,a,i,void 0,o);if(s){var c=e.arrayToMultiMap(s.map(e.FindAllReferences.toHighlightSpan),function(e){return e.fileName},function(e){return e.span});return e.arrayFrom(c.entries(),function(t){var r=t[0],i=t[1];if(!o.has(r)){e.Debug.assert(n.redirectTargetsMap.has(r));var s=n.getSourceFile(r),c=e.find(a,function(e){return!!e.redirectInfo&&e.redirectInfo.redirectTarget===s});r=c.fileName,e.Debug.assert(o.has(r))}return{fileName:r,highlightSpans:i}})}}(a,s,t,n,o)||function(t,n){var i=function(t,n){switch(t.kind){case 91:case 83:return e.isIfStatement(t.parent)?function(t,n){for(var i=function(t,r){for(var n=[];e.isIfStatement(t.parent)&&t.parent.elseStatement===t;)t=t.parent;for(;;){var i=t.getChildren(r);c(n,i[0],91);for(var a=i.length-1;a>=0&&!c(n,i[a],83);a--);if(!t.elseStatement||!e.isIfStatement(t.elseStatement))break;t=t.elseStatement}return n}(t,n),a=[],o=0;o=s.end;_--)if(!e.isWhiteSpaceSingleLine(n.text.charCodeAt(_))){l=!1;break}if(l){a.push({fileName:n.fileName,textSpan:e.createTextSpanFromBounds(s.getStart(),u.end),kind:"reference"}),o++;continue}}a.push(r(i[o],n))}return a}(t.parent,n):void 0;case 97:return y(t.parent,e.isReturnStatement,f);case 101:return y(t.parent,e.isThrowStatement,p);case 103:case 75:case 88:var i=75===t.kind?t.parent.parent:t.parent;return y(i,e.isTryStatement,d);case 99:return y(t.parent,e.isSwitchStatement,_);case 74:case 80:return y(t.parent.parent.parent,e.isSwitchStatement,_);case 73:case 78:return y(t.parent,e.isBreakOrContinueStatement,l);case 89:case 107:case 82:return y(t.parent,function(t){return e.isIterationStatement(t,!0)},u);case 124:return s(e.isConstructorDeclaration,[124]);case 126:case 137:return s(e.isAccessor,[126,137]);case 122:return y(t.parent,e.isAwaitExpression,m);case 121:return v(m(t));case 117:return v(function(t){var r=e.getContainingFunction(t);if(r){var n=[];return e.forEachChild(r,function(t){g(t,function(t){e.isYieldExpression(t)&&c(n,t.getFirstToken(),117)})}),n}}(t));default:return e.isModifierKind(t.kind)&&(e.isDeclaration(t.parent)||e.isVariableStatement(t.parent))?v((a=t.kind,o=t.parent,e.mapDefined(function(t,r){var n=t.parent;switch(n.kind){case 245:case 279:case 218:case 271:case 272:return 128&r&&e.isClassDeclaration(t)?t.members.concat([t]):n.statements;case 157:case 156:case 239:return n.parameters.concat(e.isClassLike(n.parent)?n.parent.members:[]);case 240:case 209:var i=n.members;if(28&r){var a=e.find(n.members,e.isConstructorDeclaration);if(a)return i.concat(a.parameters)}else if(128&r)return i.concat([n]);return i;default:e.Debug.assertNever(n,"Invalid container kind.")}}(o,e.modifierToFlag(a)),function(t){return e.findModifier(t,a)}))):void 0}var a,o;function s(r,i){return y(t.parent,r,function(t){return e.mapDefined(t.symbol.declarations,function(t){return r(t)?e.find(t.getChildren(n),function(t){return e.contains(i,t.kind)}):void 0})})}function y(e,t,r){return t(e)?v(r(e,n)):void 0}function v(e){return e&&e.map(function(e){return r(e,n)})}}(t,n);return i&&[{fileName:n.fileName,highlightSpans:i}]}(s,i)}}(e.DocumentHighlights||(e.DocumentHighlights={}))}(c||(c={})),function(e){function t(t,n,i){void 0===n&&(n="");var a=e.createMap(),o=e.createGetCanonicalFileName(!!t);function s(e,t,r,n,i,a,o){return u(e,t,r,n,i,a,!0,o)}function c(e,t,r,n,i,a,o){return u(e,t,r,n,i,a,!1,o)}function u(t,r,n,o,s,c,u,l){var _=e.getOrUpdate(a,o,e.createMap),d=_.get(r),p=6===l?100:n.target||1;!d&&i&&((f=i.getDocument(o,r))&&(e.Debug.assert(u),d={sourceFile:f,languageServiceRefCount:0},_.set(r,d)));if(d)d.sourceFile.version!==c&&(d.sourceFile=e.updateLanguageServiceSourceFile(d.sourceFile,s,c,s.getChangeRange(d.sourceFile.scriptSnapshot)),i&&i.setDocument(o,r,d.sourceFile)),u&&d.languageServiceRefCount++;else{var f=e.createLanguageServiceSourceFile(t,s,p,c,!1,l);i&&i.setDocument(o,r,f),d={sourceFile:f,languageServiceRefCount:1},_.set(r,d)}return e.Debug.assert(0!==d.languageServiceRefCount),d.sourceFile}function l(t,r){var n=e.Debug.assertDefined(a.get(r)),i=n.get(t);i.languageServiceRefCount--,e.Debug.assert(i.languageServiceRefCount>=0),0===i.languageServiceRefCount&&n.delete(t)}return{acquireDocument:function(t,i,a,c,u){return s(t,e.toPath(t,n,o),i,r(i),a,c,u)},acquireDocumentWithKey:s,updateDocument:function(t,i,a,s,u){return c(t,e.toPath(t,n,o),i,r(i),a,s,u)},updateDocumentWithKey:c,releaseDocument:function(t,i){return l(e.toPath(t,n,o),r(i))},releaseDocumentWithKey:l,getLanguageServiceRefCounts:function(t){return e.arrayFrom(a.entries(),function(e){var r=e[0],n=e[1].get(t);return[r,n&&n.languageServiceRefCount]})},reportStats:function(){var t=e.arrayFrom(a.keys()).filter(function(e){return e&&"_"===e.charAt(0)}).map(function(e){var t=[];return a.get(e).forEach(function(e,r){t.push({name:r,refCount:e.languageServiceRefCount})}),t.sort(function(e,t){return t.refCount-e.refCount}),{bucket:e,sourceFiles:t}});return JSON.stringify(t,void 0,2)},getKeyForCompilationSettings:r}}function r(t){return e.sourceFileAffectingCompilerOptions.map(function(r){return e.getCompilerOptionValue(t,r)}).join("|")}e.createDocumentRegistry=function(e,r){return t(e,r)},e.createDocumentRegistryInternal=t}(c||(c={})),function(e){!function(t){function r(t,r){return e.forEach(279===t.kind?t.statements:t.body.statements,function(t){return r(t)||c(t)&&e.forEach(t.body&&t.body.statements,r)})}function n(t,n){if(t.externalModuleIndicator||void 0!==t.imports)for(var i=0,a=t.imports;i=0&&!(c>n.end);){var u=c+s;0!==c&&e.isIdentifierPart(a.charCodeAt(c-1),6)||u!==o&&e.isIdentifierPart(a.charCodeAt(u),6)||i.push(c),c=a.indexOf(r,c+s+1)}return i}function p(r,n){var i=r.getSourceFile(),a=n.text,o=e.mapDefined(_(i,a,r),function(r){return r===n||e.isJumpStatementTarget(r)&&e.getTargetLabel(r,a)===n?t.nodeEntry(r):void 0});return[{definition:{type:1,node:n},references:o}]}function f(e,t,r,n){return void 0===n&&(n=!0),r.cancellationToken.throwIfCancellationRequested(),m(e,e,t,r,n)}function m(e,t,r,n,i){if(n.markSearchedSymbols(t,r.allSearchSymbols))for(var a=0,o=d(t,r.text,e);a0)return n}switch(t.kind){case 279:var i=t;return e.isExternalModule(i)?'"'+e.escapeString(e.getBaseFileName(e.removeFileExtension(e.normalizePath(i.fileName))))+'"':"";case 197:case 239:case 196:case 240:case 209:return 512&e.getModifierFlags(t)?"default":O(t);case 157:return"constructor";case 161:return"new()";case 160:return"()";case 162:return"[]";default:return""}}function k(t){return{text:C(t.node,t.name),kind:e.getNodeKind(t.node),kindModifiers:w(t.node),spans:N(t),nameSpan:t.name&&P(t.name),childItems:e.map(t.children,k)}}function E(t){return{text:C(t.node,t.name),kind:e.getNodeKind(t.node),kindModifiers:w(t.node),spans:N(t),childItems:e.map(t.children,function(t){return{text:C(t.node,t.name),kind:e.getNodeKind(t.node),kindModifiers:e.getNodeModifiers(t.node),spans:N(t),childItems:s,indent:0,bolded:!1,grayed:!1}})||s,indent:t.indent,bolded:!1,grayed:!1}}function N(e){var t=[P(e.node)];if(e.additionalNodes)for(var r=0,n=e.additionalNodes;r0)return e.declarationNameToString(t.name);if(e.isVariableDeclaration(r))return e.declarationNameToString(r.name);if(e.isBinaryExpression(r)&&59===r.operatorToken.kind)return u(r.left).replace(a,"");if(e.isPropertyAssignment(r))return u(r.name);if(512&e.getModifierFlags(t))return"default";if(e.isClassLike(t))return"";if(e.isCallExpression(r)){var i=function t(r){if(e.isIdentifier(r))return r.text;if(e.isPropertyAccessExpression(r)){var n=t(r.expression),i=r.name.text;return void 0===n?i:n+"."+i}return}(r.expression);if(void 0!==i)return i+"("+e.mapDefined(r.arguments,function(t){return e.isStringLiteral(t)?t.getText(n):void 0}).join(", ")+") callback"}return""}t.getNavigationBarItems=function(t,i){r=i,n=t;try{return e.map((a=d(t),o=[],function t(r){if(function(t){switch(l(t)){case 240:case 209:case 243:case 241:case 244:case 279:case 242:case 304:case 297:return!0;case 157:case 156:case 158:case 159:case 237:return r(t);case 197:case 239:case 196:return function(e){if(!e.node.body)return!1;switch(l(e.parent)){case 245:case 279:case 156:case 157:return!0;default:return r(e)}}(t);default:return!1}function r(t){return e.some(t.children,function(e){var t=l(e);return 237!==t&&186!==t})}}(r)&&(o.push(r),r.children))for(var n=0,i=r.children;n0?i[0]:c[0],D=0===h.length?d?void 0:e.createNamedImports(e.emptyArray):0===c.length?e.createNamedImports(h):e.updateNamedImports(c[0].importClause.namedBindings,h);return l.push(o(b,d,D)),l}function a(t){if(0===t.length)return t;var r=function(e){for(var t,r=[],n=0,i=e;n...");case 261:case 262:return function(e){if(0!==e.properties.length)return a(e.getStart(r),e.getEnd(),"code")}(t.attributes)}var i,s,c;function u(t,r){return void 0===r&&(r=18),l(t,!1,!e.isArrayLiteralExpression(t.parent),r)}function l(n,i,a,s){void 0===i&&(i=!1),void 0===a&&(a=!0),void 0===s&&(s=18);var c=e.findChildOfKind(t,s,r),u=18===s?19:23,l=e.findChildOfKind(t,u,r);if(c&&l){var _=e.createTextSpanFromBounds(a?c.getFullStart():c.getStart(r),l.getEnd());return o(_,"code",e.createTextSpanFromNode(n,r),i)}}}(c,t);u&&n.push(u),s--,e.isIfStatement(c)&&c.elseStatement&&e.isIfStatement(c.elseStatement)?(p(c.expression),p(c.thenStatement),s++,p(c.elseStatement),s--):c.forEachChild(p),s++}}}(t,r,s),function(t,r){for(var i=[],a=t.getLineStarts(),s=0;s1&&o.push(a(c,u,"comment"))}}function a(t,r,n){return o(e.createTextSpanFromBounds(t,r),n)}function o(e,t,r,n,i){return void 0===r&&(r=e),void 0===n&&(n=!1),void 0===i&&(i="..."),{textSpan:e,kind:t,hintSpan:r,bannerText:i,autoCollapse:n}}}(e.OutliningElementsCollector||(e.OutliningElementsCollector={}))}(c||(c={})),function(e){var t;function r(e,t){return{kind:e,isCaseSensitive:t}}function n(e,t){var r=t.get(e);return r||t.set(e,r=v(e)),r}function i(i,a,o){var s=function(e,t){for(var r=e.length-t.length,n=function(r){if(C(t,function(t,n){return d(e.charCodeAt(n+r))===t}))return{value:r}},i=0;i<=r;i++){var a=n(i);if("object"===f(a))return a.value}return-1}(i,a.textLowerCase);if(0===s)return r(a.text.length===i.length?t.exact:t.prefix,e.startsWith(i,a.text));if(a.isLowerCase){if(-1===s)return;for(var _=0,p=n(i,o);_0)return r(t.substring,!0);if(a.characterSpans.length>0){var g=n(i,o),y=!!u(i,g,a,!1)||!u(i,g,a,!0)&&void 0;if(void 0!==y)return r(t.camelCase,y)}}}function a(e,t,r){if(C(t.totalTextChunk.text,function(e){return 32!==e&&42!==e})){var n=i(e,t.totalTextChunk,r);if(n)return n}for(var a,s=0,c=t.subWordTextChunks;s=65&&t<=90)return!0;if(t<127||!e.isUnicodeIdentifierStart(t,6))return!1;var r=String.fromCharCode(t);return r===r.toUpperCase()}function _(t){if(t>=97&&t<=122)return!0;if(t<127||!e.isUnicodeIdentifierStart(t,6))return!1;var r=String.fromCharCode(t);return r===r.toLowerCase()}function d(e){return e>=65&&e<=90?e-65+97:e<127?e:String.fromCharCode(e).toLowerCase().charCodeAt(0)}function p(e){return e>=48&&e<=57}function m(e){return l(e)||_(e)||p(e)||95===e||36===e}function g(e){var t=e.toLowerCase();return{text:e,textLowerCase:t,isLowerCase:e===t,characterSpans:y(e)}}function y(e){return h(e,!1)}function v(e){return h(e,!0)}function h(t,r){for(var n=[],i=0,a=1;a0&&(t.push(g(e.substr(r,n))),n=0)}return n>0&&t.push(g(e.substr(r,n))),t}(t)};var t});if(!n.some(function(e){return!e.subWordTextChunks.length}))return{getFullMatch:function(t,i){return function(t,r,n,i){var s;if(a(r,e.last(n),i)&&!(n.length-1>t.length)){for(var c=n.length-2,u=t.length-1;c>=0;c-=1,u-=1)s=o(s,a(t[u],n[c],i));return s}}(t,i,n,r)},getMatchForLastSegmentOfPattern:function(t){return a(t,e.last(n),r)},patternContainsDots:n.length>1}},e.breakIntoCharacterSpans=y,e.breakIntoWordSpans=v}(c||(c={})),function(e){e.preProcessFile=function(t,r,n){void 0===r&&(r=!0),void 0===n&&(n=!1);var i,a,o,s={languageVersion:1,pragmas:void 0,checkJsDirective:void 0,referencedFiles:[],typeReferenceDirectives:[],libReferenceDirectives:[],amdDependencies:[],hasNoDefaultLib:void 0,moduleName:void 0},c=[],u=0,l=!1;function _(){return a=o,18===(o=e.scanner.scan())?u++:19===o&&u--,o}function d(){var t=e.scanner.getTokenValue(),r=e.scanner.getTokenPos();return{fileName:t,pos:r,end:r+t.length}}function p(){c.push(d()),f()}function f(){0===u&&(l=!0)}function m(){var t=e.scanner.getToken();return 125===t&&(130===(t=_())&&10===(t=_())&&(i||(i=[]),i.push({ref:d(),depth:u})),!0)}function g(){if(24===a)return!1;var t=e.scanner.getToken();if(92===t){if(20===(t=_())){if(10===(t=_()))return p(),!0}else{if(10===t)return p(),!0;if(72===t||e.isKeyword(t))if(144===(t=_())){if(10===(t=_()))return p(),!0}else if(59===t){if(v(!0))return!0}else{if(27!==t)return!0;t=_()}if(18===t){for(t=_();19!==t&&1!==t;)t=_();19===t&&144===(t=_())&&10===(t=_())&&p()}else 40===t&&119===(t=_())&&(72===(t=_())||e.isKeyword(t))&&144===(t=_())&&10===(t=_())&&p()}return!0}return!1}function y(){var t=e.scanner.getToken();if(85===t){if(f(),18===(t=_())){for(t=_();19!==t&&1!==t;)t=_();19===t&&144===(t=_())&&10===(t=_())&&p()}else if(40===t)144===(t=_())&&10===(t=_())&&p();else if(92===t&&(72===(t=_())||e.isKeyword(t))&&59===(t=_())&&v(!0))return!0;return!0}return!1}function v(t){var r=t?_():e.scanner.getToken();return 134===r&&(20===(r=_())&&10===(r=_())&&p(),!0)}function h(){var t=e.scanner.getToken();if(72===t&&"define"===e.scanner.getTokenValue()){if(20!==(t=_()))return!0;if(10===(t=_())){if(27!==(t=_()))return!0;t=_()}if(22!==t)return!0;for(t=_();23!==t&&1!==t;)10===t&&p(),t=_();return!0}return!1}if(r&&function(){for(e.scanner.setText(t),_();1!==e.scanner.getToken();)m()||g()||y()||n&&(v(!1)||h())||_();e.scanner.setText(void 0)}(),e.processCommentPragmas(s,t),e.processPragmasIntoFields(s,e.noop),l){if(i)for(var b=0,D=i;b=0&&i.length>a+1),i[a+1]}(t.parent,t,r),argumentIndex:0};var n=e.findContainingList(t);return n&&{list:n,argumentIndex:function(e,t){for(var r=0,n=0,i=e.getChildren();n0&&27===e.last(r).kind&&n++;return n}(i);return 0!==a&&e.Debug.assertLessThan(a,o),{list:i,argumentIndex:a,argumentCount:o,argumentsSpan:function(t,r){var n=t.getFullStart(),i=e.skipTrivia(r.text,t.getEnd(),!1);return e.createTextSpan(n,i-n)}(i,r)}}}function o(t,r,n){var i=t.parent;if(e.isCallOrNewExpression(i)){var o=i,s=a(t,n);if(!s)return;var u=s.list,l=s.argumentIndex,_=s.argumentCount,d=s.argumentsSpan;return{isTypeParameterList:!!i.typeArguments&&i.typeArguments.pos===u.pos,invocation:{kind:0,node:o},argumentsSpan:d,argumentIndex:l,argumentCount:_}}if(e.isNoSubstitutionTemplateLiteral(t)&&e.isTaggedTemplateExpression(i))return e.isInsideTemplateLiteral(t,r,n)?c(i,0,n):void 0;if(e.isTemplateHead(t)&&193===i.parent.kind){var p=i,f=p.parent;return e.Debug.assert(206===p.kind),c(f,l=e.isInsideTemplateLiteral(t,r,n)?0:1,n)}if(e.isTemplateSpan(i)&&e.isTaggedTemplateExpression(i.parent.parent)){var m=i;f=i.parent.parent;if(e.isTemplateTail(t)&&!e.isInsideTemplateLiteral(t,r,n))return;return c(f,l=function(t,r,n,i){if(e.Debug.assert(n>=r.getStart(),"Assumed 'position' could not occur before node."),e.isTemplateLiteralToken(r))return e.isInsideTemplateLiteral(r,n,i)?0:t+2;return t+1}(m.parent.templateSpans.indexOf(m),t,r,n),n)}if(e.isJsxOpeningLikeElement(i)){var g=i.attributes.pos,y=e.skipTrivia(n.text,i.attributes.end,!1);return{isTypeParameterList:!1,invocation:{kind:0,node:i},argumentsSpan:e.createTextSpan(g,y-g),argumentIndex:0,argumentCount:1}}var v=e.getPossibleTypeArgumentsInfo(t,n);if(v){var h=v.called,b=v.nTypeArguments;return{isTypeParameterList:!0,invocation:o={kind:1,called:h},argumentsSpan:d=e.createTextSpanFromBounds(h.getStart(n),t.end),argumentIndex:b,argumentCount:b+1}}}function s(t){return e.isBinaryExpression(t.left)?s(t.left)+1:2}function c(t,r,n){var i=e.isNoSubstitutionTemplateLiteral(t.template)?1:t.template.templateSpans.length+1;return 0!==r&&e.Debug.assertLessThan(r,i),{isTypeParameterList:!1,invocation:{kind:0,node:t},argumentsSpan:function(t,r){var n=t.template,i=n.getStart(),a=n.getEnd();if(206===n.kind){var o=e.last(n.templateSpans);0===o.literal.getFullWidth()&&(a=e.skipTrivia(r.text,a,!1))}return e.createTextSpan(i,a-i)}(t,n),argumentIndex:r,argumentCount:i}}function u(t){return 0===t.kind?e.getInvokedExpression(t.node):t.called}function l(e){return 0===e.kind?e.node:1===e.kind?e.called:e.node}!function(e){e[e.Call=0]="Call",e[e.TypeArgs=1]="TypeArgs",e[e.Contextual=2]="Contextual"}(r||(r={})),t.getSignatureHelpItems=function(t,r,n,c,_){var g=t.getTypeChecker(),y=e.findTokenOnLeftOfPosition(r,n);if(y){var v=!!c&&"characterTyped"===c.kind;if(!v||!e.isInString(r,n,y)&&!e.isInComment(r,n)){var h=!!c&&"invoked"===c.kind,b=function(t,r,n,i,c){for(var u=function(t){e.Debug.assert(e.rangeContainsRange(t.parent,t),"Not a subspan",function(){return"Child: "+e.Debug.showSyntaxKind(t)+", parent: "+e.Debug.showSyntaxKind(t.parent)});var c=function(t,r,n,i){return function(t,r,n,i){var o=function(t,r,n){if(20===t.kind||27===t.kind){var i=t.parent;switch(i.kind){case 195:case 156:case 196:case 197:var o=a(t,r);if(!o)return;var c=o.argumentIndex,u=o.argumentCount,l=o.argumentsSpan,_=e.isMethodDeclaration(i)?n.getContextualTypeForObjectLiteralElement(i):n.getContextualType(i);return _&&{contextualType:_,argumentIndex:c,argumentCount:u,argumentsSpan:l};case 204:var d=function t(r){return e.isBinaryExpression(r.parent)?t(r.parent):r}(i),p=n.getContextualType(d),f=20===t.kind?0:s(i)-1,m=s(d);return p&&{contextualType:p,argumentIndex:f,argumentCount:m,argumentsSpan:e.createTextSpanFromNode(i)};default:return}}}(t,n,i);if(o){var c,u=o.contextualType,l=o.argumentIndex,_=o.argumentCount,d=o.argumentsSpan,p=u.getCallSignatures();return 1!==p.length?void 0:{isTypeParameterList:!1,invocation:{kind:2,signature:e.first(p),node:t,symbol:(c=u.symbol,"__type"===c.name&&e.firstDefined(c.declarations,function(t){return e.isFunctionTypeNode(t)?t.parent.symbol:void 0})||c)},argumentsSpan:d,argumentIndex:l,argumentCount:_}}}(t,0,n,i)||o(t,r,n)}(t,r,n,i);if(c)return{value:c}},l=t;c||!e.isBlock(l)&&!e.isSourceFile(l);l=l.parent){var _=u(l);if("object"===f(_))return _.value}}(y,n,r,g,h);if(b){_.throwIfCancellationRequested();var D=function(t,r,n,a,o){var s=t.invocation,c=t.argumentCount;switch(s.kind){case 0:if(o&&!function(t,r,n){if(!e.isCallOrNewExpression(r))return!1;var a=r.getChildren(n);switch(t.kind){case 20:return e.contains(a,t);case 27:var o=e.findContainingList(t);return!!o&&e.contains(a,o);case 28:return i(t,n,r.expression);default:return!1}}(a,s.node,n))return;var u=[],l=r.getResolvedSignatureForSignatureHelp(s.node,u,c);return 0===u.length?void 0:{kind:0,candidates:u,resolvedSignature:l};case 1:var _=s.called;if(o&&!i(a,n,e.isIdentifier(_)?_.parent:_))return;var u=e.getPossibleGenericSignatures(_,c,r);if(0!==u.length)return{kind:0,candidates:u,resolvedSignature:e.first(u)};var d=r.getSymbolAtLocation(_);return d&&{kind:1,symbol:d};case 2:return{kind:0,candidates:[s.signature],resolvedSignature:s.signature};default:return e.Debug.assertNever(s)}}(b,g,r,y,v);return _.throwIfCancellationRequested(),D?g.runWithCancellationToken(_,function(t){return 0===D.kind?d(D.candidates,D.resolvedSignature,b,r,t):function(t,r,n,i){var a=r.argumentCount,o=r.argumentsSpan,s=r.invocation,c=r.argumentIndex,u=i.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(t);return u?{items:[function(t,r,n,i,a){var o=e.symbolToDisplayParts(n,t),s=e.createPrinter({removeComments:!0}),c=r.map(function(e){return m(e,n,i,a,s)}),u=t.getDocumentationComment(n),l=t.getJsDocTags();return{isVariadic:!1,prefixDisplayParts:o.concat([e.punctuationPart(28)]),suffixDisplayParts:[e.punctuationPart(30)],separatorDisplayParts:p,parameters:c,documentation:u,tags:l}}(t,u,i,l(s),n)],applicableSpan:o,selectedItemIndex:0,argumentIndex:c,argumentCount:a}:void 0}(D.symbol,b,r,t)}):e.isSourceFileJS(r)?function(t,r,n){if(2!==t.invocation.kind){var i=u(t.invocation),a=e.isIdentifier(i)?i.text:e.isPropertyAccessExpression(i)?i.name.text:void 0,o=r.getTypeChecker();return void 0===a?void 0:e.firstDefined(r.getSourceFiles(),function(r){return e.firstDefined(r.getNamedDeclarations().get(a),function(e){var i=e.symbol&&o.getTypeOfSymbolAtLocation(e.symbol,e),a=i&&i.getCallSignatures();if(a&&a.length)return o.runWithCancellationToken(n,function(e){return d(a,a[0],t,r,e)})})})}}(b,t,_):void 0}}}},function(e){e[e.Candidate=0]="Candidate",e[e.Type=1]="Type"}(n||(n={})),t.getArgumentInfoForCompletions=function(e,t,r){var n=o(e,t,r);return!n||n.isTypeParameterList||0!==n.invocation.kind?void 0:{invocation:n.invocation.node,argumentCount:n.argumentCount,argumentIndex:n.argumentIndex}};var _=70246400;function d(t,r,n,i,a){var o=n.isTypeParameterList,s=n.argumentCount,c=n.argumentsSpan,d=n.invocation,f=n.argumentIndex,g=l(d),y=2===d.kind?d.symbol:a.getSymbolAtLocation(u(d)),v=y?e.symbolToDisplayParts(a,y,void 0,void 0):e.emptyArray,h=t.map(function(t){return function(t,r,n,i,a,o){var s=(n?function(t,r,n,i){var a=(t.target||t).typeParameters,o=e.createPrinter({removeComments:!0}),s=(a||e.emptyArray).map(function(e){return m(e,r,n,i,o)}),c=e.mapToDisplayParts(function(a){var s=t.thisParameter?[r.symbolToParameterDeclaration(t.thisParameter,n,_)]:[],c=e.createNodeArray(s.concat(t.parameters.map(function(e){return r.symbolToParameterDeclaration(e,n,_)})));o.writeList(2576,c,i,a)});return{isVariadic:!1,parameters:s,prefix:[e.punctuationPart(28)],suffix:[e.punctuationPart(30)].concat(c)}}:function(t,r,n,i){var a=t.hasRestParameter,o=e.createPrinter({removeComments:!0}),s=e.mapToDisplayParts(function(a){if(t.typeParameters&&t.typeParameters.length){var s=e.createNodeArray(t.typeParameters.map(function(e){return r.typeParameterToDeclaration(e,n)}));o.writeList(53776,s,i,a)}}),c=t.parameters.map(function(t){return function(t,r,n,i,a){var o=e.mapToDisplayParts(function(e){var o=r.symbolToParameterDeclaration(t,n,_);a.writeNode(4,o,i,e)}),s=r.isOptionalParameter(t.valueDeclaration);return{name:t.name,documentation:t.getDocumentationComment(r),displayParts:o,isOptional:s}}(t,r,n,i,o)});return{isVariadic:a,parameters:c,prefix:s.concat([e.punctuationPart(20)]),suffix:[e.punctuationPart(21)]}})(t,i,a,o),c=s.isVariadic,u=s.parameters,l=s.prefix,d=s.suffix,f=r.concat(l),g=d.concat(function(t,r,n){return e.mapToDisplayParts(function(e){e.writePunctuation(":"),e.writeSpace(" ");var i=n.getTypePredicateOfSignature(t);i?n.writeTypePredicate(i,r,void 0,e):n.writeType(n.getReturnTypeOfSignature(t),r,void 0,e)})}(t,a,i)),y=t.getDocumentationComment(i),v=t.getJsDocTags();return{isVariadic:c,prefixDisplayParts:f,suffixDisplayParts:g,separatorDisplayParts:p,parameters:u,documentation:y,tags:v}}(t,v,o,a,g,i)});0!==f&&e.Debug.assertLessThan(f,s);var b=t.indexOf(r);return e.Debug.assert(-1!==b),{items:h,applicableSpan:c,selectedItemIndex:b,argumentIndex:f,argumentCount:s}}var p=[e.punctuationPart(27),e.spacePart()];function m(t,r,n,i,a){var o=e.mapToDisplayParts(function(e){var o=r.typeParameterToDeclaration(t,n);a.writeNode(4,o,i,e)});return{name:t.symbol.name,documentation:t.symbol.getDocumentationComment(r),displayParts:o,isOptional:!1}}}(e.SignatureHelp||(e.SignatureHelp={}))}(c||(c={})),function(e){var t=/^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;e.getSourceMapper=function(r,n,i,a,o){var s,c=e.createGetCanonicalFileName(r);return{tryGetSourcePosition:function t(r){if(e.isDeclarationFileName(r.fileName)){var n=d(r.fileName);if(n){var i=_(r.fileName,n).getSourcePosition(r);return i===r?void 0:t(i)||i}}},tryGetGeneratedPosition:function(t){var r=o(),i=r.getCompilerOptions(),a=i.outFile||i.out,s=a?e.removeFileExtension(a)+".d.ts":e.getDeclarationEmitOutputFilePathWorker(t.fileName,r.getCompilerOptions(),n,r.getCommonSourceDirectory(),c);if(void 0!==s){var u=d(s);if(u){var l=_(s,u).getGeneratedPosition(t);return l===t?void 0:l}}},toLineColumnOffset:function(e,t){return d(e).getLineAndCharacterOfPosition(t)},clearCache:function(){s=function(t){var r=e.createMap();return{get:function(n){if(r.has(n))return r.get(n);if(t.fileExists&&t.readFile&&t.fileExists(n)){var i=t.readFile(n),a={text:i,lineMap:void 0,getLineAndCharacterOfPosition:function(t){return e.computeLineAndCharacterOfPosition(e.getLineStarts(this),t)}};return r.set(n,a),a}}}}(a)}};function u(t){return e.toPath(t,n,c)}function l(t,r,n){var a=e.tryParseRawSourceMap(r);if(!(a&&a.sources&&a.file&&a.mappings))return t.sourceMapper=e.identitySourceMapConsumer;var u=o();return t.sourceMapper=e.createDocumentPositionMapper({getSourceFileLike:function(e){var t=u&&u.getSourceFileByPath(e);return void 0===t||t.resolvedPath!==e?s.get(e):t},getCanonicalFileName:c,log:i},a,n)}function _(r,n){if(!a.readFile||!a.fileExists)return n.sourceMapper=e.identitySourceMapConsumer;if(n.sourceMapper)return n.sourceMapper;var i=function(t){var r=s.get(u(t));if(r)return e.tryGetSourceMappingURL(r.text,e.getLineStarts(r))}(r);if(i){var o=t.exec(i);if(o){if(o[1]){var _=o[1];return l(n,e.base64decode(e.sys,_),r)}i=void 0}}var d=[];i&&d.push(i),d.push(r+".map");for(var p=0,f=d;p0&&s.push(e.createDiagnosticForNode(e.isVariableDeclaration(i.parent)?i.parent.name:i,e.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration))}else{if(e.isVariableStatement(i)&&i.parent===n&&2&i.declarationList.flags&&1===i.declarationList.declarations.length){var _=i.declarationList.declarations[0].initializer;_&&e.isRequireCall(_,!0)&&s.push(e.createDiagnosticForNode(_,e.Diagnostics.require_call_may_be_converted_to_an_import))}e.codefix.parameterShouldGetTypeFromJSDoc(i)&&s.push(e.createDiagnosticForNode(i.name||i,e.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types))}e.isFunctionLikeDeclaration(i)&&function(t,n,i){var a;!e.isAsyncFunction(t)&&t.body&&e.isBlock(t.body)&&(a=t.body,e.forEachReturnStatement(a,r))&&function(e,t){var r=t.getTypeAtLocation(e),n=t.getSignaturesOfType(r,0),i=n.length?t.getReturnTypeOfSignature(n[0]):void 0;return!!i&&!!t.getPromisedTypeOfPromise(i)}(t,n)&&i.push(e.createDiagnosticForNode(!t.name&&e.isVariableDeclaration(t.parent)&&e.isIdentifier(t.parent.name)?t.parent.name:t,e.Diagnostics.This_may_be_converted_to_an_async_function))}(i,c,s),i.forEachChild(t)}(n),e.getAllowSyntheticDefaultImports(i.getCompilerOptions()))for(var l=0,_=n.imports;l<_.length;l++){var d=_[l],p=t(e.importFromModuleSpecifier(d));if(p){var f=e.getResolvedModule(n,d.text),m=f&&i.getSourceFile(f.resolvedFileName);m&&m.externalModuleIndicator&&e.isExportAssignment(m.externalModuleIndicator)&&m.externalModuleIndicator.isExportEquals&&s.push(e.createDiagnosticForNode(p,e.Diagnostics.Import_may_be_converted_to_a_default_import))}}return e.addRange(s,n.bindSuggestionDiagnostics),e.addRange(s,i.getSuggestionDiagnostics(n,a)),s.sort(function(e,t){return e.start-t.start})},e.isReturnStatementWithFixablePromiseHandler=r,e.isFixablePromiseHandler=n}(c||(c={})),function(e){!function(t){function r(t,r,i){var a=n(t,r,i);if(""!==a)return a;var o=e.getCombinedLocalAndExportSymbolFlags(r);return 32&o?e.getDeclarationOfKind(r,209)?"local class":"class":384&o?"enum":524288&o?"type":64&o?"interface":262144&o?"type parameter":262144&o?"type parameter":8&o?"enum member":2097152&o?"alias":1536&o?"module":a}function n(t,r,n){var a=t.getRootSymbols(r);if(1===a.length&&8192&e.first(a).flags&&0!==t.getTypeOfSymbolAtLocation(r,n).getNonNullableType().getCallSignatures().length)return"method";if(t.isUndefinedSymbol(r))return"var";if(t.isArgumentsSymbol(r))return"local var";if(100===n.kind&&e.isExpression(n))return"parameter";var o=e.getCombinedLocalAndExportSymbolFlags(r);if(3&o)return e.isFirstDeclarationOfSymbolParameter(r)?"parameter":r.valueDeclaration&&e.isVarConst(r.valueDeclaration)?"const":e.forEach(r.declarations,e.isLet)?"let":i(r)?"local var":"var";if(16&o)return i(r)?"local function":"function";if(32768&o)return"getter";if(65536&o)return"setter";if(8192&o)return"method";if(16384&o)return"constructor";if(4&o){if(33554432&o&&6&r.checkFlags){var s=e.forEach(t.getRootSymbols(r),function(t){var r=t.getFlags();if(98311&r)return"property";e.Debug.assert(!!(8208&r))});return s||(t.getTypeOfSymbolAtLocation(r,n).getCallSignatures().length?"method":"property")}switch(n.parent&&n.parent.kind){case 262:case 260:case 261:return 72===n.kind?"property":"JSX attribute";case 267:return"JSX attribute";default:return"property"}}return""}function i(t){return!t.parent&&e.forEach(t.declarations,function(t){if(196===t.kind)return!0;if(237!==t.kind&&239!==t.kind)return!1;for(var r=t.parent;!e.isFunctionBlock(r);r=r.parent)if(279===r.kind||245===r.kind)return!1;return!0})}t.getSymbolKind=r,t.getSymbolModifiers=function(t){var r=t&&t.declarations&&t.declarations.length>0?e.getNodeModifiers(t.declarations[0]):"",n=t&&16777216&t.flags?"optional":"";return r&&n?r+","+n:r||n},t.getSymbolDisplayPartsDocumentationAndSymbolKind=function t(i,a,o,s,c,u,l){void 0===u&&(u=e.getMeaningFromLocation(c));var _,d,p,f,m,g,y=[],v=e.getCombinedLocalAndExportSymbolFlags(a),h=1&u?n(i,a,c):"",b=!1,D=100===c.kind&&e.isInExpressionContext(c);if(100===c.kind&&!D)return{displayParts:[e.keywordPart(100)],documentation:[],symbolKind:"primitive type",tags:void 0};if(""!==h||32&v||2097152&v){"getter"!==h&&"setter"!==h||(h="property");var x=void 0;if(p=D?i.getTypeAtLocation(c):i.getTypeOfSymbolAtLocation(a.exportSymbol||a,c),c.parent&&189===c.parent.kind){var S=c.parent.name;(S===c||S&&0===S.getFullWidth())&&(c=c.parent)}var T=void 0;if(e.isCallOrNewExpression(c)?T=c:e.isCallExpressionTarget(c)||e.isNewExpressionTarget(c)?T=c.parent:c.parent&&e.isJsxOpeningLikeElement(c.parent)&&e.isFunctionLike(a.valueDeclaration)&&(T=c.parent),T){x=i.getResolvedSignature(T,[]);var C=192===T.kind||e.isCallExpression(T)&&98===T.expression.kind,k=C?p.getConstructSignatures():p.getCallSignatures();if(e.contains(k,x.target)||e.contains(k,x)||(x=k.length?k[0]:void 0),x){switch(C&&32&v?(h="constructor",H(p.symbol,h)):2097152&v?(G(h="alias"),y.push(e.spacePart()),C&&(y.push(e.keywordPart(95)),y.push(e.spacePart())),W(a)):H(a,h),h){case"JSX attribute":case"property":case"var":case"const":case"let":case"parameter":case"local var":y.push(e.punctuationPart(57)),y.push(e.spacePart()),16&e.getObjectFlags(p)||!p.symbol||(e.addRange(y,e.symbolToDisplayParts(i,p.symbol,s,void 0,5)),y.push(e.lineBreakPart())),C&&(y.push(e.keywordPart(95)),y.push(e.spacePart())),Y(x,k,262144);break;default:Y(x,k)}b=!0}}else if(e.isNameOfFunctionDeclaration(c)&&!(98304&v)||124===c.kind&&157===c.parent.kind){var E=c.parent;e.find(a.declarations,function(e){return e===(124===c.kind?E.parent:E)})&&(k=157===E.kind?p.getNonNullableType().getConstructSignatures():p.getNonNullableType().getCallSignatures(),x=i.isImplementationOfOverload(E)?k[0]:i.getSignatureFromDeclaration(E),157===E.kind?(h="constructor",H(p.symbol,h)):H(160!==E.kind||2048&p.symbol.flags||4096&p.symbol.flags?a:p.symbol,h),Y(x,k),b=!0)}}if(32&v&&!b&&!D&&(V(),e.getDeclarationOfKind(a,209)?G("local class"):y.push(e.keywordPart(76)),y.push(e.spacePart()),W(a),X(a,o)),64&v&&2&u&&(U(),y.push(e.keywordPart(110)),y.push(e.spacePart()),W(a),X(a,o)),524288&v&&2&u&&(U(),y.push(e.keywordPart(140)),y.push(e.spacePart()),W(a),X(a,o),y.push(e.spacePart()),y.push(e.operatorPart(59)),y.push(e.spacePart()),e.addRange(y,e.typeToDisplayParts(i,i.getDeclaredTypeOfSymbol(a),s,8388608))),384&v&&(U(),e.some(a.declarations,function(t){return e.isEnumDeclaration(t)&&e.isEnumConst(t)})&&(y.push(e.keywordPart(77)),y.push(e.spacePart())),y.push(e.keywordPart(84)),y.push(e.spacePart()),W(a)),1536&v){U();var N=(J=e.getDeclarationOfKind(a,244))&&J.name&&72===J.name.kind;y.push(e.keywordPart(N?131:130)),y.push(e.spacePart()),W(a)}if(262144&v&&2&u)if(U(),y.push(e.punctuationPart(20)),y.push(e.textPart("type parameter")),y.push(e.punctuationPart(21)),y.push(e.spacePart()),W(a),a.parent)q(),W(a.parent,s),X(a.parent,s);else{var A=e.getDeclarationOfKind(a,150);if(void 0===A)return e.Debug.fail();(J=A.parent)&&(e.isFunctionLikeKind(J.kind)?(q(),x=i.getSignatureFromDeclaration(J),161===J.kind?(y.push(e.keywordPart(95)),y.push(e.spacePart())):160!==J.kind&&J.name&&W(J.symbol),e.addRange(y,e.signatureToDisplayParts(i,x,o,32))):242===J.kind&&(q(),y.push(e.keywordPart(140)),y.push(e.spacePart()),W(J.symbol),X(J.symbol,o)))}if(8&v&&(h="enum member",H(a,"enum member"),278===(J=a.declarations[0]).kind)){var F=i.getConstantValue(J);void 0!==F&&(y.push(e.spacePart()),y.push(e.operatorPart(59)),y.push(e.spacePart()),y.push(e.displayPart(e.getTextOfConstantValue(F),"number"==typeof F?e.SymbolDisplayPartKind.numericLiteral:e.SymbolDisplayPartKind.stringLiteral)))}if(2097152&v){if(U(),!b){var P=i.getAliasedSymbol(a);if(P!==a&&P.declarations&&P.declarations.length>0){var w=P.declarations[0],O=e.getNameOfDeclaration(w);if(O){var I=e.isModuleWithStringLiteralName(w)&&e.hasModifier(w,2),M="default"!==a.name&&!I,L=t(i,P,e.getSourceFileOfNode(w),w,O,u,M?a:P);y.push.apply(y,L.displayParts),y.push(e.lineBreakPart()),m=L.documentation,g=L.tags}}}switch(a.declarations[0].kind){case 247:y.push(e.keywordPart(85)),y.push(e.spacePart()),y.push(e.keywordPart(131));break;case 254:y.push(e.keywordPart(85)),y.push(e.spacePart()),y.push(e.keywordPart(a.declarations[0].isExportEquals?59:80));break;case 257:y.push(e.keywordPart(85));break;default:y.push(e.keywordPart(92))}y.push(e.spacePart()),W(a),e.forEach(a.declarations,function(t){if(248===t.kind){var r=t;if(e.isExternalModuleImportEqualsDeclaration(r))y.push(e.spacePart()),y.push(e.operatorPart(59)),y.push(e.spacePart()),y.push(e.keywordPart(134)),y.push(e.punctuationPart(20)),y.push(e.displayPart(e.getTextOfNode(e.getExternalModuleImportEqualsDeclarationExpression(r)),e.SymbolDisplayPartKind.stringLiteral)),y.push(e.punctuationPart(21));else{var n=i.getSymbolAtLocation(r.moduleReference);n&&(y.push(e.spacePart()),y.push(e.operatorPart(59)),y.push(e.spacePart()),W(n,s))}return!0}})}if(!b)if(""!==h){if(p)if(D?(U(),y.push(e.keywordPart(100))):H(a,h),"property"===h||"JSX attribute"===h||3&v||"local var"===h||D)if(y.push(e.punctuationPart(57)),y.push(e.spacePart()),p.symbol&&262144&p.symbol.flags){var R=e.mapToDisplayParts(function(t){var r=i.typeParameterToDeclaration(p,s);K().writeNode(4,r,e.getSourceFileOfNode(e.getParseTreeNode(s)),t)});e.addRange(y,R)}else e.addRange(y,e.typeToDisplayParts(i,p,s));else(16&v||8192&v||16384&v||131072&v||98304&v||"method"===h)&&(k=p.getNonNullableType().getCallSignatures()).length&&Y(k[0],k)}else h=r(i,a,c);if(!_&&(_=a.getDocumentationComment(i),d=a.getJsDocTags(),0===_.length&&4&v&&a.parent&&e.forEach(a.parent.declarations,function(e){return 279===e.kind})))for(var B=0,j=a.declarations;B0))break}}return 0===_.length&&m&&(_=m),0===d.length&&g&&(d=g),{displayParts:y,documentation:_,symbolKind:h,tags:0===d.length?void 0:d};function K(){return f||(f=e.createPrinter({removeComments:!0})),f}function U(){y.length&&y.push(e.lineBreakPart()),V()}function V(){l&&(G("alias"),y.push(e.spacePart()))}function q(){y.push(e.spacePart()),y.push(e.keywordPart(93)),y.push(e.spacePart())}function W(t,r){l&&t===a&&(t=l);var n=e.symbolToDisplayParts(i,t,r||o,void 0,7);e.addRange(y,n),16777216&a.flags&&y.push(e.punctuationPart(56))}function H(t,r){U(),r&&(G(r),t&&!e.some(t.declarations,function(t){return e.isArrowFunction(t)||(e.isFunctionExpression(t)||e.isClassExpression(t))&&!t.name})&&(y.push(e.spacePart()),W(t)))}function G(t){switch(t){case"var":case"function":case"let":case"const":case"constructor":return void y.push(e.textOrKeywordPart(t));default:return y.push(e.punctuationPart(20)),y.push(e.textOrKeywordPart(t)),void y.push(e.punctuationPart(21))}}function Y(t,r,n){void 0===n&&(n=0),e.addRange(y,e.signatureToDisplayParts(i,t,s,32|n)),r.length>1&&(y.push(e.spacePart()),y.push(e.punctuationPart(20)),y.push(e.operatorPart(38)),y.push(e.displayPart((r.length-1).toString(),e.SymbolDisplayPartKind.numericLiteral)),y.push(e.spacePart()),y.push(e.textPart(2===r.length?"overload":"overloads")),y.push(e.punctuationPart(21)));var a=t.getDocumentationComment(i);_=0===a.length?void 0:a,d=t.getJsDocTags()}function X(t,r){var n=e.mapToDisplayParts(function(n){var a=i.symbolToTypeParameterDeclarations(t,r);K().writeList(53776,a,e.getSourceFileOfNode(e.getParseTreeNode(r)),n)});e.addRange(y,n)}}}(e.SymbolDisplay||(e.SymbolDisplay={}))}(c||(c={})),function(e){function t(t,r){var i=[],a=r.compilerOptions?n(r.compilerOptions,i):e.getDefaultCompilerOptions();a.isolatedModules=!0,a.suppressOutputPathCheck=!0,a.allowNonTsExtensions=!0,a.noLib=!0,a.lib=void 0,a.types=void 0,a.noEmit=void 0,a.noEmitOnError=void 0,a.paths=void 0,a.rootDirs=void 0,a.declaration=void 0,a.composite=void 0,a.declarationDir=void 0,a.out=void 0,a.outFile=void 0,a.noResolve=!0;var o=r.fileName||(a.jsx?"module.tsx":"module.ts"),s=e.createSourceFile(o,t,a.target);r.moduleName&&(s.moduleName=r.moduleName),r.renamedDependencies&&(s.renamedDependencies=e.createMapFromTemplate(r.renamedDependencies));var c,u,l=e.getNewLineCharacter(a),_={getSourceFile:function(t){return t===e.normalizePath(o)?s:void 0},writeFile:function(t,r){e.fileExtensionIs(t,".map")?(e.Debug.assertEqual(u,void 0,"Unexpected multiple source map outputs, file:",t),u=r):(e.Debug.assertEqual(c,void 0,"Unexpected multiple outputs, file:",t),c=r)},getDefaultLibFileName:function(){return"lib.d.ts"},useCaseSensitiveFileNames:function(){return!1},getCanonicalFileName:function(e){return e},getCurrentDirectory:function(){return""},getNewLine:function(){return l},fileExists:function(e){return e===o},readFile:function(){return""},directoryExists:function(){return!0},getDirectories:function(){return[]}},d=e.createProgram([o],a,_);return r.reportDiagnostics&&(e.addRange(i,d.getSyntacticDiagnostics(s)),e.addRange(i,d.getOptionsDiagnostics())),d.emit(void 0,void 0,void 0,void 0,r.transformers),void 0===c?e.Debug.fail("Output generation failed"):{outputText:c,diagnostics:i,sourceMapText:u}}var r;function n(t,n){r=r||e.filter(e.optionDeclarations,function(t){return"object"===f(t.type)&&!e.forEachEntry(t.type,function(e){return"number"!=typeof e})}),t=e.cloneCompilerOptions(t);for(var i=function(r){if(!e.hasProperty(t,r.name))return"continue";var i=t[r.name];e.isString(i)?t[r.name]=e.parseCustomTypeOption(r,i,n):e.forEachEntry(r.type,function(e){return e===i})||n.push(e.createCompilerDiagnosticForInvalidCustomType(r))},a=0,o=r;a>=a;return r}(f,p),0,n),c[u]=(d=1+((l=f)>>(_=p)&o),e.Debug.assert((d&o)===d,"Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."),l&~(o<<_)|d<<_)}!function(e){e[e.IgnoreRulesSpecific=0]="IgnoreRulesSpecific",e[e.IgnoreRulesAny=1*a]="IgnoreRulesAny",e[e.ContextRulesSpecific=2*a]="ContextRulesSpecific",e[e.ContextRulesAny=3*a]="ContextRulesAny",e[e.NoContextRulesSpecific=4*a]="NoContextRulesSpecific",e[e.NoContextRulesAny=5*a]="NoContextRulesAny"}(i||(i={}))}(e.formatting||(e.formatting={}))}(c||(c={})),function(e){!function(t){var r,n,i,a,o;function s(t,r,n){var i=e.findPrecedingToken(t,n);return i&&i.kind===r&&t===i.getEnd()?i:void 0}function c(e){for(var t=e;t&&t.parent&&t.parent.end===e.end&&!u(t.parent,t);)t=t.parent;return t}function u(t,r){switch(t.kind){case 240:case 241:return e.rangeContainsRange(t.members,r);case 244:var n=t.body;return!!n&&245===n.kind&&e.rangeContainsRange(n.statements,r);case 279:case 218:case 245:return e.rangeContainsRange(t.statements,r);case 274:return e.rangeContainsRange(t.block.statements,r)}return!1}function l(t,r,n,i){return t?_({pos:e.getLineStartPositionForPosition(t.getStart(r),r),end:t.end},r,n,i):[]}function _(r,n,i,a){var o=function(t,r){return function n(i){var a=e.forEachChild(i,function(n){return e.startEndContainsRange(n.getStart(r),n.end,t)&&n});if(a){var o=n(a);if(o)return o}return i}(r)}(r,n);return t.getFormattingScanner(n.text,n.languageVariant,function(t,r,n){var i=t.getStart(n);if(i===r.pos&&t.end===r.end)return i;var a=e.findPrecedingToken(r.pos,n);return a?a.end>=r.pos?t.pos:a.end:t.pos}(o,r,n),r.end,function(s){return d(r,o,t.SmartIndenter.getIndentationForNode(o,r,n,i.options),function(e,r,n){for(var i,a=-1;e;){var o=n.getLineAndCharacterOfPosition(e.getStart(n)).line;if(-1!==a&&o!==a)break;if(t.SmartIndenter.shouldIndentChildNode(r,e,i,n))return r.indentSize;a=o,i=e,e=e.parent}return 0}(o,i.options,n),s,i,a,function(t,r){if(!t.length)return a;var n=t.filter(function(t){return e.rangeOverlapsWithStartEnd(r,t.start,t.start+t.length)}).sort(function(e,t){return e.start-t.start});if(!n.length)return a;var i=0;return function(t){for(;;){if(i>=n.length)return!1;var r=n[i];if(t.end<=r.start)return!1;if(e.startEndOverlapsWithStartEnd(t.pos,t.end,r.start,r.start+r.length))return!0;i++}};function a(){return!1}}(n.parseDiagnostics,r),n)})}function d(r,n,i,a,o,s,c,u,l){var _,d,f,m,g=s.options,y=s.getRule,v=new t.FormattingContext(l,c,g),h=-1,b=[];if(o.advance(),o.isOnToken()){var D=l.getLineAndCharacterOfPosition(n.getStart(l)).line,x=D;n.decorators&&(x=l.getLineAndCharacterOfPosition(e.getNonDecoratorTokenPosOfNode(n,l)).line),function n(i,a,s,c,d,p){if(!e.rangeOverlapsWithStartEnd(r,i.getStart(l),i.getEnd()))return;var f=T(i,s,d,p);var y=a;e.forEachChild(i,function(e){b(e,-1,i,f,s,c,!1)},function(r){!function(r,n,a,s){e.Debug.assert(e.isNodeArray(r));var c=function(e,t){switch(e.kind){case 157:case 239:case 196:case 156:case 155:case 197:if(e.typeParameters===t)return 28;if(e.parameters===t)return 20;break;case 191:case 192:if(e.typeArguments===t)return 28;if(e.arguments===t)return 20;break;case 164:if(e.typeArguments===t)return 28;break;case 168:return 18}return 0}(n,r),u=s,_=a;if(0!==c)for(;o.isOnToken();){var d=o.readTokenInfo(n);if(d.token.end>r.pos)break;if(d.token.kind===c){_=l.getLineAndCharacterOfPosition(d.token.pos).line,D(d,n,s,n);var p=void 0;if(-1!==h)p=h;else{var f=e.getLineStartPositionForPosition(d.token.pos,l);p=t.SmartIndenter.findFirstNonWhitespaceColumn(f,d.token.pos,l,g)}u=T(n,a,p,g.indentSize)}else D(d,n,s,n)}for(var m=-1,y=0;yi.end)break;D(v,i,f,i)}function b(a,s,c,u,_,d,p,f){var v=a.getStart(l),b=l.getLineAndCharacterOfPosition(v).line,x=b;a.decorators&&(x=l.getLineAndCharacterOfPosition(e.getNonDecoratorTokenPosOfNode(a,l)).line);var S=-1;if(p&&e.rangeContainsRange(r,c)&&-1!==(S=function(r,n,i,a,o){if(e.rangeOverlapsWithStartEnd(a,r,n)||e.rangeContainsStartEnd(a,r,n)){if(-1!==o)return o}else{var s=l.getLineAndCharacterOfPosition(r).line,c=e.getLineStartPositionForPosition(r,l),u=t.SmartIndenter.findFirstNonWhitespaceColumn(c,r,l,g);if(s!==i||r===u){var _=t.SmartIndenter.getBaseIndentation(g);return _>u?_:u}}return-1}(v,a.end,_,r,s))&&(s=S),!e.rangeOverlapsWithStartEnd(r,a.pos,a.end))return a.endv)break;D(T,i,u,i)}if(!o.isOnToken())return s;if(e.isToken(a)&&11!==a.kind){var T=o.readTokenInfo(a);return e.Debug.assert(T.token.end===a.end,"Token end is child end"),D(T,i,u,a),s}var C=152===a.kind?b:d,k=function(e,r,n,i,a,o){var s=t.SmartIndenter.shouldIndentChildNode(g,e)?g.indentSize:0;return o===r?{indentation:r===m?h:a.getIndentation(),delta:Math.min(g.indentSize,a.getDelta(e)+s)}:-1===n?20===e.kind&&r===m?{indentation:h,delta:a.getDelta(e)}:t.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(i,e,r,l)?{indentation:a.getIndentation(),delta:s}:{indentation:a.getIndentation()+a.getDelta(e),delta:s}:{indentation:n,delta:s}}(a,b,S,i,u,C);if(n(a,y,b,x,k.indentation,k.delta),11===a.kind){var E={pos:a.getStart(),end:a.getEnd()};A(E,k.indentation,!0,!1)}return y=i,f&&187===c.kind&&-1===s&&(s=k.indentation),s}function D(t,n,i,a,s){e.Debug.assert(e.rangeContainsRange(n,t.token));var c=o.lastTrailingTriviaWasNewLine(),d=!1;t.leadingTrivia&&k(t.leadingTrivia,n,y,i);var p=0,f=e.rangeContainsRange(r,t.token),g=l.getLineAndCharacterOfPosition(t.token.pos);if(f){var v=u(t.token),b=_;if(p=E(t.token,g,n,y,i),!v)if(0===p){var D=b&&l.getLineAndCharacterOfPosition(b.end).line;d=c&&g.line!==D}else d=1===p}if(t.trailingTrivia&&k(t.trailingTrivia,n,y,i),d){var x=f&&!u(t.token)?i.getIndentationForToken(g.line,t.token.kind,a,!!s):-1,S=!0;if(t.leadingTrivia){var T=i.getIndentationForComment(t.token.kind,x,a);S=C(t.leadingTrivia,T,S,function(e){return N(e.pos,T,!1)})}-1!==x&&S&&(N(t.token.pos,x,1===p),m=g.line,h=x)}o.advance(),y=n}}(n,n,D,x,i,a)}if(!o.isOnToken()){var S=o.getCurrentLeadingTrivia();S&&(C(S,i,!1,function(e){return E(e,l.getLineAndCharacterOfPosition(e.pos),n,n,void 0)}),function(){var e=_?_.end:r.pos,t=l.getLineAndCharacterOfPosition(e).line,n=l.getLineAndCharacterOfPosition(r.end).line;F(t,n+1,_)}())}return b;function T(r,n,i,a){return{getIndentationForComment:function(e,t,r){switch(e){case 19:case 23:case 21:return i+o(r)}return-1!==t?t:i},getIndentationForToken:function(t,a,s,c){return!c&&function(t,i,a){switch(i){case 18:case 19:case 21:case 83:case 107:case 58:return!1;case 42:case 30:switch(a.kind){case 262:case 263:case 261:return!1}break;case 22:case 23:if(181!==a.kind)return!1}return n!==t&&!(r.decorators&&i===function(t){if(t.modifiers&&t.modifiers.length)return t.modifiers[0].kind;switch(t.kind){case 240:return 76;case 241:return 110;case 239:return 90;case 243:return 243;case 158:return 126;case 159:return 137;case 156:if(t.asteriskToken)return 40;case 154:case 151:var r=e.getNameOfDeclaration(t);if(r)return r.kind}}(r))}(t,a,s)?i+o(s):i},getIndentation:function(){return i},getDelta:o,recomputeIndentation:function(e){r.parent&&t.SmartIndenter.shouldIndentChildNode(g,r.parent,r,l)&&(i+=e?g.indentSize:-g.indentSize,a=t.SmartIndenter.shouldIndentChildNode(g,r)?g.indentSize:0)}};function o(e){return t.SmartIndenter.nodeWillIndentChild(g,r,e,l,!0)?a:0}}function C(t,n,i,a){for(var o=0,s=t;o0){var S=p(x,g);O(b,D.character,S)}else w(b,D.character)}}}}else i||N(r.pos,n,!1)}function F(t,r,n){for(var i=t;io)){var s=P(a,o);-1!==s&&(e.Debug.assert(s===a||!e.isWhiteSpaceSingleLine(l.text.charCodeAt(s-1))),w(s,o+1-s))}}}function P(t,r){for(var n=r;n>=t&&e.isWhiteSpaceSingleLine(l.text.charCodeAt(n));)n--;return n!==r?n+1:-1}function w(t,r){r&&b.push(e.createTextChangeFromStartLength(t,r,""))}function O(t,r,n){(r||n)&&b.push(e.createTextChangeFromStartLength(t,r,n))}}function p(t,r){if((!i||i.tabSize!==r.tabSize||i.indentSize!==r.indentSize)&&(i={tabSize:r.tabSize,indentSize:r.indentSize},a=o=void 0),r.convertTabsToSpaces){var n=void 0,s=Math.floor(t/r.indentSize),c=t%r.indentSize;return o||(o=[]),void 0===o[s]?(n=e.repeatString(" ",r.indentSize*s),o[s]=n):n=o[s],c?n+e.repeatString(" ",c):n}var u=Math.floor(t/r.tabSize),l=t-u*r.tabSize,_=void 0;return a||(a=[]),void 0===a[u]?a[u]=_=e.repeatString("\t",u):_=a[u],l?_+e.repeatString(" ",l):_}!function(e){e[e.Unknown=-1]="Unknown"}(r||(r={})),t.formatOnEnter=function(t,r,n){var i=r.getLineAndCharacterOfPosition(t).line;if(0===i)return[];for(var a=e.getEndLinePosition(i,r);e.isWhiteSpaceSingleLine(r.text.charCodeAt(a));)a--;return e.isLineBreak(r.text.charCodeAt(a))&&a--,_({pos:e.getStartPositionOfLine(i-1,r),end:a+1},r,n,2)},t.formatOnSemicolon=function(e,t,r){return l(c(s(e,26,t)),t,r,3)},t.formatOnOpeningCurly=function(t,r,n){var i=s(t,18,r);if(!i)return[];var a=c(i.parent);return _({pos:e.getLineStartPositionForPosition(a.getStart(r),r),end:t},r,n,4)},t.formatOnClosingCurly=function(e,t,r){return l(c(s(e,19,t)),t,r,5)},t.formatDocument=function(e,t){return _({pos:0,end:e.text.length},e,t,0)},t.formatSelection=function(t,r,n,i){return _({pos:e.getLineStartPositionForPosition(t,n),end:r},n,i,1)},t.formatNodeGivenIndentation=function(e,r,n,i,a,o){var s={pos:0,end:r.text.length};return t.getFormattingScanner(r.text,n,s.pos,s.end,function(t){return d(s,e,i,a,t,o,1,function(e){return!1},r)})},function(e){e[e.None=0]="None",e[e.LineAdded=1]="LineAdded",e[e.LineRemoved=2]="LineRemoved"}(n||(n={})),t.getRangeOfEnclosingComment=function(t,r,n,i){void 0===i&&(i=e.getTokenAtPosition(t,r));var a=e.findAncestor(i,e.isJSDoc);if(a&&(i=a.parent),!(i.getStart(t)<=r&&rr.end}var m=s(l,e,i),y=m.line===t.line||d(l,e,t.line,i);if(p){var v=g(e,i,u,!y);if(-1!==v)return v+n;if(-1!==(v=c(e,l,t,y,i,u)))return v+n}x(u,l,e,i,o)&&!y&&(n+=u.indentSize);var h=_(l,e,t.line,i);l=(e=l).parent,t=h?i.getLineAndCharacterOfPosition(e.getStart(i)):m}return n+a(u)}function s(e,t,r){var n=p(t,r),i=n?n.pos:e.getStart(r);return r.getLineAndCharacterOfPosition(i)}function c(t,r,n,i,a,o){return(e.isDeclaration(t)||e.isStatementButNotDeclaration(t))&&(279===r.kind||!i)?v(n,a,o):-1}function u(t,r,n,i){var a=e.findNextToken(t,r,i);return a?18===a.kind?1:19===a.kind&&n===l(a,i).line?2:0:0}function l(e,t){return t.getLineAndCharacterOfPosition(e.getStart(t))}function _(t,r,n,i){if(!e.isCallExpression(t)||!e.contains(t.arguments,r))return!1;var a=t.expression.getEnd();return e.getLineAndCharacterOfPosition(i,a).line===n}function d(t,r,n,i){if(222===t.kind&&t.elseStatement===r){var a=e.findChildOfKind(t,83,i);return e.Debug.assert(void 0!==a),l(a,i).line===n}return!1}function p(e,t){return e.parent&&f(e.getStart(t),e.getEnd(),e.parent,t)}function f(t,r,n,i){switch(n.kind){case 164:return a(n.typeArguments);case 188:return a(n.properties);case 187:return a(n.elements);case 168:return a(n.members);case 239:case 196:case 197:case 156:case 155:case 160:case 157:case 166:case 161:return a(n.typeParameters)||a(n.parameters);case 240:case 209:case 241:case 242:case 303:return a(n.typeParameters);case 192:case 191:return a(n.typeArguments)||a(n.arguments);case 238:return a(n.declarations);case 252:case 256:return a(n.elements);case 184:case 185:return a(n.elements)}function a(a){return a&&e.rangeContainsStartEnd(function(e,t,r){for(var n=e.getChildren(r),i=1;i=0&&r=0;o--)if(27!==t[o].kind){if(n.getLineAndCharacterOfPosition(t[o].end).line!==a.line)return v(a,n,i);a=l(t[o],n)}return-1}function v(e,t,r){var n=t.getPositionOfLineAndCharacter(e.line,0);return b(n,n+e.character,t,r)}function h(t,r,n,i){for(var a=0,o=0,s=t;sn.text.length)return a(i);if(i.indentStyle===e.IndentStyle.None)return 0;var c=e.findPrecedingToken(r,n,void 0,!0),_=t.getRangeOfEnclosingComment(n,r,c||null);if(_&&3===_.kind)return function(t,r,n,i){var a=e.getLineAndCharacterOfPosition(t,r).line-1,o=e.getLineAndCharacterOfPosition(t,i.pos).line;if(e.Debug.assert(o>=0),a<=o)return b(e.getStartPositionOfLine(o,t),r,t,n);var s=e.getStartPositionOfLine(a,t),c=h(s,r,t,n),u=c.column,l=c.character;return 0===u?u:42===t.text.charCodeAt(s+l)?u-1:u}(n,r,i,_);if(!c)return a(i);if(e.isStringOrRegularExpressionOrTemplateLiteral(c.kind)&&c.getStart(n)<=r&&r0;){var a=t.text.charCodeAt(i);if(!e.isWhiteSpaceLike(a))break;i--}return b(e.getLineStartPositionForPosition(i,t),i,t,n)}(n,r,i);if(27===c.kind&&204!==c.parent.kind){var p=function(t,r,n){var i=e.findListItemInfo(t);return i&&i.listItemIndex>0?y(i.list.getChildren(),i.listItemIndex-1,r,n):-1}(c,n,i);if(-1!==p)return p}var v=function(e,t,r){return t&&f(e,e,t,r)}(r,c.parent,n);return v&&!e.rangeContainsRange(v,c)?m(v,n,i)+i.indentSize:function(t,r,n,i,s,c){for(var _,d=n;d;){if(e.positionBelongsToNode(d,r,t)&&x(c,d,_,t,!0)){var p=l(d,t),f=u(n,d,i,t),m=0!==f?s&&2===f?c.indentSize:0:i!==p.line?c.indentSize:0;return o(d,p,void 0,m,t,!0,c)}var y=g(d,t,c,!0);if(-1!==y)return y;_=d,d=d.parent}return a(c)}(n,r,c,d,s,i)},r.getIndentationForNode=function(e,t,r,n){return o(e,r.getLineAndCharacterOfPosition(e.getStart(r)),t,0,r,!1,n)},r.getBaseIndentation=a,function(e){e[e.Unknown=0]="Unknown",e[e.OpenBrace=1]="OpenBrace",e[e.CloseBrace=2]="CloseBrace"}(i||(i={})),r.isArgumentAndStartLineOverlapsExpressionBeingCalled=_,r.childStartsOnTheSameLineWithElseInIfStatement=d,r.getContainingList=p,r.findFirstNonWhitespaceCharacterAndColumn=h,r.findFirstNonWhitespaceColumn=b,r.nodeWillIndentChild=D,r.shouldIndentChildNode=x}(t.SmartIndenter||(t.SmartIndenter={}))}(e.formatting||(e.formatting={}))}(c||(c={})),function(e){!function(t){function r(t){var r=t.__pos;return e.Debug.assert("number"==typeof r),r}function n(t,r){e.Debug.assert("number"==typeof r),t.__pos=r}function a(t){var r=t.__end;return e.Debug.assert("number"==typeof r),r}function o(t,r){e.Debug.assert("number"==typeof r),t.__end=r}var s,c;function u(t,r){return e.skipTrivia(t,r,!1,!0)}function l(e,t,r,n){return{pos:_(e,t,n,s.Start),end:d(e,r,n)}}function _(t,r,n,i){if(n.useNonAdjustedStartPosition)return r.getStart(t);var a=r.getFullStart(),o=r.getStart(t);if(a===o)return o;var c=e.getLineStartPositionForPosition(a,t);if(e.getLineStartPositionForPosition(o,t)===c)return i===s.Start?o:a;var l=a>0?1:0,_=e.getStartPositionOfLine(e.getLineOfLocalPosition(t,c)+l,t);return _=u(t.text,_),e.getStartPositionOfLine(e.getLineOfLocalPosition(t,_),t)}function d(t,r,n){var i=r.end;if(n.useNonAdjustedEndPosition||e.isExpression(r))return i;var a=e.skipTrivia(t.text,i,!0);return a!==i&&e.isLineBreak(t.text.charCodeAt(a-1))?a:i}function p(e,t){return!!t&&!!e.parent&&(27===t.kind||26===t.kind&&188===e.parent.kind)}!function(e){e[e.FullStart=0]="FullStart",e[e.Start=1]="Start"}(s=t.Position||(t.Position={})),t.useNonAdjustedPositions={useNonAdjustedStartPosition:!0,useNonAdjustedEndPosition:!0},function(e){e[e.Remove=0]="Remove",e[e.ReplaceWithSingleNode=1]="ReplaceWithSingleNode",e[e.ReplaceWithMultipleNodes=2]="ReplaceWithMultipleNodes",e[e.Text=3]="Text"}(c||(c={}));var f,m=function(){function r(t,r){this.newLineCharacter=t,this.formatContext=r,this.changes=[],this.newFiles=[],this.classesWithNodesInsertedAtStart=e.createMap(),this.deletedNodes=[]}return r.fromContext=function(t){return new r(e.getNewLineOrDefaultFromHost(t.host,t.formatContext.options),t.formatContext)},r.with=function(e,t){var n=r.fromContext(e);return t(n),n.getChanges()},r.prototype.deleteRange=function(e,t){this.changes.push({kind:c.Remove,sourceFile:e,range:t})},r.prototype.delete=function(e,t){this.deletedNodes.push({sourceFile:e,node:t})},r.prototype.deleteModifier=function(t,r){this.deleteRange(t,{pos:r.getStart(t),end:e.skipTrivia(t.text,r.end,!0)})},r.prototype.deleteNodeRange=function(e,t,r,n){void 0===n&&(n={});var i=_(e,t,n,s.FullStart),a=d(e,r,n);this.deleteRange(e,{pos:i,end:a})},r.prototype.deleteNodeRangeExcludingEnd=function(e,t,r,n){void 0===n&&(n={});var i=_(e,t,n,s.FullStart),a=void 0===r?e.text.length:_(e,r,n,s.FullStart);this.deleteRange(e,{pos:i,end:a})},r.prototype.replaceRange=function(e,t,r,n){void 0===n&&(n={}),this.changes.push({kind:c.ReplaceWithSingleNode,sourceFile:e,range:t,options:n,node:r})},r.prototype.replaceNode=function(e,r,n,i){void 0===i&&(i=t.useNonAdjustedPositions),this.replaceRange(e,l(e,r,r,i),n,i)},r.prototype.replaceNodeRange=function(e,r,n,i,a){void 0===a&&(a=t.useNonAdjustedPositions),this.replaceRange(e,l(e,r,n,a),i,a)},r.prototype.replaceRangeWithNodes=function(e,t,r,n){void 0===n&&(n={}),this.changes.push({kind:c.ReplaceWithMultipleNodes,sourceFile:e,range:t,options:n,nodes:r})},r.prototype.replaceNodeWithNodes=function(e,r,n,i){void 0===i&&(i=t.useNonAdjustedPositions),this.replaceRangeWithNodes(e,l(e,r,r,i),n,i)},r.prototype.replaceNodeWithText=function(e,r,n){this.replaceRangeWithText(e,l(e,r,r,t.useNonAdjustedPositions),n)},r.prototype.replaceNodeRangeWithNodes=function(e,r,n,i,a){void 0===a&&(a=t.useNonAdjustedPositions),this.replaceRangeWithNodes(e,l(e,r,n,a),i,a)},r.prototype.nextCommaToken=function(t,r){var n=e.findNextToken(r,r.parent,t);return n&&27===n.kind?n:void 0},r.prototype.replacePropertyAssignment=function(e,t,r){var n=this.nextCommaToken(e,t)?"":","+this.newLineCharacter;this.replaceNode(e,t,r,{suffix:n})},r.prototype.insertNodeAt=function(t,r,n,i){void 0===i&&(i={}),this.replaceRange(t,e.createRange(r),n,i)},r.prototype.insertNodesAt=function(t,r,n,i){void 0===i&&(i={}),this.replaceRangeWithNodes(t,e.createRange(r),n,i)},r.prototype.insertNodeAtTopOfFile=function(t,r,n){var i=function(t){for(var r,n=0,i=t.statements;n"})},r.prototype.getOptionsForInsertNodeBefore=function(t,r){return e.isStatement(t)||e.isClassElement(t)?{suffix:r?this.newLineCharacter+this.newLineCharacter:this.newLineCharacter}:e.isVariableDeclaration(t)?{suffix:", "}:e.isParameter(t)?{}:e.isStringLiteral(t)&&e.isImportDeclaration(t.parent)||e.isNamedImports(t)?{suffix:", "}:e.Debug.failBadSyntaxKind(t)},r.prototype.insertNodeAtConstructorStart=function(t,r,n){var i=e.firstOrUndefined(r.body.statements);i&&r.body.multiLine?this.insertNodeBefore(t,i,n):this.replaceConstructorBody(t,r,[n].concat(r.body.statements))},r.prototype.insertNodeAtConstructorEnd=function(t,r,n){var i=e.lastOrUndefined(r.body.statements);i&&r.body.multiLine?this.insertNodeAfter(t,i,n):this.replaceConstructorBody(t,r,r.body.statements.concat([n]))},r.prototype.replaceConstructorBody=function(t,r,n){this.replaceNode(t,r.body,e.createBlock(n,!0))},r.prototype.insertNodeAtEndOfScope=function(t,r,n){var i=_(t,r.getLastToken(),{},s.Start);this.insertNodeAt(t,i,n,{prefix:e.isLineBreak(t.text.charCodeAt(r.getLastToken().pos))?this.newLineCharacter:this.newLineCharacter+this.newLineCharacter,suffix:this.newLineCharacter})},r.prototype.insertNodeAtClassStart=function(e,t,r){this.insertNodeAtStartWorker(e,t,r)},r.prototype.insertNodeAtObjectStart=function(e,t,r){this.insertNodeAtStartWorker(e,t,r)},r.prototype.insertNodeAtStartWorker=function(t,r,n){var a=r.getStart(t),o=e.formatting.SmartIndenter.findFirstNonWhitespaceColumn(e.getLineStartPositionForPosition(a,t),a,t,this.formatContext.options)+this.formatContext.options.indentSize;this.insertNodeAt(t,v(r).pos,n,i({indentation:o},this.getInsertNodeAtStartPrefixSuffix(t,r)))},r.prototype.getInsertNodeAtStartPrefixSuffix=function(t,r){var n=e.isObjectLiteralExpression(r)?",":"";if(0===v(r).length){if(e.addToSeen(this.classesWithNodesInsertedAtStart,e.getNodeId(r),{node:r,sourceFile:t})){var i=e.positionsAreOnSameLine.apply(void 0,y(r,t).concat([t]));return{prefix:this.newLineCharacter,suffix:n+(i?this.newLineCharacter:"")}}return{prefix:"",suffix:n+this.newLineCharacter}}return{prefix:this.newLineCharacter,suffix:n}},r.prototype.insertNodeAfterComma=function(e,t,r){var n=this.insertNodeAfterWorker(e,this.nextCommaToken(e,t)||t,r);this.insertNodeAt(e,n,r,this.getInsertNodeAfterOptions(e,t))},r.prototype.insertNodeAfter=function(e,t,r){var n=this.insertNodeAfterWorker(e,t,r);this.insertNodeAt(e,n,r,this.getInsertNodeAfterOptions(e,t))},r.prototype.insertNodeAtEndOfList=function(e,t,r){this.insertNodeAt(e,t.end,r,{prefix:", "})},r.prototype.insertNodesAfter=function(t,r,n){var i=this.insertNodeAfterWorker(t,r,e.first(n));this.insertNodesAt(t,i,n,this.getInsertNodeAfterOptions(t,r))},r.prototype.insertNodeAfterWorker=function(t,r,n){var i,a;return i=r,a=n,((e.isPropertySignature(i)||e.isPropertyDeclaration(i))&&e.isClassOrTypeElement(a)&&149===a.name.kind||e.isStatementButNotDeclaration(i)&&e.isStatementButNotDeclaration(a))&&59!==t.text.charCodeAt(r.end-1)&&this.replaceRange(t,e.createRange(r.end),e.createToken(26)),d(t,r,{})},r.prototype.getInsertNodeAfterOptions=function(t,r){var n=this.getInsertNodeAfterOptionsWorker(r);return i({},n,{prefix:r.end===t.end&&e.isStatement(r)?n.prefix?"\n"+n.prefix:"\n":n.prefix})},r.prototype.getInsertNodeAfterOptionsWorker=function(t){switch(t.kind){case 240:case 244:return{prefix:this.newLineCharacter,suffix:this.newLineCharacter};case 237:case 10:case 72:return{prefix:", "};case 275:return{suffix:","+this.newLineCharacter};case 85:return{prefix:" "};case 151:return{};default:return e.Debug.assert(e.isStatement(t)||e.isClassOrTypeElement(t)),{suffix:this.newLineCharacter}}},r.prototype.insertName=function(t,r,n){if(e.Debug.assert(!r.name),197===r.kind){var i=e.findChildOfKind(r,37,t),a=e.findChildOfKind(r,20,t);a?(this.insertNodesAt(t,a.getStart(t),[e.createToken(90),e.createIdentifier(n)],{joiner:" "}),C(this,t,i)):(this.insertText(t,e.first(r.parameters).getStart(t),"function "+n+"("),this.replaceRange(t,i,e.createToken(21))),218!==r.body.kind&&(this.insertNodesAt(t,r.body.getStart(t),[e.createToken(18),e.createToken(97)],{joiner:" ",suffix:" "}),this.insertNodesAt(t,r.body.end,[e.createToken(26),e.createToken(19)],{joiner:" "}))}else{var o=e.findChildOfKind(r,196===r.kind?90:76,t).end;this.insertNodeAt(t,o,e.createIdentifier(n),{prefix:" "})}},r.prototype.insertExportModifier=function(e,t){this.insertText(e,t.getStart(e),"export ")},r.prototype.insertNodeInListAfter=function(t,r,n,i){if(void 0===i&&(i=e.formatting.SmartIndenter.getContainingList(r,t)),i){var a=e.indexOfNode(i,r);if(!(a<0)){var o=r.getEnd();if(a!==i.length-1){var s=e.getTokenAtPosition(t,r.end);if(s&&p(r,s)){var c=e.getLineAndCharacterOfPosition(t,u(t.text,i[a+1].getFullStart())),l=e.getLineAndCharacterOfPosition(t,s.end),_=void 0,d=void 0;l.line===c.line?(d=s.end,_=function(e){for(var t="",r=0;r=0;n--){var i=r[n],a=i.span,o=i.newText;t=""+t.substring(0,a.start)+o+t.substring(e.textSpanEnd(a))}return t}function b(t){var n=e.visitEachChild(t,b,e.nullTransformationContext,D,b),i=e.nodeIsSynthesized(n)?n:Object.create(n);return i.pos=r(t),i.end=a(t),i}function D(t,n,i,o,s){var c=e.visitNodes(t,n,i,o,s);if(!c)return c;var u=c===t?e.createNodeArray(c.slice(0)):c;return u.pos=r(t),u.end=a(t),u}t.ChangeTracker=m,t.getNewFileText=function(e,t,r,n){return f.newFileChangesWorker(void 0,t,e,r,n)},function(t){function r(t,r,i,a,o){var s=i.map(function(e){return n(e,t,a).text}).join(a),c=e.createSourceFile("any file name",s,6,!0,r);return h(s,e.formatting.formatDocument(c,o))+a}function n(t,r,n){var i=new S(n),a="\n"===n?1:0;return e.createPrinter({newLine:a,neverAsciiEscape:!0},i).writeNode(4,t,r,i),{text:i.getText(),node:b(t)}}t.getTextChangesFromChanges=function(t,r,i,a){return e.group(t,function(e){return e.sourceFile.path}).map(function(t){for(var o=t[0].sourceFile,s=e.stableSort(t,function(e,t){return e.range.pos-t.range.pos||e.range.end-t.range.end}),u=function(t){e.Debug.assert(s[t].range.end<=s[t+1].range.pos,"Changes overlap",function(){return JSON.stringify(s[t].range)+" and "+JSON.stringify(s[t+1].range)})},l=0;lt&&(n?a=e.concatenate(a,e.map(c.argumentTypes.slice(t),function(e){return i.getBaseTypeOfLiteralType(e)})):a.push(i.getBaseTypeOfLiteralType(c.argumentTypes[t])))}if(a.length){var u=i.getWidenedType(i.getUnionType(a,2));return n?i.createArrayType(u):u}}function c(t,r){for(var n=[],i=0;i0)return T;var C=f(s.checker.getTypeAtLocation(t),s.checker).getReturnType(),k=e.getSynthesizedDeepClone(v),E=s.checker.getPromisedTypeOfPromise(C)?e.createAwait(k):k;if(c)return[e.createReturn(E)];var N=d(r,E,s);return r&&r.types.push(C),N;default:i=!1}return e.emptyArray}function f(t,r){var n=r.getSignaturesOfType(t,0);return e.lastOrUndefined(n)}function m(t,r,n){for(var i=[],a=0,o=r;a0)return}else e.isFunctionLike(a)||e.forEachChild(a,r)})}return i}function g(t,r){var n,i=0,a=[];e.isFunctionLikeDeclaration(t)?t.parameters.length>0&&(n=o(t.parameters[0].name)):e.isIdentifier(t)&&(n=o(t));if(n&&"undefined"!==n.identifier.text)return n;function o(t){var n,o=function(e){return e.symbol?e.symbol:r.checker.getSymbolAtLocation(e)}((n=t).original?n.original:n);return o&&r.synthNamesMap.get(e.getSymbolId(o).toString())||{identifier:t,types:a,numberOfAssignmentsOriginal:i}}}t.registerCodeFix({errorCodes:n,getCodeActions:function(n){i=!0;var o=e.textChanges.ChangeTracker.with(n,function(e){return a(e,n.sourceFile,n.span.start,n.program.getTypeChecker(),n)});return i?[t.createCodeFixAction(r,o,e.Diagnostics.Convert_to_async_function,r,e.Diagnostics.Convert_all_to_async_functions)]:[]},fixIds:[r],getAllCodeActions:function(e){return t.codeFixAll(e,n,function(t,r){return a(t,r.file,r.start,e.program.getTypeChecker(),e)})}})}(e.codefix||(e.codefix={}))}(c||(c={})),function(e){!function(t){function r(t,r,n,i){for(var a=0,o=t.imports;a1?[[a(n),o(n)],!0]:[[o(n)],!0]:[[a(n)],!1]}(l.arguments[0],r):void 0;return p?(i.replaceNodeWithNodes(t,n.parent,p[0]),p[1]):(i.replaceRangeWithText(t,e.createRange(u.getStart(t),l.pos),"export default"),!0)}i.delete(t,n.parent)}else e.isExportsOrModuleExportsOrAlias(t,u.expression)&&function(t,r,n,i){var a=r.left.name.text,o=i.get(a);if(void 0!==o){var s=[_(void 0,o,r.right),d([e.createExportSpecifier(o,a)])];n.replaceNodeWithNodes(t,r.parent,s)}else!function(t,r,n){var i=t.left,a=t.right,o=t.parent,s=i.name.text;if(!(e.isFunctionExpression(a)||e.isArrowFunction(a)||e.isClassExpression(a))||a.name&&a.name.text!==s)n.replaceNodeRangeWithNodes(r,i.expression,e.findChildOfKind(i,24,r),[e.createToken(85),e.createToken(77)],{joiner:" ",suffix:" "});else{n.replaceRange(r,{pos:i.getStart(r),end:a.getStart(r)},e.createToken(85),{suffix:" "}),a.name||n.insertName(r,a,s);var c=e.findChildOfKind(o,26,r);c&&n.delete(r,c)}}(r,t,n)}(t,n,i,s);var f,m;return!1}(r,i,v,p,g)}default:return!1}}function a(e){return d(void 0,e)}function o(t){return d([e.createExportSpecifier(void 0,"default")],t)}function s(e,t){for(;t.original.has(e)||t.additional.has(e);)e="_"+e;return t.additional.set(e,!0),e}function c(t,r,n){return e.createFunctionDeclaration(e.getSynthesizedDeepClones(n.decorators),e.concatenate(r,e.getSynthesizedDeepClones(n.modifiers)),e.getSynthesizedDeepClone(n.asteriskToken),t,e.getSynthesizedDeepClones(n.typeParameters),e.getSynthesizedDeepClones(n.parameters),e.getSynthesizedDeepClone(n.type),e.convertToFunctionBody(e.getSynthesizedDeepClone(n.body)))}function u(t,r,n,i){return"default"===r?e.makeImport(e.createIdentifier(t),void 0,n,i):e.makeImport(void 0,[l(r,t)],n,i)}function l(t,r){return e.createImportSpecifier(void 0!==t&&t!==r?e.createIdentifier(t):void 0,e.createIdentifier(r))}function _(t,r,n){return e.createVariableStatement(t,e.createVariableDeclarationList([e.createVariableDeclaration(r,void 0,n)],2))}function d(t,r){return e.createExportDeclaration(void 0,void 0,t&&e.createNamedExports(t),void 0===r?void 0:e.createLiteral(r))}t.registerCodeFix({errorCodes:[e.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code],getCodeActions:function(a){var o=a.sourceFile,c=a.program,u=a.preferences,l=e.textChanges.ChangeTracker.with(a,function(t){if(function(t,r,a,o,c){var u={original:(_=t,d=e.createMultiMap(),function t(r,n){e.isIdentifier(r)&&function(e){var t=e.parent;switch(t.kind){case 189:return t.name!==e;case 186:case 253:return t.propertyName!==e;default:return!0}}(r)&&n(r),r.forEachChild(function(e){return t(e,n)})}(_,function(e){return d.add(e.text,e)}),d),additional:e.createMap()},l=function(t,r,i){var a=e.createMap();return n(t,function(t){var n=t.name,o=n.text,c=n.originalKeywordKind;!a.has(o)&&(void 0!==c&&e.isNonContextualKeyword(c)||r.resolveName(t.name.text,t,67220415,!0))&&a.set(o,s("_"+o,i))}),a}(t,r,u);var _,d;!function(t,r,i){n(t,function(n,a){if(!a){var o=n.name.text;i.replaceNode(t,n,e.createIdentifier(r.get(o)||o))}})}(t,l,a);for(var p=!1,f=0,m=t.statements;f0&&(!e.isIdentifier(n.name)||e.FindAllReferences.Core.isSymbolReferencedInFile(n.name,i,r))?n.modifiers.forEach(function(e){t.deleteModifier(r,e)}):(t.delete(r,n),function(t,r,n,i,a){e.FindAllReferences.Core.eachSignatureCall(n.parent,i,a,function(e){var i=n.parent.parameters.indexOf(n);e.arguments.length>i&&t.delete(r,e.arguments[i])})}(t,r,n,a,i)))}t.registerCodeFix({errorCodes:o,getCodeActions:function(i){var o=i.errorCode,m=i.sourceFile,g=i.program,y=g.getTypeChecker(),v=g.getSourceFiles(),h=e.getTokenAtPosition(m,i.span.start);if(e.isJSDocTemplateTag(h))return[c(e.textChanges.ChangeTracker.with(i,function(e){return e.delete(m,h)}),e.Diagnostics.Remove_template_tag)];if(28===h.kind)return[c(T=e.textChanges.ChangeTracker.with(i,function(e){return u(e,m,h)}),e.Diagnostics.Remove_type_parameters)];var b=l(h);if(b)return[c(T=e.textChanges.ChangeTracker.with(i,function(e){return e.delete(m,b)}),[e.Diagnostics.Remove_import_from_0,e.showModuleSpecifier(b)])];var D=e.textChanges.ChangeTracker.with(i,function(e){return _(h,e,m,y,v,!1)});if(D.length)return[c(D,e.Diagnostics.Remove_destructuring)];var x=e.textChanges.ChangeTracker.with(i,function(e){return d(m,h,e)});if(x.length)return[c(x,e.Diagnostics.Remove_variable_statement)];var S=[];if(127===h.kind){var T=e.textChanges.ChangeTracker.with(i,function(e){return s(e,m,h)}),C=e.cast(h.parent,e.isInferTypeNode).typeParameter.name.text;S.push(t.createCodeFixAction(r,T,[e.Diagnostics.Replace_infer_0_with_unknown,C],a,e.Diagnostics.Replace_all_unused_infer_with_unknown))}else{var k=e.textChanges.ChangeTracker.with(i,function(e){return f(m,h,e,y,v,!1)});if(k.length){C=e.isComputedPropertyName(h.parent)?h.parent:h;S.push(c(k,[e.Diagnostics.Remove_declaration_for_Colon_0,C.getText(m)]))}}var E=e.textChanges.ChangeTracker.with(i,function(e){return p(e,o,m,h)});return E.length&&S.push(t.createCodeFixAction(r,E,[e.Diagnostics.Prefix_0_with_an_underscore,h.getText(m)],n,e.Diagnostics.Prefix_all_unused_declarations_with_where_possible)),S},fixIds:[n,i,a],getAllCodeActions:function(r){var c=r.sourceFile,m=r.program,g=m.getTypeChecker(),y=m.getSourceFiles();return t.codeFixAll(r,o,function(t,o){var m=e.getTokenAtPosition(c,o.start);switch(r.fixId){case n:p(t,o.code,c,m);break;case i:if(127===m.kind)break;var v=l(m);v?t.delete(c,v):e.isJSDocTemplateTag(m)?t.delete(c,m):28===m.kind?u(t,c,m):_(m,t,c,g,y,!0)||d(c,m,t)||f(c,m,t,g,y,!0);break;case a:127===m.kind&&s(t,c,m);break;default:e.Debug.fail(JSON.stringify(r.fixId))}})}})}(e.codefix||(e.codefix={}))}(c||(c={})),function(e){!function(t){var r="fixUnreachableCode",n=[e.Diagnostics.Unreachable_code_detected.code];function i(t,r,n,i){var a=e.getTokenAtPosition(r,n),o=e.findAncestor(a,e.isStatement);e.Debug.assert(o.getStart(r)===a.getStart(r));var s=(e.isBlock(o.parent)?o.parent:o).parent;if(!e.isBlock(o.parent)||o===e.first(o.parent.statements))switch(s.kind){case 222:if(s.elseStatement){if(e.isBlock(o.parent))break;return void t.replaceNode(r,o,e.createBlock(e.emptyArray))}case 224:case 225:return void t.delete(r,s)}if(e.isBlock(o.parent)){var c=n+i,u=e.Debug.assertDefined(function(e,t){for(var r,n=0,i=e;ng.length)h(a.getSignatureFromDeclaration(c[c.length-1]),d,l,i(o));else e.Debug.assert(c.length===g.length),s(function(t,r,a,o,s){for(var c=t[0],u=t[0].minArgumentCount,l=!1,_=0,d=t;_=c.parameters.length&&(!p.hasRestParameter||c.hasRestParameter)&&(c=p)}var f=c.parameters.length-(c.hasRestParameter?1:0),m=c.parameters.map(function(e){return e.name}),g=n(f,m,void 0,u,!1);if(l){var y=e.createArrayTypeNode(e.createKeywordTypeNode(120)),v=e.createParameter(void 0,void 0,e.createToken(25),m[f]||"rest",f>=u?e.createToken(56):void 0,y,void 0);g.push(v)}return function(t,r,n,a,o,s,c){return e.createMethod(void 0,t,void 0,r,n?e.createToken(56):void 0,a,o,s,i(c))}(o,r,a,void 0,g,void 0,s)}(g,l,f,d,o))}}function h(t,n,i,o){var c=function(t,r,n,i,a,o,s){var c=t.signatureToSignatureDeclaration(r,156,n,256);if(!c)return;return c.decorators=void 0,c.modifiers=i,c.name=a,c.questionToken=o?e.createToken(56):void 0,c.body=s,c}(a,t,r,n,i,f,o);c&&s(c)}}function n(t,r,n,i,a){for(var o=[],s=0;s=i?e.createToken(56):void 0,a?void 0:n&&n[s]||e.createKeywordTypeNode(120),void 0);o.push(c)}return o}function i(t){return e.createBlock([e.createThrow(e.createNew(e.createIdentifier("Error"),void 0,[e.createLiteral("Method not implemented.","single"===t.quotePreference)]))],!0)}t.createMissingMemberNodes=function(e,t,n,i,a){for(var o=e.symbol.members,s=0,c=t;s0;if(e.isBlock(t)&&!s&&0===i.size)return{body:e.createBlock(t.statements,!0),returnValueProperty:void 0};var c=!1,u=e.createNodeArray(e.isBlock(t)?t.statements.slice(0):[e.isStatement(t)?t:e.createReturn(t)]);if(s||i.size){var l=e.visitNodes(u,function t(a){if(!c&&230===a.kind&&s){var u=f(r,n);return a.expression&&(o||(o="__return"),u.unshift(e.createPropertyAssignment(o,e.visitNode(a.expression,t)))),1===u.length?e.createReturn(u[0].name):e.createReturn(e.createObjectLiteral(u))}var l=c;c=c||e.isFunctionLikeDeclaration(a)||e.isClassLike(a);var _=i.get(e.getNodeId(a).toString()),d=_?e.getSynthesizedDeepClone(_):e.visitEachChild(a,t,e.nullTransformationContext);return c=l,d}).slice();if(s&&!a&&e.isStatement(t)){var _=f(r,n);1===_.length?l.push(e.createReturn(_[0].name)):l.push(e.createReturn(e.createObjectLiteral(_)))}return{body:e.createBlock(l,!0),returnValueProperty:o}}return{body:e.createBlock(u,!0),returnValueProperty:void 0}}(t,a,u,d,!!(o.facts&i.HasReturn)),A=N.body,F=N.returnValueProperty;if(e.suppressLeadingAndTrailingTrivia(A),e.isClassLike(r)){var P=h?[]:[e.createToken(113)];o.facts&i.InStaticRegion&&P.push(e.createToken(116)),o.facts&i.IsAsyncFunction&&P.push(e.createToken(121)),E=e.createMethod(void 0,P.length?P:void 0,o.facts&i.IsGenerator?e.createToken(40):void 0,b,void 0,T,D,c,A)}else E=e.createFunctionDeclaration(void 0,o.facts&i.IsAsyncFunction?[e.createToken(121)]:void 0,o.facts&i.IsGenerator?e.createToken(40):void 0,b,T,D,c,A);var w=e.textChanges.ChangeTracker.fromContext(s),O=function(t,r){return e.find(function(t){if(e.isFunctionLikeDeclaration(t)){var r=t.body;if(e.isBlock(r))return r.statements}else{if(e.isModuleBlock(t)||e.isSourceFile(t))return t.statements;if(e.isClassLike(t))return t.members;e.assertType(t)}return e.emptyArray}(r),function(r){return r.pos>=t&&e.isFunctionLikeDeclaration(r)&&!e.isConstructorDeclaration(r)})}((m(o.range)?e.last(o.range):o.range).end,r);O?w.insertNodeBefore(s.file,O,E,!0):w.insertNodeAtEndOfScope(s.file,r,E);var I=[],M=function(t,r,n){var a=e.createIdentifier(n);if(e.isClassLike(t)){var o=r.facts&i.InStaticRegion?e.createIdentifier(t.name.text):e.createThis();return e.createPropertyAccess(o,a)}return a}(r,o,v),L=e.createCall(M,C,x);if(o.facts&i.IsGenerator&&(L=e.createYield(e.createToken(40),L)),o.facts&i.IsAsyncFunction&&(L=e.createAwait(L)),a.length&&!u)if(e.Debug.assert(!F),e.Debug.assert(!(o.facts&i.HasReturn)),1===a.length){var R=a[0];I.push(e.createVariableStatement(void 0,e.createVariableDeclarationList([e.createVariableDeclaration(e.getSynthesizedDeepClone(R.name),e.getSynthesizedDeepClone(R.type),L)],R.parent.flags)))}else{for(var B=[],j=[],J=a[0].parent.flags,z=!1,K=0,U=a;K0);for(var a=!0,o=0,s=i;ot)return n||i[0];if(a&&!e.isPropertyDeclaration(c)){if(void 0!==n)return c;a=!1}n=c}return void 0===n?e.Debug.fail():n}(b,r);m.insertNodeBefore(o.file,D,v,!0),m.replaceNode(o.file,t,h)}else{var x=e.createVariableDeclaration(l,p,f),S=function(t,r){for(var n;void 0!==t&&t!==r;){if(e.isVariableDeclaration(t)&&t.initializer===n&&e.isVariableDeclarationList(t.parent)&&t.parent.declarations.length>1)return t;n=t,t=t.parent}}(t,r);if(S){m.insertNodeBefore(o.file,S,x);var h=e.createIdentifier(l);m.replaceNode(o.file,t,h)}else if(221===t.parent.kind&&r===e.findAncestor(t,_)){var T=e.createVariableStatement(void 0,e.createVariableDeclarationList([x],2));m.replaceNode(o.file,t.parent,T)}else{var T=e.createVariableStatement(void 0,e.createVariableDeclarationList([x],2)),D=function(t,r){var n;e.Debug.assert(!e.isClassLike(r));for(var i=t;i!==r;i=i.parent)_(i)&&(n=i);for(var i=(n||t).parent;;i=i.parent){if(g(i)){for(var a=void 0,o=0,s=i.statements;ot.pos)break;a=c}return!a&&e.isCaseClause(i)?(e.Debug.assert(e.isSwitchStatement(i.parent.parent)),i.parent.parent):e.Debug.assertDefined(a)}e.Debug.assert(i!==r,"Didn't encounter a block-like before encountering scope")}}(t,r);if(0===D.pos?m.insertNodeAtTopOfFile(o.file,T,!1):m.insertNodeBefore(o.file,D,T,!1),221===t.parent.kind)m.delete(o.file,t.parent);else{var h=e.createIdentifier(l);m.replaceNode(o.file,t,h)}}}var C=m.getChanges(),k=t.getSourceFile().fileName,E=e.getRenameLocation(C,k,l,!0);return{renameFilename:k,renameLocation:E,edits:C}}(e.isExpression(c)?c:c.statements[0].expression,o[n],u[n],t.facts,r)}(n,t,o)}e.Debug.fail("Unrecognized action name")}function l(t,r){var a=r.length;if(0===a)return{errors:[e.createFileDiagnostic(t,r.start,a,n.cannotExtractEmpty)]};var o=e.getParentNodeInSpan(e.getTokenAtPosition(t,r.start),t,r),s=e.getParentNodeInSpan(e.findTokenOnLeftOfPosition(t,e.textSpanEnd(r)),t,r),c=[],u=i.None;if(!o||!s)return{errors:[e.createFileDiagnostic(t,r.start,a,n.cannotExtractRange)]};if(o.parent!==s.parent)return{errors:[e.createFileDiagnostic(t,r.start,a,n.cannotExtractRange)]};if(o!==s){if(!g(o.parent))return{errors:[e.createFileDiagnostic(t,r.start,a,n.cannotExtractRange)]};for(var l=[],_=0,d=o.parent.statements;_=r.start+r.length)return(o||(o=[])).push(e.createDiagnosticForNode(a,n.cannotExtractSuper)),!0}else u|=i.UsesThis}if(e.isFunctionLikeDeclaration(a)||e.isClassLike(a)){switch(a.kind){case 239:case 240:e.isSourceFile(a.parent)&&void 0===a.parent.externalModuleIndicator&&(o||(o=[])).push(e.createDiagnosticForNode(a,n.functionWillNotBeVisibleInTheNewScope))}return!1}var p=_;switch(a.kind){case 222:case 235:_=0;break;case 218:a.parent&&235===a.parent.kind&&a.parent.finallyBlock===a&&(_=4);break;case 271:_|=1;break;default:e.isIterationStatement(a,!1)&&(_|=3)}switch(a.kind){case 178:case 100:u|=i.UsesThis;break;case 233:var f=a.label;(l||(l=[])).push(f.escapedText),e.forEachChild(a,t),l.pop();break;case 229:case 228:var f=a.label;f?e.contains(l,f.escapedText)||(o||(o=[])).push(e.createDiagnosticForNode(a,n.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)):_&(229===a.kind?1:2)||(o||(o=[])).push(e.createDiagnosticForNode(a,n.cannotExtractRangeContainingConditionalBreakOrContinueStatements));break;case 201:u|=i.IsAsyncFunction;break;case 207:u|=i.IsGenerator;break;case 230:4&_?u|=i.HasReturn:(o||(o=[])).push(e.createDiagnosticForNode(a,n.cannotExtractRangeContainingConditionalReturnStatement));break;default:e.forEachChild(a,t)}_=p}(t),o}}function _(t){return e.isFunctionLikeDeclaration(t)||e.isSourceFile(t)||e.isModuleBlock(t)||e.isClassLike(t)}function d(t,r){var a=r.file,o=function(t){var r=m(t.range)?e.first(t.range):t.range;if(t.facts&i.UsesThis){var n=e.getContainingClass(r);if(n){var a=e.findAncestor(r,e.isFunctionLikeDeclaration);return a?[a,n]:[n]}}for(var o=[];;)if(151===(r=r.parent).kind&&(r=e.findAncestor(r,function(t){return e.isFunctionLikeDeclaration(t)}).parent),_(r)&&(o.push(r),279===r.kind))return o}(t);return{scopes:o,readsAndWrites:function(t,r,a,o,s,c){var u,l,_=e.createMap(),d=[],p=[],f=[],g=[],y=[],v=e.createMap(),h=[],b=m(t.range)?1===t.range.length&&e.isExpressionStatement(t.range[0])?t.range[0].expression:void 0:t.range;if(void 0===b){var D=t.range,x=e.first(D).getStart(),S=e.last(D).end;l=e.createFileDiagnostic(o,x,S-x,n.expressionExpected)}else 147456&s.getTypeAtLocation(b).flags&&(l=e.createDiagnosticForNode(b,n.uselessConstantType));for(var T=0,C=r;T=u)return m;if(N.set(m,u),y){for(var v=0,h=d;v0){for(var I=e.createMap(),M=0,L=F;void 0!==L&&M=0)return;var i=e.isIdentifier(n)?q(n):s.getSymbolAtLocation(n);if(i){var a=e.find(y,function(e){return e.symbol===i});if(a)if(e.isVariableDeclaration(a)){var o=a.symbol.id.toString();v.has(o)||(h.push(a),v.set(o,!0))}else u=u||a}e.forEachChild(n,r)})}for(var K=function(r){var i=d[r];if(r>0&&(i.usages.size>0||i.typeParameterUsages.size>0)){var a=m(t.range)?t.range[0]:t.range;g[r].push(e.createDiagnosticForNode(a,n.cannotAccessVariablesFromNestedScopes))}var o,s=!1;if(d[r].usages.forEach(function(t){2===t.usage&&(s=!0,106500&t.symbol.flags&&t.symbol.valueDeclaration&&e.hasModifier(t.symbol.valueDeclaration,64)&&(o=t.symbol.valueDeclaration))}),e.Debug.assert(m(t.range)||0===h.length),s&&!m(t.range)){var c=e.createDiagnosticForNode(t.range,n.cannotWriteInExpression);f[r].push(c),g[r].push(c)}else if(o&&r>0){var c=e.createDiagnosticForNode(o,n.cannotExtractReadonlyPropertyInitializerOutsideConstructor);f[r].push(c),g[r].push(c)}else if(u){var c=e.createDiagnosticForNode(u,n.cannotExtractExportedEntity);f[r].push(c),g[r].push(c)}},U=0;Un.pos});if(-1!==a){var o=i[a];if(e.isNamedDeclaration(o)&&o.name&&e.rangeContainsRange(o.name,n))return{toMove:[i[a]],afterLast:i[a+1]};if(!(n.pos>o.getStart(r))){var s=e.findIndex(i,function(e){return e.end>n.end},a);if(-1===s||!(0===s||i[s].getStart(r)305});return n.kind<148?n:n.getFirstToken(t)}},r.prototype.getLastToken=function(t){this.assertHasRealPosition();var r=this.getChildren(t),n=e.lastOrUndefined(r);if(n)return n.kind<148?n:n.getLastToken(t)},r.prototype.forEachChild=function(t,r){return e.forEachChild(this,t,r)},r}();function n(r,n,i,a){for(e.scanner.setTextPos(n);n=n.length&&(t=this.getEnd()),t||(t=n[r+1]-1);var i=this.getFullText();return"\n"===i[t]&&"\r"===i[t-1]?t-1:t},r.prototype.getNamedDeclarations=function(){return this.namedDeclarations||(this.namedDeclarations=this.computeNamedDeclarations()),this.namedDeclarations},r.prototype.computeNamedDeclarations=function(){var t=e.createMultiMap();return this.forEachChild(function i(a){switch(a.kind){case 239:case 196:case 156:case 155:var o=a,s=n(o);if(s){var c=function(e){var r=t.get(e);r||t.set(e,r=[]);return r}(s),u=e.lastOrUndefined(c);u&&o.parent===u.parent&&o.symbol===u.symbol?o.body&&!u.body&&(c[c.length-1]=o):c.push(o)}e.forEachChild(a,i);break;case 240:case 209:case 241:case 242:case 243:case 244:case 248:case 257:case 253:case 250:case 251:case 158:case 159:case 168:r(a),e.forEachChild(a,i);break;case 151:if(!e.hasModifier(a,92))break;case 237:case 186:var l=a;if(e.isBindingPattern(l.name)){e.forEachChild(l.name,i);break}l.initializer&&i(l.initializer);case 278:case 154:case 153:r(a);break;case 255:a.exportClause&&e.forEach(a.exportClause.elements,i);break;case 249:var _=a.importClause;_&&(_.name&&r(_.name),_.namedBindings&&(251===_.namedBindings.kind?r(_.namedBindings):e.forEach(_.namedBindings.elements,i)));break;case 204:0!==e.getAssignmentDeclarationKind(a)&&r(a);default:e.forEachChild(a,i)}}),t;function r(e){var r=n(e);r&&t.add(r,e)}function n(t){var r=e.getNonAssignedNameOfDeclaration(t);return r&&(e.isComputedPropertyName(r)&&e.isPropertyAccessExpression(r.expression)?r.expression.name.text:e.isPropertyName(r)?e.getNameFromPropertyName(r):void 0)}},r}(r),g=function(){function t(e,t,r){this.fileName=e,this.text=t,this.skipTrivia=r}return t.prototype.getLineAndCharacterOfPosition=function(t){return e.getLineAndCharacterOfPosition(this,t)},t}();function y(t){var r=!0;for(var n in t)if(e.hasProperty(t,n)&&!v(n)){r=!1;break}if(r)return t;var i={};for(var n in t){if(e.hasProperty(t,n))i[v(n)?n:n.charAt(0).toLowerCase()+n.substr(1)]=t[n]}return i}function v(e){return!e.length||e.charAt(0)===e.charAt(0).toLowerCase()}function h(){return{target:1,jsx:1}}e.toEditorSettings=y,e.displayPartsToString=function(t){return t?e.map(t,function(e){return e.text}).join(""):""},e.getDefaultCompilerOptions=h,e.getSupportedCodeFixes=function(){return e.codefix.getSupportedErrorCodes()};var b=function(){function t(t,r){this.host=t,this.currentDirectory=t.getCurrentDirectory(),this.fileNameToEntry=e.createMap();for(var n=0,i=t.getScriptFileNames();n=this.throttleWaitMilliseconds&&(this.lastCancellationCheckTime=t,this.hostCancellationToken.isCancellationRequested())},t.prototype.throwIfCancellationRequested=function(){if(this.isCancellationRequested())throw new e.OperationCanceledException},t}();function E(t){var r=function(t){switch(t.kind){case 10:case 8:if(149===t.parent.kind)return e.isObjectLiteralElement(t.parent.parent)?t.parent.parent:void 0;case 72:return!e.isObjectLiteralElement(t.parent)||188!==t.parent.parent.kind&&268!==t.parent.parent.kind||t.parent.name!==t?void 0:t.parent}return}(t);return r&&(e.isObjectLiteralExpression(r.parent)||e.isJsxAttributes(r.parent))?r:void 0}function N(t,r,n,i){var a=e.getNameFromPropertyName(t.name);if(!a)return e.emptyArray;if(!n.isUnion())return(o=n.getProperty(a))?[o]:e.emptyArray;var o,s=e.mapDefined(n.types,function(n){return e.isObjectLiteralExpression(t.parent)&&r.isTypeInvalidDueToUnionDiscriminant(n,t.parent)?void 0:n.getProperty(a)});if(i&&(0===s.length||s.length===n.types.length)&&(o=n.getProperty(a)))return[o];return 0===s.length?e.mapDefined(n.types,function(e){return e.getProperty(a)}):s}e.ThrottledCancellationToken=k,e.createLanguageService=function(t,r,n){var a;void 0===r&&(r=e.createDocumentRegistry(t.useCaseSensitiveFileNames&&t.useCaseSensitiveFileNames(),t.getCurrentDirectory())),void 0===n&&(n=!1);var o,s,c=new D(t),u=0,l=new C(t.getCancellationToken&&t.getCancellationToken()),_=t.getCurrentDirectory();function d(e){t.log&&t.log(e)}!e.localizedDiagnosticMessages&&t.getLocalizedDiagnosticMessages&&(e.localizedDiagnosticMessages=t.getLocalizedDiagnosticMessages());var p=e.hostUsesCaseSensitiveFileNames(t),f=e.createGetCanonicalFileName(p),m=e.getSourceMapper(p,_,d,t,function(){return o});function g(e){var t=o.getSourceFile(e);if(!t)throw new Error("Could not find file: '"+e+"'.");return t}function v(){if(e.Debug.assert(!n),t.getProjectVersion){var i=t.getProjectVersion();if(i){if(s===i&&!t.hasChangedAutomaticTypeDirectiveNames)return;s=i}}var a=t.getTypeRootsVersion?t.getTypeRootsVersion():0;u!==a&&(d("TypeRoots version has changed; provide new program"),o=void 0,u=a);var c=new b(t,f),g=c.getRootFileNames(),y=t.hasInvalidatedResolution||e.returnFalse,v=c.getProjectReferences();if(!e.isProgramUptoDate(o,g,c.compilationSettings(),function(e){return c.getVersion(e)},T,y,!!t.hasChangedAutomaticTypeDirectiveNames,v)){var h=c.compilationSettings(),D={getSourceFile:function(t,r,n,i){return C(t,e.toPath(t,_,f),0,0,i)},getSourceFileByPath:C,getCancellationToken:function(){return l},getCanonicalFileName:f,useCaseSensitiveFileNames:function(){return p},getNewLine:function(){return e.getNewLineCharacter(h,function(){return e.getNewLineOrDefaultFromHost(t)})},getDefaultLibFileName:function(e){return t.getDefaultLibFileName(e)},writeFile:e.noop,getCurrentDirectory:function(){return _},fileExists:T,readFile:function(r){var n=e.toPath(r,_,f),i=c&&c.getEntryByPath(n);return i?e.isString(i)?void 0:e.getSnapshotText(i.scriptSnapshot):t.readFile&&t.readFile(r)},realpath:t.realpath&&function(e){return t.realpath(e)},directoryExists:function(r){return e.directoryProbablyExists(r,t)},getDirectories:function(e){return t.getDirectories?t.getDirectories(e):[]},readDirectory:function(r,n,i,a,o){return e.Debug.assertDefined(t.readDirectory,"'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"),t.readDirectory(r,n,i,a,o)},onReleaseOldSourceFile:function(e,t){var n=r.getKeyForCompilationSettings(t);r.releaseDocumentWithKey(e.resolvedPath,n)},hasInvalidatedResolution:y,hasChangedAutomaticTypeDirectiveNames:t.hasChangedAutomaticTypeDirectiveNames};t.trace&&(D.trace=function(e){return t.trace(e)}),t.resolveModuleNames&&(D.resolveModuleNames=function(e,r,n,i){return t.resolveModuleNames(e,r,n,i)}),t.resolveTypeReferenceDirectives&&(D.resolveTypeReferenceDirectives=function(e,r,n){return t.resolveTypeReferenceDirectives(e,r,n)});var x=r.getKeyForCompilationSettings(h),S={rootNames:g,options:h,host:D,oldProgram:o,projectReferences:v};return o=e.createProgram(S),c=void 0,m.clearCache(),void o.getTypeChecker()}function T(r){var n=e.toPath(r,_,f),i=c&&c.getEntryByPath(n);return i?!e.isString(i):!!t.fileExists&&t.fileExists(r)}function C(t,n,i,a,s){e.Debug.assert(void 0!==c,"getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host.");var u=c&&c.getOrCreateEntryByPath(t,n);if(u){if(!s){var l=o&&o.getSourceFileByPath(n);if(l)return e.Debug.assertEqual(u.scriptKind,l.scriptKind,"Registered script kind should match new script kind.",n),r.updateDocumentWithKey(t,n,h,x,u.scriptSnapshot,u.version,u.scriptKind)}return r.acquireDocumentWithKey(t,n,h,x,u.scriptSnapshot,u.version,u.scriptKind)}}}function h(){if(!n)return v(),o;e.Debug.assert(void 0===o)}function x(t,r,n){var i=e.normalizePath(t);e.Debug.assert(n.some(function(t){return e.normalizePath(t)===i})),v();var a=n.map(g),s=g(t);return e.DocumentHighlights.getDocumentHighlights(o,l,s,r,a)}function S(t,r,n,i){v();var a=n&&n.isForRename?o.getSourceFiles().filter(function(e){return!o.isSourceFileDefaultLibrary(e)}):o.getSourceFiles();return e.FindAllReferences.findReferenceOrRenameEntries(o,l,a,t,r,n,i)}function T(r){var n=e.getScriptKind(r,t);return 3===n||4===n}var k=e.createMapFromTemplate(((a={})[18]=19,a[20]=21,a[22]=23,a[30]=28,a));function A(r,n){var i=function(t){return e.toPath(t,_,f)};switch(r.type){case"install package":return t.installPackage?t.installPackage({fileName:i(r.file),packageName:r.packageName}):Promise.reject("Host does not implement `installPackage`");case"generate types":var a=r.fileToGenerateTypesFor,o=r.outputFileName;return t.inspectValue?t.inspectValue({fileNameToRequire:a}).then(function(r){var a=i(o);return t.writeFile(a,e.valueInfoToDeclarationFileText(r,n||e.testFormatSettings)),{successMessage:"Wrote types to '"+a+"'"}}):Promise.reject("Host does not implement `installPackage`");default:return e.Debug.assertNever(r)}}function F(r,n,i,a){var o="number"==typeof n?[n,void 0]:[n.pos,n.end];return{file:r,startPosition:o[0],endPosition:o[1],program:h(),host:t,formatContext:e.formatting.getFormatContext(a),cancellationToken:l,preferences:i}}return k.forEach(function(e,t){return k.set(e.toString(),Number(t))}),{dispose:function(){o&&(e.forEach(o.getSourceFiles(),function(e){return r.releaseDocument(e.fileName,o.getCompilerOptions())}),o=void 0),t=void 0},cleanupSemanticCache:function(){o=void 0},getSyntacticDiagnostics:function(e){return v(),o.getSyntacticDiagnostics(g(e),l).slice()},getSemanticDiagnostics:function(t){v();var r=g(t),n=o.getSemanticDiagnostics(r,l);if(!e.getEmitDeclarations(o.getCompilerOptions()))return n.slice();var i=o.getDeclarationDiagnostics(r,l);return n.concat(i)},getSuggestionDiagnostics:function(t){return v(),e.computeSuggestionDiagnostics(g(t),o,l)},getCompilerOptionsDiagnostics:function(){return v(),o.getOptionsDiagnostics(l).concat(o.getGlobalDiagnostics(l))},getSyntacticClassifications:function(t,r){return e.getSyntacticClassifications(l,c.getCurrentSourceFile(t),r)},getSemanticClassifications:function(t,r){return T(t)?(v(),e.getSemanticClassifications(o.getTypeChecker(),l,g(t),o.getClassifiableNames(),r)):[]},getEncodedSyntacticClassifications:function(t,r){return e.getEncodedSyntacticClassifications(l,c.getCurrentSourceFile(t),r)},getEncodedSemanticClassifications:function(t,r){return T(t)?(v(),e.getEncodedSemanticClassifications(o.getTypeChecker(),l,g(t),o.getClassifiableNames(),r)):{spans:[],endOfLineState:0}},getCompletionsAtPosition:function(r,n,a){void 0===a&&(a=e.emptyOptions);var s=i({},e.identity(a),{includeCompletionsForModuleExports:a.includeCompletionsForModuleExports||a.includeExternalModuleExports,includeCompletionsWithInsertText:a.includeCompletionsWithInsertText||a.includeInsertTextCompletions});return v(),e.Completions.getCompletionsAtPosition(t,o,d,g(r),n,s,a.triggerCharacter)},getCompletionEntryDetails:function(r,n,i,a,s,c){return void 0===c&&(c=e.emptyOptions),v(),e.Completions.getCompletionEntryDetails(o,d,g(r),n,{name:i,source:s},t,a&&e.formatting.getFormatContext(a),c,l)},getCompletionEntrySymbol:function(t,r,n,i){return v(),e.Completions.getCompletionEntrySymbol(o,d,g(t),r,{name:n,source:i})},getSignatureHelpItems:function(t,r,n){var i=(void 0===n?e.emptyOptions:n).triggerReason;v();var a=g(t);return e.SignatureHelp.getSignatureHelpItems(o,a,r,i,l)},getQuickInfoAtPosition:function(t,r){v();var n=g(t),i=e.getTouchingPropertyName(n,r);if(i!==n){var a=o.getTypeChecker(),s=function(t,r){var n=E(t);if(n){var i=r.getContextualType(n.parent),a=i&&N(n,r,i,!1);if(a&&1===a.length)return e.first(a)}return r.getSymbolAtLocation(t)}(i,a);if(!s||a.isUnknownSymbol(s)){var c=function(t,r,n){switch(r.kind){case 72:return!e.isLabelName(r)&&!e.isTagName(r);case 189:case 148:return!e.isInComment(t,n);case 100:case 178:case 98:return!0;default:return!1}}(n,i,r)?a.getTypeAtLocation(i):void 0;return c&&{kind:"",kindModifiers:"",textSpan:e.createTextSpanFromNode(i,n),displayParts:a.runWithCancellationToken(l,function(t){return e.typeToDisplayParts(t,c,e.getContainerNode(i))}),documentation:c.symbol?c.symbol.getDocumentationComment(a):void 0,tags:c.symbol?c.symbol.getJsDocTags():void 0}}var u=a.runWithCancellationToken(l,function(t){return e.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(t,s,n,e.getContainerNode(i),i)}),_=u.symbolKind,d=u.displayParts,p=u.documentation,f=u.tags;return{kind:_,kindModifiers:e.SymbolDisplay.getSymbolModifiers(s),textSpan:e.createTextSpanFromNode(i,n),displayParts:d,documentation:p,tags:f}}},getDefinitionAtPosition:function(t,r){return v(),e.GoToDefinition.getDefinitionAtPosition(o,g(t),r)},getDefinitionAndBoundSpan:function(t,r){return v(),e.GoToDefinition.getDefinitionAndBoundSpan(o,g(t),r)},getImplementationAtPosition:function(t,r){return v(),e.FindAllReferences.getImplementationsAtPosition(o,l,o.getSourceFiles(),g(t),r)},getTypeDefinitionAtPosition:function(t,r){return v(),e.GoToDefinition.getTypeDefinitionAtPosition(o.getTypeChecker(),g(t),r)},getReferencesAtPosition:function(t,r){return v(),S(e.getTouchingPropertyName(g(t),r),r,{},e.FindAllReferences.toReferenceEntry)},findReferences:function(t,r){return v(),e.FindAllReferences.findReferencedSymbols(o,l,o.getSourceFiles(),g(t),r)},getOccurrencesAtPosition:function(t,r){return e.flatMap(x(t,r,[t]),function(e){return e.highlightSpans.map(function(t){return{fileName:e.fileName,textSpan:t.textSpan,isWriteAccess:"writtenReference"===t.kind,isDefinition:!1,isInString:t.isInString}})})},getDocumentHighlights:x,getNameOrDottedNameSpan:function(t,r,n){var i=c.getCurrentSourceFile(t),a=e.getTouchingPropertyName(i,r);if(a!==i){switch(a.kind){case 189:case 148:case 10:case 87:case 102:case 96:case 98:case 100:case 178:case 72:break;default:return}for(var o=a;;)if(e.isRightSideOfPropertyAccess(o)||e.isRightSideOfQualifiedName(o))o=o.parent;else{if(!e.isNameOfModuleDeclaration(o))break;if(244!==o.parent.parent.kind||o.parent.parent.body!==o.parent)break;o=o.parent.parent.name}return e.createTextSpanFromBounds(o.getStart(),a.getEnd())}},getBreakpointStatementAtPosition:function(t,r){var n=c.getCurrentSourceFile(t);return e.BreakpointResolver.spanInSourceFileAtLocation(n,r)},getNavigateToItems:function(t,r,n,i){void 0===i&&(i=!1),v();var a=n?[g(n)]:o.getSourceFiles();return e.NavigateTo.getNavigateToItems(a,o.getTypeChecker(),l,t,r,i)},getRenameInfo:function(t,r){return v(),e.Rename.getRenameInfo(o,g(t),r)},findRenameLocations:function(t,r,n,i){v();var a=g(t),o=e.getTouchingPropertyName(a,r);if(e.isIdentifier(o)&&(e.isJsxOpeningElement(o.parent)||e.isJsxClosingElement(o.parent))&&e.isIntrinsicJsxName(o.escapedText)){var s=o.parent.parent;return[s.openingElement,s.closingElement].map(function(t){return{fileName:a.fileName,textSpan:e.createTextSpanFromNode(t.tagName,a)}})}return S(o,r,{findInStrings:n,findInComments:i,isForRename:!0},e.FindAllReferences.toRenameLocation)},getNavigationBarItems:function(t){return e.NavigationBar.getNavigationBarItems(c.getCurrentSourceFile(t),l)},getNavigationTree:function(t){return e.NavigationBar.getNavigationTree(c.getCurrentSourceFile(t),l)},getOutliningSpans:function(t){var r=c.getCurrentSourceFile(t);return e.OutliningElementsCollector.collectElements(r,l)},getTodoComments:function(t,r){v();var n=g(t);l.throwIfCancellationRequested();var i,a,o=n.text,s=[];if(r.length>0&&(a=n.fileName,!e.stringContains(a,"/node_modules/")))for(var c=function(){var t="("+/(?:^(?:\s|\*)*)/.source+"|"+/(?:\/\/+\s*)/.source+"|"+/(?:\/\*+\s*)/.source+")",n="(?:"+e.map(r,function(e){return"("+e.text.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")+")"}).join("|")+")";return new RegExp(t+"("+n+/(?:.*?)/.source+")"+/(?:$|\*\/)/.source,"gim")}(),u=void 0;u=c.exec(o);){l.throwIfCancellationRequested(),e.Debug.assert(u.length===r.length+3);var _=u[1],d=u.index+_.length;if(e.isInComment(n,d)){for(var p=void 0,f=0;f=97&&i<=122||i>=65&&i<=90||i>=48&&i<=57)){var m=u[2];s.push({descriptor:p,message:m,position:d})}}}return s},getBraceMatchingAtPosition:function(t,r){var n=c.getCurrentSourceFile(t),i=e.getTouchingToken(n,r),a=i.getStart(n)===r?k.get(i.kind.toString()):void 0,o=a&&e.findChildOfKind(i.parent,a,n);return o?[e.createTextSpanFromNode(i,n),e.createTextSpanFromNode(o,n)].sort(function(e,t){return e.start-t.start}):e.emptyArray},getIndentationAtPosition:function(t,r,n){var i=e.timestamp(),a=y(n),o=c.getCurrentSourceFile(t);d("getIndentationAtPosition: getCurrentSourceFile: "+(e.timestamp()-i)),i=e.timestamp();var s=e.formatting.SmartIndenter.getIndentation(r,o,a);return d("getIndentationAtPosition: computeIndentation : "+(e.timestamp()-i)),s},getFormattingEditsForRange:function(t,r,n,i){var a=c.getCurrentSourceFile(t);return e.formatting.formatSelection(r,n,a,e.formatting.getFormatContext(y(i)))},getFormattingEditsForDocument:function(t,r){return e.formatting.formatDocument(c.getCurrentSourceFile(t),e.formatting.getFormatContext(y(r)))},getFormattingEditsAfterKeystroke:function(t,r,n,i){var a=c.getCurrentSourceFile(t),o=e.formatting.getFormatContext(y(i));if(!e.isInComment(a,r))switch(n){case"{":return e.formatting.formatOnOpeningCurly(r,a,o);case"}":return e.formatting.formatOnClosingCurly(r,a,o);case";":return e.formatting.formatOnSemicolon(r,a,o);case"\n":return e.formatting.formatOnEnter(r,a,o)}return[]},getDocCommentTemplateAtPosition:function(r,n){return e.JsDoc.getDocCommentTemplateAtPosition(e.getNewLineOrDefaultFromHost(t),c.getCurrentSourceFile(r),n)},isValidBraceCompletionAtPosition:function(t,r,n){if(60===n)return!1;var i=c.getCurrentSourceFile(t);if(e.isInString(i,r))return!1;if(e.isInsideJsxElementOrAttribute(i,r))return 123===n;if(e.isInTemplateString(i,r))return!1;switch(n){case 39:case 34:case 96:return!e.isInComment(i,r)}return!0},getJsxClosingTagAtPosition:function(t,r){var n=c.getCurrentSourceFile(t),i=e.findPrecedingToken(r,n);if(i){var a=30===i.kind&&e.isJsxOpeningElement(i.parent)?i.parent.parent:e.isJsxText(i)?i.parent:void 0;return a&&function t(r){var n=r.openingElement,i=r.closingElement,a=r.parent;return!e.tagNamesAreEquivalent(n.tagName,i.tagName)||e.isJsxElement(a)&&e.tagNamesAreEquivalent(n.tagName,a.openingElement.tagName)&&t(a)}(a)?{newText:""}:void 0}},getSpanOfEnclosingComment:function(t,r,n){var i=c.getCurrentSourceFile(t),a=e.formatting.getRangeOfEnclosingComment(i,r);return!a||n&&3!==a.kind?void 0:e.createTextSpanFromRange(a)},getCodeFixesAtPosition:function(r,n,i,a,s,c){void 0===c&&(c=e.emptyOptions),v();var u=g(r),_=e.createTextSpanFromBounds(n,i),d=e.formatting.getFormatContext(s);return e.flatMap(e.deduplicate(a,e.equateValues,e.compareValues),function(r){return l.throwIfCancellationRequested(),e.codefix.getFixes({errorCode:r,sourceFile:u,span:_,program:o,host:t,cancellationToken:l,formatContext:d,preferences:c})})},getCombinedCodeFix:function(r,n,i,a){void 0===a&&(a=e.emptyOptions),v(),e.Debug.assert("file"===r.type);var s=g(r.fileName),c=e.formatting.getFormatContext(i);return e.codefix.getAllFixes({fixId:n,sourceFile:s,program:o,host:t,cancellationToken:l,formatContext:c,preferences:a})},applyCodeActionCommand:function(t,r){var n="string"==typeof t?r:t,i="string"!=typeof t?r:void 0;return e.isArray(n)?Promise.all(n.map(function(e){return A(e,i)})):A(n,i)},organizeImports:function(r,n,i){void 0===i&&(i=e.emptyOptions),v(),e.Debug.assert("file"===r.type);var a=g(r.fileName),s=e.formatting.getFormatContext(n);return e.OrganizeImports.organizeImports(a,s,t,o,i)},getEditsForFileRename:function(r,n,i,a){return void 0===a&&(a=e.emptyOptions),e.getEditsForFileRename(h(),r,n,t,e.formatting.getFormatContext(i),a,m)},getEmitOutput:function(r,n){void 0===n&&(n=!1),v();var i=g(r),a=t.getCustomTransformers&&t.getCustomTransformers();return e.getFileEmitOutput(o,i,n,l,a)},getNonBoundSourceFile:function(e){return c.getCurrentSourceFile(e)},getProgram:h,getApplicableRefactors:function(t,r,n){void 0===n&&(n=e.emptyOptions),v();var i=g(t);return e.refactor.getApplicableRefactors(F(i,r,n))},getEditsForRefactor:function(t,r,n,i,a,o){void 0===o&&(o=e.emptyOptions),v();var s=g(t);return e.refactor.getEditsForRefactor(F(s,n,o,r),i,a)},toLineColumnOffset:m.toLineColumnOffset,getSourceMapper:function(){return m}}},e.getNameTable=function(t){return t.nameTable||function(t){var r=t.nameTable=e.createUnderscoreEscapedMap();t.forEachChild(function t(n){if(e.isIdentifier(n)&&!e.isTagName(n)&&n.escapedText||e.isStringOrNumericLiteralLike(n)&&function(t){return e.isDeclarationName(t)||259===t.parent.kind||function(e){return e&&e.parent&&190===e.parent.kind&&e.parent.argumentExpression===e}(t)||e.isLiteralComputedPropertyDeclarationName(t)}(n)){var i=e.getEscapedTextOfIdentifierOrLiteral(n);r.set(i,void 0===r.get(i)?n.pos:-1)}if(e.forEachChild(n,t),e.hasJSDocNodes(n))for(var a=0,o=n.jsDoc;ai){var a=e.findPrecedingToken(n.pos,t);if(!a||t.getLineAndCharacterOfPosition(a.getEnd()).line!==i)return;n=a}if(!(4194304&n.flags))return _(n)}function o(r,n){var i=r.decorators?e.skipTrivia(t.text,r.decorators.end):r.getStart(t);return e.createTextSpanFromBounds(i,(n||r).getEnd())}function s(r,n){return o(r,e.findNextToken(n,n.parent,t))}function c(e,r){return e&&i===t.getLineAndCharacterOfPosition(e.getStart(t)).line?_(e):_(r)}function u(r){return _(e.findPrecedingToken(r.pos,t))}function l(r){return _(e.findNextToken(r,r.parent,t))}function _(r){if(r){var n=r.parent;switch(r.kind){case 219:return D(r.declarationList.declarations[0]);case 237:case 154:case 153:return D(r);case 151:return function t(r){if(e.isBindingPattern(r.name))return C(r.name);if(function(t){return!!t.initializer||void 0!==t.dotDotDotToken||e.hasModifier(t,12)}(r))return o(r);var n=r.parent,i=n.parameters.indexOf(r);return e.Debug.assert(-1!==i),0!==i?t(n.parameters[i-1]):_(n.body)}(r);case 239:case 156:case 155:case 158:case 159:case 157:case 196:case 197:return function(e){if(e.body)return x(e)?o(e):_(e.body)}(r);case 218:if(e.isFunctionBlock(r))return v=(y=r).statements.length?y.statements[0]:y.getLastToken(),x(y.parent)?c(y.parent,v):_(v);case 245:return S(r);case 274:return S(r.block);case 221:return o(r.expression);case 230:return o(r.getChildAt(0),r.expression);case 224:return s(r,r.expression);case 223:return _(r.statement);case 236:return o(r.getChildAt(0));case 222:return s(r,r.expression);case 233:return _(r.statement);case 229:case 228:return o(r.getChildAt(0),r.label);case 225:return(g=r).initializer?T(g):g.condition?o(g.condition):g.incrementor?o(g.incrementor):void 0;case 226:return s(r,r.expression);case 227:return T(r);case 232:return s(r,r.expression);case 271:case 272:return _(r.statements[0]);case 235:return S(r.tryBlock);case 234:case 254:return o(r,r.expression);case 248:return o(r,r.moduleReference);case 249:case 255:return o(r,r.moduleSpecifier);case 244:if(1!==e.getModuleInstanceState(r))return;case 240:case 243:case 278:case 186:return o(r);case 231:return _(r.statement);case 152:return h=n.decorators,e.createTextSpanFromBounds(e.skipTrivia(t.text,h.pos),h.end);case 184:case 185:return C(r);case 241:case 242:return;case 26:case 1:return c(e.findPrecedingToken(r.pos,t));case 27:return u(r);case 18:return function(r){switch(r.parent.kind){case 243:var n=r.parent;return c(e.findPrecedingToken(r.pos,t,r.parent),n.members.length?n.members[0]:n.getLastToken(t));case 240:var i=r.parent;return c(e.findPrecedingToken(r.pos,t,r.parent),i.members.length?i.members[0]:i.getLastToken(t));case 246:return c(r.parent.parent,r.parent.clauses[0])}return _(r.parent)}(r);case 19:return function(t){switch(t.parent.kind){case 245:if(1!==e.getModuleInstanceState(t.parent.parent))return;case 243:case 240:return o(t);case 218:if(e.isFunctionBlock(t.parent))return o(t);case 274:return _(e.lastOrUndefined(t.parent.statements));case 246:var r=t.parent,n=e.lastOrUndefined(r.clauses);return n?_(e.lastOrUndefined(n.statements)):void 0;case 184:var i=t.parent;return _(e.lastOrUndefined(i.elements)||i);default:if(e.isArrayLiteralOrObjectLiteralDestructuringPattern(t.parent)){var a=t.parent;return o(e.lastOrUndefined(a.properties)||a)}return _(t.parent)}}(r);case 23:return function(t){switch(t.parent.kind){case 185:var r=t.parent;return o(e.lastOrUndefined(r.elements)||r);default:if(e.isArrayLiteralOrObjectLiteralDestructuringPattern(t.parent)){var n=t.parent;return o(e.lastOrUndefined(n.elements)||n)}return _(t.parent)}}(r);case 20:return function(e){return 223===e.parent.kind||191===e.parent.kind||192===e.parent.kind?u(e):195===e.parent.kind?l(e):_(e.parent)}(r);case 21:return function(e){switch(e.parent.kind){case 196:case 239:case 197:case 156:case 155:case 158:case 159:case 157:case 224:case 223:case 225:case 227:case 191:case 192:case 195:return u(e);default:return _(e.parent)}}(r);case 57:return function(t){return e.isFunctionLike(t.parent)||275===t.parent.kind||151===t.parent.kind?u(t):_(t.parent)}(r);case 30:case 28:return function(e){return 194===e.parent.kind?l(e):_(e.parent)}(r);case 107:return function(e){return 223===e.parent.kind?s(e,e.parent.expression):_(e.parent)}(r);case 83:case 75:case 88:return l(r);case 147:return function(e){return 227===e.parent.kind?l(e):_(e.parent)}(r);default:if(e.isArrayLiteralOrObjectLiteralDestructuringPattern(r))return k(r);if((72===r.kind||208===r.kind||275===r.kind||276===r.kind)&&e.isArrayLiteralOrObjectLiteralDestructuringPattern(n))return o(r);if(204===r.kind){var i=r,a=i.left,d=i.operatorToken;if(e.isArrayLiteralOrObjectLiteralDestructuringPattern(a))return k(a);if(59===d.kind&&e.isArrayLiteralOrObjectLiteralDestructuringPattern(r.parent))return o(r);if(27===d.kind)return _(a)}if(e.isExpressionNode(r))switch(n.kind){case 223:return u(r);case 152:return _(r.parent);case 225:case 227:return o(r);case 204:if(27===r.parent.operatorToken.kind)return o(r);break;case 197:if(r.parent.body===r)return o(r)}switch(r.parent.kind){case 275:if(r.parent.name===r&&!e.isArrayLiteralOrObjectLiteralDestructuringPattern(r.parent.parent))return _(r.parent.initializer);break;case 194:if(r.parent.type===r)return l(r.parent.type);break;case 237:case 151:var p=r.parent,f=p.initializer,m=p.type;if(f===r||m===r||e.isAssignmentOperator(r.kind))return u(r);break;case 204:if(a=r.parent.left,e.isArrayLiteralOrObjectLiteralDestructuringPattern(a)&&r!==a)return u(r);break;default:if(e.isFunctionLike(r.parent)&&r.parent.type===r)return u(r)}return _(r.parent)}}var g,y,v,h;function b(r){return e.isVariableDeclarationList(r.parent)&&r.parent.declarations[0]===r?o(e.findPrecedingToken(r.pos,t,r.parent),r):o(r)}function D(r){if(226===r.parent.parent.kind)return _(r.parent.parent);var n=r.parent;return e.isBindingPattern(r.name)?C(r.name):r.initializer||e.hasModifier(r,1)||227===n.parent.kind?b(r):e.isVariableDeclarationList(r.parent)&&r.parent.declarations[0]!==r?_(e.findPrecedingToken(r.pos,t,r.parent)):void 0}function x(t){return e.hasModifier(t,1)||240===t.parent.kind&&157!==t.kind}function S(r){switch(r.parent.kind){case 244:if(1!==e.getModuleInstanceState(r.parent))return;case 224:case 222:case 226:return c(r.parent,r.statements[0]);case 225:case 227:return c(e.findPrecedingToken(r.pos,t,r.parent),r.statements[0])}return _(r.statements[0])}function T(e){if(238!==e.initializer.kind)return _(e.initializer);var t=e.initializer;return t.declarations.length>0?_(t.declarations[0]):void 0}function C(t){var r=e.forEach(t.elements,function(e){return 210!==e.kind?e:void 0});return r?_(r):186===t.parent.kind?o(t.parent):b(t.parent)}function k(t){e.Debug.assert(185!==t.kind&&184!==t.kind);var r=187===t.kind?t.elements:t.properties,n=e.forEach(r,function(e){return 210!==e.kind?e:void 0});return n?_(n):o(204===t.parent.kind?t.parent:t)}}}}(e.BreakpointResolver||(e.BreakpointResolver={}))}(c||(c={})),function(e){e.transform=function(t,r,n){var i=[];n=e.fixupCompilerOptions(n,i);var a=e.isArray(t)?t:[t],o=e.transformNodes(void 0,void 0,n,a,r,!0);return o.diagnostics=e.concatenate(o.diagnostics,i),o}}(c||(c={}));var c,u,l=function(){return this}();!function(t){function r(e,t){e&&e.log("*INTERNAL ERROR* - Exception in typescript services: "+t.message)}var n=function(){function e(e){this.scriptSnapshotShim=e}return e.prototype.getText=function(e,t){return this.scriptSnapshotShim.getText(e,t)},e.prototype.getLength=function(){return this.scriptSnapshotShim.getLength()},e.prototype.getChangeRange=function(e){var r=e,n=this.scriptSnapshotShim.getChangeRange(r.scriptSnapshotShim);if(null===n)return null;var i=JSON.parse(n);return t.createTextChangeRange(t.createTextSpan(i.span.start,i.span.length),i.newLength)},e.prototype.dispose=function(){"dispose"in this.scriptSnapshotShim&&this.scriptSnapshotShim.dispose()},e}(),i=function(){function e(e){var r=this;this.shimHost=e,this.loggingEnabled=!1,this.tracingEnabled=!1,"getModuleResolutionsForFile"in this.shimHost&&(this.resolveModuleNames=function(e,n){var i=JSON.parse(r.shimHost.getModuleResolutionsForFile(n));return t.map(e,function(e){var r=t.getProperty(i,e);return r?{resolvedFileName:r,extension:t.extensionFromPath(r),isExternalLibraryImport:!1}:void 0})}),"directoryExists"in this.shimHost&&(this.directoryExists=function(e){return r.shimHost.directoryExists(e)}),"getTypeReferenceDirectiveResolutionsForFile"in this.shimHost&&(this.resolveTypeReferenceDirectives=function(e,n){var i=JSON.parse(r.shimHost.getTypeReferenceDirectiveResolutionsForFile(n));return t.map(e,function(e){return t.getProperty(i,e)})})}return e.prototype.log=function(e){this.loggingEnabled&&this.shimHost.log(e)},e.prototype.trace=function(e){this.tracingEnabled&&this.shimHost.trace(e)},e.prototype.error=function(e){this.shimHost.error(e)},e.prototype.getProjectVersion=function(){if(this.shimHost.getProjectVersion)return this.shimHost.getProjectVersion()},e.prototype.getTypeRootsVersion=function(){return this.shimHost.getTypeRootsVersion?this.shimHost.getTypeRootsVersion():0},e.prototype.useCaseSensitiveFileNames=function(){return!!this.shimHost.useCaseSensitiveFileNames&&this.shimHost.useCaseSensitiveFileNames()},e.prototype.getCompilationSettings=function(){var e=this.shimHost.getCompilationSettings();if(null===e||""===e)throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");var t=JSON.parse(e);return t.allowNonTsExtensions=!0,t},e.prototype.getScriptFileNames=function(){var e=this.shimHost.getScriptFileNames();return JSON.parse(e)},e.prototype.getScriptSnapshot=function(e){var t=this.shimHost.getScriptSnapshot(e);return t&&new n(t)},e.prototype.getScriptKind=function(e){return"getScriptKind"in this.shimHost?this.shimHost.getScriptKind(e):0},e.prototype.getScriptVersion=function(e){return this.shimHost.getScriptVersion(e)},e.prototype.getLocalizedDiagnosticMessages=function(){var e=this.shimHost.getLocalizedDiagnosticMessages();if(null===e||""===e)return null;try{return JSON.parse(e)}catch(e){return this.log(e.description||"diagnosticMessages.generated.json has invalid JSON format"),null}},e.prototype.getCancellationToken=function(){var e=this.shimHost.getCancellationToken();return new t.ThrottledCancellationToken(e)},e.prototype.getCurrentDirectory=function(){return this.shimHost.getCurrentDirectory()},e.prototype.getDirectories=function(e){return JSON.parse(this.shimHost.getDirectories(e))},e.prototype.getDefaultLibFileName=function(e){return this.shimHost.getDefaultLibFileName(JSON.stringify(e))},e.prototype.readDirectory=function(e,r,n,i,a){var o=t.getFileMatcherPatterns(e,n,i,this.shimHost.useCaseSensitiveFileNames(),this.shimHost.getCurrentDirectory());return JSON.parse(this.shimHost.readDirectory(e,JSON.stringify(r),JSON.stringify(o.basePaths),o.excludePattern,o.includeFilePattern,o.includeDirectoryPattern,a))},e.prototype.readFile=function(e,t){return this.shimHost.readFile(e,t)},e.prototype.fileExists=function(e){return this.shimHost.fileExists(e)},e}();t.LanguageServiceShimHostAdapter=i;var a=function(){function e(e){var t=this;this.shimHost=e,this.useCaseSensitiveFileNames=!!this.shimHost.useCaseSensitiveFileNames&&this.shimHost.useCaseSensitiveFileNames(),"directoryExists"in this.shimHost?this.directoryExists=function(e){return t.shimHost.directoryExists(e)}:this.directoryExists=void 0,"realpath"in this.shimHost?this.realpath=function(e){return t.shimHost.realpath(e)}:this.realpath=void 0}return e.prototype.readDirectory=function(e,r,n,i,a){var o=t.getFileMatcherPatterns(e,n,i,this.shimHost.useCaseSensitiveFileNames(),this.shimHost.getCurrentDirectory());return JSON.parse(this.shimHost.readDirectory(e,JSON.stringify(r),JSON.stringify(o.basePaths),o.excludePattern,o.includeFilePattern,o.includeDirectoryPattern,a))},e.prototype.fileExists=function(e){return this.shimHost.fileExists(e)},e.prototype.readFile=function(e){return this.shimHost.readFile(e)},e.prototype.getDirectories=function(e){return JSON.parse(this.shimHost.getDirectories(e))},e}();function o(e,t,r,n){return c(e,t,!0,r,n)}function c(e,n,i,a,o){try{var s=function(e,r,n,i){var a;i&&(e.log(r),a=t.timestamp());var o=n();if(i){var s=t.timestamp();if(e.log(r+" completed in "+(s-a)+" msec"),t.isString(o)){var c=o;c.length>128&&(c=c.substring(0,128)+"..."),e.log(" result.length="+c.length+", result='"+JSON.stringify(c)+"'")}}return o}(e,n,a,o);return i?JSON.stringify({result:s}):s}catch(i){return i instanceof t.OperationCanceledException?JSON.stringify({canceled:!0}):(r(e,i),i.description=n,JSON.stringify({error:i}))}}t.CoreServicesShimHostAdapter=a;var u=function(){function e(e){this.factory=e,e.registerShim(this)}return e.prototype.dispose=function(e){this.factory.unregisterShim(this)},e}();function _(e,r){return e.map(function(e){return function(e,r){return{message:t.flattenDiagnosticMessageText(e.messageText,r),start:e.start,length:e.length,category:t.diagnosticCategoryName(e),code:e.code,reportsUnnecessary:e.reportsUnnecessary}}(e,r)})}t.realizeDiagnostics=_;var d=function(e){function r(t,r,n){var i=e.call(this,t)||this;return i.host=r,i.languageService=n,i.logPerformance=!1,i.logger=i.host,i}return s(r,e),r.prototype.forwardJSONCall=function(e,t){return o(this.logger,e,t,this.logPerformance)},r.prototype.dispose=function(t){this.logger.log("dispose()"),this.languageService.dispose(),this.languageService=null,l&&l.CollectGarbage&&(l.CollectGarbage(),this.logger.log("CollectGarbage()")),this.logger=null,e.prototype.dispose.call(this,t)},r.prototype.refresh=function(e){this.forwardJSONCall("refresh("+e+")",function(){return null})},r.prototype.cleanupSemanticCache=function(){var e=this;this.forwardJSONCall("cleanupSemanticCache()",function(){return e.languageService.cleanupSemanticCache(),null})},r.prototype.realizeDiagnostics=function(e){return _(e,t.getNewLineOrDefaultFromHost(this.host))},r.prototype.getSyntacticClassifications=function(e,r,n){var i=this;return this.forwardJSONCall("getSyntacticClassifications('"+e+"', "+r+", "+n+")",function(){return i.languageService.getSyntacticClassifications(e,t.createTextSpan(r,n))})},r.prototype.getSemanticClassifications=function(e,r,n){var i=this;return this.forwardJSONCall("getSemanticClassifications('"+e+"', "+r+", "+n+")",function(){return i.languageService.getSemanticClassifications(e,t.createTextSpan(r,n))})},r.prototype.getEncodedSyntacticClassifications=function(e,r,n){var i=this;return this.forwardJSONCall("getEncodedSyntacticClassifications('"+e+"', "+r+", "+n+")",function(){return p(i.languageService.getEncodedSyntacticClassifications(e,t.createTextSpan(r,n)))})},r.prototype.getEncodedSemanticClassifications=function(e,r,n){var i=this;return this.forwardJSONCall("getEncodedSemanticClassifications('"+e+"', "+r+", "+n+")",function(){return p(i.languageService.getEncodedSemanticClassifications(e,t.createTextSpan(r,n)))})},r.prototype.getSyntacticDiagnostics=function(e){var t=this;return this.forwardJSONCall("getSyntacticDiagnostics('"+e+"')",function(){var r=t.languageService.getSyntacticDiagnostics(e);return t.realizeDiagnostics(r)})},r.prototype.getSemanticDiagnostics=function(e){var t=this;return this.forwardJSONCall("getSemanticDiagnostics('"+e+"')",function(){var r=t.languageService.getSemanticDiagnostics(e);return t.realizeDiagnostics(r)})},r.prototype.getSuggestionDiagnostics=function(e){var t=this;return this.forwardJSONCall("getSuggestionDiagnostics('"+e+"')",function(){return t.realizeDiagnostics(t.languageService.getSuggestionDiagnostics(e))})},r.prototype.getCompilerOptionsDiagnostics=function(){var e=this;return this.forwardJSONCall("getCompilerOptionsDiagnostics()",function(){var t=e.languageService.getCompilerOptionsDiagnostics();return e.realizeDiagnostics(t)})},r.prototype.getQuickInfoAtPosition=function(e,t){var r=this;return this.forwardJSONCall("getQuickInfoAtPosition('"+e+"', "+t+")",function(){return r.languageService.getQuickInfoAtPosition(e,t)})},r.prototype.getNameOrDottedNameSpan=function(e,t,r){var n=this;return this.forwardJSONCall("getNameOrDottedNameSpan('"+e+"', "+t+", "+r+")",function(){return n.languageService.getNameOrDottedNameSpan(e,t,r)})},r.prototype.getBreakpointStatementAtPosition=function(e,t){var r=this;return this.forwardJSONCall("getBreakpointStatementAtPosition('"+e+"', "+t+")",function(){return r.languageService.getBreakpointStatementAtPosition(e,t)})},r.prototype.getSignatureHelpItems=function(e,t,r){var n=this;return this.forwardJSONCall("getSignatureHelpItems('"+e+"', "+t+")",function(){return n.languageService.getSignatureHelpItems(e,t,r)})},r.prototype.getDefinitionAtPosition=function(e,t){var r=this;return this.forwardJSONCall("getDefinitionAtPosition('"+e+"', "+t+")",function(){return r.languageService.getDefinitionAtPosition(e,t)})},r.prototype.getDefinitionAndBoundSpan=function(e,t){var r=this;return this.forwardJSONCall("getDefinitionAndBoundSpan('"+e+"', "+t+")",function(){return r.languageService.getDefinitionAndBoundSpan(e,t)})},r.prototype.getTypeDefinitionAtPosition=function(e,t){var r=this;return this.forwardJSONCall("getTypeDefinitionAtPosition('"+e+"', "+t+")",function(){return r.languageService.getTypeDefinitionAtPosition(e,t)})},r.prototype.getImplementationAtPosition=function(e,t){var r=this;return this.forwardJSONCall("getImplementationAtPosition('"+e+"', "+t+")",function(){return r.languageService.getImplementationAtPosition(e,t)})},r.prototype.getRenameInfo=function(e,t){var r=this;return this.forwardJSONCall("getRenameInfo('"+e+"', "+t+")",function(){return r.languageService.getRenameInfo(e,t)})},r.prototype.findRenameLocations=function(e,t,r,n){var i=this;return this.forwardJSONCall("findRenameLocations('"+e+"', "+t+", "+r+", "+n+")",function(){return i.languageService.findRenameLocations(e,t,r,n)})},r.prototype.getBraceMatchingAtPosition=function(e,t){var r=this;return this.forwardJSONCall("getBraceMatchingAtPosition('"+e+"', "+t+")",function(){return r.languageService.getBraceMatchingAtPosition(e,t)})},r.prototype.isValidBraceCompletionAtPosition=function(e,t,r){var n=this;return this.forwardJSONCall("isValidBraceCompletionAtPosition('"+e+"', "+t+", "+r+")",function(){return n.languageService.isValidBraceCompletionAtPosition(e,t,r)})},r.prototype.getSpanOfEnclosingComment=function(e,t,r){var n=this;return this.forwardJSONCall("getSpanOfEnclosingComment('"+e+"', "+t+")",function(){return n.languageService.getSpanOfEnclosingComment(e,t,r)})},r.prototype.getIndentationAtPosition=function(e,t,r){var n=this;return this.forwardJSONCall("getIndentationAtPosition('"+e+"', "+t+")",function(){var i=JSON.parse(r);return n.languageService.getIndentationAtPosition(e,t,i)})},r.prototype.getReferencesAtPosition=function(e,t){var r=this;return this.forwardJSONCall("getReferencesAtPosition('"+e+"', "+t+")",function(){return r.languageService.getReferencesAtPosition(e,t)})},r.prototype.findReferences=function(e,t){var r=this;return this.forwardJSONCall("findReferences('"+e+"', "+t+")",function(){return r.languageService.findReferences(e,t)})},r.prototype.getOccurrencesAtPosition=function(e,t){var r=this;return this.forwardJSONCall("getOccurrencesAtPosition('"+e+"', "+t+")",function(){return r.languageService.getOccurrencesAtPosition(e,t)})},r.prototype.getDocumentHighlights=function(e,r,n){var i=this;return this.forwardJSONCall("getDocumentHighlights('"+e+"', "+r+")",function(){var a=i.languageService.getDocumentHighlights(e,r,JSON.parse(n)),o=t.normalizeSlashes(e).toLowerCase();return t.filter(a,function(e){return t.normalizeSlashes(e.fileName).toLowerCase()===o})})},r.prototype.getCompletionsAtPosition=function(e,t,r){var n=this;return this.forwardJSONCall("getCompletionsAtPosition('"+e+"', "+t+", "+r+")",function(){return n.languageService.getCompletionsAtPosition(e,t,r)})},r.prototype.getCompletionEntryDetails=function(e,t,r,n,i,a){var o=this;return this.forwardJSONCall("getCompletionEntryDetails('"+e+"', "+t+", '"+r+"')",function(){var s=void 0===n?void 0:JSON.parse(n);return o.languageService.getCompletionEntryDetails(e,t,r,s,i,a)})},r.prototype.getFormattingEditsForRange=function(e,t,r,n){var i=this;return this.forwardJSONCall("getFormattingEditsForRange('"+e+"', "+t+", "+r+")",function(){var a=JSON.parse(n);return i.languageService.getFormattingEditsForRange(e,t,r,a)})},r.prototype.getFormattingEditsForDocument=function(e,t){var r=this;return this.forwardJSONCall("getFormattingEditsForDocument('"+e+"')",function(){var n=JSON.parse(t);return r.languageService.getFormattingEditsForDocument(e,n)})},r.prototype.getFormattingEditsAfterKeystroke=function(e,t,r,n){var i=this;return this.forwardJSONCall("getFormattingEditsAfterKeystroke('"+e+"', "+t+", '"+r+"')",function(){var a=JSON.parse(n);return i.languageService.getFormattingEditsAfterKeystroke(e,t,r,a)})},r.prototype.getDocCommentTemplateAtPosition=function(e,t){var r=this;return this.forwardJSONCall("getDocCommentTemplateAtPosition('"+e+"', "+t+")",function(){return r.languageService.getDocCommentTemplateAtPosition(e,t)})},r.prototype.getNavigateToItems=function(e,t,r){var n=this;return this.forwardJSONCall("getNavigateToItems('"+e+"', "+t+", "+r+")",function(){return n.languageService.getNavigateToItems(e,t,r)})},r.prototype.getNavigationBarItems=function(e){var t=this;return this.forwardJSONCall("getNavigationBarItems('"+e+"')",function(){return t.languageService.getNavigationBarItems(e)})},r.prototype.getNavigationTree=function(e){var t=this;return this.forwardJSONCall("getNavigationTree('"+e+"')",function(){return t.languageService.getNavigationTree(e)})},r.prototype.getOutliningSpans=function(e){var t=this;return this.forwardJSONCall("getOutliningSpans('"+e+"')",function(){return t.languageService.getOutliningSpans(e)})},r.prototype.getTodoComments=function(e,t){var r=this;return this.forwardJSONCall("getTodoComments('"+e+"')",function(){return r.languageService.getTodoComments(e,JSON.parse(t))})},r.prototype.getEmitOutput=function(e){var t=this;return this.forwardJSONCall("getEmitOutput('"+e+"')",function(){return t.languageService.getEmitOutput(e)})},r.prototype.getEmitOutputObject=function(e){var t=this;return c(this.logger,"getEmitOutput('"+e+"')",!1,function(){return t.languageService.getEmitOutput(e)},this.logPerformance)},r}(u);function p(e){return{spans:e.spans.join(","),endOfLineState:e.endOfLineState}}var f=function(e){function r(r,n){var i=e.call(this,r)||this;return i.logger=n,i.logPerformance=!1,i.classifier=t.createClassifier(),i}return s(r,e),r.prototype.getEncodedLexicalClassifications=function(e,t,r){var n=this;return void 0===r&&(r=!1),o(this.logger,"getEncodedLexicalClassifications",function(){return p(n.classifier.getEncodedLexicalClassifications(e,t,r))},this.logPerformance)},r.prototype.getClassificationsForLine=function(e,t,r){void 0===r&&(r=!1);for(var n=this.classifier.getClassificationsForLine(e,t,r),i="",a=0,o=n.entries;a0&&l(t[0])},d.watchFile=function(e,t){var r=i.default.normalize(e);return c.set(r,t),{close:function(){c.delete(r)}}},d.watchDirectory=function(){return _};var f=d.onCachedDirectoryStructureHostCreate;d.onCachedDirectoryStructureHostCreate=function(e){var t=e.readDirectory;e.readDirectory=function(e,n,i,a,o){return t(e,n?n.concat(r.extraFileExtensions):void 0,i,a,o)},f(e)};var m=a.default.createWatchProgram(d),y=m.getProgram().getProgram();s.set(e,m),n.push(y)},v=r.projects[Symbol.iterator]();!(p=(g=v.next()).done);p=!0)y()}catch(e){f=!0,m=e}finally{try{p||null==v.return||v.return()}finally{if(f)throw m}}return n},t.createProgram=function(e,t,r){if(r.projects&&1===r.projects.length){var n=r.projects[0];i.default.isAbsolute(n)||(n=i.default.join(r.tsconfigRootDir,n));var s=a.default.getParsedCommandLineOfConfigFile(n,o,Object.assign({},a.default.sys,{onUnRecoverableConfigFileDiagnostic:function(){}}));if(s){var c=a.default.createCompilerHost(s.options,!0),u=c.readFile;return c.readFile=function(r){return i.default.normalize(r)===i.default.normalize(t)?e:u(r)},a.default.createProgram([t],s.options,c)}}}});i(Ut);var Vt=a(function(e,t){var r;t=e.exports=Y,r="object"===f(H)&&H.env&&H.env.NODE_DEBUG&&/\bsemver\b/i.test(H.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},t.SEMVER_SPEC_VERSION="2.0.0";var n=256,i=Number.MAX_SAFE_INTEGER||9007199254740991,a=t.re=[],o=t.src=[],s=0,c=s++;o[c]="0|[1-9]\\d*";var u=s++;o[u]="[0-9]+";var l=s++;o[l]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var _=s++;o[_]="("+o[c]+")\\.("+o[c]+")\\.("+o[c]+")";var d=s++;o[d]="("+o[u]+")\\.("+o[u]+")\\.("+o[u]+")";var p=s++;o[p]="(?:"+o[c]+"|"+o[l]+")";var m=s++;o[m]="(?:"+o[u]+"|"+o[l]+")";var g=s++;o[g]="(?:-("+o[p]+"(?:\\."+o[p]+")*))";var y=s++;o[y]="(?:-?("+o[m]+"(?:\\."+o[m]+")*))";var v=s++;o[v]="[0-9A-Za-z-]+";var h=s++;o[h]="(?:\\+("+o[v]+"(?:\\."+o[v]+")*))";var b=s++,D="v?"+o[_]+o[g]+"?"+o[h]+"?";o[b]="^"+D+"$";var x="[v=\\s]*"+o[d]+o[y]+"?"+o[h]+"?",S=s++;o[S]="^"+x+"$";var T=s++;o[T]="((?:<|>)?=?)";var C=s++;o[C]=o[u]+"|x|X|\\*";var k=s++;o[k]=o[c]+"|x|X|\\*";var E=s++;o[E]="[v=\\s]*("+o[k]+")(?:\\.("+o[k]+")(?:\\.("+o[k]+")(?:"+o[g]+")?"+o[h]+"?)?)?";var N=s++;o[N]="[v=\\s]*("+o[C]+")(?:\\.("+o[C]+")(?:\\.("+o[C]+")(?:"+o[y]+")?"+o[h]+"?)?)?";var A=s++;o[A]="^"+o[T]+"\\s*"+o[E]+"$";var F=s++;o[F]="^"+o[T]+"\\s*"+o[N]+"$";var P=s++;o[P]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var w=s++;o[w]="(?:~>?)";var O=s++;o[O]="(\\s*)"+o[w]+"\\s+",a[O]=new RegExp(o[O],"g");var I=s++;o[I]="^"+o[w]+o[E]+"$";var M=s++;o[M]="^"+o[w]+o[N]+"$";var L=s++;o[L]="(?:\\^)";var R=s++;o[R]="(\\s*)"+o[L]+"\\s+",a[R]=new RegExp(o[R],"g");var B=s++;o[B]="^"+o[L]+o[E]+"$";var j=s++;o[j]="^"+o[L]+o[N]+"$";var J=s++;o[J]="^"+o[T]+"\\s*("+x+")$|^$";var z=s++;o[z]="^"+o[T]+"\\s*("+D+")$|^$";var K=s++;o[K]="(\\s*)"+o[T]+"\\s*("+x+"|"+o[E]+")",a[K]=new RegExp(o[K],"g");var U=s++;o[U]="^\\s*("+o[E]+")\\s+-\\s+("+o[E]+")\\s*$";var V=s++;o[V]="^\\s*("+o[N]+")\\s+-\\s+("+o[N]+")\\s*$";var q=s++;o[q]="(<|>)?=?\\s*\\*";for(var W=0;Wn)return null;if(!(t?a[S]:a[b]).test(e))return null;try{return new Y(e,t)}catch(e){return null}}function Y(e,t){if(e instanceof Y){if(e.loose===t)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>n)throw new TypeError("version is longer than "+n+" characters");if(!(this instanceof Y))return new Y(e,t);r("SemVer",e,t),this.loose=t;var o=e.trim().match(t?a[S]:a[b]);if(!o)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>i||this.major<0)throw new TypeError("Invalid major version");if(this.minor>i||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>i||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map(function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);-1===r&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},t.inc=function(e,t,r,n){"string"==typeof r&&(n=r,r=void 0);try{return new Y(e,r).inc(t,n).version}catch(e){return null}},t.diff=function(e,t){if(te(e,t))return null;var r=G(e),n=G(t);if(r.prerelease.length||n.prerelease.length){for(var i in r)if(("major"===i||"minor"===i||"patch"===i)&&r[i]!==n[i])return"pre"+i;return"prerelease"}for(var i in r)if(("major"===i||"minor"===i||"patch"===i)&&r[i]!==n[i])return i},t.compareIdentifiers=Q;var X=/^[0-9]+$/;function Q(e,t){var r=X.test(e),n=X.test(t);return r&&n&&(e=+e,t=+t),r&&!n?-1:n&&!r?1:et?1:0}function $(e,t,r){return new Y(e,r).compare(new Y(t,r))}function Z(e,t,r){return $(e,t,r)>0}function ee(e,t,r){return $(e,t,r)<0}function te(e,t,r){return 0===$(e,t,r)}function re(e,t,r){return 0!==$(e,t,r)}function ne(e,t,r){return $(e,t,r)>=0}function ie(e,t,r){return $(e,t,r)<=0}function ae(e,t,r,n){var i;switch(t){case"===":"object"===f(e)&&(e=e.version),"object"===f(r)&&(r=r.version),i=e===r;break;case"!==":"object"===f(e)&&(e=e.version),"object"===f(r)&&(r=r.version),i=e!==r;break;case"":case"=":case"==":i=te(e,r,n);break;case"!=":i=re(e,r,n);break;case">":i=Z(e,r,n);break;case">=":i=ne(e,r,n);break;case"<":i=ee(e,r,n);break;case"<=":i=ie(e,r,n);break;default:throw new TypeError("Invalid operator: "+t)}return i}function oe(e,t){if(e instanceof oe){if(e.loose===t)return e;e=e.value}if(!(this instanceof oe))return new oe(e,t);r("comparator",e,t),this.loose=t,this.parse(e),this.semver===se?this.value="":this.value=this.operator+this.semver.version,r("comp",this)}t.rcompareIdentifiers=function(e,t){return Q(t,e)},t.major=function(e,t){return new Y(e,t).major},t.minor=function(e,t){return new Y(e,t).minor},t.patch=function(e,t){return new Y(e,t).patch},t.compare=$,t.compareLoose=function(e,t){return $(e,t,!0)},t.rcompare=function(e,t,r){return $(t,e,r)},t.sort=function(e,r){return e.sort(function(e,n){return t.compare(e,n,r)})},t.rsort=function(e,r){return e.sort(function(e,n){return t.rcompare(e,n,r)})},t.gt=Z,t.lt=ee,t.eq=te,t.neq=re,t.gte=ne,t.lte=ie,t.cmp=ae,t.Comparator=oe;var se={};function ce(e,t){if(e instanceof ce)return e.loose===t?e:new ce(e.raw,t);if(e instanceof oe)return new ce(e.value,t);if(!(this instanceof ce))return new ce(e,t);if(this.loose=t,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map(function(e){return this.parseRange(e.trim())},this).filter(function(e){return e.length}),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function ue(e){return!e||"x"===e.toLowerCase()||"*"===e}function le(e,t,r,n,i,a,o,s,c,u,l,_,d){return((t=ue(r)?"":ue(n)?">="+r+".0.0":ue(i)?">="+r+"."+n+".0":">="+t)+" "+(s=ue(c)?"":ue(u)?"<"+(+c+1)+".0.0":ue(l)?"<"+c+"."+(+u+1)+".0":_?"<="+c+"."+u+"."+l+"-"+_:"<="+s)).trim()}function _e(e,t){for(var n=0;n0){var i=e[n].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}return!1}return!0}function de(e,t,r){try{t=new ce(t,r)}catch(e){return!1}return t.test(e)}function pe(e,t,r,n){var i,a,o,s,c;switch(e=new Y(e,n),t=new ce(t,n),r){case">":i=Z,a=ie,o=ee,s=">",c=">=";break;case"<":i=ee,a=ne,o=Z,s="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(de(e,t,n))return!1;for(var u=0;u=0.0.0")),l=l||e,_=_||e,i(e.semver,l.semver,n)?l=e:o(e.semver,_.semver,n)&&(_=e)}),l.operator===s||l.operator===c)return!1;if((!_.operator||_.operator===s)&&a(e,_.semver))return!1;if(_.operator===c&&o(e,_.semver))return!1}return!0}oe.prototype.parse=function(e){var t=this.loose?a[J]:a[z],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1],"="===this.operator&&(this.operator=""),r[2]?this.semver=new Y(r[2],this.loose):this.semver=se},oe.prototype.toString=function(){return this.value},oe.prototype.test=function(e){return r("Comparator.test",e,this.loose),this.semver===se||("string"==typeof e&&(e=new Y(e,this.loose)),ae(e,this.operator,this.semver,this.loose))},oe.prototype.intersects=function(e,t){if(!(e instanceof oe))throw new TypeError("a Comparator is required");var r;if(""===this.operator)return r=new ce(e.value,t),de(this.value,r,t);if(""===e.operator)return r=new ce(this.value,t),de(e.semver,r,t);var n=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),i=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),a=this.semver.version===e.semver.version,o=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),s=ae(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),c=ae(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return n||i||a&&o||s||c},t.Range=ce,ce.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range},ce.prototype.toString=function(){return this.range},ce.prototype.parseRange=function(e){var t=this.loose;e=e.trim(),r("range",e,t);var n=t?a[V]:a[U];e=e.replace(n,le),r("hyphen replace",e),e=e.replace(a[K],"$1$2$3"),r("comparator trim",e,a[K]),e=(e=(e=e.replace(a[O],"$1~")).replace(a[R],"$1^")).split(/\s+/).join(" ");var i=t?a[J]:a[z],o=e.split(" ").map(function(e){return function(e,t){return r("comp",e),e=function(e,t){return e.trim().split(/\s+/).map(function(e){return function(e,t){r("caret",e,t);var n=t?a[j]:a[B];return e.replace(n,function(t,n,i,a,o){var s;return r("caret",e,t,n,i,a,o),ue(n)?s="":ue(i)?s=">="+n+".0.0 <"+(+n+1)+".0.0":ue(a)?s="0"===n?">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":">="+n+"."+i+".0 <"+(+n+1)+".0.0":o?(r("replaceCaret pr",o),"-"!==o.charAt(0)&&(o="-"+o),s="0"===n?"0"===i?">="+n+"."+i+"."+a+o+" <"+n+"."+i+"."+(+a+1):">="+n+"."+i+"."+a+o+" <"+n+"."+(+i+1)+".0":">="+n+"."+i+"."+a+o+" <"+(+n+1)+".0.0"):(r("no pr"),s="0"===n?"0"===i?">="+n+"."+i+"."+a+" <"+n+"."+i+"."+(+a+1):">="+n+"."+i+"."+a+" <"+n+"."+(+i+1)+".0":">="+n+"."+i+"."+a+" <"+(+n+1)+".0.0"),r("caret return",s),s})}(e,t)}).join(" ")}(e,t),r("caret",e),e=function(e,t){return e.trim().split(/\s+/).map(function(e){return function(e,t){var n=t?a[M]:a[I];return e.replace(n,function(t,n,i,a,o){var s;return r("tilde",e,t,n,i,a,o),ue(n)?s="":ue(i)?s=">="+n+".0.0 <"+(+n+1)+".0.0":ue(a)?s=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":o?(r("replaceTilde pr",o),"-"!==o.charAt(0)&&(o="-"+o),s=">="+n+"."+i+"."+a+o+" <"+n+"."+(+i+1)+".0"):s=">="+n+"."+i+"."+a+" <"+n+"."+(+i+1)+".0",r("tilde return",s),s})}(e,t)}).join(" ")}(e,t),r("tildes",e),e=function(e,t){return r("replaceXRanges",e,t),e.split(/\s+/).map(function(e){return function(e,t){e=e.trim();var n=t?a[F]:a[A];return e.replace(n,function(t,n,i,a,o,s){r("xRange",e,t,n,i,a,o,s);var c=ue(i),u=c||ue(a),l=u||ue(o),_=l;return"="===n&&_&&(n=""),c?t=">"===n||"<"===n?"<0.0.0":"*":n&&_?(u&&(a=0),l&&(o=0),">"===n?(n=">=",u?(i=+i+1,a=0,o=0):l&&(a=+a+1,o=0)):"<="===n&&(n="<",u?i=+i+1:a=+a+1),t=n+i+"."+a+"."+o):u?t=">="+i+".0.0 <"+(+i+1)+".0.0":l&&(t=">="+i+"."+a+".0 <"+i+"."+(+a+1)+".0"),r("xRange return",t),t})}(e,t)}).join(" ")}(e,t),r("xrange",e),e=function(e,t){return r("replaceStars",e,t),e.trim().replace(a[q],"")}(e,t),r("stars",e),e}(e,t)}).join(" ").split(/\s+/);return this.loose&&(o=o.filter(function(e){return!!e.match(i)})),o=o.map(function(e){return new oe(e,t)})},ce.prototype.intersects=function(e,t){if(!(e instanceof ce))throw new TypeError("a Range is required");return this.set.some(function(r){return r.every(function(r){return e.set.some(function(e){return e.every(function(e){return r.intersects(e,t)})})})})},t.toComparators=function(e,t){return new ce(e,t).set.map(function(e){return e.map(function(e){return e.value}).join(" ").trim().split(" ")})},ce.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new Y(e,this.loose));for(var t=0;t",r)},t.outside=pe,t.prerelease=function(e,t){var r=G(e,t);return r&&r.prerelease.length?r.prerelease:null},t.intersects=function(e,t,r){return e=new ce(e,r),t=new ce(t,r),e.intersects(t)},t.coerce=function(e){if(e instanceof Y)return e;if("string"!=typeof e)return null;var t=e.match(a[P]);return null==t?null:G((t[1]||"0")+"."+(t[2]||"0")+"."+(t[3]||"0"))}}),qt=1/0,Wt="[object Symbol]",Ht=/&(?:amp|lt|gt|quot|#39|#96);/g,Gt=RegExp(Ht.source),Yt="object"==f(r)&&r&&r.Object===Object&&r,Xt="object"==("undefined"==typeof self?"undefined":f(self))&&self&&self.Object===Object&&self,Qt=Yt||Xt||Function("return this")();var $t,Zt=($t={"&":"&","<":"<",">":">",""":'"',"'":"'","`":"`"},function(e){return null==$t?void 0:$t[e]}),er=Object.prototype.toString,tr=Qt.Symbol,rr=tr?tr.prototype:void 0,nr=rr?rr.toString:void 0;function ir(e){if("string"==typeof e)return e;if(function(e){return"symbol"==f(e)||function(e){return!!e&&"object"==f(e)}(e)&&er.call(e)==Wt}(e))return nr?nr.call(e):"";var t=e+"";return"0"==t&&1/e==-qt?"-0":t}var ar=function(e){var t;return(e=null==(t=e)?"":ir(t))&&Gt.test(e)?e.replace(Ht,Zt):e},or=a(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.ArrayExpression="ArrayExpression",e.ArrayPattern="ArrayPattern",e.ArrowFunctionExpression="ArrowFunctionExpression",e.AssignmentExpression="AssignmentExpression",e.AssignmentPattern="AssignmentPattern",e.AwaitExpression="AwaitExpression",e.BigIntLiteral="BigIntLiteral",e.BinaryExpression="BinaryExpression",e.BlockStatement="BlockStatement",e.BreakStatement="BreakStatement",e.CallExpression="CallExpression",e.CatchClause="CatchClause",e.ClassBody="ClassBody",e.ClassDeclaration="ClassDeclaration",e.ClassExpression="ClassExpression",e.ClassProperty="ClassProperty",e.ConditionalExpression="ConditionalExpression",e.ContinueStatement="ContinueStatement",e.DebuggerStatement="DebuggerStatement",e.Decorator="Decorator",e.DoWhileStatement="DoWhileStatement",e.EmptyStatement="EmptyStatement",e.ExportAllDeclaration="ExportAllDeclaration",e.ExportDefaultDeclaration="ExportDefaultDeclaration",e.ExportNamedDeclaration="ExportNamedDeclaration",e.ExportSpecifier="ExportSpecifier",e.ExpressionStatement="ExpressionStatement",e.ForInStatement="ForInStatement",e.ForOfStatement="ForOfStatement",e.ForStatement="ForStatement",e.FunctionDeclaration="FunctionDeclaration",e.FunctionExpression="FunctionExpression",e.Identifier="Identifier",e.IfStatement="IfStatement",e.Import="Import",e.ImportDeclaration="ImportDeclaration",e.ImportDefaultSpecifier="ImportDefaultSpecifier",e.ImportNamespaceSpecifier="ImportNamespaceSpecifier",e.ImportSpecifier="ImportSpecifier",e.JSXAttribute="JSXAttribute",e.JSXClosingElement="JSXClosingElement",e.JSXClosingFragment="JSXClosingFragment",e.JSXElement="JSXElement",e.JSXEmptyExpression="JSXEmptyExpression",e.JSXExpressionContainer="JSXExpressionContainer",e.JSXFragment="JSXFragment",e.JSXIdentifier="JSXIdentifier",e.JSXMemberExpression="JSXMemberExpression",e.JSXNamespacedName="JSXNamespacedName",e.JSXOpeningElement="JSXOpeningElement",e.JSXOpeningFragment="JSXOpeningFragment",e.JSXSpreadAttribute="JSXSpreadAttribute",e.JSXSpreadChild="JSXSpreadChild",e.JSXText="JSXText",e.LabeledStatement="LabeledStatement",e.Literal="Literal",e.LogicalExpression="LogicalExpression",e.MemberExpression="MemberExpression",e.MetaProperty="MetaProperty",e.MethodDefinition="MethodDefinition",e.NewExpression="NewExpression",e.ObjectExpression="ObjectExpression",e.ObjectPattern="ObjectPattern",e.Program="Program",e.Property="Property",e.RestElement="RestElement",e.ReturnStatement="ReturnStatement",e.SequenceExpression="SequenceExpression",e.SpreadElement="SpreadElement",e.Super="Super",e.SwitchCase="SwitchCase",e.SwitchStatement="SwitchStatement",e.TaggedTemplateExpression="TaggedTemplateExpression",e.TemplateElement="TemplateElement",e.TemplateLiteral="TemplateLiteral",e.ThisExpression="ThisExpression",e.ThrowStatement="ThrowStatement",e.TryStatement="TryStatement",e.UnaryExpression="UnaryExpression",e.UpdateExpression="UpdateExpression",e.VariableDeclaration="VariableDeclaration",e.VariableDeclarator="VariableDeclarator",e.WhileStatement="WhileStatement",e.WithStatement="WithStatement",e.YieldExpression="YieldExpression",e.TSAbstractClassDeclaration="TSAbstractClassDeclaration",e.TSAbstractClassProperty="TSAbstractClassProperty",e.TSAbstractKeyword="TSAbstractKeyword",e.TSAbstractMethodDefinition="TSAbstractMethodDefinition",e.TSAnyKeyword="TSAnyKeyword",e.TSArrayType="TSArrayType",e.TSAsExpression="TSAsExpression",e.TSAsyncKeyword="TSAsyncKeyword",e.TSBooleanKeyword="TSBooleanKeyword",e.TSBigIntKeyword="TSBigIntKeyword",e.TSConditionalType="TSConditionalType",e.TSConstructorType="TSConstructorType",e.TSCallSignatureDeclaration="TSCallSignatureDeclaration",e.TSClassImplements="TSClassImplements",e.TSConstructSignatureDeclaration="TSConstructSignatureDeclaration",e.TSDeclareKeyword="TSDeclareKeyword",e.TSDeclareFunction="TSDeclareFunction",e.TSEnumDeclaration="TSEnumDeclaration",e.TSEnumMember="TSEnumMember",e.TSExportAssignment="TSExportAssignment",e.TSExportKeyword="TSExportKeyword",e.TSExternalModuleReference="TSExternalModuleReference",e.TSImportType="TSImportType",e.TSInferType="TSInferType",e.TSLiteralType="TSLiteralType",e.TSIndexedAccessType="TSIndexedAccessType",e.TSIndexSignature="TSIndexSignature",e.TSInterfaceBody="TSInterfaceBody",e.TSInterfaceDeclaration="TSInterfaceDeclaration",e.TSInterfaceHeritage="TSInterfaceHeritage",e.TSImportEqualsDeclaration="TSImportEqualsDeclaration",e.TSFunctionType="TSFunctionType",e.TSMethodSignature="TSMethodSignature",e.TSModuleBlock="TSModuleBlock",e.TSModuleDeclaration="TSModuleDeclaration",e.TSNamespaceExportDeclaration="TSNamespaceExportDeclaration",e.TSNonNullExpression="TSNonNullExpression",e.TSNeverKeyword="TSNeverKeyword",e.TSNullKeyword="TSNullKeyword",e.TSNumberKeyword="TSNumberKeyword",e.TSMappedType="TSMappedType",e.TSObjectKeyword="TSObjectKeyword",e.TSParameterProperty="TSParameterProperty",e.TSPrivateKeyword="TSPrivateKeyword",e.TSPropertySignature="TSPropertySignature",e.TSProtectedKeyword="TSProtectedKeyword",e.TSPublicKeyword="TSPublicKeyword",e.TSQualifiedName="TSQualifiedName",e.TSQuestionToken="TSQuestionToken",e.TSReadonlyKeyword="TSReadonlyKeyword",e.TSRestType="TSRestType",e.TSStaticKeyword="TSStaticKeyword",e.TSStringKeyword="TSStringKeyword",e.TSSymbolKeyword="TSSymbolKeyword",e.TSThisType="TSThisType",e.TSTypeAnnotation="TSTypeAnnotation",e.TSTypeAliasDeclaration="TSTypeAliasDeclaration",e.TSTypeAssertion="TSTypeAssertion",e.TSTypeLiteral="TSTypeLiteral",e.TSTypeOperator="TSTypeOperator",e.TSTypeParameter="TSTypeParameter",e.TSTypeParameterDeclaration="TSTypeParameterDeclaration",e.TSTypeParameterInstantiation="TSTypeParameterInstantiation",e.TSTypePredicate="TSTypePredicate",e.TSTypeReference="TSTypeReference",e.TSTypeQuery="TSTypeQuery",e.TSIntersectionType="TSIntersectionType",e.TSTupleType="TSTupleType",e.TSOptionalType="TSOptionalType",e.TSParenthesizedType="TSParenthesizedType",e.TSUnionType="TSUnionType",e.TSUndefinedKeyword="TSUndefinedKeyword",e.TSUnknownKeyword="TSUnknownKeyword",e.TSVoidKeyword="TSVoidKeyword"}(t.AST_NODE_TYPES||(t.AST_NODE_TYPES={}))});i(or);var sr=a(function(e,t){var n,i=r&&r.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var a=i(Kt),o=i(ar),s=a.default.SyntaxKind,c=[s.EqualsToken,s.PlusEqualsToken,s.MinusEqualsToken,s.AsteriskEqualsToken,s.AsteriskAsteriskEqualsToken,s.SlashEqualsToken,s.PercentEqualsToken,s.LessThanLessThanEqualsToken,s.GreaterThanGreaterThanEqualsToken,s.GreaterThanGreaterThanGreaterThanEqualsToken,s.AmpersandEqualsToken,s.BarEqualsToken,s.CaretEqualsToken],u=[s.BarBarToken,s.AmpersandAmpersandToken],l=(m(n={},s.OpenBraceToken,"{"),m(n,s.CloseBraceToken,"}"),m(n,s.OpenParenToken,"("),m(n,s.CloseParenToken,")"),m(n,s.OpenBracketToken,"["),m(n,s.CloseBracketToken,"]"),m(n,s.DotToken,"."),m(n,s.DotDotDotToken,"..."),m(n,s.SemicolonToken,","),m(n,s.CommaToken,","),m(n,s.LessThanToken,"<"),m(n,s.GreaterThanToken,">"),m(n,s.LessThanEqualsToken,"<="),m(n,s.GreaterThanEqualsToken,">="),m(n,s.EqualsEqualsToken,"=="),m(n,s.ExclamationEqualsToken,"!="),m(n,s.EqualsEqualsEqualsToken,"==="),m(n,s.InstanceOfKeyword,"instanceof"),m(n,s.ExclamationEqualsEqualsToken,"!=="),m(n,s.EqualsGreaterThanToken,"=>"),m(n,s.PlusToken,"+"),m(n,s.MinusToken,"-"),m(n,s.AsteriskToken,"*"),m(n,s.AsteriskAsteriskToken,"**"),m(n,s.SlashToken,"/"),m(n,s.PercentToken,"%"),m(n,s.PlusPlusToken,"++"),m(n,s.MinusMinusToken,"--"),m(n,s.LessThanLessThanToken,"<<"),m(n,s.LessThanSlashToken,">"),m(n,s.GreaterThanGreaterThanGreaterThanToken,">>>"),m(n,s.AmpersandToken,"&"),m(n,s.BarToken,"|"),m(n,s.CaretToken,"^"),m(n,s.ExclamationToken,"!"),m(n,s.TildeToken,"~"),m(n,s.AmpersandAmpersandToken,"&&"),m(n,s.BarBarToken,"||"),m(n,s.QuestionToken,"?"),m(n,s.ColonToken,":"),m(n,s.EqualsToken,"="),m(n,s.PlusEqualsToken,"+="),m(n,s.MinusEqualsToken,"-="),m(n,s.AsteriskEqualsToken,"*="),m(n,s.AsteriskAsteriskEqualsToken,"**="),m(n,s.SlashEqualsToken,"/="),m(n,s.PercentEqualsToken,"%="),m(n,s.LessThanLessThanEqualsToken,"<<="),m(n,s.GreaterThanGreaterThanEqualsToken,">>="),m(n,s.GreaterThanGreaterThanGreaterThanEqualsToken,">>>="),m(n,s.AmpersandEqualsToken,"&="),m(n,s.BarEqualsToken,"|="),m(n,s.CaretEqualsToken,"^="),m(n,s.AtToken,"@"),m(n,s.InKeyword,"in"),m(n,s.UniqueKeyword,"unique"),m(n,s.KeyOfKeyword,"keyof"),m(n,s.NewKeyword,"new"),m(n,s.ImportKeyword,"import"),n);function _(e){return c.indexOf(e.kind)>-1}function d(e){return u.indexOf(e.kind)>-1}function p(e){return e.kind===s.SingleLineCommentTrivia||e.kind===s.MultiLineCommentTrivia}function f(e){return e.kind===s.JSDocComment}function g(e,t,r){var n=r.getLineAndCharacterOfPosition(e),i=r.getLineAndCharacterOfPosition(t);return{start:{line:n.line+1,column:n.character},end:{line:i.line+1,column:i.character}}}function y(e){return e.kind>=s.FirstToken&&e.kind<=s.LastToken}function v(e){return e.kind>=s.JsxElement&&e.kind<=s.JsxAttribute}function h(e,t,r){return function t(n){if(a.default.isToken(n)&&n.pos===e.end)return n;return T(n.getChildren(r),function(n){var i=n.pos<=e.pos&&n.end>e.end||n.pos===e.end;return i&&function(e,t){return e.kind===s.EndOfFileToken?!!e.jsDoc:0!==e.getWidth(t)}(n,r)?t(n):void 0})}(t)}function b(e,t){for(;e;){if(t(e))return e;e=e.parent}}function D(e){return!!b(e,v)}function x(e){if(e.originalKeywordKind)switch(e.originalKeywordKind){case s.NullKeyword:return"Null";case s.GetKeyword:case s.SetKeyword:case s.TypeKeyword:case s.ModuleKeyword:return"Identifier";default:return"Keyword"}if(e.kind>=s.FirstKeyword&&e.kind<=s.LastFutureReservedWord)return e.kind===s.FalseKeyword||e.kind===s.TrueKeyword?"Boolean":"Keyword";if(e.kind>=s.FirstPunctuation&&e.kind<=s.LastBinaryOperator)return"Punctuator";if(e.kind>=s.NoSubstitutionTemplateLiteral&&e.kind<=s.TemplateTail)return"Template";switch(e.kind){case s.NumericLiteral:return"Numeric";case s.JsxText:return"JSXText";case s.StringLiteral:return!e.parent||e.parent.kind!==s.JsxAttribute&&e.parent.kind!==s.JsxElement?"String":"JSXText";case s.RegularExpressionLiteral:return"RegularExpression";case s.Identifier:case s.ConstructorKeyword:case s.GetKeyword:case s.SetKeyword:}if(e.parent){if(e.kind===s.Identifier&&e.parent.kind===s.PropertyAccessExpression&&D(e))return"JSXIdentifier";if(v(e.parent)){if(e.kind===s.PropertyAccessExpression)return"JSXMemberExpression";if(e.kind===s.Identifier)return"JSXIdentifier"}}return"Identifier"}function S(e,t){var r=e.kind===s.JsxText?e.getFullStart():e.getStart(t),n=e.getEnd(),i=t.text.slice(r,n),a={type:x(e),value:i,range:[r,n],loc:g(r,n,t)};return"RegularExpression"===a.type&&(a.regex={pattern:i.slice(1,i.lastIndexOf("/")),flags:i.slice(i.lastIndexOf("/")+1)}),a}function T(e,t){if(void 0!==e)for(var r=0;r=a&&r<=o&&(y(i)?n=i:i.getChildren().forEach(e))}(e),n},isComment:p,isJSDocComment:f,createError:function(e,t,r){var n=e.getLineAndCharacterOfPosition(t);return{index:t,lineNumber:n.line+1,column:n.character,message:r}},firstDefined:T}});i(sr);var cr=a(function(e,t){var n=r&&r.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var i=n(Kt),a=n(sr),o=i.default.SyntaxKind,s=new WeakMap,c=new WeakMap;t.resetASTMaps=function(){s=new WeakMap,c=new WeakMap},t.getASTMaps=function(){return{esTreeNodeToTSNodeMap:s,tsNodeToESTreeNodeMap:c}},t.convertError=function(e){return a.default.createError(e.file,e.start,e.message||e.messageText)},t.default=function e(t){var r=t.node,n=t.parent,u=t.ast,l=t.additionalOptions||{};if(!r)return null;var _={type:"",range:[r.getStart(u),r.end],loc:a.default.getLoc(r,u)};function d(t,n,i){return t?e({node:t,parent:r,inTypeMode:n,allowPattern:i,ast:u,additionalOptions:l}):null}function p(e){return d(e,t.inTypeMode,!0)}function m(e){return d(e,t.inTypeMode,!1)}function g(e){return d(e,!0,!1)}function y(e){var t=g(e),n=r.kind===o.FunctionType||r.kind===o.ConstructorType?2:1,i=e.getFullStart()-n,s=a.default.getLocFor(i,e.end,u);return{type:or.AST_NODE_TYPES.TSTypeAnnotation,loc:s,range:[i,e.end],typeAnnotation:t}}function v(e){var t=[],n=a.default.canContainDirective(r);return e.map(function(e){var r=m(e);if(n&&r&&r.expression&&i.default.isExpressionStatement(e)&&i.default.isStringLiteral(e.expression)){var a=r.expression.raw;-1===t.indexOf(a)&&(r.directive=a.slice(1,-1),t.push(a))}return r}).filter(function(e){return e})}function h(e){var t=e.pos-1,r=e.end+1;if(e&&e.length){var n=e[0].parent;if(n&&(n.kind===o.CallExpression||n.kind===o.TypeReference)){var i=e[e.length-1];r=a.default.findNextToken(i,u,u).end}}return{type:or.AST_NODE_TYPES.TSTypeParameterInstantiation,range:[t,r],loc:a.default.getLocFor(t,r,u),params:e.map(function(e){return g(e)})}}function b(e){var t=e[0],r=e[e.length-1],n=a.default.findNextToken(r,u,u);return{type:or.AST_NODE_TYPES.TSTypeParameterDeclaration,range:[t.pos-1,n.end],loc:a.default.getLocFor(t.pos-1,n.end,u),params:e.map(function(e){return g(e)})}}function D(e,t){var r=m(t.expression),n={type:e,loc:r.loc,range:r.range,expression:r};return t.typeArguments&&t.typeArguments.length&&(n.typeParameters=h(t.typeArguments)),n}function x(e){return e&&e.length?e.map(function(e){var t=m(e);return e.decorators&&e.decorators.length?Object.assign(t,{decorators:e.decorators.map(m)}):t}):[]}function S(e){var t=a.default.convertToken(e,u);if(t.type===or.AST_NODE_TYPES.JSXMemberExpression){var n=r.tagName.expression.kind===o.PropertyAccessExpression;t.object=m(r.tagName.expression),t.property=m(r.tagName.name),t.object.type=n?or.AST_NODE_TYPES.JSXMemberExpression:or.AST_NODE_TYPES.JSXIdentifier,t.property.type=or.AST_NODE_TYPES.JSXIdentifier,e.expression.kind===o.ThisKeyword&&(t.object.name="this")}else t.type=or.AST_NODE_TYPES.JSXIdentifier,t.name=t.value;return delete t.value,t}function T(e){if(e&&e.length){for(var t={},r=0;rQ.pos)&&(Q=a.default.findNextToken($,u,u)),_.typeParameters=b(r.typeParameters)}if(r.modifiers&&r.modifiers.length){r.kind===o.ClassDeclaration&&a.default.hasModifier(o.AbstractKeyword,r)&&(X="TSAbstract".concat(X));var Z=r.modifiers[r.modifiers.length-1];(!Q||Z.pos>Q.pos)&&(Q=a.default.findNextToken(Z,u,u))}else Q||(Q=r.getFirstToken());var ee=a.default.findNextToken(Q,u,u),te=Y.find(function(e){return e.token===o.ExtendsKeyword});if(te){if(te.types.length>1)throw a.default.createError(u,te.types[1].pos,"Classes can only extend a single class.");te.types[0]&&te.types[0].typeArguments&&(_.superTypeParameters=h(te.types[0].typeArguments))}var re=Y.find(function(e){return e.token===o.ImplementsKeyword});Object.assign(_,{type:X,id:m(r.name),body:{type:or.AST_NODE_TYPES.ClassBody,body:[],range:[ee.getStart(u),r.end],loc:a.default.getLocFor(ee.getStart(u),r.end,u)},superClass:te&&te.types[0]?m(te.types[0].expression):null}),re&&(_.implements=re.types.map(function(e){return D(or.AST_NODE_TYPES.TSClassImplements,e)})),a.default.hasModifier(o.DeclareKeyword,r)&&(_.declare=!0),r.decorators&&(_.decorators=r.decorators.map(m));var ne=r.members.filter(a.default.isESTreeClassMember);ne.length&&(_.body.body=ne.map(m)),_=a.default.fixExports(r,_,u);break;case o.ModuleBlock:Object.assign(_,{type:or.AST_NODE_TYPES.TSModuleBlock,body:v(r.statements)});break;case o.ImportDeclaration:if(Object.assign(_,{type:or.AST_NODE_TYPES.ImportDeclaration,source:m(r.moduleSpecifier),specifiers:[]}),r.importClause&&(r.importClause.name&&_.specifiers.push(m(r.importClause)),r.importClause.namedBindings))switch(r.importClause.namedBindings.kind){case o.NamespaceImport:_.specifiers.push(m(r.importClause.namedBindings));break;case o.NamedImports:_.specifiers=_.specifiers.concat(r.importClause.namedBindings.elements.map(m))}break;case o.NamespaceImport:Object.assign(_,{type:or.AST_NODE_TYPES.ImportNamespaceSpecifier,local:m(r.name)});break;case o.ImportSpecifier:Object.assign(_,{type:or.AST_NODE_TYPES.ImportSpecifier,local:m(r.name),imported:m(r.propertyName||r.name)});break;case o.ImportClause:Object.assign(_,{type:or.AST_NODE_TYPES.ImportDefaultSpecifier,local:m(r.name)}),_.range[1]=r.name.end,_.loc=a.default.getLocFor(_.range[0],_.range[1],u);break;case o.ExportDeclaration:r.exportClause?Object.assign(_,{type:or.AST_NODE_TYPES.ExportNamedDeclaration,source:m(r.moduleSpecifier),specifiers:r.exportClause.elements.map(m),declaration:null}):Object.assign(_,{type:or.AST_NODE_TYPES.ExportAllDeclaration,source:m(r.moduleSpecifier)});break;case o.ExportSpecifier:Object.assign(_,{type:or.AST_NODE_TYPES.ExportSpecifier,local:m(r.propertyName||r.name),exported:m(r.name)});break;case o.ExportAssignment:r.isExportEquals?Object.assign(_,{type:or.AST_NODE_TYPES.TSExportAssignment,expression:m(r.expression)}):Object.assign(_,{type:or.AST_NODE_TYPES.ExportDefaultDeclaration,declaration:m(r.expression)});break;case o.PrefixUnaryExpression:case o.PostfixUnaryExpression:var ie=a.default.getTextForTokenKind(r.operator)||"";Object.assign(_,{type:/^(?:\+\+|--)$/.test(ie)?or.AST_NODE_TYPES.UpdateExpression:or.AST_NODE_TYPES.UnaryExpression,operator:ie,prefix:r.kind===o.PrefixUnaryExpression,argument:m(r.operand)});break;case o.DeleteExpression:Object.assign(_,{type:or.AST_NODE_TYPES.UnaryExpression,operator:"delete",prefix:!0,argument:m(r.expression)});break;case o.VoidExpression:Object.assign(_,{type:or.AST_NODE_TYPES.UnaryExpression,operator:"void",prefix:!0,argument:m(r.expression)});break;case o.TypeOfExpression:Object.assign(_,{type:or.AST_NODE_TYPES.UnaryExpression,operator:"typeof",prefix:!0,argument:m(r.expression)});break;case o.TypeOperator:Object.assign(_,{type:or.AST_NODE_TYPES.TSTypeOperator,operator:a.default.getTextForTokenKind(r.operator),typeAnnotation:m(r.type)});break;case o.BinaryExpression:if(a.default.isComma(r.operatorToken)){Object.assign(_,{type:or.AST_NODE_TYPES.SequenceExpression,expressions:[]});var ae=m(r.left),oe=m(r.right);ae.type===or.AST_NODE_TYPES.SequenceExpression?_.expressions=_.expressions.concat(ae.expressions):_.expressions.push(ae),oe.type===or.AST_NODE_TYPES.SequenceExpression?_.expressions=_.expressions.concat(oe.expressions):_.expressions.push(oe)}else{var se=a.default.getBinaryExpressionType(r.operatorToken);Object.assign(_,{type:se,operator:a.default.getTextForTokenKind(r.operatorToken.kind),left:d(r.left,t.inTypeMode,se===or.AST_NODE_TYPES.AssignmentExpression),right:m(r.right)}),_.type===or.AST_NODE_TYPES.AssignmentExpression&&t.allowPattern&&(delete _.operator,_.type=or.AST_NODE_TYPES.AssignmentPattern)}break;case o.PropertyAccessExpression:if(a.default.isJSXToken(n)){var ce={type:or.AST_NODE_TYPES.MemberExpression,object:m(r.expression),property:m(r.name)},ue=r.expression.kind===o.PropertyAccessExpression;r.expression.kind===o.ThisKeyword&&(ce.object.name="this"),ce.object.type=ue?or.AST_NODE_TYPES.MemberExpression:or.AST_NODE_TYPES.JSXIdentifier,ce.property.type=or.AST_NODE_TYPES.JSXIdentifier,Object.assign(_,ce)}else Object.assign(_,{type:or.AST_NODE_TYPES.MemberExpression,object:m(r.expression),property:m(r.name),computed:!1});break;case o.ElementAccessExpression:Object.assign(_,{type:or.AST_NODE_TYPES.MemberExpression,object:m(r.expression),property:m(r.argumentExpression),computed:!0});break;case o.ConditionalExpression:Object.assign(_,{type:or.AST_NODE_TYPES.ConditionalExpression,test:m(r.condition),consequent:m(r.whenTrue),alternate:m(r.whenFalse)});break;case o.CallExpression:Object.assign(_,{type:or.AST_NODE_TYPES.CallExpression,callee:m(r.expression),arguments:r.arguments.map(m)}),r.typeArguments&&r.typeArguments.length&&(_.typeParameters=h(r.typeArguments));break;case o.NewExpression:Object.assign(_,{type:or.AST_NODE_TYPES.NewExpression,callee:m(r.expression),arguments:r.arguments?r.arguments.map(m):[]}),r.typeArguments&&r.typeArguments.length&&(_.typeParameters=h(r.typeArguments));break;case o.MetaProperty:var le=a.default.convertToken(r.getFirstToken(),u);Object.assign(_,{type:or.AST_NODE_TYPES.MetaProperty,meta:{type:or.AST_NODE_TYPES.Identifier,range:le.range,loc:le.loc,name:a.default.getTextForTokenKind(r.keywordToken)},property:m(r.name)});break;case o.Decorator:Object.assign(_,{type:or.AST_NODE_TYPES.Decorator,expression:m(r.expression)});break;case o.StringLiteral:Object.assign(_,{type:or.AST_NODE_TYPES.Literal,raw:u.text.slice(_.range[0],_.range[1])}),n.name&&n.name===r?_.value=r.text:_.value=a.default.unescapeStringLiteralText(r.text);break;case o.NumericLiteral:Object.assign(_,{type:or.AST_NODE_TYPES.Literal,value:Number(r.text),raw:u.text.slice(_.range[0],_.range[1])});break;case o.BigIntLiteral:var _e=u.text.slice(_.range[0],_.range[1]),de=_e.slice(0,-1);Object.assign(_,{type:or.AST_NODE_TYPES.BigIntLiteral,raw:_e,value:de});break;case o.RegularExpressionLiteral:var pe=r.text.slice(1,r.text.lastIndexOf("/")),fe=r.text.slice(r.text.lastIndexOf("/")+1),me=null;try{me=new RegExp(pe,fe)}catch(e){me=null}Object.assign(_,{type:or.AST_NODE_TYPES.Literal,value:me,raw:r.text,regex:{pattern:pe,flags:fe}});break;case o.TrueKeyword:Object.assign(_,{type:or.AST_NODE_TYPES.Literal,value:!0,raw:"true"});break;case o.FalseKeyword:Object.assign(_,{type:or.AST_NODE_TYPES.Literal,value:!1,raw:"false"});break;case o.NullKeyword:t.inTypeMode?Object.assign(_,{type:or.AST_NODE_TYPES.TSNullKeyword}):Object.assign(_,{type:or.AST_NODE_TYPES.Literal,value:null,raw:"null"});break;case o.ImportKeyword:Object.assign(_,{type:or.AST_NODE_TYPES.Import});break;case o.EmptyStatement:case o.DebuggerStatement:Object.assign(_,{type:o[r.kind]});break;case o.JsxElement:Object.assign(_,{type:or.AST_NODE_TYPES.JSXElement,openingElement:m(r.openingElement),closingElement:m(r.closingElement),children:r.children.map(m)});break;case o.JsxFragment:Object.assign(_,{type:or.AST_NODE_TYPES.JSXFragment,openingFragment:m(r.openingFragment),closingFragment:m(r.closingFragment),children:r.children.map(m)});break;case o.JsxSelfClosingElement:Object.assign(_,{type:or.AST_NODE_TYPES.JSXElement,openingElement:{type:or.AST_NODE_TYPES.JSXOpeningElement,typeParameters:r.typeArguments?h(r.typeArguments):void 0,selfClosing:!0,name:S(r.tagName),attributes:r.attributes.properties.map(m),range:_.range,loc:_.loc},closingElement:null,children:[]});break;case o.JsxOpeningElement:Object.assign(_,{type:or.AST_NODE_TYPES.JSXOpeningElement,typeParameters:r.typeArguments?h(r.typeArguments):void 0,selfClosing:!1,name:S(r.tagName),attributes:r.attributes.properties.map(m)});break;case o.JsxClosingElement:Object.assign(_,{type:or.AST_NODE_TYPES.JSXClosingElement,name:S(r.tagName)});break;case o.JsxOpeningFragment:Object.assign(_,{type:or.AST_NODE_TYPES.JSXOpeningFragment});break;case o.JsxClosingFragment:Object.assign(_,{type:or.AST_NODE_TYPES.JSXClosingFragment});break;case o.JsxExpression:var ge=u.getLineAndCharacterOfPosition(_.range[0]+1),ye=r.expression?m(r.expression):{type:or.AST_NODE_TYPES.JSXEmptyExpression,loc:{start:{line:ge.line+1,column:ge.character},end:{line:_.loc.end.line,column:_.loc.end.column-1}},range:[_.range[0]+1,_.range[1]-1]};Object.assign(_,{type:r.dotDotDotToken?or.AST_NODE_TYPES.JSXSpreadChild:or.AST_NODE_TYPES.JSXExpressionContainer,expression:ye});break;case o.JsxAttribute:var ve=a.default.convertToken(r.name,u);ve.type=or.AST_NODE_TYPES.JSXIdentifier,ve.name=ve.value,delete ve.value,Object.assign(_,{type:or.AST_NODE_TYPES.JSXAttribute,name:ve,value:m(r.initializer)});break;case o.JsxText:var he=r.getFullStart(),be=r.getEnd(),De=l.useJSXTextNode?or.AST_NODE_TYPES.JSXText:or.AST_NODE_TYPES.Literal;Object.assign(_,{type:De,value:u.text.slice(he,be),raw:u.text.slice(he,be)}),_.loc=a.default.getLocFor(he,be,u),_.range=[he,be];break;case o.JsxSpreadAttribute:Object.assign(_,{type:or.AST_NODE_TYPES.JSXSpreadAttribute,argument:m(r.expression)});break;case o.QualifiedName:Object.assign(_,{type:or.AST_NODE_TYPES.TSQualifiedName,left:m(r.left),right:m(r.right)});break;case o.TypeReference:Object.assign(_,{type:or.AST_NODE_TYPES.TSTypeReference,typeName:g(r.typeName),typeParameters:r.typeArguments?h(r.typeArguments):void 0});break;case o.TypeParameter:Object.assign(_,{type:or.AST_NODE_TYPES.TSTypeParameter,name:g(r.name),constraint:r.constraint?g(r.constraint):void 0,default:r.default?g(r.default):void 0});break;case o.ThisType:case o.AnyKeyword:case o.BigIntKeyword:case o.BooleanKeyword:case o.NeverKeyword:case o.NumberKeyword:case o.ObjectKeyword:case o.StringKeyword:case o.SymbolKeyword:case o.UnknownKeyword:case o.VoidKeyword:case o.UndefinedKeyword:Object.assign(_,{type:or.AST_NODE_TYPES["TS".concat(o[r.kind])]});break;case o.NonNullExpression:Object.assign(_,{type:or.AST_NODE_TYPES.TSNonNullExpression,expression:m(r.expression)});break;case o.TypeLiteral:Object.assign(_,{type:or.AST_NODE_TYPES.TSTypeLiteral,members:r.members.map(m)});break;case o.ArrayType:Object.assign(_,{type:or.AST_NODE_TYPES.TSArrayType,elementType:g(r.elementType)});break;case o.IndexedAccessType:Object.assign(_,{type:or.AST_NODE_TYPES.TSIndexedAccessType,objectType:g(r.objectType),indexType:g(r.indexType)});break;case o.ConditionalType:Object.assign(_,{type:or.AST_NODE_TYPES.TSConditionalType,checkType:g(r.checkType),extendsType:g(r.extendsType),trueType:g(r.trueType),falseType:g(r.falseType)});break;case o.TypeQuery:Object.assign(_,{type:or.AST_NODE_TYPES.TSTypeQuery,exprName:g(r.exprName)});break;case o.MappedType:Object.assign(_,{type:or.AST_NODE_TYPES.TSMappedType,typeParameter:g(r.typeParameter)}),r.readonlyToken&&(r.readonlyToken.kind===o.ReadonlyKeyword?_.readonly=!0:_.readonly=a.default.getTextForTokenKind(r.readonlyToken.kind)),r.questionToken&&(r.questionToken.kind===o.QuestionToken?_.optional=!0:_.optional=a.default.getTextForTokenKind(r.questionToken.kind)),r.type&&(_.typeAnnotation=g(r.type));break;case o.ParenthesizedExpression:return e({node:r.expression,parent:n,ast:u,additionalOptions:l});case o.TypeAliasDeclaration:Object.assign(_,{type:or.AST_NODE_TYPES.TSTypeAliasDeclaration,id:m(r.name),typeAnnotation:g(r.type)}),a.default.hasModifier(o.DeclareKeyword,r)&&(_.declare=!0),r.typeParameters&&r.typeParameters.length&&(_.typeParameters=b(r.typeParameters)),_=a.default.fixExports(r,_,u);break;case o.MethodSignature:Object.assign(_,{type:or.AST_NODE_TYPES.TSMethodSignature,computed:a.default.isComputedProperty(r.name),key:m(r.name),params:x(r.parameters)}),a.default.isOptional(r)&&(_.optional=!0),r.type&&(_.returnType=y(r.type)),a.default.hasModifier(o.ReadonlyKeyword,r)&&(_.readonly=!0),r.typeParameters&&(_.typeParameters=b(r.typeParameters));var xe=a.default.getTSNodeAccessibility(r);xe&&(_.accessibility=xe),a.default.hasModifier(o.ExportKeyword,r)&&(_.export=!0),a.default.hasModifier(o.StaticKeyword,r)&&(_.static=!0);break;case o.PropertySignature:Object.assign(_,{type:or.AST_NODE_TYPES.TSPropertySignature,optional:a.default.isOptional(r)||void 0,computed:a.default.isComputedProperty(r.name),key:m(r.name),typeAnnotation:r.type?y(r.type):void 0,initializer:m(r.initializer)||void 0,readonly:a.default.hasModifier(o.ReadonlyKeyword,r)||void 0,static:a.default.hasModifier(o.StaticKeyword,r)||void 0,export:a.default.hasModifier(o.ExportKeyword,r)||void 0});var Se=a.default.getTSNodeAccessibility(r);Se&&(_.accessibility=Se);break;case o.IndexSignature:Object.assign(_,{type:or.AST_NODE_TYPES.TSIndexSignature,parameters:r.parameters.map(m),typeAnnotation:r.type?y(r.type):null}),a.default.hasModifier(o.ReadonlyKeyword,r)&&(_.readonly=!0);var Te=a.default.getTSNodeAccessibility(r);Te&&(_.accessibility=Te),a.default.hasModifier(o.ExportKeyword,r)&&(_.export=!0),a.default.hasModifier(o.StaticKeyword,r)&&(_.static=!0);break;case o.ConstructorType:case o.FunctionType:case o.ConstructSignature:case o.CallSignature:var Ce;switch(r.kind){case o.ConstructSignature:Ce=or.AST_NODE_TYPES.TSConstructSignatureDeclaration;break;case o.CallSignature:Ce=or.AST_NODE_TYPES.TSCallSignatureDeclaration;break;case o.FunctionType:Ce=or.AST_NODE_TYPES.TSFunctionType;break;case o.ConstructorType:default:Ce=or.AST_NODE_TYPES.TSConstructorType}Object.assign(_,{type:Ce,params:x(r.parameters)}),r.type&&(_.returnType=y(r.type)),r.typeParameters&&(_.typeParameters=b(r.typeParameters));break;case o.InterfaceDeclaration:var ke=r.heritageClauses||[],Ee=ke.length?ke[ke.length-1]:r.name;if(r.typeParameters&&r.typeParameters.length){var Ne=r.typeParameters[r.typeParameters.length-1];(!Ee||Ne.pos>Ee.pos)&&(Ee=a.default.findNextToken(Ne,u,u)),_.typeParameters=b(r.typeParameters)}var Ae=a.default.findNextToken(Ee,u,u),Fe={type:or.AST_NODE_TYPES.TSInterfaceBody,body:r.members.map(function(e){return m(e)}),range:[Ae.getStart(u),r.end],loc:a.default.getLocFor(Ae.getStart(u),r.end,u)};if(Object.assign(_,{type:or.AST_NODE_TYPES.TSInterfaceDeclaration,body:Fe,id:m(r.name)}),ke.length>0){var Pe=[],we=[],Oe=!0,Ie=!1,Me=void 0;try{for(var Le,Re=ke[Symbol.iterator]();!(Oe=(Le=Re.next()).done);Oe=!0){var Be=Le.value;if(Be.token===o.ExtendsKeyword){var je=!0,Je=!1,ze=void 0;try{for(var Ke,Ue=Be.types[Symbol.iterator]();!(je=(Ke=Ue.next()).done);je=!0){var Ve=Ke.value;Pe.push(D(or.AST_NODE_TYPES.TSInterfaceHeritage,Ve))}}catch(e){Je=!0,ze=e}finally{try{je||null==Ue.return||Ue.return()}finally{if(Je)throw ze}}}else if(Be.token===o.ImplementsKeyword){var qe=!0,We=!1,He=void 0;try{for(var Ge,Ye=Be.types[Symbol.iterator]();!(qe=(Ge=Ye.next()).done);qe=!0){var Xe=Ge.value;we.push(D(or.AST_NODE_TYPES.TSInterfaceHeritage,Xe))}}catch(e){We=!0,He=e}finally{try{qe||null==Ye.return||Ye.return()}finally{if(We)throw He}}}}}catch(e){Ie=!0,Me=e}finally{try{Oe||null==Re.return||Re.return()}finally{if(Ie)throw Me}}Pe.length&&(_.extends=Pe),we.length&&(_.implements=we)}r.decorators&&(_.decorators=r.decorators.map(m)),a.default.hasModifier(o.AbstractKeyword,r)&&(_.abstract=!0),a.default.hasModifier(o.DeclareKeyword,r)&&(_.declare=!0),_=a.default.fixExports(r,_,u);break;case o.FirstTypeNode:Object.assign(_,{type:or.AST_NODE_TYPES.TSTypePredicate,parameterName:m(r.parameterName),typeAnnotation:y(r.type)}),_.typeAnnotation.loc=_.typeAnnotation.typeAnnotation.loc,_.typeAnnotation.range=_.typeAnnotation.typeAnnotation.range;break;case o.ImportType:Object.assign(_,{type:or.AST_NODE_TYPES.TSImportType,isTypeOf:!!r.isTypeOf,parameter:m(r.argument),qualifier:m(r.qualifier),typeParameters:r.typeArguments?h(r.typeArguments):null});break;case o.EnumDeclaration:Object.assign(_,{type:or.AST_NODE_TYPES.TSEnumDeclaration,id:m(r.name),members:r.members.map(m)}),T(r.modifiers),_=a.default.fixExports(r,_,u),r.decorators&&(_.decorators=r.decorators.map(m));break;case o.EnumMember:Object.assign(_,{type:or.AST_NODE_TYPES.TSEnumMember,id:m(r.name)}),r.initializer&&(_.initializer=m(r.initializer));break;case o.AbstractKeyword:Object.assign(_,{type:or.AST_NODE_TYPES.TSAbstractKeyword});break;case o.ModuleDeclaration:Object.assign(_,{type:or.AST_NODE_TYPES.TSModuleDeclaration,id:m(r.name)}),r.body&&(_.body=m(r.body)),T(r.modifiers),r.flags&i.default.NodeFlags.GlobalAugmentation&&(_.global=!0),_=a.default.fixExports(r,_,u);break;case o.OptionalType:Object.assign(_,{type:or.AST_NODE_TYPES.TSOptionalType,typeAnnotation:g(r.type)});break;case o.ParenthesizedType:Object.assign(_,{type:or.AST_NODE_TYPES.TSParenthesizedType,typeAnnotation:g(r.type)});break;case o.TupleType:Object.assign(_,{type:or.AST_NODE_TYPES.TSTupleType,elementTypes:r.elementTypes.map(g)});break;case o.UnionType:Object.assign(_,{type:or.AST_NODE_TYPES.TSUnionType,types:r.types.map(g)});break;case o.IntersectionType:Object.assign(_,{type:or.AST_NODE_TYPES.TSIntersectionType,types:r.types.map(g)});break;case o.RestType:Object.assign(_,{type:or.AST_NODE_TYPES.TSRestType,typeAnnotation:g(r.type)});break;case o.AsExpression:Object.assign(_,{type:or.AST_NODE_TYPES.TSAsExpression,expression:m(r.expression),typeAnnotation:g(r.type)});break;case o.InferType:Object.assign(_,{type:or.AST_NODE_TYPES.TSInferType,typeParameter:g(r.typeParameter)});break;case o.LiteralType:Object.assign(_,{type:or.AST_NODE_TYPES.TSLiteralType,literal:g(r.literal)});break;case o.TypeAssertionExpression:Object.assign(_,{type:or.AST_NODE_TYPES.TSTypeAssertion,typeAnnotation:g(r.type),expression:m(r.expression)});break;case o.ImportEqualsDeclaration:Object.assign(_,{type:or.AST_NODE_TYPES.TSImportEqualsDeclaration,id:m(r.name),moduleReference:m(r.moduleReference),isExport:a.default.hasModifier(o.ExportKeyword,r)});break;case o.ExternalModuleReference:Object.assign(_,{type:or.AST_NODE_TYPES.TSExternalModuleReference,expression:m(r.expression)});break;case o.NamespaceExportDeclaration:Object.assign(_,{type:or.AST_NODE_TYPES.TSNamespaceExportDeclaration,id:m(r.name)});break;default:!function(){var e="TS".concat(o[r.kind]);if(l.errorOnUnknownASTType&&!or.AST_NODE_TYPES[e])throw new Error('Unknown AST_NODE_TYPE: "'.concat(e,'"'));_.type=e,Object.keys(r).filter(function(e){return!/^(?:_children|kind|parent|pos|end|flags|modifierFlagsCache|jsDoc)$/.test(e)}).forEach(function(e){"type"===e?_.typeAnnotation=r.type?y(r.type):null:"typeArguments"===e?_.typeParameters=r.typeArguments?h(r.typeArguments):null:"typeParameters"===e?_.typeParameters=r.typeParameters?b(r.typeParameters):null:"decorators"===e?r.decorators&&r.decorators.length&&(_.decorators=r.decorators.map(m)):Array.isArray(r[e])?_[e]=r[e].map(m):r[e]&&"object"===f(r[e])&&r[e].kind?_[e]=m(r[e]):_[e]=r[e]})}()}return l.shouldProvideParserServices&&(c.set(r,_),s.set(_,r)),_}});i(cr);var ur=a(function(e,t){var n=r&&r.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var i=n(Kt),a=n(sr);function o(e,t,r){var n=e.getToken()===i.default.SyntaxKind.MultiLineCommentTrivia,o={pos:e.getTokenPos(),end:e.getTextPos(),kind:e.getToken()},s=r.substring(o.pos,o.end),c=n?s.replace(/^\/\*/,"").replace(/\*\/$/,""):s.replace(/^\/\//,""),u=a.default.getLocFor(o.pos,o.end,t);return function(e,t,r,n,i,a){var o={type:e?"Block":"Line",value:t};return"number"==typeof r&&(o.range=[r,n]),"object"===f(i)&&(o.loc={start:i,end:a}),o}(n,c,o.pos,o.end,u.start,u.end)}t.convertComments=function(e,t){for(var r=[],n=i.default.createScanner(e.languageVersion,!1,e.languageVariant,t),s=n.scan();s!==i.default.SyntaxKind.EndOfFileToken;){var c=n.getTokenPos(),u=n.getTextPos(),l=null;switch(s){case i.default.SyntaxKind.SingleLineCommentTrivia:case i.default.SyntaxKind.MultiLineCommentTrivia:var _=o(n,e,t);r.push(_);break;case i.default.SyntaxKind.GreaterThanToken:if((l=a.default.getNodeContainer(e,c,u))&&l.parent&&l.parent.kind===i.default.SyntaxKind.JsxOpeningElement&&l.parent.parent&&l.parent.parent.kind===i.default.SyntaxKind.JsxElement){s=n.reScanJsxToken();continue}break;case i.default.SyntaxKind.CloseBraceToken:if((l=a.default.getNodeContainer(e,c,u)).kind===i.default.SyntaxKind.TemplateMiddle||l.kind===i.default.SyntaxKind.TemplateTail){s=n.reScanTemplateToken();continue}break;case i.default.SyntaxKind.SlashToken:case i.default.SyntaxKind.SlashEqualsToken:if((l=a.default.getNodeContainer(e,c,u)).kind===i.default.SyntaxKind.RegularExpressionLiteral){s=n.reScanSlashToken();continue}}s=n.scan()}return r}});i(ur);var lr=a(function(e,t){var n=r&&r.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t},i=r&&r.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var a=n(cr),o=i(sr);t.default=function(e,t,r){if(e.parseDiagnostics.length)throw a.convertError(e.parseDiagnostics[0]);var n=a.default({node:e,parent:null,ast:e,additionalOptions:{errorOnUnknownASTType:t.errorOnUnknownASTType||!1,useJSXTextNode:t.useJSXTextNode||!1,shouldProvideParserServices:r}});t.tokens&&(n.tokens=o.default.convertTokens(e)),t.comment&&(n.comments=ur.convertComments(e,t.code));var i=void 0;return r&&(i=a.getASTMaps(),a.resetASTMaps()),{estree:n,astMaps:i}}});i(lr);var _r=a(function(e,t){var n=r&&r.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var i=n(Kt);function a(e){return e.filter(function(e){switch(e.code){case 1014:case 1044:case 1045:case 1048:case 1049:case 1070:case 1071:case 1090:case 1096:case 1097:case 1117:case 1121:case 1123:case 1141:case 1172:case 1173:case 1175:case 1176:case 1190:case 1200:case 1206:case 1211:case 1242:case 1246:case 2364:case 2369:case 2462:case 17012:case 17013:return!0}return!1})}function o(e){return Object.assign({},e,{message:i.default.flattenDiagnosticMessageText(e.messageText,i.default.sys.newLine)})}t.getFirstSemanticOrSyntacticError=function(e,t){try{var r=a(e.getSyntacticDiagnostics(t));if(r.length)return o(r[0]);var n=a(e.getSemanticDiagnostics(t));return n.length?o(n[0]):void 0}catch(e){return void console.warn('Warning From TSC: "'.concat(e.message))}}});i(_r);var dr="typescript-estree",pr="A parser that converts TypeScript source code into an ESTree compatible form",fr="https://github.com/JamesHenry/typescript-estree",mr="dist/parser.js",gr=["dist","README.md","LICENSE"],yr={node:">=6.14.0"},vr={url:"https://github.com/JamesHenry/typescript-estree/issues"},hr={"@babel/code-frame":"7.0.0","@babel/parser":"7.2.3","@commitlint/cli":"^7.1.2","@commitlint/config-conventional":"^7.1.2","@commitlint/travis-cli":"^7.1.2","@types/babel-code-frame":"^6.20.1","@types/jest":"^23.3.9","@types/lodash.isplainobject":"^4.0.4","@types/lodash.unescape":"^4.0.4","@types/node":"^10.12.2","@types/semver":"^5.5.0","@types/shelljs":"^0.8.0","cz-conventional-changelog":"2.1.0",glob:"7.1.2",husky:"0.14.3",jest:"23.6.0","lint-staged":"7.3.0","lodash.isplainobject":"4.0.6",prettier:"^1.14.3","semantic-release":"^15.9.16",shelljs:"0.8.2","travis-deploy-once":"^5.0.8","ts-jest":"^23.10.4",typescript:"~3.2.1"},br=["ast","estree","ecmascript","javascript","typescript","parser","syntax"],Dr={build:"tsc",test:"jest --coverage","unit-tests":'jest "./tests/lib/.*"',"ast-alignment-tests":"jest spec.ts",precommit:"npm test && lint-staged",cz:"git-cz",commitmsg:"commitlint -E GIT_PARAMS","check-format":'prettier --list-different "./**/*.{ts,js,json,md}"',"semantic-release":"semantic-release","travis-deploy-once":"travis-deploy-once"},xr={"lodash.unescape":"4.0.1",semver:"5.5.0"},Sr={typescript:"*"},Tr={commitizen:{path:"./node_modules/cz-conventional-changelog"}},Cr={extends:["@commitlint/config-conventional"]},kr={name:dr,description:pr,homepage:fr,main:mr,version:"18.0.0",files:gr,engines:yr,repository:"JamesHenry/typescript-estree",bugs:vr,license:"BSD-2-Clause",devDependencies:hr,keywords:br,scripts:Dr,dependencies:xr,peerDependencies:Sr,config:Tr,commitlint:Cr,"lint-staged":{"*.{ts,js,json,md}":["prettier --write","git add"]}},Er=Object.freeze({name:dr,description:pr,homepage:fr,main:mr,version:"18.0.0",files:gr,engines:yr,repository:"JamesHenry/typescript-estree",bugs:vr,license:"BSD-2-Clause",devDependencies:hr,keywords:br,scripts:Dr,dependencies:xr,peerDependencies:Sr,config:Tr,commitlint:Cr,default:kr}),Nr=Er&&kr||Er,Ar=a(function(e,t){var n=r&&r.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});var i,a=n(Vt),o=n(Kt),s=n(lr),c=n(sr),u=Nr.devDependencies.typescript,l=o.default.version,_=a.default.satisfies(l,u),d=!1;function p(e){return e.jsx?"estree.tsx":"estree.ts"}function f(e,t,r){return r&&function(e,t){return c.default.firstDefined(Ut.calculateProjectParserOptions(e,t.filePath||p(t),i),function(e){var r=e.getSourceFile(t.filePath||p(t));return r&&{ast:r,program:e}})}(e,t)||r&&function(e,t){var r=t.filePath||p(t),n=Ut.createProgram(e,r,i),a=n&&n.getSourceFile(r);return a&&{ast:a,program:n}}(e,t)||function(e){var t=p(i),r={fileExists:function(){return!0},getCanonicalFileName:function(){return t},getCurrentDirectory:function(){return""},getDirectories:function(){return[]},getDefaultLibFileName:function(){return"lib.d.ts"},getNewLine:function(){return"\n"},getSourceFile:function(t){return o.default.createSourceFile(t,e,o.default.ScriptTarget.Latest,!0)},readFile:function(){},useCaseSensitiveFileNames:function(){return!0},writeFile:function(){return null}},n=o.default.createProgram([t],{noResolve:!0,target:o.default.ScriptTarget.Latest,jsx:i.jsx?o.default.JsxEmit.Preserve:void 0},r);return{ast:n.getSourceFile(t),program:n}}(e)}function m(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=String;if("string"==typeof e||e instanceof String||(e=n(e)),i={tokens:null,range:!1,loc:!1,comment:!1,comments:[],strict:!1,jsx:!1,useJSXTextNode:!1,log:console.log,projects:[],errorOnUnknownASTType:!1,errorOnTypeScriptSyntacticAndSemanticIssues:!1,code:"",tsconfigRootDir:H.cwd(),extraFileExtensions:[]},void 0!==t&&(i.range="boolean"==typeof t.range&&t.range,i.loc="boolean"==typeof t.loc&&t.loc,"boolean"==typeof t.tokens&&t.tokens&&(i.tokens=[]),"boolean"==typeof t.comment&&t.comment&&(i.comment=!0,i.comments=[]),"boolean"==typeof t.jsx&&t.jsx&&(i.jsx=!0),"boolean"==typeof t.errorOnUnknownASTType&&t.errorOnUnknownASTType&&(i.errorOnUnknownASTType=!0),r&&"boolean"==typeof t.errorOnTypeScriptSyntacticAndSemanticIssues&&t.errorOnTypeScriptSyntacticAndSemanticIssues&&(i.errorOnTypeScriptSyntacticAndSemanticIssues=!0),"boolean"==typeof t.useJSXTextNode&&t.useJSXTextNode&&(i.useJSXTextNode=!0),"function"==typeof t.loggerFn?i.log=t.loggerFn:!1===t.loggerFn&&(i.log=Function.prototype),"string"==typeof t.project?i.projects=[t.project]:Array.isArray(t.project)&&t.project.every(function(e){return"string"==typeof e})&&(i.projects=t.project),"string"==typeof t.tsconfigRootDir&&(i.tsconfigRootDir=t.tsconfigRootDir),Array.isArray(t.extraFileExtensions)&&t.extraFileExtensions.every(function(e){return"string"==typeof e})&&(i.extraFileExtensions=t.extraFileExtensions)),!_&&!d){var a=["=============","WARNING: You are currently running a version of TypeScript which is not officially supported by typescript-estree.","You may find that it works just fine, or you may not.","SUPPORTED TYPESCRIPT VERSIONS: ".concat(u),"YOUR TYPESCRIPT VERSION: ".concat(l),"Please only submit bug reports when using the officially supported version.","============="];i.log(a.join("\n\n")),d=!0}var o=r&&i.projects&&i.projects.length>0,c=f(e,t,o),p=c.ast,m=c.program;i.code=e;var g=s.default(p,i,o),y=g.estree,v=g.astMaps;if(m&&i.errorOnTypeScriptSyntacticAndSemanticIssues){var h=_r.getFirstSemanticOrSyntacticError(m,p);if(h)throw cr.convertError(h)}return{estree:y,program:o?m:void 0,astMaps:o?v:{esTreeNodeToTSNodeMap:void 0,tsNodeToESTreeNodeMap:void 0}}}t.AST_NODE_TYPES=or.AST_NODE_TYPES;var g=Nr.version;t.version=g,t.parse=function(e,t){if(t&&t.errorOnTypeScriptSyntacticAndSemanticIssues)throw new Error('"errorOnTypeScriptSyntacticAndSemanticIssues" is only supported for parseAndGenerateServices()');return m(e,t).estree},t.parseAndGenerateServices=function(e,t){var r=m(e,t,!0);return{ast:r.estree,services:{program:r.program,esTreeNodeToTSNodeMap:r.astMaps.esTreeNodeToTSNodeMap,tsNodeToESTreeNodeMap:r.astMaps.tsNodeToESTreeNodeMap}}}});i(Ar);var Fr=_;function Pr(e,t){return Ar.parse(e,{loc:!0,range:!0,tokens:!0,comment:!0,useJSXTextNode:!0,jsx:t,loggerFn:function(){}})}return{parsers:{typescript:Object.assign({parse:function(r,n,i){var a,o=function(e){return new RegExp(["(^[^\"'`]*)"].join(""),"m").test(e)}(r);try{a=Pr(r,o)}catch(t){try{a=Pr(r,!o)}catch(r){var s=t;if(void 0===s.lineNumber)throw s;throw e(s.message,{start:{line:s.lineNumber,column:s.column+1}})}}return delete a.tokens,t(r,a),D(a,Object.assign({},i,{originalText:r}))},astFormat:"estree",hasPragma:Fr},p)}}}); diff --git a/prettier/prettier.ts b/prettier/prettier.ts new file mode 100644 index 000000000..84b815377 --- /dev/null +++ b/prettier/prettier.ts @@ -0,0 +1,9 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import "./standalone.js"; +import "./parser_typescript.js"; +import "./parser_markdown.js"; + +// TODO: provide decent type declarions for these +const { prettier, prettierPlugins } = window as any; + +export { prettier, prettierPlugins }; diff --git a/prettier/standalone.js b/prettier/standalone.js new file mode 100644 index 000000000..4aefa2e97 --- /dev/null +++ b/prettier/standalone.js @@ -0,0 +1,30688 @@ +// This file is copied from prettier@1.16.1 +/** + * Copyright © James Long and contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.prettier = factory()); +}(globalThis, (function () { 'use strict'; + +var name = "prettier"; +var version$1 = "1.16.1"; +var description = "Prettier is an opinionated code formatter"; +var bin = { + "prettier": "./bin/prettier.js" +}; +var repository = "prettier/prettier"; +var homepage = "https://prettier.io"; +var author = "James Long"; +var license = "MIT"; +var main = "./index.js"; +var engines = { + "node": ">=6" +}; +var dependencies = { + "@angular/compiler": "6.1.10", + "@babel/code-frame": "7.0.0-beta.46", + "@babel/parser": "7.2.0", + "@glimmer/syntax": "0.30.3", + "@iarna/toml": "2.0.0", + "angular-estree-parser": "1.1.5", + "angular-html-parser": "1.2.0", + "camelcase": "4.1.0", + "chalk": "2.1.0", + "cjk-regex": "2.0.0", + "cosmiconfig": "5.0.7", + "dashify": "0.2.2", + "dedent": "0.7.0", + "diff": "3.2.0", + "editorconfig": "0.15.2", + "editorconfig-to-prettier": "0.1.1", + "escape-string-regexp": "1.0.5", + "esutils": "2.0.2", + "find-parent-dir": "0.3.0", + "find-project-root": "1.1.1", + "flow-parser": "0.84.0", + "get-stream": "3.0.0", + "globby": "6.1.0", + "graphql": "0.13.2", + "html-element-attributes": "2.0.0", + "html-styles": "1.0.0", + "html-tag-names": "1.1.2", + "ignore": "3.3.7", + "jest-docblock": "23.2.0", + "json-stable-stringify": "1.0.1", + "leven": "2.1.0", + "lines-and-columns": "1.1.6", + "linguist-languages": "6.2.1-dev.20180706", + "lodash.uniqby": "4.7.0", + "mem": "1.1.0", + "minimatch": "3.0.4", + "minimist": "1.2.0", + "n-readlines": "1.0.0", + "normalize-path": "3.0.0", + "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee", + "postcss-less": "1.1.5", + "postcss-media-query-parser": "0.2.3", + "postcss-scss": "2.0.0", + "postcss-selector-parser": "2.2.3", + "postcss-values-parser": "1.5.0", + "regexp-util": "1.2.2", + "remark-math": "1.0.4", + "remark-parse": "5.0.0", + "resolve": "1.5.0", + "semver": "5.4.1", + "string-width": "3.0.0", + "typescript": "3.2.2", + "typescript-estree": "18.0.0", + "unicode-regex": "2.0.0", + "unified": "6.1.6", + "vnopts": "1.0.2", + "yaml": "1.0.2", + "yaml-unist-parser": "1.0.0" +}; +var devDependencies = { + "@babel/cli": "7.2.0", + "@babel/core": "7.2.0", + "@babel/preset-env": "7.2.0", + "babel-loader": "8.0.4", + "benchmark": "2.1.4", + "builtin-modules": "2.0.0", + "codecov": "codecov/codecov-node#e427d900309adb50746a39a50aa7d80071a5ddd0", + "cross-env": "5.0.5", + "eslint": "4.18.2", + "eslint-config-prettier": "2.9.0", + "eslint-friendly-formatter": "3.0.0", + "eslint-plugin-import": "2.9.0", + "eslint-plugin-prettier": "2.6.0", + "eslint-plugin-react": "7.7.0", + "execa": "0.10.0", + "jest": "23.3.0", + "jest-junit": "5.0.0", + "jest-snapshot-serializer-ansi": "1.0.0", + "jest-snapshot-serializer-raw": "1.1.0", + "jest-watch-typeahead": "0.1.0", + "mkdirp": "0.5.1", + "prettier": "1.16.0", + "prettylint": "1.0.0", + "rimraf": "2.6.2", + "rollup": "0.47.6", + "rollup-plugin-alias": "1.4.0", + "rollup-plugin-babel": "4.0.0-beta.4", + "rollup-plugin-commonjs": "8.2.6", + "rollup-plugin-json": "2.1.1", + "rollup-plugin-node-builtins": "2.0.0", + "rollup-plugin-node-globals": "1.1.0", + "rollup-plugin-node-resolve": "2.0.0", + "rollup-plugin-replace": "1.2.1", + "rollup-plugin-uglify": "3.0.0", + "shelljs": "0.8.1", + "snapshot-diff": "0.4.0", + "strip-ansi": "4.0.0", + "tempy": "0.2.1", + "webpack": "3.12.0" +}; +var resolutions = { + "@babel/code-frame": "7.0.0-beta.46" +}; +var scripts = { + "prepublishOnly": "echo \"Error: must publish from dist/\" && exit 1", + "prepare-release": "yarn && yarn build && yarn test:dist", + "test": "jest", + "test:dist": "node ./scripts/test-dist.js", + "test-integration": "jest tests_integration", + "perf-repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "perf-repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "perf-benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "lint": "cross-env EFF_NO_LINK_RULES=true eslint . --format node_modules/eslint-friendly-formatter", + "lint-docs": "prettylint {.,docs,website,website/blog}/*.md", + "lint-dist": "eslint --no-eslintrc --no-ignore --env=browser \"dist/!(bin-prettier|index|third-party).js\"", + "build": "node --max-old-space-size=2048 ./scripts/build/build.js", + "build-docs": "node ./scripts/build-docs.js", + "check-deps": "node ./scripts/check-deps.js" +}; +var _package = { + name: name, + version: version$1, + description: description, + bin: bin, + repository: repository, + homepage: homepage, + author: author, + license: license, + main: main, + engines: engines, + dependencies: dependencies, + devDependencies: devDependencies, + resolutions: resolutions, + scripts: scripts +}; + +var _package$1 = Object.freeze({ + name: name, + version: version$1, + description: description, + bin: bin, + repository: repository, + homepage: homepage, + author: author, + license: license, + main: main, + engines: engines, + dependencies: dependencies, + devDependencies: devDependencies, + resolutions: resolutions, + scripts: scripts, + default: _package +}); + +var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + + +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var base = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports['default'] = + /*istanbul ignore end*/ + Diff; + + function Diff() {} + + Diff.prototype = { + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + diff: function diff(oldString, newString) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = + /*istanbul ignore start*/ + void 0; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + equals: function equals(left, right) { + return left === right; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + castInput: function castInput(value) { + return value; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + tokenize: function tokenize(value) { + return value.split(''); + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + join: function join(chars) { + return chars.join(''); + } + }; + + function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored. For this case we merge the + // terminal into the prior string and drop the change. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; + } + + function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; + } +}); +unwrapExports(base); + +var character = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports.characterDiff = undefined; + exports. + /*istanbul ignore end*/ + diffChars = diffChars; + /*istanbul ignore start*/ + + var _base2 = _interopRequireDefault(base); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + 'default': obj + }; + } + /*istanbul ignore end*/ + + + var characterDiff = + /*istanbul ignore start*/ + exports. + /*istanbul ignore end*/ + characterDiff = new + /*istanbul ignore start*/ + _base2['default'](); + + function diffChars(oldStr, newStr, callback) { + return characterDiff.diff(oldStr, newStr, callback); + } +}); +unwrapExports(character); + +var params = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports. + /*istanbul ignore end*/ + generateOptions = generateOptions; + + function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; + } +}); +unwrapExports(params); + +var word = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports.wordDiff = undefined; + exports. + /*istanbul ignore end*/ + diffWords = diffWords; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffWordsWithSpace = diffWordsWithSpace; + /*istanbul ignore start*/ + + var _base2 = _interopRequireDefault(base); + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + 'default': obj + }; + } + /*istanbul ignore end*/ + // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode + // + // Ranges and exceptions: + // Latin-1 Supplement, 0080–00FF + // - U+00D7 × Multiplication sign + // - U+00F7 ÷ Division sign + // Latin Extended-A, 0100–017F + // Latin Extended-B, 0180–024F + // IPA Extensions, 0250–02AF + // Spacing Modifier Letters, 02B0–02FF + // - U+02C7 ˇ ˇ Caron + // - U+02D8 ˘ ˘ Breve + // - U+02D9 ˙ ˙ Dot Above + // - U+02DA ˚ ˚ Ring Above + // - U+02DB ˛ ˛ Ogonek + // - U+02DC ˜ ˜ Small Tilde + // - U+02DD ˝ ˝ Double Acute Accent + // Latin Extended Additional, 1E00–1EFF + + + var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; + var reWhitespace = /\S/; + var wordDiff = + /*istanbul ignore start*/ + exports. + /*istanbul ignore end*/ + wordDiff = new + /*istanbul ignore start*/ + _base2['default'](); + + wordDiff.equals = function (left, right) { + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); + }; + + wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; + }; + + function diffWords(oldStr, newStr, callback) { + var options = + /*istanbul ignore start*/ + (0, params.generateOptions + /*istanbul ignore end*/ + )(callback, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); + } + + function diffWordsWithSpace(oldStr, newStr, callback) { + return wordDiff.diff(oldStr, newStr, callback); + } +}); +unwrapExports(word); + +var line = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports.lineDiff = undefined; + exports. + /*istanbul ignore end*/ + diffLines = diffLines; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffTrimmedLines = diffTrimmedLines; + /*istanbul ignore start*/ + + var _base2 = _interopRequireDefault(base); + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + 'default': obj + }; + } + /*istanbul ignore end*/ + + + var lineDiff = + /*istanbul ignore start*/ + exports. + /*istanbul ignore end*/ + lineDiff = new + /*istanbul ignore start*/ + _base2['default'](); + + lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; + }; + + function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); + } + + function diffTrimmedLines(oldStr, newStr, callback) { + var options = + /*istanbul ignore start*/ + (0, params.generateOptions + /*istanbul ignore end*/ + )(callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); + } +}); +unwrapExports(line); + +var sentence = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports.sentenceDiff = undefined; + exports. + /*istanbul ignore end*/ + diffSentences = diffSentences; + /*istanbul ignore start*/ + + var _base2 = _interopRequireDefault(base); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + 'default': obj + }; + } + /*istanbul ignore end*/ + + + var sentenceDiff = + /*istanbul ignore start*/ + exports. + /*istanbul ignore end*/ + sentenceDiff = new + /*istanbul ignore start*/ + _base2['default'](); + + sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); + }; + + function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); + } +}); +unwrapExports(sentence); + +var css = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports.cssDiff = undefined; + exports. + /*istanbul ignore end*/ + diffCss = diffCss; + /*istanbul ignore start*/ + + var _base2 = _interopRequireDefault(base); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + 'default': obj + }; + } + /*istanbul ignore end*/ + + + var cssDiff = + /*istanbul ignore start*/ + exports. + /*istanbul ignore end*/ + cssDiff = new + /*istanbul ignore start*/ + _base2['default'](); + + cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); + }; + + function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); + } +}); +unwrapExports(css); + +function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} + +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); +} + +function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); +} + +function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); +} + +function isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); + return true; + } catch (e) { + return false; + } +} + +function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + _construct = Reflect.construct; + } else { + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) _setPrototypeOf(instance, Class.prototype); + return instance; + }; + } + + return _construct.apply(null, arguments); +} + +function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} + +function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !_isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return _construct(Class, arguments, _getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return _setPrototypeOf(Wrapper, Class); + }; + + return _wrapNativeSuper(Class); +} + +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} + +function _possibleConstructorReturn(self, call) { + if (call && (typeof call === "object" || typeof call === "function")) { + return call; + } + + return _assertThisInitialized(self); +} + +function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = _getPrototypeOf(object); + if (object === null) break; + } + + return object; +} + +function _get(target, property, receiver) { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get; + } else { + _get = function _get(target, property, receiver) { + var base = _superPropBase(target, property); + + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.get) { + return desc.get.call(receiver); + } + + return desc.value; + }; + } + + return _get(target, property, receiver || target); +} + +function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); +} + +function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); +} + +function _toArray(arr) { + return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); +} + +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); +} + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } +} + +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} + +function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); +} + +function _iterableToArrayLimit(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; +} + +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); +} + +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); +} + +function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + + return (hint === "string" ? String : Number)(input); +} + +function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + + return typeof key === "symbol" ? key : String(key); +} + +function _addElementPlacement(element, placements, silent) { + var keys = placements[element.placement]; + + if (!silent && keys.indexOf(element.key) !== -1) { + throw new TypeError("Duplicated element (" + element.key + ")"); + } + + keys.push(element.key); +} + +function _fromElementDescriptor(element) { + var obj = { + kind: element.kind, + key: element.key, + placement: element.placement, + descriptor: element.descriptor + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + if (element.kind === "field") obj.initializer = element.initializer; + return obj; +} + +function _toElementDescriptors(elementObjects) { + if (elementObjects === undefined) return; + return _toArray(elementObjects).map(function (elementObject) { + var element = _toElementDescriptor(elementObject); + + _disallowProperty(elementObject, "finisher", "An element descriptor"); + + _disallowProperty(elementObject, "extras", "An element descriptor"); + + return element; + }); +} + +function _toElementDescriptor(elementObject) { + var kind = String(elementObject.kind); + + if (kind !== "method" && kind !== "field") { + throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); + } + + var key = _toPropertyKey(elementObject.key); + + var placement = String(elementObject.placement); + + if (placement !== "static" && placement !== "prototype" && placement !== "own") { + throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); + } + + var descriptor = elementObject.descriptor; + + _disallowProperty(elementObject, "elements", "An element descriptor"); + + var element = { + kind: kind, + key: key, + placement: placement, + descriptor: Object.assign({}, descriptor) + }; + + if (kind !== "field") { + _disallowProperty(elementObject, "initializer", "A method descriptor"); + } else { + _disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); + + _disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); + + _disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); + + element.initializer = elementObject.initializer; + } + + return element; +} + +function _toElementFinisherExtras(elementObject) { + var element = _toElementDescriptor(elementObject); + + var finisher = _optionalCallableProperty(elementObject, "finisher"); + + var extras = _toElementDescriptors(elementObject.extras); + + return { + element: element, + finisher: finisher, + extras: extras + }; +} + +function _fromClassDescriptor(elements) { + var obj = { + kind: "class", + elements: elements.map(_fromElementDescriptor) + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + return obj; +} + +function _toClassDescriptor(obj) { + var kind = String(obj.kind); + + if (kind !== "class") { + throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); + } + + _disallowProperty(obj, "key", "A class descriptor"); + + _disallowProperty(obj, "placement", "A class descriptor"); + + _disallowProperty(obj, "descriptor", "A class descriptor"); + + _disallowProperty(obj, "initializer", "A class descriptor"); + + _disallowProperty(obj, "extras", "A class descriptor"); + + var finisher = _optionalCallableProperty(obj, "finisher"); + + var elements = _toElementDescriptors(obj.elements); + + return { + elements: elements, + finisher: finisher + }; +} + +function _disallowProperty(obj, name, objectType) { + if (obj[name] !== undefined) { + throw new TypeError(objectType + " can't have a ." + name + " property."); + } +} + +function _optionalCallableProperty(obj, name) { + var value = obj[name]; + + if (value !== undefined && typeof value !== "function") { + throw new TypeError("Expected '" + name + "' to be a function"); + } + + return value; +} + +var json = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports.jsonDiff = undefined; + + var _typeof$$1 = typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol" ? function (obj) { + return _typeof(obj); + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : _typeof(obj); + }; + + exports. + /*istanbul ignore end*/ + diffJson = diffJson; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + canonicalize = canonicalize; + /*istanbul ignore start*/ + + var _base2 = _interopRequireDefault$$1(base); + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + + + function _interopRequireDefault$$1(obj) { + return obj && obj.__esModule ? obj : { + 'default': obj + }; + } + /*istanbul ignore end*/ + + + var objectPrototypeToString = Object.prototype.toString; + var jsonDiff = + /*istanbul ignore start*/ + exports. + /*istanbul ignore end*/ + jsonDiff = new + /*istanbul ignore start*/ + _base2['default'](); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a + // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + + jsonDiff.useLongestToken = true; + jsonDiff.tokenize = + /*istanbul ignore start*/ + line.lineDiff. + /*istanbul ignore end*/ + tokenize; + + jsonDiff.castInput = function (value) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + undefinedReplacement = this.options.undefinedReplacement; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), function (k, v) { + if (typeof v === 'undefined') { + return undefinedReplacement; + } + + return v; + }, ' '); + }; + + jsonDiff.equals = function (left, right) { + return ( + /*istanbul ignore start*/ + _base2['default']. + /*istanbul ignore end*/ + prototype.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')) + ); + }; + + function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); + } // This function handles the presence of circular references by bailing out when encountering an + // object that is already on the "stack" of items being processed. + + + function canonicalize(obj, stack, replacementStack) { + stack = stack || []; + replacementStack = replacementStack || []; + var i = + /*istanbul ignore start*/ + void 0; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj = + /*istanbul ignore start*/ + void 0; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if ( + /*istanbul ignore start*/ + (typeof + /*istanbul ignore end*/ + obj === 'undefined' ? 'undefined' : _typeof$$1(obj)) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + var sortedKeys = [], + key = + /*istanbul ignore start*/ + void 0; + + for (key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(key)) { + sortedKeys.push(key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + key = sortedKeys[i]; + canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; + } +}); +unwrapExports(json); + +var array = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports.arrayDiff = undefined; + exports. + /*istanbul ignore end*/ + diffArrays = diffArrays; + /*istanbul ignore start*/ + + var _base2 = _interopRequireDefault(base); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + 'default': obj + }; + } + /*istanbul ignore end*/ + + + var arrayDiff = + /*istanbul ignore start*/ + exports. + /*istanbul ignore end*/ + arrayDiff = new + /*istanbul ignore start*/ + _base2['default'](); + + arrayDiff.tokenize = arrayDiff.join = function (value) { + return value.slice(); + }; + + function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); + } +}); +unwrapExports(array); + +var parse = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports. + /*istanbul ignore end*/ + parsePatch = parsePatch; + + function parsePatch(uniDiff) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + + if (header) { + index.index = header[1]; + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var headerPattern = /^(---|\+\+\+)\s+([\S ]*)(?:\t(.*?)\s*)?$/; + var fileHeader = headerPattern.exec(diffstr[i]); + + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + index[keyPrefix + 'FileName'] = fileHeader[2]; + index[keyPrefix + 'Header'] = fileHeader[3]; + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; + } +}); +unwrapExports(parse); + +var distanceIterator = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + "use strict"; + + exports.__esModule = true; + + exports["default"] = + /*istanbul ignore end*/ + function (start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text lenght, then + // hunk can't fit on the text. Return undefined + + }; + }; +}); +unwrapExports(distanceIterator); + +var apply = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports. + /*istanbul ignore end*/ + applyPatch = applyPatch; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + applyPatches = applyPatches; + /*istanbul ignore start*/ + + var _distanceIterator2 = _interopRequireDefault(distanceIterator); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + 'default': obj + }; + } + /*istanbul ignore end*/ + + + function applyPatch(source, uniDiff) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + + if (typeof uniDiff === 'string') { + uniDiff = + /*istanbul ignore start*/ + (0, parse.parsePatch + /*istanbul ignore end*/ + )(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) + /*istanbul ignore start*/ + { + return ( + /*istanbul ignore end*/ + line === patchContent + ); + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL = + /*istanbul ignore start*/ + void 0 + /*istanbul ignore end*/ + , + addEOFNL = + /*istanbul ignore start*/ + void 0; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line[0], + content = line.substr(1); + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = + /*istanbul ignore start*/ + (0, _distanceIterator2['default'] + /*istanbul ignore end*/ + )(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.offset + _hunk.newStart - 1; + + if (_hunk.newLines == 0) { + _toPos++; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line[0], + content = line.substr(1), + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); + } // Wrapper that supports multiple file patches via callbacks. + + + function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = + /*istanbul ignore start*/ + (0, parse.parsePatch + /*istanbul ignore end*/ + )(uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); + } +}); +unwrapExports(apply); + +var create = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports. + /*istanbul ignore end*/ + structuredPatch = structuredPatch; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + createTwoFilesPatch = createTwoFilesPatch; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + createPatch = createPatch; + /*istanbul ignore start*/ + + function _toConsumableArray(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { + arr2[i] = arr[i]; + } + + return arr2; + } else { + return Array.from(arr); + } + } + /*istanbul ignore end*/ + + + function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = + /*istanbul ignore start*/ + (0, line.diffLines + /*istanbul ignore end*/ + )(oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + /*istanbul ignore start*/ + + var _loop = function _loop( + /*istanbul ignore end*/ + i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + /*istanbul ignore start*/ + var _curRange; + /*istanbul ignore end*/ + // If we have previous context, start with that + + + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + /*istanbul ignore start*/ + + + (_curRange = + /*istanbul ignore end*/ + curRange).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _curRange + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + /*istanbul ignore start*/ + var _curRange2; + /*istanbul ignore end*/ + // Overlapping + + /*istanbul ignore start*/ + + + (_curRange2 = + /*istanbul ignore end*/ + curRange).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _curRange2 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + contextLines(lines))); + } else { + /*istanbul ignore start*/ + var _curRange3; + /*istanbul ignore end*/ + // end the range and output + + + var contextSize = Math.min(lines.length, options.context); + /*istanbul ignore start*/ + + (_curRange3 = + /*istanbul ignore end*/ + curRange).push. + /*istanbul ignore start*/ + apply + /*istanbul ignore end*/ + ( + /*istanbul ignore start*/ + _curRange3 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + + if (lines.length == 0 && !oldEOFNewline) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } else if (!oldEOFNewline || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + /*istanbul ignore start*/ + _loop( + /*istanbul ignore end*/ + i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; + } + + function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; + } + + function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); + } +}); +unwrapExports(create); + +var dmp = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + "use strict"; + + exports.__esModule = true; + exports. + /*istanbul ignore end*/ + convertChangesToDMP = convertChangesToDMP; // See: http://code.google.com/p/google-diff-match-patch/wiki/API + + function convertChangesToDMP(changes) { + var ret = [], + change = + /*istanbul ignore start*/ + void 0 + /*istanbul ignore end*/ + , + operation = + /*istanbul ignore start*/ + void 0; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; + } +}); +unwrapExports(dmp); + +var xml = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports. + /*istanbul ignore end*/ + convertChangesToXML = convertChangesToXML; + + function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); + } + + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; + } +}); +unwrapExports(xml); + +var lib = createCommonjsModule(function (module, exports) { + /*istanbul ignore start*/ + 'use strict'; + + exports.__esModule = true; + exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffArrays = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diffTrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWords = exports.diffChars = exports.Diff = undefined; + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + + var _base2 = _interopRequireDefault(base); + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + 'default': obj + }; + } + + exports. + /*istanbul ignore end*/ + Diff = _base2['default']; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffChars = character.diffChars; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffWords = word.diffWords; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffWordsWithSpace = word.diffWordsWithSpace; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffLines = line.diffLines; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffTrimmedLines = line.diffTrimmedLines; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffSentences = sentence.diffSentences; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffCss = css.diffCss; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffJson = json.diffJson; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + diffArrays = array.diffArrays; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + structuredPatch = create.structuredPatch; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + createTwoFilesPatch = create.createTwoFilesPatch; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + createPatch = create.createPatch; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + applyPatch = apply.applyPatch; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + applyPatches = apply.applyPatches; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + parsePatch = parse.parsePatch; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + convertChangesToDMP = dmp.convertChangesToDMP; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + convertChangesToXML = xml.convertChangesToXML; + /*istanbul ignore start*/ + + exports. + /*istanbul ignore end*/ + canonicalize = json.canonicalize; + /* See LICENSE file for terms of use */ + + /* + * Text diff implementation. + * + * This library supports the following APIS: + * JsDiff.diffChars: Character by character diff + * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace + * JsDiff.diffLines: Line based diff + * + * JsDiff.diffCss: Diff targeted at CSS content + * + * These methods are based on the implementation proposed in + * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 + */ +}); +unwrapExports(lib); + +var _shim_fs = {}; + +var _shim_fs$1 = Object.freeze({ + default: _shim_fs +}); + +/*! + * normalize-path + * + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. + */ +var normalizePath = function normalizePath(path, stripTrailing) { + if (typeof path !== 'string') { + throw new TypeError('expected path to be a string'); + } + + if (path === '\\' || path === '/') return '/'; + var len = path.length; + if (len <= 1) return path; // ensure that win32 namespaces has two leading slashes, so that the path is + // handled properly by the win32 version of path.parse() after being normalized + // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + + var prefix = ''; + + if (len > 4 && path[3] === '\\') { + var ch = path[2]; + + if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { + path = path.slice(2); + prefix = '//'; + } + } + + var segs = path.split(/[/\\]+/); + + if (stripTrailing !== false && segs[segs.length - 1] === '') { + segs.pop(); + } + + return prefix + segs.join('/'); +}; + +var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; + +function init() { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray(b64) { + if (!inited) { + init(); + } + + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4'); + } // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + + + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data + + arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars + + l = placeHolders > 0 ? len - 4 : len; + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = tmp >> 16 & 0xFF; + arr[L++] = tmp >> 8 & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; + arr[L++] = tmp >> 8 & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr; +} + +function tripletToBase64(num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; +} + +function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; + output.push(tripletToBase64(tmp)); + } + + return output.join(''); +} + +function fromByteArray(uint8) { + if (!inited) { + init(); + } + + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + // go through the array every three bytes, we'll deal with trailing stuff later + + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } // pad the end with zeros, but make sure to not forget the extra bytes + + + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[tmp << 4 & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + output += lookup[tmp >> 10]; + output += lookup[tmp >> 4 & 0x3F]; + output += lookup[tmp << 2 & 0x3F]; + output += '='; + } + + parts.push(output); + return parts.join(''); +} + +function read(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +} +function write(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = e << mLen | m; + eLen += mLen; + + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; +var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +/* eslint-disable no-proto */ + +var INSPECT_MAX_BYTES = 50; +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; +function kMaxLength() { + return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff; +} + +function createBuffer(that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length'); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + + that.length = length; + } + + return that; +} +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + +function Buffer(arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length); + } // Common case. + + + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error('If encoding is specified then the first argument must be a string'); + } + + return allocUnsafe(this, arg); + } + + return from(this, arg, encodingOrOffset, length); +} +Buffer.poolSize = 8192; // not used by this implementation +// TODO: Legacy, not needed anymore. Remove in next major version. + +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr; +}; + +function from(that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number'); + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length); + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset); + } + + return fromObject(that, value); +} +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + + +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length); +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + + if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) {// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + // Object.defineProperty(Buffer, Symbol.species, { + // value: null, + // configurable: true + // }) + } +} + +function assertSize(size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number'); + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative'); + } +} + +function alloc(that, size, fill, encoding) { + assertSize(size); + + if (size <= 0) { + return createBuffer(that, size); + } + + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill); + } + + return createBuffer(that, size); +} +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + + +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding); +}; + +function allocUnsafe(that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + + return that; +} +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + + +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size); +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + + +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size); +}; + +function fromString(that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding'); + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that; +} + +function fromArrayLike(that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + + return that; +} + +function fromArrayBuffer(that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds'); + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds'); + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + + return that; +} + +function fromObject(that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that; + } + + obj.copy(that, 0, 0, len); + return that; + } + + if (obj) { + if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0); + } + + return fromArrayLike(that, obj); + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data); + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.'); +} + +function checked(length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes'); + } + + return length | 0; +} + + +Buffer.isBuffer = isBuffer; + +function internalIsBuffer(b) { + return !!(b != null && b._isBuffer); +} + +Buffer.compare = function compare(a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers'); + } + + if (a === b) return 0; + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; +}; + +Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true; + + default: + return false; + } +}; + +Buffer.concat = function concat(list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + + if (list.length === 0) { + return Buffer.alloc(0); + } + + var i; + + if (length === undefined) { + length = 0; + + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + + buf.copy(buffer, pos); + pos += buf.length; + } + + return buffer; +}; + +function byteLength(string, encoding) { + if (internalIsBuffer(string)) { + return string.length; + } + + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength; + } + + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0; // Use a for loop to avoid recursion + + var loweredCase = false; + + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len; + + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length; + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2; + + case 'hex': + return len >>> 1; + + case 'base64': + return base64ToBytes(string).length; + + default: + if (loweredCase) return utf8ToBytes(string).length; // assume utf8 + + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} + +Buffer.byteLength = byteLength; + +function slowToString(encoding, start, end) { + var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + + if (start === undefined || start < 0) { + start = 0; + } // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + + + if (start > this.length) { + return ''; + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return ''; + } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + + + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return ''; + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end); + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end); + + case 'ascii': + return asciiSlice(this, start, end); + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end); + + case 'base64': + return base64Slice(this, start, end); + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end); + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. + + +Buffer.prototype._isBuffer = true; + +function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16() { + var len = this.length; + + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits'); + } + + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + + return this; +}; + +Buffer.prototype.swap32 = function swap32() { + var len = this.length; + + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits'); + } + + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + + return this; +}; + +Buffer.prototype.swap64 = function swap64() { + var len = this.length; + + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits'); + } + + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + + return this; +}; + +Buffer.prototype.toString = function toString() { + var length = this.length | 0; + if (length === 0) return ''; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); +}; + +Buffer.prototype.equals = function equals(b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer'); + if (this === b) return true; + return Buffer.compare(this, b) === 0; +}; + +Buffer.prototype.inspect = function inspect() { + var str = ''; + var max = INSPECT_MAX_BYTES; + + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + + return ''; +}; + +Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer'); + } + + if (start === undefined) { + start = 0; + } + + if (end === undefined) { + end = target ? target.length : 0; + } + + if (thisStart === undefined) { + thisStart = 0; + } + + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index'); + } + + if (thisStart >= thisEnd && start >= end) { + return 0; + } + + if (thisStart >= thisEnd) { + return -1; + } + + if (start >= end) { + return 1; + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) return 0; + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; +}; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf + + +function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1; // Normalize byteOffset + + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + + byteOffset = +byteOffset; // Coerce to Number. + + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1; + } // Normalize byteOffset: negative offsets start from the end of the buffer + + + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + + if (byteOffset >= buffer.length) { + if (dir) return -1;else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0;else return -1; + } // Normalize val + + + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } // Finally, search either indexOf (if dir is true) or lastIndexOf + + + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1; + } + + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + + if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + + throw new TypeError('val must be string, number or Buffer'); +} + +function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + + if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1; + } + + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read$$1(buf, i) { + if (indexSize === 1) { + return buf[i]; + } else { + return buf.readUInt16BE(i * indexSize); + } + } + + var i; + + if (dir) { + var foundIndex = -1; + + for (i = byteOffset; i < arrLength; i++) { + if (read$$1(arr, i) === read$$1(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + + for (i = byteOffset; i >= 0; i--) { + var found = true; + + for (var j = 0; j < valLength; j++) { + if (read$$1(arr, i + j) !== read$$1(val, j)) { + found = false; + break; + } + } + + if (found) return i; + } + } + + return -1; +} + +Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; +}; + +Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); +}; + +function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + + if (!length) { + length = remaining; + } else { + length = Number(length); + + if (length > remaining) { + length = remaining; + } + } // must be an even number of digits + + + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string'); + + if (length > strLen / 2) { + length = strLen / 2; + } + + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i; + buf[offset + i] = parsed; + } + + return i; +} + +function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); +} + +function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); +} + +function latin1Write(buf, string, offset, length) { + return asciiWrite(buf, string, offset, length); +} + +function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); +} + +function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); +} + +Buffer.prototype.write = function write$$1(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } // legacy write(string, encoding, offset, length) - remove in v0.13 + + } else { + throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds'); + } + + if (!encoding) encoding = 'utf8'; + var loweredCase = false; + + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length); + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length); + + case 'ascii': + return asciiWrite(this, string, offset, length); + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length); + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length); + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length); + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON() { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + }; +}; + +function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf); + } else { + return fromByteArray(buf.slice(start, end)); + } +} + +function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + var i = start; + + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + + break; + + case 2: + secondByte = buf[i + 1]; + + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; + + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + + break; + + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; + + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + + break; + + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; + + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res); +} // Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety + + +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } // Decode in chunks to avoid "call stack size exceeded". + + + var res = ''; + var i = 0; + + while (i < len) { + res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); + } + + return res; +} + +function asciiSlice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + + return ret; +} + +function latin1Slice(buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + + return ret; +} + +function hexSlice(buf, start, end) { + var len = buf.length; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + var out = ''; + + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + + return out; +} + +function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + + return res; +} + +Buffer.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + var newBuf; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf; +}; +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + + +function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); +} + +Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val; +}; + +Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val; +}; + +Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); +}; + +Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var val = this[offset]; + var mul = 1; + var i = 0; + + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + mul *= 0x80; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; +}; + +Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + + mul *= 0x80; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + return val; +}; + +Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return this[offset]; + return (0xff - this[offset] + 1) * -1; +}; + +Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | this[offset + 1] << 8; + return val & 0x8000 ? val | 0xFFFF0000 : val; +}; + +Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | this[offset] << 8; + return val & 0x8000 ? val | 0xFFFF0000 : val; +}; + +Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; +}; + +Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; +}; + +Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4); +}; + +Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4); +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8); +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8); +}; + +function checkInt(buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError('Index out of range'); +} + +Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = value / mul & 0xFF; + } + + return offset + byteLength; +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = value / mul & 0xFF; + } + + return offset + byteLength; +}; + +Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = value & 0xff; + return offset + 1; +}; + +function objectWriteUInt16(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + } else { + objectWriteUInt16(this, value, offset, true); + } + + return offset + 2; +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + } else { + objectWriteUInt16(this, value, offset, false); + } + + return offset + 2; +}; + +function objectWriteUInt32(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, true); + } + + return offset + 4; +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, false); + } + + return offset + 4; +}; + +Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + + this[offset + i] = (value / mul >> 0) - sub & 0xFF; + } + + return offset + byteLength; +}; + +Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + + this[offset + i] = (value / mul >> 0) - sub & 0xFF; + } + + return offset + byteLength; +}; + +Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = value & 0xff; + return offset + 1; +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + } else { + objectWriteUInt16(this, value, offset, true); + } + + return offset + 2; +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + } else { + objectWriteUInt16(this, value, offset, false); + } + + return offset + 2; +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + } else { + objectWriteUInt32(this, value, offset, true); + } + + return offset + 4; +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, false); + } + + return offset + 4; +}; + +function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range'); + if (offset < 0) throw new RangeError('Index out of range'); +} + +function writeFloat(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38); + } + + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; +} + +Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); +}; + +function writeDouble(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308); + } + + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); +}; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + + +Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done + + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions + + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds'); + } + + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds'); + if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? + + if (end > this.length) end = this.length; + + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart); + } + + return len; +}; // Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) + + +Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + + if (val.length === 1) { + var code = val.charCodeAt(0); + + if (code < 256) { + val = code; + } + } + + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string'); + } + + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding); + } + } else if (typeof val === 'number') { + val = val & 255; + } // Invalid ranges are not set to a default, so can range check early. + + + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index'); + } + + if (end <= start) { + return this; + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + if (!val) val = 0; + var i; + + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this; +}; // HELPER FUNCTIONS +// ================ + + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean(str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' + + if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + + while (str.length % 4 !== 0) { + str = str + '='; + } + + return str; +} + +function stringtrim(str) { + if (str.trim) return str.trim(); + return str.replace(/^\s+|\s+$/g, ''); +} + +function toHex(n) { + if (n < 16) return '0' + n.toString(16); + return n.toString(16); +} + +function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); // is surrogate component + + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue; + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue; + } // valid lead + + + leadSurrogate = codePoint; + continue; + } // 2 leads in a row + + + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue; + } // valid surrogate pair + + + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; // encode utf8 + + if (codePoint < 0x80) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break; + bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break; + bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break; + bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); + } else { + throw new Error('Invalid code point'); + } + } + + return bytes; +} + +function asciiToBytes(str) { + var byteArray = []; + + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + + return byteArray; +} + +function utf16leToBytes(str, units) { + var c, hi, lo; + var byteArray = []; + + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray; +} + +function base64ToBytes(str) { + return toByteArray(base64clean(str)); +} + +function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + + return i; +} + +function isnan(val) { + return val !== val; // eslint-disable-line no-self-compare +} // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually + + +function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)); +} + +function isFastBuffer(obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj); +} // For Node v0.10 support. Remove this eventually. + + +function isSlowBuffer(obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)); +} + +var fs = ( _shim_fs$1 && _shim_fs ) || _shim_fs$1; + +/** + * @class + */ + + +var LineByLine = +/*#__PURE__*/ +function () { + function LineByLine(file, options) { + _classCallCheck(this, LineByLine); + + options = options || {}; + if (!options.readChunk) options.readChunk = 1024; + + if (!options.newLineCharacter) { + options.newLineCharacter = 0x0a; //linux line ending + } else { + options.newLineCharacter = options.newLineCharacter.charCodeAt(0); + } + + if (typeof file === 'number') { + this.fd = file; + } else { + this.fd = fs.openSync(file, 'r'); + } + + this.options = options; + this.newLineCharacter = options.newLineCharacter; + this.reset(); + } + + _createClass(LineByLine, [{ + key: "_searchInBuffer", + value: function _searchInBuffer(buffer, hexNeedle) { + var found = -1; + + for (var i = 0; i <= buffer.length; i++) { + var b_byte = buffer[i]; + + if (b_byte === hexNeedle) { + found = i; + break; + } + } + + return found; + } + }, { + key: "reset", + value: function reset() { + this.eofReached = false; + this.linesCache = []; + this.fdPosition = 0; + } + }, { + key: "close", + value: function close() { + fs.closeSync(this.fd); + this.fd = null; + } + }, { + key: "_extractLines", + value: function _extractLines(buffer) { + var line; + var lines = []; + var bufferPosition = 0; + var lastNewLineBufferPosition = 0; + + while (true) { + var bufferPositionValue = buffer[bufferPosition++]; + + if (bufferPositionValue === this.newLineCharacter) { + line = buffer.slice(lastNewLineBufferPosition, bufferPosition); + lines.push(line); + lastNewLineBufferPosition = bufferPosition; + } else if (!bufferPositionValue) { + break; + } + } + + var leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition); + + if (leftovers.length) { + lines.push(leftovers); + } + + return lines; + } + }, { + key: "_readChunk", + value: function _readChunk(lineLeftovers) { + var totalBytesRead = 0; + var bytesRead; + var buffers = []; + + do { + var readBuffer = new Buffer(this.options.readChunk); + bytesRead = fs.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition); + totalBytesRead = totalBytesRead + bytesRead; + this.fdPosition = this.fdPosition + bytesRead; + buffers.push(readBuffer); + } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1); + + var bufferData = Buffer.concat(buffers); + + if (bytesRead < this.options.readChunk) { + this.eofReached = true; + bufferData = bufferData.slice(0, totalBytesRead); + } + + if (totalBytesRead) { + this.linesCache = this._extractLines(bufferData); + + if (lineLeftovers) { + this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]); + } + } + + return totalBytesRead; + } + }, { + key: "next", + value: function next() { + if (!this.fd) return false; + var line = false; + + if (this.eofReached && this.linesCache.length === 0) { + return line; + } + + var bytesRead; + + if (!this.linesCache.length) { + bytesRead = this._readChunk(); + } + + if (this.linesCache.length) { + line = this.linesCache.shift(); + var lastLineCharacter = line[line.length - 1]; + + if (lastLineCharacter !== 0x0a) { + bytesRead = this._readChunk(line); + + if (bytesRead) { + line = this.linesCache.shift(); + } + } + } + + if (this.eofReached && this.linesCache.length === 0) { + this.close(); + } + + if (line && line[line.length - 1] === this.newLineCharacter) { + line = line.slice(0, line.length - 1); + } + + return line; + } + }]); + + return LineByLine; +}(); + +var readlines = LineByLine; + +var ConfigError = +/*#__PURE__*/ +function (_Error) { + _inherits(ConfigError, _Error); + + function ConfigError() { + _classCallCheck(this, ConfigError); + + return _possibleConstructorReturn(this, _getPrototypeOf(ConfigError).apply(this, arguments)); + } + + return ConfigError; +}(_wrapNativeSuper(Error)); + +var DebugError = +/*#__PURE__*/ +function (_Error2) { + _inherits(DebugError, _Error2); + + function DebugError() { + _classCallCheck(this, DebugError); + + return _possibleConstructorReturn(this, _getPrototypeOf(DebugError).apply(this, arguments)); + } + + return DebugError; +}(_wrapNativeSuper(Error)); + +var UndefinedParserError$1 = +/*#__PURE__*/ +function (_Error3) { + _inherits(UndefinedParserError, _Error3); + + function UndefinedParserError() { + _classCallCheck(this, UndefinedParserError); + + return _possibleConstructorReturn(this, _getPrototypeOf(UndefinedParserError).apply(this, arguments)); + } + + return UndefinedParserError; +}(_wrapNativeSuper(Error)); + +var errors = { + ConfigError: ConfigError, + DebugError: DebugError, + UndefinedParserError: UndefinedParserError$1 +}; + +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} + +function defaultClearTimeout() { + throw new Error('clearTimeout has not been defined'); +} + +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; + +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} + +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } // if setTimeout wasn't available but was latter defined + + + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } +} + +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } // if clearTimeout wasn't available but was latter defined + + + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } +} + +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + + draining = false; + + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + + while (len) { + currentQueue = queue; + queue = []; + + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + + queueIndex = -1; + len = queue.length; + } + + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +function nextTick(fun) { + var args = new Array(arguments.length - 1); + + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + + queue.push(new Item(fun, args)); + + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} // v8 likes predictible objects + +function Item(fun, array) { + this.fun = fun; + this.array = array; +} + +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; + +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version$2 = ''; // empty string to avoid regexp issues + +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; +function binding(name) { + throw new Error('process.binding is not supported'); +} +function cwd() { + return '/'; +} +function chdir(dir) { + throw new Error('process.chdir is not supported'); +} + +function umask() { + return 0; +} // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + +var performance = global$1.performance || {}; + +var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { + return new Date().getTime(); +}; // generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime + + +function hrtime(previousTimestamp) { + var clocktime = performanceNow.call(performance) * 1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor(clocktime % 1 * 1e9); + + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + + if (nanoseconds < 0) { + seconds--; + nanoseconds += 1e9; + } + } + + return [seconds, nanoseconds]; +} +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version$2, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var semver = createCommonjsModule(function (module, exports) { + exports = module.exports = SemVer; // The debug function is excluded entirely from the minified version. + + /* nomin */ + + var debug; + /* nomin */ + + if (_typeof(process) === 'object' && + /* nomin */ + process.env && + /* nomin */ + process.env.NODE_DEBUG && + /* nomin */ + /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ + debug = function debug() { + /* nomin */ + var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ + + args.unshift('SEMVER'); + /* nomin */ + + console.log.apply(console, args); + /* nomin */ + }; + /* nomin */ + else + /* nomin */ + debug = function debug() {}; // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + + exports.SEMVER_SPEC_VERSION = '2.0.0'; + var MAX_LENGTH = 256; + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // The actual regexps go on exports.re + + var re = exports.re = []; + var src = exports.src = []; + var R = 0; // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + var NUMERICIDENTIFIER = R++; + src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; + var NUMERICIDENTIFIERLOOSE = R++; + src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + var NONNUMERICIDENTIFIER = R++; + src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version + // Three dot-separated numeric identifiers. + + var MAINVERSION = R++; + src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')'; + var MAINVERSIONLOOSE = R++; + src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + var PRERELEASEIDENTIFIER = R++; + src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')'; + var PRERELEASEIDENTIFIERLOOSE = R++; + src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + var PRERELEASE = R++; + src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + var PRERELEASELOOSE = R++; + src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + var BUILDIDENTIFIER = R++; + src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + var BUILD = R++; + src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + var FULL = R++; + var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?'; + src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + + var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?'; + var LOOSE = R++; + src[LOOSE] = '^' + LOOSEPLAIN + '$'; + var GTLT = R++; + src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + + var XRANGEIDENTIFIERLOOSE = R++; + src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; + var XRANGEIDENTIFIER = R++; + src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + var XRANGEPLAIN = R++; + src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?'; + var XRANGEPLAINLOOSE = R++; + src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?'; + var XRANGE = R++; + src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; + var XRANGELOOSE = R++; + src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Tilde ranges. + // Meaning is "reasonably at or greater than" + + var LONETILDE = R++; + src[LONETILDE] = '(?:~>?)'; + var TILDETRIM = R++; + src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; + re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); + var tildeTrimReplace = '$1~'; + var TILDE = R++; + src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; + var TILDELOOSE = R++; + src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges. + // Meaning is "at least and backwards compatible with" + + var LONECARET = R++; + src[LONECARET] = '(?:\\^)'; + var CARETTRIM = R++; + src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; + re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); + var caretTrimReplace = '$1^'; + var CARET = R++; + src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; + var CARETLOOSE = R++; + src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version" + + var COMPARATORLOOSE = R++; + src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; + var COMPARATOR = R++; + src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + + var COMPARATORTRIM = R++; + src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag + + re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); + var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + + var HYPHENRANGE = R++; + src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$'; + var HYPHENRANGELOOSE = R++; + src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all. + + var STAR = R++; + src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects. + // All are flag-free, unless they were created above with a flag. + + for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) re[i] = new RegExp(src[i]); + } + + exports.parse = parse; + + function parse(version, loose) { + if (version instanceof SemVer) return version; + if (typeof version !== 'string') return null; + if (version.length > MAX_LENGTH) return null; + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) return null; + + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } + } + + exports.valid = valid; + + function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; + } + + exports.clean = clean; + + function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; + } + + exports.SemVer = SemVer; + + function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) return version;else version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters'); + if (!(this instanceof SemVer)) return new SemVer(version, loose); + debug('SemVer', version, loose); + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + if (!m) throw new TypeError('Invalid Version: ' + version); + this.raw = version; // these are actually numbers + + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) throw new TypeError('Invalid major version'); + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) throw new TypeError('Invalid minor version'); + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) throw new TypeError('Invalid patch version'); // numberify any prerelease numeric ids + + if (!m[4]) this.prerelease = [];else this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) return num; + } + + return id; + }); + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) this.version += '-' + this.prerelease.join('.'); + return this.version; + }; + + SemVer.prototype.toString = function () { + return this.version; + }; + + SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.loose, other); + if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); + return this.compareMain(other) || this.comparePre(other); + }; + + SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); + return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); + }; + + SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); // NOT having a prerelease is > having one + + if (this.prerelease.length && !other.prerelease.length) return -1;else if (!this.prerelease.length && other.prerelease.length) return 1;else if (!this.prerelease.length && !other.prerelease.length) return 0; + var i = 0; + + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) return 0;else if (b === undefined) return 1;else if (a === undefined) return -1;else if (a === b) continue;else return compareIdentifiers(a, b); + } while (++i); + }; // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + + + SemVer.prototype.inc = function (release$$1, identifier) { + switch (release$$1) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + + case 'prerelease': + if (this.prerelease.length === 0) this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) this.minor++; + this.patch = 0; + this.prerelease = []; + break; + + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + + case 'pre': + if (this.prerelease.length === 0) this.prerelease = [0];else { + var i = this.prerelease.length; + + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) this.prerelease = [identifier, 0]; + } else this.prerelease = [identifier, 0]; + } + + break; + + default: + throw new Error('invalid increment argument: ' + release$$1); + } + + this.format(); + this.raw = this.version; + return this; + }; + + exports.inc = inc; + + function inc(version, release$$1, loose, identifier) { + if (typeof loose === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release$$1, identifier).version; + } catch (er) { + return null; + } + } + + exports.diff = diff; + + function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre' + key; + } + } + } + + return 'prerelease'; + } + + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } + } + + exports.compareIdentifiers = compareIdentifiers; + var numeric = /^[0-9]+$/; + + function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : a > b ? 1 : 0; + } + + exports.rcompareIdentifiers = rcompareIdentifiers; + + function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); + } + + exports.major = major; + + function major(a, loose) { + return new SemVer(a, loose).major; + } + + exports.minor = minor; + + function minor(a, loose) { + return new SemVer(a, loose).minor; + } + + exports.patch = patch; + + function patch(a, loose) { + return new SemVer(a, loose).patch; + } + + exports.compare = compare; + + function compare(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); + } + + exports.compareLoose = compareLoose; + + function compareLoose(a, b) { + return compare(a, b, true); + } + + exports.rcompare = rcompare; + + function rcompare(a, b, loose) { + return compare(b, a, loose); + } + + exports.sort = sort; + + function sort(list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose); + }); + } + + exports.rsort = rsort; + + function rsort(list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose); + }); + } + + exports.gt = gt; + + function gt(a, b, loose) { + return compare(a, b, loose) > 0; + } + + exports.lt = lt; + + function lt(a, b, loose) { + return compare(a, b, loose) < 0; + } + + exports.eq = eq; + + function eq(a, b, loose) { + return compare(a, b, loose) === 0; + } + + exports.neq = neq; + + function neq(a, b, loose) { + return compare(a, b, loose) !== 0; + } + + exports.gte = gte; + + function gte(a, b, loose) { + return compare(a, b, loose) >= 0; + } + + exports.lte = lte; + + function lte(a, b, loose) { + return compare(a, b, loose) <= 0; + } + + exports.cmp = cmp; + + function cmp(a, op, b, loose) { + var ret; + + switch (op) { + case '===': + if (_typeof(a) === 'object') a = a.version; + if (_typeof(b) === 'object') b = b.version; + ret = a === b; + break; + + case '!==': + if (_typeof(a) === 'object') a = a.version; + if (_typeof(b) === 'object') b = b.version; + ret = a !== b; + break; + + case '': + case '=': + case '==': + ret = eq(a, b, loose); + break; + + case '!=': + ret = neq(a, b, loose); + break; + + case '>': + ret = gt(a, b, loose); + break; + + case '>=': + ret = gte(a, b, loose); + break; + + case '<': + ret = lt(a, b, loose); + break; + + case '<=': + ret = lte(a, b, loose); + break; + + default: + throw new TypeError('Invalid operator: ' + op); + } + + return ret; + } + + exports.Comparator = Comparator; + + function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) return comp;else comp = comp.value; + } + + if (!(this instanceof Comparator)) return new Comparator(comp, loose); + debug('comparator', comp, loose); + this.loose = loose; + this.parse(comp); + if (this.semver === ANY) this.value = '';else this.value = this.operator + this.semver.version; + debug('comp', this); + } + + var ANY = {}; + + Comparator.prototype.parse = function (comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + if (!m) throw new TypeError('Invalid comparator: ' + comp); + this.operator = m[1]; + if (this.operator === '=') this.operator = ''; // if it literally is just '>' or '' then allow anything. + + if (!m[2]) this.semver = ANY;else this.semver = new SemVer(m[2], this.loose); + }; + + Comparator.prototype.toString = function () { + return this.value; + }; + + Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.loose); + if (this.semver === ANY) return true; + if (typeof version === 'string') version = new SemVer(version, this.loose); + return cmp(version, this.operator, this.semver, this.loose); + }; + + Comparator.prototype.intersects = function (comp, loose) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required'); + } + + var rangeTmp; + + if (this.operator === '') { + rangeTmp = new Range(comp.value, loose); + return satisfies(this.value, rangeTmp, loose); + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, loose); + return satisfies(comp.semver, rangeTmp, loose); + } + + var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>'); + var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<'); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); + var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, loose) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<'); + var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, loose) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>'); + return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; + }; + + exports.Range = Range; + + function Range(range, loose) { + if (range instanceof Range) { + if (range.loose === loose) { + return range; + } else { + return new Range(range.raw, loose); + } + } + + if (range instanceof Comparator) { + return new Range(range.value, loose); + } + + if (!(this instanceof Range)) return new Range(range, loose); + this.loose = loose; // First, split based on boolean or || + + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()); + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); + } + + Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; + }; + + Range.prototype.toString = function () { + return this.range; + }; + + Range.prototype.parseRange = function (range) { + var loose = this.loose; + range = range.trim(); + debug('range', range, loose); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3` + + range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3` + + range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces + + range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe); + }); + } + + set = set.map(function (comp) { + return new Comparator(comp, loose); + }); + return set; + }; + + Range.prototype.intersects = function (range, loose) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required'); + } + + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, loose); + }); + }); + }); + }); + }; // Mostly just for testing and legacy API reasons + + + exports.toComparators = toComparators; + + function toComparators(range, loose) { + return new Range(range, loose).set.map(function (comp) { + return comp.map(function (c) { + return c.value; + }).join(' ').trim().split(' '); + }); + } // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + + + function parseComparator(comp, loose) { + debug('comp', comp); + comp = replaceCarets(comp, loose); + debug('caret', comp); + comp = replaceTildes(comp, loose); + debug('tildes', comp); + comp = replaceXRanges(comp, loose); + debug('xrange', comp); + comp = replaceStars(comp, loose); + debug('stars', comp); + return comp; + } + + function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; + } // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 + + + function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, loose); + }).join(' '); + } + + function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0'; + } else // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; + debug('tilde return', ret); + return ret; + }); + } // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 + // ^1.2.3 --> >=1.2.3 <2.0.0 + // ^1.2.0 --> >=1.2.0 <2.0.0 + + + function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, loose); + }).join(' '); + } + + function replaceCaret(comp, loose) { + debug('caret', comp, loose); + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) { + if (M === '0') ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') pr = '-' + pr; + + if (M === '0') { + if (m === '0') ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0'; + } else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + + if (M === '0') { + if (m === '0') ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; + } else ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0'; + } + debug('caret return', ret); + return ret; + }); + } + + function replaceXRanges(comp, loose) { + debug('replaceXRanges', comp, loose); + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, loose); + }).join(' '); + } + + function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + if (gtlt === '=' && anyX) gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) m = 0; + if (xp) p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) M = +M + 1;else m = +m + 1; + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + return ret; + }); + } // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + + + function replaceStars(comp, loose) { + debug('replaceStars', comp, loose); // Looseness is ignored here. star is always as loose as it gets! + + return comp.trim().replace(re[STAR], ''); + } // This function is passed to string.replace(re[HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0 + + + function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { + if (isX(fM)) from = '';else if (isX(fm)) from = '>=' + fM + '.0.0';else if (isX(fp)) from = '>=' + fM + '.' + fm + '.0';else from = '>=' + from; + if (isX(tM)) to = '';else if (isX(tm)) to = '<' + (+tM + 1) + '.0.0';else if (isX(tp)) to = '<' + tM + '.' + (+tm + 1) + '.0';else if (tpr) to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;else to = '<=' + to; + return (from + ' ' + to).trim(); + } // if ANY of the sets match ALL of its comparators, then pass + + + Range.prototype.test = function (version) { + if (!version) return false; + if (typeof version === 'string') version = new SemVer(version, this.loose); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) return true; + } + + return false; + }; + + function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) return false; + } + + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) return true; + } + } // Version has a -pre, but it's not one of the ones we like. + + + return false; + } + + return true; + } + + exports.satisfies = satisfies; + + function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + + return range.test(version); + } + + exports.maxSatisfying = maxSatisfying; + + function maxSatisfying(versions$$1, range, loose) { + var max = null; + var maxSV = null; + + try { + var rangeObj = new Range(range, loose); + } catch (er) { + return null; + } + + versions$$1.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, loose) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer(max, loose); + } + } + }); + return max; + } + + exports.minSatisfying = minSatisfying; + + function minSatisfying(versions$$1, range, loose) { + var min = null; + var minSV = null; + + try { + var rangeObj = new Range(range, loose); + } catch (er) { + return null; + } + + versions$$1.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, loose) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer(min, loose); + } + } + }); + return min; + } + + exports.validRange = validRange; + + function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } + } // Determine if version is less than all the versions possible in the range + + + exports.ltr = ltr; + + function ltr(version, range, loose) { + return outside(version, range, '<', loose); + } // Determine if version is greater than all the versions possible in the range. + + + exports.gtr = gtr; + + function gtr(version, range, loose) { + return outside(version, range, '>', loose); + } + + exports.outside = outside; + + function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); + var gtfn, ltefn, ltfn, comp, ecomp; + + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } // If it satisifes the range it is not outside + + + if (satisfies(version, range, loose)) { + return false; + } // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + var high = null; + var low = null; + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0'); + } + + high = high || comparator; + low = low || comparator; + + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); // If the edge version comparator has a operator then our version + // isn't outside it + + if (high.operator === comp || high.operator === ecomp) { + return false; + } // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + + + if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + + return true; + } + + exports.prerelease = prerelease; + + function prerelease(version, loose) { + var parsed = parse(version, loose); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; + } + + exports.intersects = intersects; + + function intersects(r1, r2, loose) { + r1 = new Range(r1, loose); + r2 = new Range(r2, loose); + return r1.intersects(r2); + } +}); + +var arrayify = function arrayify(object, keyName) { + return Object.keys(object).reduce(function (array, key) { + return array.concat(Object.assign(_defineProperty({}, keyName, key), object[key])); + }, []); +}; + +var dedent_1 = createCommonjsModule(function (module) { + "use strict"; + + function dedent(strings) { + var raw = void 0; + + if (typeof strings === "string") { + // dedent can be used as a plain function + raw = [strings]; + } else { + raw = strings.raw; + } // first, perform interpolation + + + var result = ""; + + for (var i = 0; i < raw.length; i++) { + result += raw[i]. // join lines when there is a suppressed newline + replace(/\\\n[ \t]*/g, ""). // handle escaped backticks + replace(/\\`/g, "`"); + + if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) { + result += arguments.length <= i + 1 ? undefined : arguments[i + 1]; + } + } // now strip indentation + + + var lines = result.split("\n"); + var mindent = null; + lines.forEach(function (l) { + var m = l.match(/^(\s+)\S+/); + + if (m) { + var indent = m[1].length; + + if (!mindent) { + // this is the first indented line + mindent = indent; + } else { + mindent = Math.min(mindent, indent); + } + } + }); + + if (mindent !== null) { + result = lines.map(function (l) { + return l[0] === " " ? l.slice(mindent) : l; + }).join("\n"); + } // dedent eats leading and trailing whitespace too + + + result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too + + return result.replace(/\\n/g, "\n"); + } + + { + module.exports = dedent; + } +}); + +function _templateObject6() { + var data = _taggedTemplateLiteral(["\n Require either '@prettier' or '@format' to be present in the file's first docblock comment\n in order for it to be formatted.\n "]); + + _templateObject6 = function _templateObject6() { + return data; + }; + + return data; +} + +function _templateObject5() { + var data = _taggedTemplateLiteral(["\n Format code starting at a given character offset.\n The range will extend backwards to the start of the first line containing the selected statement.\n This option cannot be used with --cursor-offset.\n "]); + + _templateObject5 = function _templateObject5() { + return data; + }; + + return data; +} + +function _templateObject4() { + var data = _taggedTemplateLiteral(["\n Format code ending at a given character offset (exclusive).\n The range will extend forwards to the end of the selected statement.\n This option cannot be used with --cursor-offset.\n "]); + + _templateObject4 = function _templateObject4() { + return data; + }; + + return data; +} + +function _templateObject3() { + var data = _taggedTemplateLiteral(["\n Custom directory that contains prettier plugins in node_modules subdirectory.\n Overrides default behavior when plugins are searched relatively to the location of Prettier.\n Multiple values are accepted.\n "]); + + _templateObject3 = function _templateObject3() { + return data; + }; + + return data; +} + +function _templateObject2() { + var data = _taggedTemplateLiteral(["\n Maintain existing\n (mixed values within one file are normalised by looking at what's used after the first line)\n "]); + + _templateObject2 = function _templateObject2() { + return data; + }; + + return data; +} + +function _templateObject() { + var data = _taggedTemplateLiteral(["\n Print (to stderr) where a cursor at the given position would move to after formatting.\n This option cannot be used with --range-start and --range-end.\n "]); + + _templateObject = function _templateObject() { + return data; + }; + + return data; +} + +var CATEGORY_CONFIG = "Config"; +var CATEGORY_EDITOR = "Editor"; +var CATEGORY_FORMAT = "Format"; +var CATEGORY_OTHER = "Other"; +var CATEGORY_OUTPUT = "Output"; +var CATEGORY_GLOBAL = "Global"; +var CATEGORY_SPECIAL = "Special"; +/** + * @typedef {Object} OptionInfo + * @property {string} since - available since version + * @property {string} category + * @property {'int' | 'boolean' | 'choice' | 'path'} type + * @property {boolean} array - indicate it's an array of the specified type + * @property {boolean?} deprecated - deprecated since version + * @property {OptionRedirectInfo?} redirect - redirect deprecated option + * @property {string} description + * @property {string?} oppositeDescription - for `false` option + * @property {OptionValueInfo} default + * @property {OptionRangeInfo?} range - for type int + * @property {OptionChoiceInfo?} choices - for type choice + * @property {(value: any) => boolean} exception + * + * @typedef {number | boolean | string} OptionValue + * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo + * + * @typedef {Object} OptionRedirectInfo + * @property {string} option + * @property {OptionValue} value + * + * @typedef {Object} OptionRangeInfo + * @property {number} start - recommended range start + * @property {number} end - recommended range end + * @property {number} step - recommended range step + * + * @typedef {Object} OptionChoiceInfo + * @property {boolean | string} value - boolean for the option that is originally boolean type + * @property {string?} description - undefined if redirect + * @property {string?} since - undefined if available since the first version of the option + * @property {string?} deprecated - deprecated since version + * @property {OptionValueInfo?} redirect - redirect deprecated value + * + * @property {string?} cliName + * @property {string?} cliCategory + * @property {string?} cliDescription + */ + +/** @type {{ [name: string]: OptionInfo } */ + +var options$2 = { + cursorOffset: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: -1, + range: { + start: -1, + end: Infinity, + step: 1 + }, + description: dedent_1(_templateObject()), + cliCategory: CATEGORY_EDITOR + }, + endOfLine: { + since: "1.15.0", + category: CATEGORY_GLOBAL, + type: "choice", + default: "auto", + description: "Which end of line characters to apply.", + choices: [{ + value: "auto", + description: dedent_1(_templateObject2()) + }, { + value: "lf", + description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos" + }, { + value: "crlf", + description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows" + }, { + value: "cr", + description: "Carriage Return character only (\\r), used very rarely" + }] + }, + filepath: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "path", + description: "Specify the input filepath. This will be used to do parser inference.", + cliName: "stdin-filepath", + cliCategory: CATEGORY_OTHER, + cliDescription: "Path to the file to pretend that stdin comes from." + }, + insertPragma: { + since: "1.8.0", + category: CATEGORY_SPECIAL, + type: "boolean", + default: false, + description: "Insert @format pragma into file's first docblock comment.", + cliCategory: CATEGORY_OTHER + }, + parser: { + since: "0.0.10", + category: CATEGORY_GLOBAL, + type: "choice", + default: [{ + since: "0.0.10", + value: "babylon" + }, { + since: "1.13.0", + value: undefined + }], + description: "Which parser to use.", + exception: function exception(value) { + return typeof value === "string" || typeof value === "function"; + }, + choices: [{ + value: "flow", + description: "Flow" + }, { + value: "babylon", + description: "JavaScript", + deprecated: "1.16.0", + redirect: "babel" + }, { + value: "babel", + since: "1.16.0", + description: "JavaScript" + }, { + value: "babel-flow", + since: "1.16.0", + description: "Flow" + }, { + value: "typescript", + since: "1.4.0", + description: "TypeScript" + }, { + value: "css", + since: "1.7.1", + description: "CSS" + }, { + value: "postcss", + since: "1.4.0", + description: "CSS/Less/SCSS", + deprecated: "1.7.1", + redirect: "css" + }, { + value: "less", + since: "1.7.1", + description: "Less" + }, { + value: "scss", + since: "1.7.1", + description: "SCSS" + }, { + value: "json", + since: "1.5.0", + description: "JSON" + }, { + value: "json5", + since: "1.13.0", + description: "JSON5" + }, { + value: "json-stringify", + since: "1.13.0", + description: "JSON.stringify" + }, { + value: "graphql", + since: "1.5.0", + description: "GraphQL" + }, { + value: "markdown", + since: "1.8.0", + description: "Markdown" + }, { + value: "mdx", + since: "1.15.0", + description: "MDX" + }, { + value: "vue", + since: "1.10.0", + description: "Vue" + }, { + value: "yaml", + since: "1.14.0", + description: "YAML" + }, { + value: "glimmer", + since: null, + description: "Handlebars" + }, { + value: "html", + since: "1.15.0", + description: "HTML" + }, { + value: "angular", + since: "1.15.0", + description: "Angular" + }] + }, + plugins: { + since: "1.10.0", + type: "path", + array: true, + default: [{ + value: [] + }], + category: CATEGORY_GLOBAL, + description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.", + exception: function exception(value) { + return typeof value === "string" || _typeof(value) === "object"; + }, + cliName: "plugin", + cliCategory: CATEGORY_CONFIG + }, + pluginSearchDirs: { + since: "1.13.0", + type: "path", + array: true, + default: [{ + value: [] + }], + category: CATEGORY_GLOBAL, + description: dedent_1(_templateObject3()), + exception: function exception(value) { + return typeof value === "string" || _typeof(value) === "object"; + }, + cliName: "plugin-search-dir", + cliCategory: CATEGORY_CONFIG + }, + printWidth: { + since: "0.0.0", + category: CATEGORY_GLOBAL, + type: "int", + default: 80, + description: "The line length where Prettier will try wrap.", + range: { + start: 0, + end: Infinity, + step: 1 + } + }, + rangeEnd: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: Infinity, + range: { + start: 0, + end: Infinity, + step: 1 + }, + description: dedent_1(_templateObject4()), + cliCategory: CATEGORY_EDITOR + }, + rangeStart: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: 0, + range: { + start: 0, + end: Infinity, + step: 1 + }, + description: dedent_1(_templateObject5()), + cliCategory: CATEGORY_EDITOR + }, + requirePragma: { + since: "1.7.0", + category: CATEGORY_SPECIAL, + type: "boolean", + default: false, + description: dedent_1(_templateObject6()), + cliCategory: CATEGORY_OTHER + }, + tabWidth: { + type: "int", + category: CATEGORY_GLOBAL, + default: 2, + description: "Number of spaces per indentation level.", + range: { + start: 0, + end: Infinity, + step: 1 + } + }, + useFlowParser: { + since: "0.0.0", + category: CATEGORY_GLOBAL, + type: "boolean", + default: [{ + since: "0.0.0", + value: false + }, { + since: "1.15.0", + value: undefined + }], + deprecated: "0.0.10", + description: "Use flow parser.", + redirect: { + option: "parser", + value: "flow" + }, + cliName: "flow-parser" + }, + useTabs: { + since: "1.0.0", + category: CATEGORY_GLOBAL, + type: "boolean", + default: false, + description: "Indent with tabs instead of spaces." + } +}; +var coreOptions$1 = { + CATEGORY_CONFIG: CATEGORY_CONFIG, + CATEGORY_EDITOR: CATEGORY_EDITOR, + CATEGORY_FORMAT: CATEGORY_FORMAT, + CATEGORY_OTHER: CATEGORY_OTHER, + CATEGORY_OUTPUT: CATEGORY_OUTPUT, + CATEGORY_GLOBAL: CATEGORY_GLOBAL, + CATEGORY_SPECIAL: CATEGORY_SPECIAL, + options: options$2 +}; + +var require$$0 = ( _package$1 && _package ) || _package$1; + +var currentVersion = require$$0.version; +var coreOptions = coreOptions$1.options; + +function getSupportInfo$2(version, opts) { + opts = Object.assign({ + plugins: [], + showUnreleased: false, + showDeprecated: false, + showInternal: false + }, opts); + + if (!version) { + // pre-release version is smaller than the normal version in semver, + // we need to treat it as the normal one so as to test new features. + version = currentVersion.split("-", 1)[0]; + } + + var plugins = opts.plugins; + var options = arrayify(Object.assign(plugins.reduce(function (currentOptions, plugin) { + return Object.assign(currentOptions, plugin.options); + }, {}), coreOptions), "name").sort(function (a, b) { + return a.name === b.name ? 0 : a.name < b.name ? -1 : 1; + }).filter(filterSince).filter(filterDeprecated).map(mapDeprecated).map(mapInternal).map(function (option) { + var newOption = Object.assign({}, option); + + if (Array.isArray(newOption.default)) { + newOption.default = newOption.default.length === 1 ? newOption.default[0].value : newOption.default.filter(filterSince).sort(function (info1, info2) { + return semver.compare(info2.since, info1.since); + })[0].value; + } + + if (Array.isArray(newOption.choices)) { + newOption.choices = newOption.choices.filter(filterSince).filter(filterDeprecated).map(mapDeprecated); + } + + return newOption; + }).map(function (option) { + var filteredPlugins = plugins.filter(function (plugin) { + return plugin.defaultOptions && plugin.defaultOptions[option.name]; + }); + var pluginDefaults = filteredPlugins.reduce(function (reduced, plugin) { + reduced[plugin.name] = plugin.defaultOptions[option.name]; + return reduced; + }, {}); + return Object.assign(option, { + pluginDefaults: pluginDefaults + }); + }); + var usePostCssParser = semver.lt(version, "1.7.1"); + var languages = plugins.reduce(function (all, plugin) { + return all.concat(plugin.languages || []); + }, []).filter(filterSince).map(function (language) { + // Prevent breaking changes + if (language.name === "Markdown") { + return Object.assign({}, language, { + parsers: ["markdown"] + }); + } + + if (language.name === "TypeScript") { + return Object.assign({}, language, { + parsers: ["typescript"] + }); + } + + if (usePostCssParser && (language.name === "CSS" || language.group === "CSS")) { + return Object.assign({}, language, { + parsers: ["postcss"] + }); + } + + return language; + }); + return { + languages: languages, + options: options + }; + + function filterSince(object) { + return opts.showUnreleased || !("since" in object) || object.since && semver.gte(version, object.since); + } + + function filterDeprecated(object) { + return opts.showDeprecated || !("deprecated" in object) || object.deprecated && semver.lt(version, object.deprecated); + } + + function mapDeprecated(object) { + if (!object.deprecated || opts.showDeprecated) { + return object; + } + + var newObject = Object.assign({}, object); + delete newObject.deprecated; + delete newObject.redirect; + return newObject; + } + + function mapInternal(object) { + if (opts.showInternal) { + return object; + } + + var newObject = Object.assign({}, object); + delete newObject.cliName; + delete newObject.cliCategory; + delete newObject.cliDescription; + return newObject; + } +} + +var support = { + getSupportInfo: getSupportInfo$2 +}; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +/* global Reflect, Promise */ +var _extendStatics = function extendStatics(d, b) { + _extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) { + if (b.hasOwnProperty(p)) d[p] = b[p]; + } + }; + + return _extendStatics(d, b); +}; + +function __extends(d, b) { + _extendStatics(d, b); + + function __() { + this.constructor = d; + } + + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var _assign = function __assign() { + _assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + + for (var p in s) { + if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + } + + return t; + }; + + return _assign.apply(this, arguments); +}; + +function __rest(s, e) { + var t = {}; + + for (var p in s) { + if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + } + + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; + } + return t; +} +function __decorate(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) { + if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + } + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function (target, key) { + decorator(target, key, paramIndex); + }; +} +function __metadata(metadataKey, metadataValue) { + if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + + function step(result) { + result.done ? resolve(result.value) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _ = { + label: 0, + sent: function sent() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [] + }, + f, + y, + t, + g; + return g = { + next: verb(0), + "throw": verb(1), + "return": verb(2) + }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + + while (_) { + try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + + switch (op[0]) { + case 0: + case 1: + t = op; + break; + + case 4: + _.label++; + return { + value: op[1], + done: false + }; + + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + + case 7: + op = _.ops.pop(); + + _.trys.pop(); + + continue; + + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + + if (t && _.label < t[2]) { + _.label = t[2]; + + _.ops.push(op); + + break; + } + + if (t[2]) _.ops.pop(); + + _.trys.pop(); + + continue; + } + + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + } + + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; + } +} +function __exportStar(m, exports) { + for (var p in m) { + if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } +} +function __values(o) { + var m = typeof Symbol === "function" && o[Symbol.iterator], + i = 0; + if (m) return m.call(o); + return { + next: function next() { + if (o && i >= o.length) o = void 0; + return { + value: o && o[i++], + done: !o + }; + } + }; +} +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), + r, + ar = [], + e; + + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) { + ar.push(r.value); + } + } catch (error) { + e = { + error: error + }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + + return ar; +} +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) { + ar = ar.concat(__read(arguments[i])); + } + + return ar; +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i; + + function verb(n) { + if (g[n]) i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + + function fulfill(value) { + resume("next", value); + } + + function reject(value) { + resume("throw", value); + } + + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function () { + return this; + }, i; + + function verb(n, f) { + i[n] = o[n] ? function (v) { + return (p = !p) ? { + value: __await(o[n](v)), + done: n === "return" + } : f ? f(v) : v; + } : f; + } +} +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + + function verb(n) { + i[n] = o[n] && function (v) { + return new Promise(function (resolve, reject) { + v = o[n](v), settle(resolve, reject, v.done, v.value); + }); + }; + } + + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { + value: raw + }); + } else { + cooked.raw = raw; + } + + return cooked; +} + +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) { + if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + } + result.default = mod; + return result; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { + default: mod + }; +} + +var tslib_1 = Object.freeze({ + __extends: __extends, + get __assign () { return _assign; }, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __exportStar: __exportStar, + __values: __values, + __read: __read, + __spread: __spread, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault +}); + +var api = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.apiDescriptor = { + key: function key(_key) { + return /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(_key) ? _key : JSON.stringify(_key); + }, + value: function value(_value) { + if (_value === null || _typeof(_value) !== 'object') { + return JSON.stringify(_value); + } + + if (Array.isArray(_value)) { + return "[".concat(_value.map(function (subValue) { + return exports.apiDescriptor.value(subValue); + }).join(', '), "]"); + } + + var keys = Object.keys(_value); + return keys.length === 0 ? '{}' : "{ ".concat(keys.map(function (key) { + return "".concat(exports.apiDescriptor.key(key), ": ").concat(exports.apiDescriptor.value(_value[key])); + }).join(', '), " }"); + }, + pair: function pair(_ref) { + var key = _ref.key, + value = _ref.value; + return exports.apiDescriptor.value(_defineProperty({}, key, value)); + } + }; +}); +unwrapExports(api); + +var descriptors = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(api, exports); +}); +unwrapExports(descriptors); + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +var escapeStringRegexp = function escapeStringRegexp(str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + +var colorName = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; + +var conversions = createCommonjsModule(function (module) { + /* MIT license */ + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) + var reverseKeywords = {}; + + for (var key in colorName) { + if (colorName.hasOwnProperty(key)) { + reverseKeywords[colorName[key]] = key; + } + } + + var convert = module.exports = { + rgb: { + channels: 3, + labels: 'rgb' + }, + hsl: { + channels: 3, + labels: 'hsl' + }, + hsv: { + channels: 3, + labels: 'hsv' + }, + hwb: { + channels: 3, + labels: 'hwb' + }, + cmyk: { + channels: 4, + labels: 'cmyk' + }, + xyz: { + channels: 3, + labels: 'xyz' + }, + lab: { + channels: 3, + labels: 'lab' + }, + lch: { + channels: 3, + labels: 'lch' + }, + hex: { + channels: 1, + labels: ['hex'] + }, + keyword: { + channels: 1, + labels: ['keyword'] + }, + ansi16: { + channels: 1, + labels: ['ansi16'] + }, + ansi256: { + channels: 1, + labels: ['ansi256'] + }, + hcg: { + channels: 3, + labels: ['h', 'c', 'g'] + }, + apple: { + channels: 3, + labels: ['r16', 'g16', 'b16'] + }, + gray: { + channels: 1, + labels: ['gray'] + } + }; // hide .channels and .labels properties + + for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', { + value: channels + }); + Object.defineProperty(convert[model], 'labels', { + value: labels + }); + } + } + + convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; + }; + + convert.rgb.hsv = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var v; + + if (max === 0) { + s = 0; + } else { + s = delta / max * 1000 / 10; + } + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + v = max / 255 * 1000 / 10; + return [h, s, v]; + }; + + convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + return [h, w * 100, b * 100]; + }; + + convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; + }; + /** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ + + + function comparativeDistance(x, y) { + return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); + } + + convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in colorName) { + if (colorName.hasOwnProperty(keyword)) { + var value = colorName[keyword]; // Compute comparative distance + + var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest + + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; + }; + + convert.keyword.rgb = function (keyword) { + return colorName[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; // assume sRGB + + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; + var x = r * 0.4124 + g * 0.3576 + b * 0.1805; + var y = r * 0.2126 + g * 0.7152 + b * 0.0722; + var z = r * 0.0193 + g * 0.1192 + b * 0.9505; + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + rgb = [0, 0, 0]; + + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; + }; + + convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - s * f); + var t = 255 * v * (1 - s * (1 - f)); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + + case 1: + return [q, v, p]; + + case 2: + return [p, v, t]; + + case 3: + return [p, q, v]; + + case 4: + return [t, p, v]; + + case 5: + return [v, p, q]; + } + }; + + convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; + }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + + + convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; // wh + bl cant be > 1 + + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + + switch (i) { + default: + case 6: + case 0: + r = v; + g = n; + b = wh; + break; + + case 1: + r = n; + g = v; + b = wh; + break; + + case 2: + r = wh; + g = v; + b = n; + break; + + case 3: + r = wh; + g = n; + b = v; + break; + + case 4: + r = n; + g = wh; + b = v; + break; + + case 5: + r = v; + g = wh; + b = n; + break; + } + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + r = x * 3.2406 + y * -1.5372 + z * -0.4986; + g = x * -0.9689 + y * 1.8758 + z * 0.0415; + b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB + + r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; + g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; + b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92; + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + x *= 95.047; + y *= 100; + z *= 108.883; + return [x, y, z]; + }; + + convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; + }; + + convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + + convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round((r - 8) / 247 * 24) + 232; + } + + var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); + return ansi; + }; + + convert.ansi16.rgb = function (args) { + var color = args % 10; // handle greyscale + + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = (color & 1) * mult * 255; + var g = (color >> 1 & 1) * mult * 255; + var b = (color >> 2 & 1) * mult * 255; + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = rem % 6 / 5 * 255; + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = integer >> 16 & 0xFF; + var g = integer >> 8 & 0xFF; + var b = integer & 0xFF; + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = max - min; + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else if (max === r) { + hue = (g - b) / chroma % 6; + } else if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = h % 1 * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; + pure[1] = v; + pure[2] = 0; + break; + + case 1: + pure[0] = w; + pure[1] = 1; + pure[2] = 0; + break; + + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v; + break; + + case 3: + pure[0] = 0; + pure[1] = w; + pure[2] = 1; + break; + + case 4: + pure[0] = v; + pure[1] = 0; + pure[2] = 1; + break; + + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w; + } + + mg = (1.0 - c) * g; + return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; + }; + + convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; + }; + + convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; + }; + + convert.apple.rgb = function (apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; + }; + + convert.rgb.apple = function (rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; + }; + + convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + + convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; + }; + + convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; + }; + + convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; + }; + + convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; + }; + + convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; +}); + +/* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ +// https://jsperf.com/object-keys-vs-for-in-with-closure/3 + +var models$1 = Object.keys(conversions); + +function buildGraph() { + var graph = {}; + + for (var len = models$1.length, i = 0; i < len; i++) { + graph[models$1[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} // https://en.wikipedia.org/wiki/Breadth-first_search + + +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + var cur = graph[toModel].parent; + + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +var route = function route(fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + var models = Object.keys(graph); + + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + +var convert = {}; +var models = Object.keys(conversions); + +function wrapRaw(fn) { + var wrappedFn = function wrappedFn(args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; // preserve .conversion property if there is one + + + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + var wrappedFn = function wrappedFn(args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + + if (_typeof(result) === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; // preserve .conversion property if there is one + + + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(function (fromModel) { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], 'channels', { + value: conversions[fromModel].channels + }); + Object.defineProperty(convert[fromModel], 'labels', { + value: conversions[fromModel].labels + }); + var routes = route(fromModel); + var routeModels = Object.keys(routes); + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); +var colorConvert = convert; + +var ansiStyles = createCommonjsModule(function (module) { + 'use strict'; + + var wrapAnsi16 = function wrapAnsi16(fn, offset) { + return function () { + var code = fn.apply(colorConvert, arguments); + return "\x1B[".concat(code + offset, "m"); + }; + }; + + var wrapAnsi256 = function wrapAnsi256(fn, offset) { + return function () { + var code = fn.apply(colorConvert, arguments); + return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); + }; + }; + + var wrapAnsi16m = function wrapAnsi16m(fn, offset) { + return function () { + var rgb = fn.apply(colorConvert, arguments); + return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m"); + }; + }; + + function assembleStyles() { + var codes = new Map(); + var styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; // Fix humans + + styles.color.grey = styles.color.gray; + + var _arr = Object.keys(styles); + + for (var _i = 0; _i < _arr.length; _i++) { + var groupName = _arr[_i]; + var group = styles[groupName]; + + var _arr3 = Object.keys(group); + + for (var _i3 = 0; _i3 < _arr3.length; _i3++) { + var styleName = _arr3[_i3]; + var style = group[styleName]; + styles[styleName] = { + open: "\x1B[".concat(style[0], "m"), + close: "\x1B[".concat(style[1], "m") + }; + group[styleName] = styles[styleName]; + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } + + var ansi2ansi = function ansi2ansi(n) { + return n; + }; + + var rgb2rgb = function rgb2rgb(r, g, b) { + return [r, g, b]; + }; + + styles.color.close = "\x1B[39m"; + styles.bgColor.close = "\x1B[49m"; + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + var _arr2 = Object.keys(colorConvert); + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var key = _arr2[_i2]; + + if (_typeof(colorConvert[key]) !== 'object') { + continue; + } + + var suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; + } // Make the export immutable + + + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); +}); + +var os = { + EOL: "\n" +}; + +var os$1 = Object.freeze({ + default: os +}); + +var hasFlag = createCommonjsModule(function (module) { + 'use strict'; + + module.exports = function (flag, argv$$1) { + argv$$1 = argv$$1 || process.argv; + var prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; + var pos = argv$$1.indexOf(prefix + flag); + var terminatorPos = argv$$1.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + }; +}); + +var require$$1$1 = ( os$1 && os ) || os$1; + +var env$1 = process.env; +var forceColor; + +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { + forceColor = true; +} + +if ('FORCE_COLOR' in env$1) { + forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + var min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + var osRelease = require$$1$1.release().split('.'); + + if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$1) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) { + return sign in env$1; + }) || env$1.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$1) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$1.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$1) { + var version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$1.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$1.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { + return 1; + } + + if ('COLORTERM' in env$1) { + return 1; + } + + if (env$1.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + var level = supportsColor(stream); + return translateLevel(level); +} + +var supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; + +var templates = createCommonjsModule(function (module) { + 'use strict'; + + var TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + var ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + var ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', "\x1B"], ['a', "\x07"]]); + + function unescape(c) { + if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES.get(c) || c; + } + + function parseArguments(name, args) { + var results = []; + var chunks = args.trim().split(/\s*,\s*/g); + var matches; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var chunk = _step.value; + + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if (matches = chunk.match(STRING_REGEX)) { + results.push(matches[2].replace(ESCAPE_REGEX, function (m, escape, chr) { + return escape ? unescape(escape) : chr; + })); + } else { + throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return results; + } + + function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + var results = []; + var matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + var name = matches[1]; + + if (matches[2]) { + var args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; + } + + function buildStyle(chalk, styles) { + var enabled = {}; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = styles[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var layer = _step2.value; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = layer.styles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var style = _step3.value; + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var current = chalk; + + var _arr = Object.keys(enabled); + + for (var _i = 0; _i < _arr.length; _i++) { + var styleName = _arr[_i]; + + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error("Unknown Chalk style: ".concat(styleName)); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; + } + + module.exports = function (chalk, tmp) { + var styles = []; + var chunks = []; + var chunk = []; // eslint-disable-next-line max-params + + tmp.replace(TEMPLATE_REGEX, function (m, escapeChar, inverse, style, close, chr) { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + var str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({ + inverse: inverse, + styles: parseStyle(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + chunks.push(chunk.join('')); + + if (styles.length > 0) { + var errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); + throw new Error(errMsg); + } + + return chunks.join(''); + }; +}); + +var chalk = createCommonjsModule(function (module) { + 'use strict'; + + var stdoutColor = supportsColor_1.stdout; + var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping + + var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such + + var skipModels = new Set(['gray']); + var styles = Object.create(null); + + function applyOptions(obj, options) { + options = options || {}; // Detect level if not set manually + + var scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; + } + + function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + var _chalk = {}; + applyOptions(_chalk, options); + + _chalk.template = function () { + var args = [].slice.call(arguments); + return chalkTag.apply(null, [_chalk.template].concat(args)); + }; + + Object.setPrototypeOf(_chalk, Chalk.prototype); + Object.setPrototypeOf(_chalk.template, _chalk); + _chalk.template.constructor = Chalk; + return _chalk.template; + } + + applyOptions(this, options); + } // Use bright blue on Windows as the normal blue color is illegible + + + if (isSimpleWindowsTerm) { + ansiStyles.blue.open = "\x1B[94m"; + } + + var _arr = Object.keys(ansiStyles); + + var _loop = function _loop() { + var key = _arr[_i]; + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + styles[key] = { + get: function get() { + var codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; + }; + + for (var _i = 0; _i < _arr.length; _i++) { + _loop(); + } + + styles.visible = { + get: function get() { + return build.call(this, this._styles || [], true, 'visible'); + } + }; + ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); + + var _arr2 = Object.keys(ansiStyles.color.ansi); + + var _loop2 = function _loop2() { + var model = _arr2[_i2]; + + if (skipModels.has(model)) { + return "continue"; + } + + styles[model] = { + get: function get() { + var level = this.level; + return function () { + var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + var codes = { + open: open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; + }; + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var _ret = _loop2(); + + if (_ret === "continue") continue; + } + + ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); + + var _arr3 = Object.keys(ansiStyles.bgColor.ansi); + + var _loop3 = function _loop3() { + var model = _arr3[_i3]; + + if (skipModels.has(model)) { + return "continue"; + } + + var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get: function get() { + var level = this.level; + return function () { + var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + var codes = { + open: open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; + }; + + for (var _i3 = 0; _i3 < _arr3.length; _i3++) { + var _ret2 = _loop3(); + + if (_ret2 === "continue") continue; + } + + var proto = Object.defineProperties(function () {}, styles); + + function build(_styles, _empty, key) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + var self = this; + Object.defineProperty(builder, 'level', { + enumerable: true, + get: function get() { + return self.level; + }, + set: function set(level) { + self.level = level; + } + }); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get: function get() { + return self.enabled; + }, + set: function set(enabled) { + self.enabled = enabled; + } + }); // See below for fix regarding invisible grey/dim combination on Windows + + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; + } + + function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + var args = arguments; + var argsLen = args.length; + var str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + + + var originalDim = ansiStyles.dim.open; + + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = this._styles.slice().reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var code = _step.value; + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + + str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open)); + } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + ansiStyles.dim.open = originalDim; + return str; + } + + function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + var args = [].slice.call(arguments, 2); + var parts = [strings.raw[0]]; + + for (var i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return templates(chalk, parts.join('')); + } + + Object.defineProperties(Chalk.prototype, styles); + module.exports = Chalk(); // eslint-disable-line new-cap + + module.exports.supportsColor = stdoutColor; + module.exports.default = module.exports; // For TypeScript +}); + +var common = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.commonDeprecatedHandler = function (keyOrPair, redirectTo, _ref) { + var descriptor = _ref.descriptor; + var messages = ["".concat(chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair)), " is deprecated")]; + + if (redirectTo) { + messages.push("we now treat it as ".concat(chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo)))); + } + + return messages.join('; ') + '.'; + }; +}); +unwrapExports(common); + +var deprecated = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(common, exports); +}); +unwrapExports(deprecated); + +var common$2 = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.commonInvalidHandler = function (key, value, utils) { + return ["Invalid ".concat(chalk.default.red(utils.descriptor.key(key)), " value."), "Expected ".concat(chalk.default.blue(utils.schemas[key].expected(utils)), ","), "but received ".concat(chalk.default.red(utils.descriptor.value(value)), ".")].join(' '); + }; +}); +unwrapExports(common$2); + +var invalid = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(common$2, exports); +}); +unwrapExports(invalid); + +/* eslint-disable no-nested-ternary */ +var arr = []; +var charCodeCache = []; + +var leven$1 = function leven(a, b) { + if (a === b) { + return 0; + } + + var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the + // shortest & which one is the longest + + if (a.length > b.length) { + a = b; + b = swap; + } + + var aLen = a.length; + var bLen = b.length; + + if (aLen === 0) { + return bLen; + } + + if (bLen === 0) { + return aLen; + } // Performing suffix trimming: + // We can linearly drop suffix common to both strings since they + // don't increase distance at all + // Note: `~-` is the bitwise way to perform a `- 1` operation + + + while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) { + aLen--; + bLen--; + } + + if (aLen === 0) { + return bLen; + } // Performing prefix trimming + // We can linearly drop prefix common to both strings since they + // don't increase distance at all + + + var start = 0; + + while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) { + start++; + } + + aLen -= start; + bLen -= start; + + if (aLen === 0) { + return bLen; + } + + var bCharCode; + var ret; + var tmp; + var tmp2; + var i = 0; + var j = 0; + + while (i < aLen) { + charCodeCache[start + i] = a.charCodeAt(start + i); + arr[i] = ++i; + } + + while (j < bLen) { + bCharCode = b.charCodeAt(start + j); + tmp = j++; + ret = j; + + for (i = 0; i < aLen; i++) { + tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1; + tmp = arr[i]; + ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2; + } + } + + return ret; +}; + +var leven_1 = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.levenUnknownHandler = function (key, value, _ref) { + var descriptor = _ref.descriptor, + logger = _ref.logger, + schemas = _ref.schemas; + var messages = ["Ignored unknown option ".concat(chalk.default.yellow(descriptor.pair({ + key: key, + value: value + })), ".")]; + var suggestion = Object.keys(schemas).sort().find(function (knownKey) { + return leven$1(key, knownKey) < 3; + }); + + if (suggestion) { + messages.push("Did you mean ".concat(chalk.default.blue(descriptor.key(suggestion)), "?")); + } + + logger.warn(messages.join(' ')); + }; +}); +unwrapExports(leven_1); + +var unknown = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(leven_1, exports); +}); +unwrapExports(unknown); + +var handlers = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(deprecated, exports); + + tslib_1.__exportStar(invalid, exports); + + tslib_1.__exportStar(unknown, exports); +}); +unwrapExports(handlers); + +var schema = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + var HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess']; + + function createSchema(SchemaConstructor, parameters) { + var schema = new SchemaConstructor(parameters); + var subSchema = Object.create(schema); + + for (var _i = 0; _i < HANDLER_KEYS.length; _i++) { + var handlerKey = HANDLER_KEYS[_i]; + + if (handlerKey in parameters) { + subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length); + } + } + + return subSchema; + } + + exports.createSchema = createSchema; + + var Schema = + /*#__PURE__*/ + function () { + function Schema(parameters) { + _classCallCheck(this, Schema); + + this.name = parameters.name; + } + + _createClass(Schema, [{ + key: "default", + value: function _default(_utils) { + return undefined; + } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length` + + }, { + key: "expected", + value: function expected(_utils) { + return 'nothing'; + } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length` + + }, { + key: "validate", + value: function validate(_value, _utils) { + return false; + } + }, { + key: "deprecated", + value: function deprecated(_value, _utils) { + return false; + } + }, { + key: "forward", + value: function forward(_value, _utils) { + return undefined; + } + }, { + key: "redirect", + value: function redirect(_value, _utils) { + return undefined; + } + }, { + key: "overlap", + value: function overlap(currentValue, _newValue, _utils) { + return currentValue; + } + }, { + key: "preprocess", + value: function preprocess(value, _utils) { + return value; + } + }, { + key: "postprocess", + value: function postprocess(value, _utils) { + return value; + } + }], [{ + key: "create", + value: function create(parameters) { + // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863 + return createSchema(this, parameters); + } + }]); + + return Schema; + }(); + + exports.Schema = Schema; + + function normalizeHandler(handler, superSchema, handlerArgumentsLength) { + return typeof handler === 'function' ? function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return handler.apply(void 0, _toConsumableArray(args.slice(0, handlerArgumentsLength - 1)).concat([superSchema], _toConsumableArray(args.slice(handlerArgumentsLength - 1)))); + } : function () { + return handler; + }; + } +}); +unwrapExports(schema); + +var alias = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var AliasSchema = + /*#__PURE__*/ + function (_schema_1$Schema) { + _inherits(AliasSchema, _schema_1$Schema); + + function AliasSchema(parameters) { + var _this; + + _classCallCheck(this, AliasSchema); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(AliasSchema).call(this, parameters)); + _this._sourceName = parameters.sourceName; + return _this; + } + + _createClass(AliasSchema, [{ + key: "expected", + value: function expected(utils) { + return utils.schemas[this._sourceName].expected(utils); + } + }, { + key: "validate", + value: function validate(value, utils) { + return utils.schemas[this._sourceName].validate(value, utils); + } + }, { + key: "redirect", + value: function redirect(_value, _utils) { + return this._sourceName; + } + }]); + + return AliasSchema; + }(schema.Schema); + + exports.AliasSchema = AliasSchema; +}); +unwrapExports(alias); + +var any = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var AnySchema = + /*#__PURE__*/ + function (_schema_1$Schema) { + _inherits(AnySchema, _schema_1$Schema); + + function AnySchema() { + _classCallCheck(this, AnySchema); + + return _possibleConstructorReturn(this, _getPrototypeOf(AnySchema).apply(this, arguments)); + } + + _createClass(AnySchema, [{ + key: "expected", + value: function expected() { + return 'anything'; + } + }, { + key: "validate", + value: function validate() { + return true; + } + }]); + + return AnySchema; + }(schema.Schema); + + exports.AnySchema = AnySchema; +}); +unwrapExports(any); + +var array$2 = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var ArraySchema = + /*#__PURE__*/ + function (_schema_1$Schema) { + _inherits(ArraySchema, _schema_1$Schema); + + function ArraySchema(_a) { + var _this; + + _classCallCheck(this, ArraySchema); + + var valueSchema = _a.valueSchema, + _a$name = _a.name, + name = _a$name === void 0 ? valueSchema.name : _a$name, + handlers = tslib_1.__rest(_a, ["valueSchema", "name"]); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(ArraySchema).call(this, Object.assign({}, handlers, { + name: name + }))); + _this._valueSchema = valueSchema; + return _this; + } + + _createClass(ArraySchema, [{ + key: "expected", + value: function expected(utils) { + return "an array of ".concat(this._valueSchema.expected(utils)); + } + }, { + key: "validate", + value: function validate(value, utils) { + if (!Array.isArray(value)) { + return false; + } + + var invalidValues = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = value[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var subValue = _step.value; + var subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue); + + if (subValidateResult !== true) { + invalidValues.push(subValidateResult.value); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return invalidValues.length === 0 ? true : { + value: invalidValues + }; + } + }, { + key: "deprecated", + value: function deprecated(value, utils) { + var deprecatedResult = []; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = value[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var subValue = _step2.value; + var subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue); + + if (subDeprecatedResult !== false) { + deprecatedResult.push.apply(deprecatedResult, _toConsumableArray(subDeprecatedResult.map(function (_ref) { + var deprecatedValue = _ref.value; + return { + value: [deprecatedValue] + }; + }))); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return deprecatedResult; + } + }, { + key: "forward", + value: function forward(value, utils) { + var forwardResult = []; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = value[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var subValue = _step3.value; + var subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue); + forwardResult.push.apply(forwardResult, _toConsumableArray(subForwardResult.map(wrapTransferResult))); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return forwardResult; + } + }, { + key: "redirect", + value: function redirect(value, utils) { + var remain = []; + var redirect = []; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = value[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var subValue = _step4.value; + var subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue); + + if ('remain' in subRedirectResult) { + remain.push(subRedirectResult.remain); + } + + redirect.push.apply(redirect, _toConsumableArray(subRedirectResult.redirect.map(wrapTransferResult))); + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + + return remain.length === 0 ? { + redirect: redirect + } : { + redirect: redirect, + remain: remain + }; + } + }, { + key: "overlap", + value: function overlap(currentValue, newValue) { + return currentValue.concat(newValue); + } + }]); + + return ArraySchema; + }(schema.Schema); + + exports.ArraySchema = ArraySchema; + + function wrapTransferResult(_ref2) { + var from = _ref2.from, + to = _ref2.to; + return { + from: [from], + to: to + }; + } +}); +unwrapExports(array$2); + +var boolean_1 = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var BooleanSchema = + /*#__PURE__*/ + function (_schema_1$Schema) { + _inherits(BooleanSchema, _schema_1$Schema); + + function BooleanSchema() { + _classCallCheck(this, BooleanSchema); + + return _possibleConstructorReturn(this, _getPrototypeOf(BooleanSchema).apply(this, arguments)); + } + + _createClass(BooleanSchema, [{ + key: "expected", + value: function expected() { + return 'true or false'; + } + }, { + key: "validate", + value: function validate(value) { + return typeof value === 'boolean'; + } + }]); + + return BooleanSchema; + }(schema.Schema); + + exports.BooleanSchema = BooleanSchema; +}); +unwrapExports(boolean_1); + +var utils = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function recordFromArray(array, mainKey) { + var record = Object.create(null); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var value = _step.value; + var key = value[mainKey]; // istanbul ignore next + + if (record[key]) { + throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key))); + } // @ts-ignore + + + record[key] = value; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return record; + } + + exports.recordFromArray = recordFromArray; + + function mapFromArray(array, mainKey) { + var map = new Map(); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = array[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var value = _step2.value; + var key = value[mainKey]; // istanbul ignore next + + if (map.has(key)) { + throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key))); + } + + map.set(key, value); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return map; + } + + exports.mapFromArray = mapFromArray; + + function createAutoChecklist() { + var map = Object.create(null); + return function (id) { + var idString = JSON.stringify(id); + + if (map[idString]) { + return true; + } + + map[idString] = true; + return false; + }; + } + + exports.createAutoChecklist = createAutoChecklist; + + function partition(array, predicate) { + var trueArray = []; + var falseArray = []; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = array[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var value = _step3.value; + + if (predicate(value)) { + trueArray.push(value); + } else { + falseArray.push(value); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return [trueArray, falseArray]; + } + + exports.partition = partition; + + function isInt(value) { + return value === Math.floor(value); + } + + exports.isInt = isInt; + + function comparePrimitive(a, b) { + if (a === b) { + return 0; + } + + var typeofA = _typeof(a); + + var typeofB = _typeof(b); + + var orders = ['undefined', 'object', 'boolean', 'number', 'string']; + + if (typeofA !== typeofB) { + return orders.indexOf(typeofA) - orders.indexOf(typeofB); + } + + if (typeofA !== 'string') { + return Number(a) - Number(b); + } + + return a.localeCompare(b); + } + + exports.comparePrimitive = comparePrimitive; + + function normalizeDefaultResult(result) { + return result === undefined ? {} : result; + } + + exports.normalizeDefaultResult = normalizeDefaultResult; + + function normalizeValidateResult(result, value) { + return result === true ? true : result === false ? { + value: value + } : result; + } + + exports.normalizeValidateResult = normalizeValidateResult; + + function normalizeDeprecatedResult(result, value) { + var doNotNormalizeTrue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{ + value: value + }] : 'value' in result ? [result] : result.length === 0 ? false : result; + } + + exports.normalizeDeprecatedResult = normalizeDeprecatedResult; + + function normalizeTransferResult(result, value) { + return typeof result === 'string' || 'key' in result ? { + from: value, + to: result + } : 'from' in result ? { + from: result.from, + to: result.to + } : { + from: value, + to: result.to + }; + } + + exports.normalizeTransferResult = normalizeTransferResult; + + function normalizeForwardResult(result, value) { + return result === undefined ? [] : Array.isArray(result) ? result.map(function (transferResult) { + return normalizeTransferResult(transferResult, value); + }) : [normalizeTransferResult(result, value)]; + } + + exports.normalizeForwardResult = normalizeForwardResult; + + function normalizeRedirectResult(result, value) { + var redirect = normalizeForwardResult(_typeof(result) === 'object' && 'redirect' in result ? result.redirect : result, value); + return redirect.length === 0 ? { + remain: value, + redirect: redirect + } : _typeof(result) === 'object' && 'remain' in result ? { + remain: result.remain, + redirect: redirect + } : { + redirect: redirect + }; + } + + exports.normalizeRedirectResult = normalizeRedirectResult; +}); +unwrapExports(utils); + +var choice = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var ChoiceSchema = + /*#__PURE__*/ + function (_schema_1$Schema) { + _inherits(ChoiceSchema, _schema_1$Schema); + + function ChoiceSchema(parameters) { + var _this; + + _classCallCheck(this, ChoiceSchema); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(ChoiceSchema).call(this, parameters)); + _this._choices = utils.mapFromArray(parameters.choices.map(function (choice) { + return choice && _typeof(choice) === 'object' ? choice : { + value: choice + }; + }), 'value'); + return _this; + } + + _createClass(ChoiceSchema, [{ + key: "expected", + value: function expected(_ref) { + var _this2 = this; + + var descriptor = _ref.descriptor; + var choiceValues = Array.from(this._choices.keys()).map(function (value) { + return _this2._choices.get(value); + }).filter(function (choiceInfo) { + return !choiceInfo.deprecated; + }).map(function (choiceInfo) { + return choiceInfo.value; + }).sort(utils.comparePrimitive).map(descriptor.value); + var head = choiceValues.slice(0, -2); + var tail = choiceValues.slice(-2); + return head.concat(tail.join(' or ')).join(', '); + } + }, { + key: "validate", + value: function validate(value) { + return this._choices.has(value); + } + }, { + key: "deprecated", + value: function deprecated(value) { + var choiceInfo = this._choices.get(value); + + return choiceInfo && choiceInfo.deprecated ? { + value: value + } : false; + } + }, { + key: "forward", + value: function forward(value) { + var choiceInfo = this._choices.get(value); + + return choiceInfo ? choiceInfo.forward : undefined; + } + }, { + key: "redirect", + value: function redirect(value) { + var choiceInfo = this._choices.get(value); + + return choiceInfo ? choiceInfo.redirect : undefined; + } + }]); + + return ChoiceSchema; + }(schema.Schema); + + exports.ChoiceSchema = ChoiceSchema; +}); +unwrapExports(choice); + +var number = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var NumberSchema = + /*#__PURE__*/ + function (_schema_1$Schema) { + _inherits(NumberSchema, _schema_1$Schema); + + function NumberSchema() { + _classCallCheck(this, NumberSchema); + + return _possibleConstructorReturn(this, _getPrototypeOf(NumberSchema).apply(this, arguments)); + } + + _createClass(NumberSchema, [{ + key: "expected", + value: function expected() { + return 'a number'; + } + }, { + key: "validate", + value: function validate(value, _utils) { + return typeof value === 'number'; + } + }]); + + return NumberSchema; + }(schema.Schema); + + exports.NumberSchema = NumberSchema; +}); +unwrapExports(number); + +var integer = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var IntegerSchema = + /*#__PURE__*/ + function (_number_1$NumberSchem) { + _inherits(IntegerSchema, _number_1$NumberSchem); + + function IntegerSchema() { + _classCallCheck(this, IntegerSchema); + + return _possibleConstructorReturn(this, _getPrototypeOf(IntegerSchema).apply(this, arguments)); + } + + _createClass(IntegerSchema, [{ + key: "expected", + value: function expected() { + return 'an integer'; + } + }, { + key: "validate", + value: function validate(value, utils$$2) { + return utils$$2.normalizeValidateResult(_get(_getPrototypeOf(IntegerSchema.prototype), "validate", this).call(this, value, utils$$2), value) === true && utils.isInt(value); + } + }]); + + return IntegerSchema; + }(number.NumberSchema); + + exports.IntegerSchema = IntegerSchema; +}); +unwrapExports(integer); + +var string = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var StringSchema = + /*#__PURE__*/ + function (_schema_1$Schema) { + _inherits(StringSchema, _schema_1$Schema); + + function StringSchema() { + _classCallCheck(this, StringSchema); + + return _possibleConstructorReturn(this, _getPrototypeOf(StringSchema).apply(this, arguments)); + } + + _createClass(StringSchema, [{ + key: "expected", + value: function expected() { + return 'a string'; + } + }, { + key: "validate", + value: function validate(value) { + return typeof value === 'string'; + } + }]); + + return StringSchema; + }(schema.Schema); + + exports.StringSchema = StringSchema; +}); +unwrapExports(string); + +var schemas = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(alias, exports); + + tslib_1.__exportStar(any, exports); + + tslib_1.__exportStar(array$2, exports); + + tslib_1.__exportStar(boolean_1, exports); + + tslib_1.__exportStar(choice, exports); + + tslib_1.__exportStar(integer, exports); + + tslib_1.__exportStar(number, exports); + + tslib_1.__exportStar(string, exports); +}); +unwrapExports(schemas); + +var defaults = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.defaultDescriptor = api.apiDescriptor; + exports.defaultUnknownHandler = leven_1.levenUnknownHandler; + exports.defaultInvalidHandler = invalid.commonInvalidHandler; + exports.defaultDeprecatedHandler = common.commonDeprecatedHandler; +}); +unwrapExports(defaults); + +var normalize$1 = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.normalize = function (options, schemas, opts) { + return new Normalizer(schemas, opts).normalize(options); + }; + + var Normalizer = + /*#__PURE__*/ + function () { + function Normalizer(schemas, opts) { + _classCallCheck(this, Normalizer); + + // istanbul ignore next + var _ref = opts || {}, + _ref$logger = _ref.logger, + logger = _ref$logger === void 0 ? console : _ref$logger, + _ref$descriptor = _ref.descriptor, + descriptor = _ref$descriptor === void 0 ? defaults.defaultDescriptor : _ref$descriptor, + _ref$unknown = _ref.unknown, + unknown = _ref$unknown === void 0 ? defaults.defaultUnknownHandler : _ref$unknown, + _ref$invalid = _ref.invalid, + invalid = _ref$invalid === void 0 ? defaults.defaultInvalidHandler : _ref$invalid, + _ref$deprecated = _ref.deprecated, + deprecated = _ref$deprecated === void 0 ? defaults.defaultDeprecatedHandler : _ref$deprecated; + + this._utils = { + descriptor: descriptor, + logger: + /* istanbul ignore next */ + logger || { + warn: function warn() {} + }, + schemas: utils.recordFromArray(schemas, 'name'), + normalizeDefaultResult: utils.normalizeDefaultResult, + normalizeDeprecatedResult: utils.normalizeDeprecatedResult, + normalizeForwardResult: utils.normalizeForwardResult, + normalizeRedirectResult: utils.normalizeRedirectResult, + normalizeValidateResult: utils.normalizeValidateResult + }; + this._unknownHandler = unknown; + this._invalidHandler = invalid; + this._deprecatedHandler = deprecated; + this.cleanHistory(); + } + + _createClass(Normalizer, [{ + key: "cleanHistory", + value: function cleanHistory() { + this._hasDeprecationWarned = utils.createAutoChecklist(); + } + }, { + key: "normalize", + value: function normalize(options) { + var _this = this; + + var normalized = {}; + var restOptionsArray = [options]; + + var applyNormalization = function applyNormalization() { + while (restOptionsArray.length !== 0) { + var currentOptions = restOptionsArray.shift(); + + var transferredOptionsArray = _this._applyNormalization(currentOptions, normalized); + + restOptionsArray.push.apply(restOptionsArray, _toConsumableArray(transferredOptionsArray)); + } + }; + + applyNormalization(); + + var _arr = Object.keys(this._utils.schemas); + + for (var _i = 0; _i < _arr.length; _i++) { + var key = _arr[_i]; + var schema = this._utils.schemas[key]; + + if (!(key in normalized)) { + var defaultResult = utils.normalizeDefaultResult(schema.default(this._utils)); + + if ('value' in defaultResult) { + restOptionsArray.push(_defineProperty({}, key, defaultResult.value)); + } + } + } + + applyNormalization(); + + var _arr2 = Object.keys(this._utils.schemas); + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var _key = _arr2[_i2]; + var _schema = this._utils.schemas[_key]; + + if (_key in normalized) { + normalized[_key] = _schema.postprocess(normalized[_key], this._utils); + } + } + + return normalized; + } + }, { + key: "_applyNormalization", + value: function _applyNormalization(options, normalized) { + var _this2 = this; + + var transferredOptionsArray = []; + + var _utils_1$partition = utils.partition(Object.keys(options), function (key) { + return key in _this2._utils.schemas; + }), + _utils_1$partition2 = _slicedToArray(_utils_1$partition, 2), + knownOptionNames = _utils_1$partition2[0], + unknownOptionNames = _utils_1$partition2[1]; + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + var _loop = function _loop() { + var key = _step.value; + var schema = _this2._utils.schemas[key]; + var value = schema.preprocess(options[key], _this2._utils); + var validateResult = utils.normalizeValidateResult(schema.validate(value, _this2._utils), value); + + if (validateResult !== true) { + var invalidValue = validateResult.value; + + var errorMessageOrError = _this2._invalidHandler(key, invalidValue, _this2._utils); + + throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) : + /* istanbul ignore next*/ + errorMessageOrError; + } + + var appendTransferredOptions = function appendTransferredOptions(_ref2) { + var from = _ref2.from, + to = _ref2.to; + transferredOptionsArray.push(typeof to === 'string' ? _defineProperty({}, to, from) : _defineProperty({}, to.key, to.value)); + }; + + var warnDeprecated = function warnDeprecated(_ref5) { + var currentValue = _ref5.value, + redirectTo = _ref5.redirectTo; + var deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, _this2._utils), value, + /* doNotNormalizeTrue */ + true); + + if (deprecatedResult === false) { + return; + } + + if (deprecatedResult === true) { + if (!_this2._hasDeprecationWarned(key)) { + _this2._utils.logger.warn(_this2._deprecatedHandler(key, redirectTo, _this2._utils)); + } + } else { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = deprecatedResult[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var deprecatedValue = _step3.value.value; + var pair = { + key: key, + value: deprecatedValue + }; + + if (!_this2._hasDeprecationWarned(pair)) { + var redirectToPair = typeof redirectTo === 'string' ? { + key: redirectTo, + value: deprecatedValue + } : redirectTo; + + _this2._utils.logger.warn(_this2._deprecatedHandler(pair, redirectToPair, _this2._utils)); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + }; + + var forwardResult = utils.normalizeForwardResult(schema.forward(value, _this2._utils), value); + forwardResult.forEach(appendTransferredOptions); + var redirectResult = utils.normalizeRedirectResult(schema.redirect(value, _this2._utils), value); + redirectResult.redirect.forEach(appendTransferredOptions); + + if ('remain' in redirectResult) { + var remainingValue = redirectResult.remain; + normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, _this2._utils) : remainingValue; + warnDeprecated({ + value: remainingValue + }); + } + + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = redirectResult.redirect[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _step4$value = _step4.value, + from = _step4$value.from, + to = _step4$value.to; + warnDeprecated({ + value: from, + redirectTo: to + }); + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + }; + + for (var _iterator = knownOptionNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + _loop(); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = unknownOptionNames[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var key = _step2.value; + var value = options[key]; + + var unknownResult = this._unknownHandler(key, value, this._utils); + + if (unknownResult) { + var _arr3 = Object.keys(unknownResult); + + for (var _i3 = 0; _i3 < _arr3.length; _i3++) { + var unknownKey = _arr3[_i3]; + + var unknownOption = _defineProperty({}, unknownKey, unknownResult[unknownKey]); + + if (unknownKey in this._utils.schemas) { + transferredOptionsArray.push(unknownOption); + } else { + Object.assign(normalized, unknownOption); + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return transferredOptionsArray; + } + }]); + + return Normalizer; + }(); + + exports.Normalizer = Normalizer; +}); +unwrapExports(normalize$1); + +var lib$1 = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_1.__exportStar(descriptors, exports); + + tslib_1.__exportStar(handlers, exports); + + tslib_1.__exportStar(schemas, exports); + + tslib_1.__exportStar(normalize$1, exports); + + tslib_1.__exportStar(schema, exports); +}); +unwrapExports(lib$1); + +var hasFlag$3 = function hasFlag(flag, argv$$1) { + argv$$1 = argv$$1 || process.argv; + var terminatorPos = argv$$1.indexOf('--'); + var prefix = /^-{1,2}/.test(flag) ? '' : '--'; + var pos = argv$$1.indexOf(prefix + flag); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; + +var supportsColor$1 = createCommonjsModule(function (module) { + 'use strict'; + + var env$$1 = process.env; + + var support = function support(level) { + if (level === 0) { + return false; + } + + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + }; + + var supportLevel = function () { + if (hasFlag$3('no-color') || hasFlag$3('no-colors') || hasFlag$3('color=false')) { + return 0; + } + + if (hasFlag$3('color=16m') || hasFlag$3('color=full') || hasFlag$3('color=truecolor')) { + return 3; + } + + if (hasFlag$3('color=256')) { + return 2; + } + + if (hasFlag$3('color') || hasFlag$3('colors') || hasFlag$3('color=true') || hasFlag$3('color=always')) { + return 1; + } + + if (process.stdout && !process.stdout.isTTY) { + return 0; + } + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. + var osRelease = require$$1$1.release().split('.'); + + if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return 2; + } + + return 1; + } + + if ('CI' in env$$1) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) { + return sign in env$$1; + }) || env$$1.CI_NAME === 'codeship') { + return 1; + } + + return 0; + } + + if ('TEAMCITY_VERSION' in env$$1) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$$1.TEAMCITY_VERSION) ? 1 : 0; + } + + if ('TERM_PROGRAM' in env$$1) { + var version = parseInt((env$$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$$1.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + + case 'Hyper': + return 3; + + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$$1.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env$$1.TERM)) { + return 1; + } + + if ('COLORTERM' in env$$1) { + return 1; + } + + if (env$$1.TERM === 'dumb') { + return 0; + } + + return 0; + }(); + + if ('FORCE_COLOR' in env$$1) { + supportLevel = parseInt(env$$1.FORCE_COLOR, 10) === 0 ? 0 : supportLevel || 1; + } + + module.exports = process && support(supportLevel); +}); + +var templates$2 = createCommonjsModule(function (module) { + 'use strict'; + + var TEMPLATE_REGEX = /(?:\\(u[a-f0-9]{4}|x[a-f0-9]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + var ESCAPE_REGEX = /\\(u[0-9a-f]{4}|x[0-9a-f]{2}|.)|([^\\])/gi; + var ESCAPES = { + n: '\n', + r: '\r', + t: '\t', + b: '\b', + f: '\f', + v: '\v', + 0: '\0', + '\\': '\\', + e: "\x1B", + a: "\x07" + }; + + function unescape(c) { + if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES[c] || c; + } + + function parseArguments(name, args) { + var results = []; + var chunks = args.trim().split(/\s*,\s*/g); + var matches; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var chunk = _step.value; + + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if (matches = chunk.match(STRING_REGEX)) { + results.push(matches[2].replace(ESCAPE_REGEX, function (m, escape, chr) { + return escape ? unescape(escape) : chr; + })); + } else { + throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return results; + } + + function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + var results = []; + var matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + var name = matches[1]; + + if (matches[2]) { + var args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; + } + + function buildStyle(chalk, styles) { + var enabled = {}; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = styles[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var layer = _step2.value; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = layer.styles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var style = _step3.value; + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var current = chalk; + + var _arr = Object.keys(enabled); + + for (var _i = 0; _i < _arr.length; _i++) { + var styleName = _arr[_i]; + + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error("Unknown Chalk style: ".concat(styleName)); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; + } + + module.exports = function (chalk, tmp) { + var styles = []; + var chunks = []; + var chunk = []; // eslint-disable-next-line max-params + + tmp.replace(TEMPLATE_REGEX, function (m, escapeChar, inverse, style, close, chr) { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + var str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({ + inverse: inverse, + styles: parseStyle(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + chunks.push(chunk.join('')); + + if (styles.length > 0) { + var errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); + throw new Error(errMsg); + } + + return chunks.join(''); + }; +}); + +var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping + +var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such + +var skipModels = new Set(['gray']); +var styles = Object.create(null); + +function applyOptions(obj, options) { + options = options || {}; // Detect level if not set manually + + var scLevel = supportsColor$1 ? supportsColor$1.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; +} + +function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + var _chalk = {}; + applyOptions(_chalk, options); + + _chalk.template = function () { + var args = [].slice.call(arguments); + return chalkTag.apply(null, [_chalk.template].concat(args)); + }; + + Object.setPrototypeOf(_chalk, Chalk.prototype); + Object.setPrototypeOf(_chalk.template, _chalk); + _chalk.template.constructor = Chalk; + return _chalk.template; + } + + applyOptions(this, options); +} // Use bright blue on Windows as the normal blue color is illegible + + +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = "\x1B[94m"; +} + +var _arr = Object.keys(ansiStyles); + +var _loop = function _loop() { + var key = _arr[_i]; + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + styles[key] = { + get: function get() { + var codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], key); + } + }; +}; + +for (var _i = 0; _i < _arr.length; _i++) { + _loop(); +} + +ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); + +var _arr2 = Object.keys(ansiStyles.color.ansi); + +var _loop2 = function _loop2() { + var model = _arr2[_i2]; + + if (skipModels.has(model)) { + return "continue"; + } + + styles[model] = { + get: function get() { + var level = this.level; + return function () { + var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + var codes = { + open: open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model); + }; + } + }; +}; + +for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var _ret = _loop2(); + + if (_ret === "continue") continue; +} + +ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); + +var _arr3 = Object.keys(ansiStyles.bgColor.ansi); + +var _loop3 = function _loop3() { + var model = _arr3[_i3]; + + if (skipModels.has(model)) { + return "continue"; + } + + var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get: function get() { + var level = this.level; + return function () { + var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + var codes = { + open: open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model); + }; + } + }; +}; + +for (var _i3 = 0; _i3 < _arr3.length; _i3++) { + var _ret2 = _loop3(); + + if (_ret2 === "continue") continue; +} + +var proto = Object.defineProperties(function () {}, styles); + +function build(_styles, key) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + var self = this; + Object.defineProperty(builder, 'level', { + enumerable: true, + get: function get() { + return self.level; + }, + set: function set(level) { + self.level = level; + } + }); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get: function get() { + return self.enabled; + }, + set: function set(enabled) { + self.enabled = enabled; + } + }); // See below for fix regarding invisible grey/dim combination on Windows + + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; +} + +function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + var args = arguments; + var argsLen = args.length; + var str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return str; + } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + + + var originalDim = ansiStyles.dim.open; + + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = this._styles.slice().reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var code = _step.value; + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + + str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open)); + } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + ansiStyles.dim.open = originalDim; + return str; +} + +function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + var args = [].slice.call(arguments, 2); + var parts = [strings.raw[0]]; + + for (var i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return templates$2(chalk, parts.join('')); +} + +Object.defineProperties(Chalk.prototype, styles); +var chalk$2 = Chalk(); // eslint-disable-line new-cap + +var supportsColor_1$2 = supportsColor$1; +chalk$2.supportsColor = supportsColor_1$2; + +var cliDescriptor = { + key: function key(_key) { + return _key.length === 1 ? "-".concat(_key) : "--".concat(_key); + }, + value: function value(_value) { + return lib$1.apiDescriptor.value(_value); + }, + pair: function pair(_ref) { + var key = _ref.key, + value = _ref.value; + return value === false ? "--no-".concat(key) : value === true ? cliDescriptor.key(key) : value === "" ? "".concat(cliDescriptor.key(key), " without an argument") : "".concat(cliDescriptor.key(key), "=").concat(value); + } +}; + +var FlagSchema = +/*#__PURE__*/ +function (_vnopts$ChoiceSchema) { + _inherits(FlagSchema, _vnopts$ChoiceSchema); + + function FlagSchema(_ref2) { + var _this; + + var name = _ref2.name, + flags = _ref2.flags; + + _classCallCheck(this, FlagSchema); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(FlagSchema).call(this, { + name: name, + choices: flags + })); + _this._flags = flags.slice().sort(); + return _this; + } + + _createClass(FlagSchema, [{ + key: "preprocess", + value: function preprocess(value, utils) { + if (typeof value === "string" && value.length !== 0 && this._flags.indexOf(value) === -1) { + var suggestion = this._flags.find(function (flag) { + return leven$1(flag, value) < 3; + }); + + if (suggestion) { + utils.logger.warn(["Unknown flag ".concat(chalk$2.yellow(utils.descriptor.value(value)), ","), "did you mean ".concat(chalk$2.blue(utils.descriptor.value(suggestion)), "?")].join(" ")); + return suggestion; + } + } + + return value; + } + }, { + key: "expected", + value: function expected() { + return "a flag"; + } + }]); + + return FlagSchema; +}(lib$1.ChoiceSchema); + +var hasDeprecationWarned; + +function normalizeOptions$1(options, optionInfos) { + var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + logger = _ref3.logger, + _ref3$isCLI = _ref3.isCLI, + isCLI = _ref3$isCLI === void 0 ? false : _ref3$isCLI, + _ref3$passThrough = _ref3.passThrough, + passThrough = _ref3$passThrough === void 0 ? false : _ref3$passThrough; + + var unknown = !passThrough ? lib$1.levenUnknownHandler : Array.isArray(passThrough) ? function (key, value) { + return passThrough.indexOf(key) === -1 ? undefined : _defineProperty({}, key, value); + } : function (key, value) { + return _defineProperty({}, key, value); + }; + var descriptor = isCLI ? cliDescriptor : lib$1.apiDescriptor; + var schemas = optionInfosToSchemas(optionInfos, { + isCLI: isCLI + }); + var normalizer = new lib$1.Normalizer(schemas, { + logger: logger, + unknown: unknown, + descriptor: descriptor + }); + var shouldSuppressDuplicateDeprecationWarnings = logger !== false; + + if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) { + normalizer._hasDeprecationWarned = hasDeprecationWarned; + } + + var normalized = normalizer.normalize(options); + + if (shouldSuppressDuplicateDeprecationWarnings) { + hasDeprecationWarned = normalizer._hasDeprecationWarned; + } + + return normalized; +} + +function optionInfosToSchemas(optionInfos, _ref6) { + var isCLI = _ref6.isCLI; + var schemas = []; + + if (isCLI) { + schemas.push(lib$1.AnySchema.create({ + name: "_" + })); + } + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = optionInfos[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var optionInfo = _step.value; + schemas.push(optionInfoToSchema(optionInfo, { + isCLI: isCLI, + optionInfos: optionInfos + })); + + if (optionInfo.alias && isCLI) { + schemas.push(lib$1.AliasSchema.create({ + name: optionInfo.alias, + sourceName: optionInfo.name + })); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return schemas; +} + +function optionInfoToSchema(optionInfo, _ref7) { + var isCLI = _ref7.isCLI, + optionInfos = _ref7.optionInfos; + var SchemaConstructor; + var parameters = { + name: optionInfo.name + }; + var handlers = {}; + + switch (optionInfo.type) { + case "int": + SchemaConstructor = lib$1.IntegerSchema; + + if (isCLI) { + parameters.preprocess = function (value) { + return Number(value); + }; + } + + break; + + case "choice": + SchemaConstructor = lib$1.ChoiceSchema; + parameters.choices = optionInfo.choices.map(function (choiceInfo) { + return _typeof(choiceInfo) === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, { + redirect: { + to: { + key: optionInfo.name, + value: choiceInfo.redirect + } + } + }) : choiceInfo; + }); + break; + + case "boolean": + SchemaConstructor = lib$1.BooleanSchema; + break; + + case "flag": + SchemaConstructor = FlagSchema; + parameters.flags = optionInfos.map(function (optionInfo) { + return [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? "no-".concat(optionInfo.name) : []); + }).reduce(function (a, b) { + return a.concat(b); + }, []); + break; + + case "path": + SchemaConstructor = lib$1.StringSchema; + break; + + default: + throw new Error("Unexpected type ".concat(optionInfo.type)); + } + + if (optionInfo.exception) { + parameters.validate = function (value, schema, utils) { + return optionInfo.exception(value) || schema.validate(value, utils); + }; + } else { + parameters.validate = function (value, schema, utils) { + return value === undefined || schema.validate(value, utils); + }; + } + + if (optionInfo.redirect) { + handlers.redirect = function (value) { + return !value ? undefined : { + to: { + key: optionInfo.redirect.option, + value: optionInfo.redirect.value + } + }; + }; + } + + if (optionInfo.deprecated) { + handlers.deprecated = true; + } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2 + + + if (isCLI && !optionInfo.array) { + var originalPreprocess = parameters.preprocess || function (x) { + return x; + }; + + parameters.preprocess = function (value, schema, utils) { + return schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils); + }; + } + + return optionInfo.array ? lib$1.ArraySchema.create(Object.assign(isCLI ? { + preprocess: function preprocess(v) { + return [].concat(v); + } + } : {}, handlers, { + valueSchema: SchemaConstructor.create(parameters) + })) : SchemaConstructor.create(Object.assign({}, parameters, handlers)); +} + +function normalizeApiOptions(options, optionInfos, opts) { + return normalizeOptions$1(options, optionInfos, opts); +} + +function normalizeCliOptions(options, optionInfos, opts) { + return normalizeOptions$1(options, optionInfos, Object.assign({ + isCLI: true + }, opts)); +} + +var optionsNormalizer = { + normalizeApiOptions: normalizeApiOptions, + normalizeCliOptions: normalizeCliOptions +}; + +var getLast = function getLast(arr) { + return arr.length > 0 ? arr[arr.length - 1] : null; +}; + +function locStart$1(node, opts) { + opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator + + if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) { + return locStart$1(node.declaration.decorators[0]); + } + + if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) { + return locStart$1(node.decorators[0]); + } + + if (node.__location) { + return node.__location.startOffset; + } + + if (node.range) { + return node.range[0]; + } + + if (typeof node.start === "number") { + return node.start; + } + + if (node.loc) { + return node.loc.start; + } + + return null; +} + +function locEnd$1(node) { + var endNode = node.nodes && getLast(node.nodes); + + if (endNode && node.source && !node.source.end) { + node = endNode; + } + + if (node.__location) { + return node.__location.endOffset; + } + + var loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null; + + if (node.typeAnnotation) { + return Math.max(loc, locEnd$1(node.typeAnnotation)); + } + + if (node.loc && !loc) { + return node.loc.end; + } + + return loc; +} + +var loc = { + locStart: locStart$1, + locEnd: locEnd$1 +}; + +var jsTokens = createCommonjsModule(function (module, exports) { + // Copyright 2014, 2015, 2016, 2017 Simon Lydell + // License: MIT. (See LICENSE.) + Object.defineProperty(exports, "__esModule", { + value: true + }); // This regex comes from regex.coffee, and is inserted here by generate-index.js + // (run `npm run build`). + + exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyu]{1,5}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; + + exports.matchToToken = function (match) { + var token = { + type: "invalid", + value: match[0] + }; + if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace"; + return token; + }; +}); +unwrapExports(jsTokens); + +var ast = createCommonjsModule(function (module) { + /* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + 'use strict'; + + function isExpression(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'ArrayExpression': + case 'AssignmentExpression': + case 'BinaryExpression': + case 'CallExpression': + case 'ConditionalExpression': + case 'FunctionExpression': + case 'Identifier': + case 'Literal': + case 'LogicalExpression': + case 'MemberExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'SequenceExpression': + case 'ThisExpression': + case 'UnaryExpression': + case 'UpdateExpression': + return true; + } + + return false; + } + + function isIterationStatement(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'DoWhileStatement': + case 'ForInStatement': + case 'ForStatement': + case 'WhileStatement': + return true; + } + + return false; + } + + function isStatement(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'BlockStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'DebuggerStatement': + case 'DoWhileStatement': + case 'EmptyStatement': + case 'ExpressionStatement': + case 'ForInStatement': + case 'ForStatement': + case 'IfStatement': + case 'LabeledStatement': + case 'ReturnStatement': + case 'SwitchStatement': + case 'ThrowStatement': + case 'TryStatement': + case 'VariableDeclaration': + case 'WhileStatement': + case 'WithStatement': + return true; + } + + return false; + } + + function isSourceElement(node) { + return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; + } + + function trailingStatement(node) { + switch (node.type) { + case 'IfStatement': + if (node.alternate != null) { + return node.alternate; + } + + return node.consequent; + + case 'LabeledStatement': + case 'ForStatement': + case 'ForInStatement': + case 'WhileStatement': + case 'WithStatement': + return node.body; + } + + return null; + } + + function isProblematicIfStatement(node) { + var current; + + if (node.type !== 'IfStatement') { + return false; + } + + if (node.alternate == null) { + return false; + } + + current = node.consequent; + + do { + if (current.type === 'IfStatement') { + if (current.alternate == null) { + return true; + } + } + + current = trailingStatement(current); + } while (current); + + return false; + } + + module.exports = { + isExpression: isExpression, + isStatement: isStatement, + isIterationStatement: isIterationStatement, + isSourceElement: isSourceElement, + isProblematicIfStatement: isProblematicIfStatement, + trailingStatement: trailingStatement + }; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + +}); + +var code = createCommonjsModule(function (module) { + /* + Copyright (C) 2013-2014 Yusuke Suzuki + Copyright (C) 2014 Ivan Nikulin + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + 'use strict'; + + var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`. + + ES5Regex = { + // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, + // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ + }; + ES6Regex = { + // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/, + // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + + function isDecimalDigit(ch) { + return 0x30 <= ch && ch <= 0x39; // 0..9 + } + + function isHexDigit(ch) { + return 0x30 <= ch && ch <= 0x39 || // 0..9 + 0x61 <= ch && ch <= 0x66 || // a..f + 0x41 <= ch && ch <= 0x46; // A..F + } + + function isOctalDigit(ch) { + return ch >= 0x30 && ch <= 0x37; // 0..7 + } // 7.2 White Space + + + NON_ASCII_WHITESPACES = [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF]; + + function isWhiteSpace(ch) { + return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; + } // 7.3 Line Terminators + + + function isLineTerminator(ch) { + return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; + } // 7.6 Identifier Names and Identifiers + + + function fromCodePoint(cp) { + if (cp <= 0xFFFF) { + return String.fromCharCode(cp); + } + + var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); + var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); + return cu1 + cu2; + } + + IDENTIFIER_START = new Array(0x80); + + for (ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + IDENTIFIER_PART = new Array(0x80); + + for (ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch >= 0x30 && ch <= 0x39 || // 0..9 + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + function isIdentifierStartES5(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES5(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + function isIdentifierStartES6(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES6(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStartES5: isIdentifierStartES5, + isIdentifierPartES5: isIdentifierPartES5, + isIdentifierStartES6: isIdentifierStartES6, + isIdentifierPartES6: isIdentifierPartES6 + }; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + +}); + +var keyword = createCommonjsModule(function (module) { + /* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + 'use strict'; + + var code$$1 = code; + + function isStrictModeReservedWordES6(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'let': + return true; + + default: + return false; + } + } + + function isKeywordES5(id, strict) { + // yield should not be treated as keyword under non-strict mode. + if (!strict && id === 'yield') { + return false; + } + + return isKeywordES6(id, strict); + } + + function isKeywordES6(id, strict) { + if (strict && isStrictModeReservedWordES6(id)) { + return true; + } + + switch (id.length) { + case 2: + return id === 'if' || id === 'in' || id === 'do'; + + case 3: + return id === 'var' || id === 'for' || id === 'new' || id === 'try'; + + case 4: + return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum'; + + case 5: + return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super'; + + case 6: + return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import'; + + case 7: + return id === 'default' || id === 'finally' || id === 'extends'; + + case 8: + return id === 'function' || id === 'continue' || id === 'debugger'; + + case 10: + return id === 'instanceof'; + + default: + return false; + } + } + + function isReservedWordES5(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); + } + + function isReservedWordES6(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + function isIdentifierNameES5(id) { + var i, iz, ch; + + if (id.length === 0) { + return false; + } + + ch = id.charCodeAt(0); + + if (!code$$1.isIdentifierStartES5(ch)) { + return false; + } + + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + + if (!code$$1.isIdentifierPartES5(ch)) { + return false; + } + } + + return true; + } + + function decodeUtf16(lead, trail) { + return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + } + + function isIdentifierNameES6(id) { + var i, iz, ch, lowCh, check; + + if (id.length === 0) { + return false; + } + + check = code$$1.isIdentifierStartES6; + + for (i = 0, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + + if (0xD800 <= ch && ch <= 0xDBFF) { + ++i; + + if (i >= iz) { + return false; + } + + lowCh = id.charCodeAt(i); + + if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { + return false; + } + + ch = decodeUtf16(ch, lowCh); + } + + if (!check(ch)) { + return false; + } + + check = code$$1.isIdentifierPartES6; + } + + return true; + } + + function isIdentifierES5(id, strict) { + return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); + } + + function isIdentifierES6(id, strict) { + return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); + } + + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isReservedWordES5: isReservedWordES5, + isReservedWordES6: isReservedWordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierNameES5: isIdentifierNameES5, + isIdentifierNameES6: isIdentifierNameES6, + isIdentifierES5: isIdentifierES5, + isIdentifierES6: isIdentifierES6 + }; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + +}); + +var utils$2 = createCommonjsModule(function (module, exports) { + /* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + 'use strict'; + + exports.ast = ast; + exports.code = code; + exports.keyword = keyword; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + +}); + +var hasFlag$6 = createCommonjsModule(function (module) { + 'use strict'; + + module.exports = function (flag, argv$$1) { + argv$$1 = argv$$1 || process.argv; + var prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; + var pos = argv$$1.indexOf(prefix + flag); + var terminatorPos = argv$$1.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); + }; +}); + +var env$2 = process.env; +var forceColor$1; + +if (hasFlag$6('no-color') || hasFlag$6('no-colors') || hasFlag$6('color=false')) { + forceColor$1 = false; +} else if (hasFlag$6('color') || hasFlag$6('colors') || hasFlag$6('color=true') || hasFlag$6('color=always')) { + forceColor$1 = true; +} + +if ('FORCE_COLOR' in env$2) { + forceColor$1 = env$2.FORCE_COLOR.length === 0 || parseInt(env$2.FORCE_COLOR, 10) !== 0; +} + +function translateLevel$1(level) { + if (level === 0) { + return false; + } + + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor$4(stream) { + if (forceColor$1 === false) { + return 0; + } + + if (hasFlag$6('color=16m') || hasFlag$6('color=full') || hasFlag$6('color=truecolor')) { + return 3; + } + + if (hasFlag$6('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor$1 !== true) { + return 0; + } + + var min = forceColor$1 ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + var osRelease = require$$1$1.release().split('.'); + + if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$2) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) { + return sign in env$2; + }) || env$2.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$2) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$2.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$2) { + var version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$2.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$2.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { + return 1; + } + + if ('COLORTERM' in env$2) { + return 1; + } + + if (env$2.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel$1(stream) { + var level = supportsColor$4(stream); + return translateLevel$1(level); +} + +var supportsColor_1$3 = { + supportsColor: getSupportLevel$1, + stdout: getSupportLevel$1(process.stdout), + stderr: getSupportLevel$1(process.stderr) +}; + +var templates$4 = createCommonjsModule(function (module) { + 'use strict'; + + var TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + var ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; + var ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', "\x1B"], ['a', "\x07"]]); + + function unescape(c) { + if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES.get(c) || c; + } + + function parseArguments(name, args) { + var results = []; + var chunks = args.trim().split(/\s*,\s*/g); + var matches; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var chunk = _step.value; + + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if (matches = chunk.match(STRING_REGEX)) { + results.push(matches[2].replace(ESCAPE_REGEX, function (m, escape, chr) { + return escape ? unescape(escape) : chr; + })); + } else { + throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return results; + } + + function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + var results = []; + var matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + var name = matches[1]; + + if (matches[2]) { + var args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; + } + + function buildStyle(chalk, styles) { + var enabled = {}; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = styles[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var layer = _step2.value; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = layer.styles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var style = _step3.value; + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var current = chalk; + + var _arr = Object.keys(enabled); + + for (var _i = 0; _i < _arr.length; _i++) { + var styleName = _arr[_i]; + + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error("Unknown Chalk style: ".concat(styleName)); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; + } + + module.exports = function (chalk, tmp) { + var styles = []; + var chunks = []; + var chunk = []; // eslint-disable-next-line max-params + + tmp.replace(TEMPLATE_REGEX, function (m, escapeChar, inverse, style, close, chr) { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + var str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({ + inverse: inverse, + styles: parseStyle(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + chunks.push(chunk.join('')); + + if (styles.length > 0) { + var errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); + throw new Error(errMsg); + } + + return chunks.join(''); + }; +}); + +var chalk$5 = createCommonjsModule(function (module) { + 'use strict'; + + var stdoutColor = supportsColor_1$3.stdout; + var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping + + var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such + + var skipModels = new Set(['gray']); + var styles = Object.create(null); + + function applyOptions(obj, options) { + options = options || {}; // Detect level if not set manually + + var scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; + } + + function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + var _chalk = {}; + applyOptions(_chalk, options); + + _chalk.template = function () { + var args = [].slice.call(arguments); + return chalkTag.apply(null, [_chalk.template].concat(args)); + }; + + Object.setPrototypeOf(_chalk, Chalk.prototype); + Object.setPrototypeOf(_chalk.template, _chalk); + _chalk.template.constructor = Chalk; + return _chalk.template; + } + + applyOptions(this, options); + } // Use bright blue on Windows as the normal blue color is illegible + + + if (isSimpleWindowsTerm) { + ansiStyles.blue.open = "\x1B[94m"; + } + + var _arr = Object.keys(ansiStyles); + + var _loop = function _loop() { + var key = _arr[_i]; + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + styles[key] = { + get: function get() { + var codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + }; + }; + + for (var _i = 0; _i < _arr.length; _i++) { + _loop(); + } + + styles.visible = { + get: function get() { + return build.call(this, this._styles || [], true, 'visible'); + } + }; + ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); + + var _arr2 = Object.keys(ansiStyles.color.ansi); + + var _loop2 = function _loop2() { + var model = _arr2[_i2]; + + if (skipModels.has(model)) { + return "continue"; + } + + styles[model] = { + get: function get() { + var level = this.level; + return function () { + var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + var codes = { + open: open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; + }; + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var _ret = _loop2(); + + if (_ret === "continue") continue; + } + + ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); + + var _arr3 = Object.keys(ansiStyles.bgColor.ansi); + + var _loop3 = function _loop3() { + var model = _arr3[_i3]; + + if (skipModels.has(model)) { + return "continue"; + } + + var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get: function get() { + var level = this.level; + return function () { + var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + var codes = { + open: open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + }; + }; + + for (var _i3 = 0; _i3 < _arr3.length; _i3++) { + var _ret2 = _loop3(); + + if (_ret2 === "continue") continue; + } + + var proto = Object.defineProperties(function () {}, styles); + + function build(_styles, _empty, key) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + var self = this; + Object.defineProperty(builder, 'level', { + enumerable: true, + get: function get() { + return self.level; + }, + set: function set(level) { + self.level = level; + } + }); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + get: function get() { + return self.enabled; + }, + set: function set(enabled) { + self.enabled = enabled; + } + }); // See below for fix regarding invisible grey/dim combination on Windows + + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; + } + + function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + var args = arguments; + var argsLen = args.length; + var str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + + + var originalDim = ansiStyles.dim.open; + + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = this._styles.slice().reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var code = _step.value; + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + + str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open)); + } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + ansiStyles.dim.open = originalDim; + return str; + } + + function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + var args = [].slice.call(arguments, 2); + var parts = [strings.raw[0]]; + + for (var i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return templates$4(chalk, parts.join('')); + } + + Object.defineProperties(Chalk.prototype, styles); + module.exports = Chalk(); // eslint-disable-line new-cap + + module.exports.supportsColor = stdoutColor; + module.exports.default = module.exports; // For TypeScript +}); + +var lib$3 = createCommonjsModule(function (module, exports) { + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.shouldHighlight = shouldHighlight; + exports.getChalk = getChalk; + exports.default = highlight; + + function _jsTokens() { + var data = _interopRequireWildcard(jsTokens); + + _jsTokens = function _jsTokens() { + return data; + }; + + return data; + } + + function _esutils() { + var data = _interopRequireDefault(utils$2); + + _esutils = function _esutils() { + return data; + }; + + return data; + } + + function _chalk() { + var data = _interopRequireDefault(chalk$5); + + _chalk = function _chalk() { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; + + if (desc.get || desc.set) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + } + + newObj.default = obj; + return newObj; + } + } + + function getDefs(chalk) { + return { + keyword: chalk.cyan, + capitalized: chalk.yellow, + jsx_tag: chalk.yellow, + punctuator: chalk.yellow, + number: chalk.magenta, + string: chalk.green, + regex: chalk.magenta, + comment: chalk.grey, + invalid: chalk.white.bgRed.bold + }; + } + + var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + var JSX_TAG = /^[a-z][\w-]*$/i; + var BRACKET = /^[()[\]{}]$/; + + function getTokenType(match) { + var _match$slice = match.slice(-2), + offset = _match$slice[0], + text = _match$slice[1]; + + var token = (0, _jsTokens().matchToToken)(match); + + if (token.type === "name") { + if (_esutils().default.keyword.isReservedWordES6(token.value)) { + return "keyword"; + } + + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == ""), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); + } else { + return " " + maybeHighlight(defs.gutter, gutter) + line; + } + }).join("\n"); + + if (opts.message && !hasColumns) { + frame = "" + " ".repeat(numberMaxWidth + 1) + opts.message + "\n" + frame; + } + + if (highlighted) { + return chalk.reset(frame); + } else { + return frame; + } + } + + function _default(rawLines, lineNumber, colNumber, opts) { + if (opts === void 0) { + opts = {}; + } + + if (!deprecationWarningShown) { + deprecationWarningShown = true; + var message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + var deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + + colNumber = Math.max(colNumber, 0); + var location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); + } +}); +unwrapExports(lib$2); + +var ConfigError$1 = errors.ConfigError; +var locStart = loc.locStart; +var locEnd = loc.locEnd; // Use defineProperties()/getOwnPropertyDescriptor() to prevent +// triggering the parsers getters. + +var ownNames = Object.getOwnPropertyNames; +var ownDescriptor = Object.getOwnPropertyDescriptor; + +function getParsers(options) { + var parsers = {}; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = options.plugins[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var plugin = _step.value; + + if (!plugin.parsers) { + continue; + } + + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = ownNames(plugin.parsers)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var name = _step2.value; + Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name)); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return parsers; +} + +function resolveParser$1(opts, parsers) { + parsers = parsers || getParsers(opts); + + if (typeof opts.parser === "function") { + // Custom parser API always works with JavaScript. + return { + parse: opts.parser, + astFormat: "estree", + locStart: locStart, + locEnd: locEnd + }; + } + + if (typeof opts.parser === "string") { + if (parsers.hasOwnProperty(opts.parser)) { + return parsers[opts.parser]; + } + /* istanbul ignore next */ + + + { + throw new ConfigError$1("Couldn't resolve parser \"".concat(opts.parser, "\". Parsers must be explicitly added to the standalone bundle.")); + } + } +} + +function parse$2(text, opts) { + var parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call + // the parsers getters when actually calling the parser `parse` function. + + var parsersForCustomParserApi = Object.keys(parsers).reduce(function (object, parserName) { + return Object.defineProperty(object, parserName, { + enumerable: true, + get: function get() { + return parsers[parserName].parse; + } + }); + }, {}); + var parser = resolveParser$1(opts, parsers); + + try { + if (parser.preprocess) { + text = parser.preprocess(text, opts); + } + + return { + text: text, + ast: parser.parse(text, parsersForCustomParserApi, opts) + }; + } catch (error) { + var loc$$1 = error.loc; + + if (loc$$1) { + var codeFrame = lib$2; + error.codeFrame = codeFrame.codeFrameColumns(text, loc$$1, { + highlightCode: true + }); + error.message += "\n" + error.codeFrame; + throw error; + } + /* istanbul ignore next */ + + + throw error.stack; + } +} + +var parser = { + parse: parse$2, + resolveParser: resolveParser$1 +}; + +var UndefinedParserError = errors.UndefinedParserError; +var getSupportInfo$1 = support.getSupportInfo; +var resolveParser = parser.resolveParser; +var hiddenDefaults = { + astFormat: "estree", + printer: {}, + originalText: undefined, + locStart: null, + locEnd: null +}; // Copy options and fill in default values. + +function normalize(options, opts) { + opts = opts || {}; + var rawOptions = Object.assign({}, options); + var supportOptions = getSupportInfo$1(null, { + plugins: options.plugins, + showUnreleased: true, + showDeprecated: true + }).options; + var defaults = supportOptions.reduce(function (reduced, optionInfo) { + return optionInfo.default !== undefined ? Object.assign(reduced, _defineProperty({}, optionInfo.name, optionInfo.default)) : reduced; + }, Object.assign({}, hiddenDefaults)); + + if (!rawOptions.parser) { + if (!rawOptions.filepath) { + var logger = opts.logger || console; + logger.warn("No parser and no filepath given, using 'babel' the parser now " + "but this will throw an error in the future. " + "Please specify a parser or a filepath so one can be inferred."); + rawOptions.parser = "babel"; + } else { + rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins); + + if (!rawOptions.parser) { + throw new UndefinedParserError("No parser could be inferred for file: ".concat(rawOptions.filepath)); + } + } + } + + var parser$$1 = resolveParser(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(function (x) { + return x.name === "parser"; + })], { + passThrough: true, + logger: false + })); + rawOptions.astFormat = parser$$1.astFormat; + rawOptions.locEnd = parser$$1.locEnd; + rawOptions.locStart = parser$$1.locStart; + var plugin = getPlugin(rawOptions); + rawOptions.printer = plugin.printers[rawOptions.astFormat]; + var pluginDefaults = supportOptions.filter(function (optionInfo) { + return optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name]; + }).reduce(function (reduced, optionInfo) { + return Object.assign(reduced, _defineProperty({}, optionInfo.name, optionInfo.pluginDefaults[plugin.name])); + }, {}); + var mixedDefaults = Object.assign({}, defaults, pluginDefaults); + Object.keys(mixedDefaults).forEach(function (k) { + if (rawOptions[k] == null) { + rawOptions[k] = mixedDefaults[k]; + } + }); + + if (rawOptions.parser === "json") { + rawOptions.trailingComma = "none"; + } + + return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({ + passThrough: Object.keys(hiddenDefaults) + }, opts)); +} + +function getPlugin(options) { + var astFormat = options.astFormat; + + if (!astFormat) { + throw new Error("getPlugin() requires astFormat to be set"); + } + + var printerPlugin = options.plugins.find(function (plugin) { + return plugin.printers && plugin.printers[astFormat]; + }); + + if (!printerPlugin) { + throw new Error("Couldn't find plugin for AST format \"".concat(astFormat, "\"")); + } + + return printerPlugin; +} + +function getInterpreter(filepath) { + if (typeof filepath !== "string") { + return ""; + } + + var fd; + + try { + fd = fs.openSync(filepath, "r"); + } catch (err) { + return ""; + } + + try { + var liner = new readlines(fd); + var firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node + + var m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/); + + if (m1) { + return m1[1]; + } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node + + + var m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/); + + if (m2) { + return m2[1]; + } + + return ""; + } catch (err) { + // There are some weird cases where paths are missing, causing Jest + // failures. It's unclear what these correspond to in the real world. + return ""; + } finally { + try { + // There are some weird cases where paths are missing, causing Jest + // failures. It's unclear what these correspond to in the real world. + fs.closeSync(fd); + } catch (err) {// nop + } + } +} + +function inferParser(filepath, plugins) { + var filepathParts = normalizePath(filepath).split("/"); + var filename = filepathParts[filepathParts.length - 1].toLowerCase(); // If the file has no extension, we can try to infer the language from the + // interpreter in the shebang line, if any; but since this requires FS access, + // do it last. + + var language = getSupportInfo$1(null, { + plugins: plugins + }).languages.find(function (language) { + return language.since !== null && (language.extensions && language.extensions.some(function (extension) { + return filename.endsWith(extension); + }) || language.filenames && language.filenames.find(function (name) { + return name.toLowerCase() === filename; + }) || filename.indexOf(".") === -1 && language.interpreters && language.interpreters.indexOf(getInterpreter(filepath)) !== -1); + }); + return language && language.parsers[0]; +} + +var options = { + normalize: normalize, + hiddenDefaults: hiddenDefaults, + inferParser: inferParser +}; + +function massageAST(ast, options, parent) { + if (Array.isArray(ast)) { + return ast.map(function (e) { + return massageAST(e, options, parent); + }).filter(function (e) { + return e; + }); + } + + if (!ast || _typeof(ast) !== "object") { + return ast; + } + + var newObj = {}; + + var _arr = Object.keys(ast); + + for (var _i = 0; _i < _arr.length; _i++) { + var key = _arr[_i]; + + if (typeof ast[key] !== "function") { + newObj[key] = massageAST(ast[key], options, ast); + } + } + + if (options.printer.massageAstNode) { + var result = options.printer.massageAstNode(ast, newObj, parent); + + if (result === null) { + return undefined; + } + + if (result) { + return result; + } + } + + return newObj; +} + +var massageAst = massageAST; + +function assert() {} + +assert.ok = function () {}; + +assert.strictEqual = function () {}; + + + +var assert$2 = Object.freeze({ + default: assert +}); + +function concat$1(parts) { + return { + type: "concat", + parts: parts + }; +} + +function indent$1(contents) { + return { + type: "indent", + contents: contents + }; +} + +function align(n, contents) { + return { + type: "align", + contents: contents, + n: n + }; +} + +function group(contents, opts) { + opts = opts || {}; + + return { + type: "group", + id: opts.id, + contents: contents, + break: !!opts.shouldBreak, + expandedStates: opts.expandedStates + }; +} + +function dedentToRoot(contents) { + return align(-Infinity, contents); +} + +function markAsRoot(contents) { + return align({ + type: "root" + }, contents); +} + +function dedent$1(contents) { + return align(-1, contents); +} + +function conditionalGroup(states, opts) { + return group(states[0], Object.assign(opts || {}, { + expandedStates: states + })); +} + +function fill(parts) { + return { + type: "fill", + parts: parts + }; +} + +function ifBreak(breakContents, flatContents, opts) { + opts = opts || {}; + + return { + type: "if-break", + breakContents: breakContents, + flatContents: flatContents, + groupId: opts.groupId + }; +} + +function lineSuffix$1(contents) { + return { + type: "line-suffix", + contents: contents + }; +} + +var lineSuffixBoundary = { + type: "line-suffix-boundary" +}; +var breakParent$1 = { + type: "break-parent" +}; +var trim = { + type: "trim" +}; +var line$2 = { + type: "line" +}; +var softline = { + type: "line", + soft: true +}; +var hardline$1 = concat$1([{ + type: "line", + hard: true +}, breakParent$1]); +var literalline = concat$1([{ + type: "line", + hard: true, + literal: true +}, breakParent$1]); +var cursor$1 = { + type: "cursor", + placeholder: Symbol("cursor") +}; + +function join$1(sep, arr) { + var res = []; + + for (var i = 0; i < arr.length; i++) { + if (i !== 0) { + res.push(sep); + } + + res.push(arr[i]); + } + + return concat$1(res); +} + +function addAlignmentToDoc(doc, size, tabWidth) { + var aligned = doc; + + if (size > 0) { + // Use indent to add tabs for all the levels of tabs we need + for (var i = 0; i < Math.floor(size / tabWidth); ++i) { + aligned = indent$1(aligned); + } // Use align for all the spaces that are needed + + + aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current + // indentation, so we use -Infinity to reset the indentation to 0 + + aligned = align(-Infinity, aligned); + } + + return aligned; +} + +var docBuilders = { + concat: concat$1, + join: join$1, + line: line$2, + softline: softline, + hardline: hardline$1, + literalline: literalline, + group: group, + conditionalGroup: conditionalGroup, + fill: fill, + lineSuffix: lineSuffix$1, + lineSuffixBoundary: lineSuffixBoundary, + cursor: cursor$1, + breakParent: breakParent$1, + ifBreak: ifBreak, + trim: trim, + indent: indent$1, + align: align, + addAlignmentToDoc: addAlignmentToDoc, + markAsRoot: markAsRoot, + dedentToRoot: dedentToRoot, + dedent: dedent$1 +}; + +var ansiRegex = createCommonjsModule(function (module) { + 'use strict'; + + module.exports = function (options) { + options = Object.assign({ + onlyFirst: false + }, options); + var pattern = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)", '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|'); + return new RegExp(pattern, options.onlyFirst ? undefined : 'g'); + }; +}); + +var stripAnsi = function stripAnsi(input) { + return typeof input === 'string' ? input.replace(ansiRegex(), '') : input; +}; + +var isFullwidthCodePoint = createCommonjsModule(function (module) { + 'use strict'; + /* eslint-disable yoda */ + + module.exports = function (x) { + if (Number.isNaN(x)) { + return false; + } // code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + + + if (x >= 0x1100 && (x <= 0x115f || // Hangul Jamo + x === 0x2329 || // LEFT-POINTING ANGLE BRACKET + x === 0x232a || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + 0x2e80 <= x && x <= 0x3247 && x !== 0x303f || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + 0x3250 <= x && x <= 0x4dbf || // CJK Unified Ideographs .. Yi Radicals + 0x4e00 <= x && x <= 0xa4c6 || // Hangul Jamo Extended-A + 0xa960 <= x && x <= 0xa97c || // Hangul Syllables + 0xac00 <= x && x <= 0xd7a3 || // CJK Compatibility Ideographs + 0xf900 <= x && x <= 0xfaff || // Vertical Forms + 0xfe10 <= x && x <= 0xfe19 || // CJK Compatibility Forms .. Small Form Variants + 0xfe30 <= x && x <= 0xfe6b || // Halfwidth and Fullwidth Forms + 0xff01 <= x && x <= 0xff60 || 0xffe0 <= x && x <= 0xffe6 || // Kana Supplement + 0x1b000 <= x && x <= 0x1b001 || // Enclosed Ideographic Supplement + 0x1f200 <= x && x <= 0x1f251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + 0x20000 <= x && x <= 0x3fffd)) { + return true; + } + + return false; + }; +}); + +var emojiRegex = function emojiRegex() { + // https://mths.be/emoji + return /\uD83C\uDFF4(?:\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\u200D\u2620\uFE0F)|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3]))|\uD83D\uDC69\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDD1-\uDDDD])/g; +}; + +var stringWidth = createCommonjsModule(function (module) { + 'use strict'; + + var emojiRegex$$1 = emojiRegex(); + + module.exports = function (input) { + input = input.replace(emojiRegex$$1, ' '); + + if (typeof input !== 'string' || input.length === 0) { + return 0; + } + + input = stripAnsi(input); + var width = 0; + + for (var i = 0; i < input.length; i++) { + var code = input.codePointAt(i); // Ignore control characters + + if (code <= 0x1F || code >= 0x7F && code <= 0x9F) { + continue; + } // Ignore combining characters + + + if (code >= 0x300 && code <= 0x36F) { + continue; + } // Surrogates + + + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint(code) ? 2 : 1; + } + + return width; + }; +}); + +var notAsciiRegex = /[^\x20-\x7F]/; + +function isExportDeclaration(node) { + if (node) { + switch (node.type) { + case "ExportDefaultDeclaration": + case "ExportDefaultSpecifier": + case "DeclareExportDeclaration": + case "ExportNamedDeclaration": + case "ExportAllDeclaration": + return true; + } + } + + return false; +} + +function getParentExportDeclaration(path) { + var parentNode = path.getParentNode(); + + if (path.getName() === "declaration" && isExportDeclaration(parentNode)) { + return parentNode; + } + + return null; +} + +function getPenultimate(arr) { + if (arr.length > 1) { + return arr[arr.length - 2]; + } + + return null; +} + +function getLast$3(arr) { + if (arr.length > 0) { + return arr[arr.length - 1]; + } + + return null; +} + +function skip(chars) { + return function (text, index, opts) { + var backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having + // to check for failures (did someone say monads?). + + if (index === false) { + return false; + } + + var length = text.length; + var cursor = index; + + while (cursor >= 0 && cursor < length) { + var c = text.charAt(cursor); + + if (chars instanceof RegExp) { + if (!chars.test(c)) { + return cursor; + } + } else if (chars.indexOf(c) === -1) { + return cursor; + } + + backwards ? cursor-- : cursor++; + } + + if (cursor === -1 || cursor === length) { + // If we reached the beginning or end of the file, return the + // out-of-bounds cursor. It's up to the caller to handle this + // correctly. We don't want to indicate `false` though if it + // actually skipped valid characters. + return cursor; + } + + return false; + }; +} + +var skipWhitespace = skip(/\s/); +var skipSpaces = skip(" \t"); +var skipToLineEnd = skip(",; \t"); +var skipEverythingButNewLine = skip(/[^\r\n]/); + +function skipInlineComment(text, index) { + if (index === false) { + return false; + } + + if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") { + for (var i = index + 2; i < text.length; ++i) { + if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") { + return i + 2; + } + } + } + + return index; +} + +function skipTrailingComment(text, index) { + if (index === false) { + return false; + } + + if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") { + return skipEverythingButNewLine(text, index); + } + + return index; +} // This one doesn't use the above helper function because it wants to +// test \r\n in order and `skip` doesn't support ordering and we only +// want to skip one newline. It's simple to implement. + + +function skipNewline$1(text, index, opts) { + var backwards = opts && opts.backwards; + + if (index === false) { + return false; + } + + var atIndex = text.charAt(index); + + if (backwards) { + if (text.charAt(index - 1) === "\r" && atIndex === "\n") { + return index - 2; + } + + if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { + return index - 1; + } + } else { + if (atIndex === "\r" && text.charAt(index + 1) === "\n") { + return index + 2; + } + + if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { + return index + 1; + } + } + + return index; +} + +function hasNewline$1(text, index, opts) { + opts = opts || {}; + var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); + var idx2 = skipNewline$1(text, idx, opts); + return idx !== idx2; +} + +function hasNewlineInRange(text, start, end) { + for (var i = start; i < end; ++i) { + if (text.charAt(i) === "\n") { + return true; + } + } + + return false; +} // Note: this function doesn't ignore leading comments unlike isNextLineEmpty + + +function isPreviousLineEmpty$1(text, node, locStart) { + var idx = locStart(node) - 1; + idx = skipSpaces(text, idx, { + backwards: true + }); + idx = skipNewline$1(text, idx, { + backwards: true + }); + idx = skipSpaces(text, idx, { + backwards: true + }); + var idx2 = skipNewline$1(text, idx, { + backwards: true + }); + return idx !== idx2; +} + +function isNextLineEmptyAfterIndex(text, index) { + var oldIdx = null; + var idx = index; + + while (idx !== oldIdx) { + // We need to skip all the potential trailing inline comments + oldIdx = idx; + idx = skipToLineEnd(text, idx); + idx = skipInlineComment(text, idx); + idx = skipSpaces(text, idx); + } + + idx = skipTrailingComment(text, idx); + idx = skipNewline$1(text, idx); + return hasNewline$1(text, idx); +} + +function isNextLineEmpty(text, node, locEnd) { + return isNextLineEmptyAfterIndex(text, locEnd(node)); +} + +function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) { + var oldIdx = null; + + while (idx !== oldIdx) { + oldIdx = idx; + idx = skipSpaces(text, idx); + idx = skipInlineComment(text, idx); + idx = skipTrailingComment(text, idx); + idx = skipNewline$1(text, idx); + } + + return idx; +} + +function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) { + return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node)); +} + +function getNextNonSpaceNonCommentCharacter(text, node, locEnd) { + return text.charAt(getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)); +} + +function hasSpaces(text, index, opts) { + opts = opts || {}; + var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); + return idx !== index; +} + +function setLocStart(node, index) { + if (node.range) { + node.range[0] = index; + } else { + node.start = index; + } +} + +function setLocEnd(node, index) { + if (node.range) { + node.range[1] = index; + } else { + node.end = index; + } +} + +var PRECEDENCE = {}; +[["|>"], ["||", "??"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach(function (tier, i) { + tier.forEach(function (op) { + PRECEDENCE[op] = i; + }); +}); + +function getPrecedence(op) { + return PRECEDENCE[op]; +} + +var equalityOperators = { + "==": true, + "!=": true, + "===": true, + "!==": true +}; +var multiplicativeOperators = { + "*": true, + "/": true, + "%": true +}; +var bitshiftOperators = { + ">>": true, + ">>>": true, + "<<": true +}; + +function shouldFlatten(parentOp, nodeOp) { + if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) { + return false; + } // ** is right-associative + // x ** y ** z --> x ** (y ** z) + + + if (parentOp === "**") { + return false; + } // x == y == z --> (x == y) == z + + + if (equalityOperators[parentOp] && equalityOperators[nodeOp]) { + return false; + } // x * y % z --> (x * y) % z + + + if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) { + return false; + } // x * y / z --> (x * y) / z + // x / y * z --> (x / y) * z + + + if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) { + return false; + } // x << y << z --> (x << y) << z + + + if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) { + return false; + } + + return true; +} + +function isBitwiseOperator(operator) { + return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&"; +} // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr +// holds) `function`, `class`, or `do {}`. Will be overzealous if there's +// already necessary grouping parentheses. + + +function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) { + node = getLeftMost(node); + + switch (node.type) { + case "FunctionExpression": + case "ClassExpression": + case "DoExpression": + return forbidFunctionClassAndDoExpr; + + case "ObjectExpression": + return true; + + case "MemberExpression": + return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); + + case "TaggedTemplateExpression": + if (node.tag.type === "FunctionExpression") { + // IIFEs are always already parenthesized + return false; + } + + return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr); + + case "CallExpression": + if (node.callee.type === "FunctionExpression") { + // IIFEs are always already parenthesized + return false; + } + + return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr); + + case "ConditionalExpression": + return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr); + + case "UpdateExpression": + return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr); + + case "BindExpression": + return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); + + case "SequenceExpression": + return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr); + + case "TSAsExpression": + return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr); + + default: + return false; + } +} + +function getLeftMost(node) { + if (node.left) { + return getLeftMost(node.left); + } + + return node; +} + +function getAlignmentSize(value, tabWidth, startIndex) { + startIndex = startIndex || 0; + var size = 0; + + for (var i = startIndex; i < value.length; ++i) { + if (value[i] === "\t") { + // Tabs behave in a way that they are aligned to the nearest + // multiple of tabWidth: + // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4 + // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ... + size = size + tabWidth - size % tabWidth; + } else { + size++; + } + } + + return size; +} + +function getIndentSize(value, tabWidth) { + var lastNewlineIndex = value.lastIndexOf("\n"); + + if (lastNewlineIndex === -1) { + return 0; + } + + return getAlignmentSize( // All the leading whitespaces + value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth); +} + +function getPreferredQuote(raw, preferredQuote) { + // `rawContent` is the string exactly like it appeared in the input source + // code, without its enclosing quotes. + var rawContent = raw.slice(1, -1); + var double = { + quote: '"', + regex: /"/g + }; + var single = { + quote: "'", + regex: /'/g + }; + var preferred = preferredQuote === "'" ? single : double; + var alternate = preferred === single ? double : single; + var result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing + // the string, we might want to enclose with the alternate quote instead, to + // minimize the number of escaped quotes. + + if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) { + var numPreferredQuotes = (rawContent.match(preferred.regex) || []).length; + var numAlternateQuotes = (rawContent.match(alternate.regex) || []).length; + result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote; + } + + return result; +} + +function printString(raw, options, isDirectiveLiteral) { + // `rawContent` is the string exactly like it appeared in the input source + // code, without its enclosing quotes. + var rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap + // the quotes on a DirectiveLiteral. + + var canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'"); + var enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't + // change the escape sequences they use. + // See https://github.com/prettier/prettier/issues/1555 + // and https://tc39.github.io/ecma262/#directive-prologue + + if (isDirectiveLiteral) { + if (canChangeDirectiveQuotes) { + return enclosingQuote + rawContent + enclosingQuote; + } + + return raw; + } // It might sound unnecessary to use `makeString` even if the string already + // is enclosed with `enclosingQuote`, but it isn't. The string could contain + // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes + // sure that we consistently output the minimum amount of escaped quotes. + + + return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.parentParser === "html" || options.parentParser === "vue" || options.parentParser === "angular")); +} + +function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) { + var otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double). + + var regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to + // enclose `rawContent` with `enclosingQuote`. + + var newContent = rawContent.replace(regex, function (match, escaped, quote) { + // If we matched an escape, and the escaped character is a quote of the + // other type than we intend to enclose the string with, there's no need for + // it to be escaped, so return it _without_ the backslash. + if (escaped === otherQuote) { + return escaped; + } // If we matched an unescaped quote and it is of the _same_ type as we + // intend to enclose the string with, it must be escaped, so return it with + // a backslash. + + + if (quote === enclosingQuote) { + return "\\" + quote; + } + + if (quote) { + return quote; + } // Unescape any unnecessarily escaped character. + // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27 + + + return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped; + }); + return enclosingQuote + newContent + enclosingQuote; +} + +function printNumber(rawNumber) { + return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation. + .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0). + .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit. + .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes. + .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot. + .replace(/\.(?=e|$)/, ""); +} + +function getMaxContinuousCount(str, target) { + var results = str.match(new RegExp("(".concat(escapeStringRegexp(target), ")+"), "g")); + + if (results === null) { + return 0; + } + + return results.reduce(function (maxCount, result) { + return Math.max(maxCount, result.length / target.length); + }, 0); +} + +function getStringWidth$1(text) { + if (!text) { + return 0; + } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width` + + + if (!notAsciiRegex.test(text)) { + return text.length; + } + + return stringWidth(text); +} + +function hasIgnoreComment(path) { + var node = path.getValue(); + return hasNodeIgnoreComment(node); +} + +function hasNodeIgnoreComment(node) { + return node && node.comments && node.comments.length > 0 && node.comments.some(function (comment) { + return comment.value.trim() === "prettier-ignore"; + }); +} + +function matchAncestorTypes(path, types, index) { + index = index || 0; + types = types.slice(); + + while (types.length) { + var parent = path.getParentNode(index); + var type = types.shift(); + + if (!parent || parent.type !== type) { + return false; + } + + index++; + } + + return true; +} + +function addCommentHelper(node, comment) { + var comments = node.comments || (node.comments = []); + comments.push(comment); + comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment + // We already "print" it via the raw text, we don't need to re-print it as a + // comment + + if (node.type === "JSXText") { + comment.printed = true; + } +} + +function addLeadingComment$1(node, comment) { + comment.leading = true; + comment.trailing = false; + addCommentHelper(node, comment); +} + +function addDanglingComment$1(node, comment) { + comment.leading = false; + comment.trailing = false; + addCommentHelper(node, comment); +} + +function addTrailingComment$1(node, comment) { + comment.leading = false; + comment.trailing = true; + addCommentHelper(node, comment); +} + +function isWithinParentArrayProperty(path, propertyName) { + var node = path.getValue(); + var parent = path.getParentNode(); + + if (parent == null) { + return false; + } + + if (!Array.isArray(parent[propertyName])) { + return false; + } + + var key = path.getName(); + return parent[propertyName][key] === node; +} + +function replaceEndOfLineWith(text, replacement) { + var parts = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = text.split("\n")[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var part = _step.value; + + if (parts.length !== 0) { + parts.push(replacement); + } + + parts.push(part); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return parts; +} + +var util = { + replaceEndOfLineWith: replaceEndOfLineWith, + getStringWidth: getStringWidth$1, + getMaxContinuousCount: getMaxContinuousCount, + getPrecedence: getPrecedence, + shouldFlatten: shouldFlatten, + isBitwiseOperator: isBitwiseOperator, + isExportDeclaration: isExportDeclaration, + getParentExportDeclaration: getParentExportDeclaration, + getPenultimate: getPenultimate, + getLast: getLast$3, + getNextNonSpaceNonCommentCharacterIndexWithStartIndex: getNextNonSpaceNonCommentCharacterIndexWithStartIndex, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex, + getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter, + skip: skip, + skipWhitespace: skipWhitespace, + skipSpaces: skipSpaces, + skipToLineEnd: skipToLineEnd, + skipEverythingButNewLine: skipEverythingButNewLine, + skipInlineComment: skipInlineComment, + skipTrailingComment: skipTrailingComment, + skipNewline: skipNewline$1, + isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex, + isNextLineEmpty: isNextLineEmpty, + isPreviousLineEmpty: isPreviousLineEmpty$1, + hasNewline: hasNewline$1, + hasNewlineInRange: hasNewlineInRange, + hasSpaces: hasSpaces, + setLocStart: setLocStart, + setLocEnd: setLocEnd, + startsWithNoLookaheadToken: startsWithNoLookaheadToken, + getAlignmentSize: getAlignmentSize, + getIndentSize: getIndentSize, + getPreferredQuote: getPreferredQuote, + printString: printString, + printNumber: printNumber, + hasIgnoreComment: hasIgnoreComment, + hasNodeIgnoreComment: hasNodeIgnoreComment, + makeString: makeString, + matchAncestorTypes: matchAncestorTypes, + addLeadingComment: addLeadingComment$1, + addDanglingComment: addDanglingComment$1, + addTrailingComment: addTrailingComment$1, + isWithinParentArrayProperty: isWithinParentArrayProperty +}; + +function guessEndOfLine$1(text) { + var index = text.indexOf("\r"); + + if (index >= 0) { + return text.charAt(index + 1) === "\n" ? "crlf" : "cr"; + } + + return "lf"; +} + +function convertEndOfLineToChars$2(value) { + switch (value) { + case "cr": + return "\r"; + + case "crlf": + return "\r\n"; + + default: + return "\n"; + } +} + +var endOfLine = { + guessEndOfLine: guessEndOfLine$1, + convertEndOfLineToChars: convertEndOfLineToChars$2 +}; + +var getStringWidth = util.getStringWidth; +var convertEndOfLineToChars$1 = endOfLine.convertEndOfLineToChars; +var concat$2 = docBuilders.concat; +var fill$1 = docBuilders.fill; +var cursor$2 = docBuilders.cursor; +/** @type {{[groupId: PropertyKey]: MODE}} */ + +var groupModeMap; +var MODE_BREAK = 1; +var MODE_FLAT = 2; + +function rootIndent() { + return { + value: "", + length: 0, + queue: [] + }; +} + +function makeIndent(ind, options) { + return generateInd(ind, { + type: "indent" + }, options); +} + +function makeAlign(ind, n, options) { + return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, { + type: "dedent" + }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, { + root: ind + }) : typeof n === "string" ? generateInd(ind, { + type: "stringAlign", + n: n + }, options) : generateInd(ind, { + type: "numberAlign", + n: n + }, options); +} + +function generateInd(ind, newPart, options) { + var queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart); + var value = ""; + var length = 0; + var lastTabs = 0; + var lastSpaces = 0; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = queue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var part = _step.value; + + switch (part.type) { + case "indent": + flush(); + + if (options.useTabs) { + addTabs(1); + } else { + addSpaces(options.tabWidth); + } + + break; + + case "stringAlign": + flush(); + value += part.n; + length += part.n.length; + break; + + case "numberAlign": + lastTabs += 1; + lastSpaces += part.n; + break; + + /* istanbul ignore next */ + + default: + throw new Error("Unexpected type '".concat(part.type, "'")); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + flushSpaces(); + return Object.assign({}, ind, { + value: value, + length: length, + queue: queue + }); + + function addTabs(count) { + value += "\t".repeat(count); + length += options.tabWidth * count; + } + + function addSpaces(count) { + value += " ".repeat(count); + length += count; + } + + function flush() { + if (options.useTabs) { + flushTabs(); + } else { + flushSpaces(); + } + } + + function flushTabs() { + if (lastTabs > 0) { + addTabs(lastTabs); + } + + resetLast(); + } + + function flushSpaces() { + if (lastSpaces > 0) { + addSpaces(lastSpaces); + } + + resetLast(); + } + + function resetLast() { + lastTabs = 0; + lastSpaces = 0; + } +} + +function trim$1(out) { + if (out.length === 0) { + return 0; + } + + var trimCount = 0; // Trim whitespace at the end of line + + while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) { + trimCount += out.pop().length; + } + + if (out.length && typeof out[out.length - 1] === "string") { + var trimmed = out[out.length - 1].replace(/[ \t]*$/, ""); + trimCount += out[out.length - 1].length - trimmed.length; + out[out.length - 1] = trimmed; + } + + return trimCount; +} + +function fits(next, restCommands, width, options, mustBeFlat) { + var restIdx = restCommands.length; + var cmds = [next]; // `out` is only used for width counting because `trim` requires to look + // backwards for space characters. + + var out = []; + + while (width >= 0) { + if (cmds.length === 0) { + if (restIdx === 0) { + return true; + } + + cmds.push(restCommands[restIdx - 1]); + restIdx--; + continue; + } + + var x = cmds.pop(); + var ind = x[0]; + var mode = x[1]; + var doc = x[2]; + + if (typeof doc === "string") { + out.push(doc); + width -= getStringWidth(doc); + } else { + switch (doc.type) { + case "concat": + for (var i = doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, doc.parts[i]]); + } + + break; + + case "indent": + cmds.push([makeIndent(ind, options), mode, doc.contents]); + break; + + case "align": + cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); + break; + + case "trim": + width += trim$1(out); + break; + + case "group": + if (mustBeFlat && doc.break) { + return false; + } + + cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]); + + if (doc.id) { + groupModeMap[doc.id] = cmds[cmds.length - 1][1]; + } + + break; + + case "fill": + for (var _i = doc.parts.length - 1; _i >= 0; _i--) { + cmds.push([ind, mode, doc.parts[_i]]); + } + + break; + + case "if-break": + { + var groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; + + if (groupMode === MODE_BREAK) { + if (doc.breakContents) { + cmds.push([ind, mode, doc.breakContents]); + } + } + + if (groupMode === MODE_FLAT) { + if (doc.flatContents) { + cmds.push([ind, mode, doc.flatContents]); + } + } + + break; + } + + case "line": + switch (mode) { + // fallthrough + case MODE_FLAT: + if (!doc.hard) { + if (!doc.soft) { + out.push(" "); + width -= 1; + } + + break; + } + + return true; + + case MODE_BREAK: + return true; + } + + break; + } + } + } + + return false; +} + +function printDocToString(doc, options) { + groupModeMap = {}; + var width = options.printWidth; + var newLine = convertEndOfLineToChars$1(options.endOfLine); + var pos = 0; // cmds is basically a stack. We've turned a recursive call into a + // while loop which is much faster. The while loop below adds new + // cmds to the array instead of recursively calling `print`. + + var cmds = [[rootIndent(), MODE_BREAK, doc]]; + var out = []; + var shouldRemeasure = false; + var lineSuffix = []; + + while (cmds.length !== 0) { + var x = cmds.pop(); + var ind = x[0]; + var mode = x[1]; + var _doc = x[2]; + + if (typeof _doc === "string") { + out.push(_doc); + pos += getStringWidth(_doc); + } else { + switch (_doc.type) { + case "cursor": + out.push(cursor$2.placeholder); + break; + + case "concat": + for (var i = _doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, _doc.parts[i]]); + } + + break; + + case "indent": + cmds.push([makeIndent(ind, options), mode, _doc.contents]); + break; + + case "align": + cmds.push([makeAlign(ind, _doc.n, options), mode, _doc.contents]); + break; + + case "trim": + pos -= trim$1(out); + break; + + case "group": + switch (mode) { + case MODE_FLAT: + if (!shouldRemeasure) { + cmds.push([ind, _doc.break ? MODE_BREAK : MODE_FLAT, _doc.contents]); + break; + } + + // fallthrough + + case MODE_BREAK: + { + shouldRemeasure = false; + var next = [ind, MODE_FLAT, _doc.contents]; + var rem = width - pos; + + if (!_doc.break && fits(next, cmds, rem, options)) { + cmds.push(next); + } else { + // Expanded states are a rare case where a document + // can manually provide multiple representations of + // itself. It provides an array of documents + // going from the least expanded (most flattened) + // representation first to the most expanded. If a + // group has these, we need to manually go through + // these states and find the first one that fits. + if (_doc.expandedStates) { + var mostExpanded = _doc.expandedStates[_doc.expandedStates.length - 1]; + + if (_doc.break) { + cmds.push([ind, MODE_BREAK, mostExpanded]); + break; + } else { + for (var _i2 = 1; _i2 < _doc.expandedStates.length + 1; _i2++) { + if (_i2 >= _doc.expandedStates.length) { + cmds.push([ind, MODE_BREAK, mostExpanded]); + break; + } else { + var state = _doc.expandedStates[_i2]; + var cmd = [ind, MODE_FLAT, state]; + + if (fits(cmd, cmds, rem, options)) { + cmds.push(cmd); + break; + } + } + } + } + } else { + cmds.push([ind, MODE_BREAK, _doc.contents]); + } + } + + break; + } + } + + if (_doc.id) { + groupModeMap[_doc.id] = cmds[cmds.length - 1][1]; + } + + break; + // Fills each line with as much code as possible before moving to a new + // line with the same indentation. + // + // Expects doc.parts to be an array of alternating content and + // whitespace. The whitespace contains the linebreaks. + // + // For example: + // ["I", line, "love", line, "monkeys"] + // or + // [{ type: group, ... }, softline, { type: group, ... }] + // + // It uses this parts structure to handle three main layout cases: + // * The first two content items fit on the same line without + // breaking + // -> output the first content item and the whitespace "flat". + // * Only the first content item fits on the line without breaking + // -> output the first content item "flat" and the whitespace with + // "break". + // * Neither content item fits on the line without breaking + // -> output the first content item and the whitespace with "break". + + case "fill": + { + var _rem = width - pos; + + var parts = _doc.parts; + + if (parts.length === 0) { + break; + } + + var content = parts[0]; + var contentFlatCmd = [ind, MODE_FLAT, content]; + var contentBreakCmd = [ind, MODE_BREAK, content]; + var contentFits = fits(contentFlatCmd, [], _rem, options, true); + + if (parts.length === 1) { + if (contentFits) { + cmds.push(contentFlatCmd); + } else { + cmds.push(contentBreakCmd); + } + + break; + } + + var whitespace = parts[1]; + var whitespaceFlatCmd = [ind, MODE_FLAT, whitespace]; + var whitespaceBreakCmd = [ind, MODE_BREAK, whitespace]; + + if (parts.length === 2) { + if (contentFits) { + cmds.push(whitespaceFlatCmd); + cmds.push(contentFlatCmd); + } else { + cmds.push(whitespaceBreakCmd); + cmds.push(contentBreakCmd); + } + + break; + } // At this point we've handled the first pair (context, separator) + // and will create a new fill doc for the rest of the content. + // Ideally we wouldn't mutate the array here but coping all the + // elements to a new array would make this algorithm quadratic, + // which is unusable for large arrays (e.g. large texts in JSX). + + + parts.splice(0, 2); + var remainingCmd = [ind, mode, fill$1(parts)]; + var secondContent = parts[0]; + var firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$2([content, whitespace, secondContent])]; + var firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], _rem, options, true); + + if (firstAndSecondContentFits) { + cmds.push(remainingCmd); + cmds.push(whitespaceFlatCmd); + cmds.push(contentFlatCmd); + } else if (contentFits) { + cmds.push(remainingCmd); + cmds.push(whitespaceBreakCmd); + cmds.push(contentFlatCmd); + } else { + cmds.push(remainingCmd); + cmds.push(whitespaceBreakCmd); + cmds.push(contentBreakCmd); + } + + break; + } + + case "if-break": + { + var groupMode = _doc.groupId ? groupModeMap[_doc.groupId] : mode; + + if (groupMode === MODE_BREAK) { + if (_doc.breakContents) { + cmds.push([ind, mode, _doc.breakContents]); + } + } + + if (groupMode === MODE_FLAT) { + if (_doc.flatContents) { + cmds.push([ind, mode, _doc.flatContents]); + } + } + + break; + } + + case "line-suffix": + lineSuffix.push([ind, mode, _doc.contents]); + break; + + case "line-suffix-boundary": + if (lineSuffix.length > 0) { + cmds.push([ind, mode, { + type: "line", + hard: true + }]); + } + + break; + + case "line": + switch (mode) { + case MODE_FLAT: + if (!_doc.hard) { + if (!_doc.soft) { + out.push(" "); + pos += 1; + } + + break; + } else { + // This line was forced into the output even if we + // were in flattened mode, so we need to tell the next + // group that no matter what, it needs to remeasure + // because the previous measurement didn't accurately + // capture the entire expression (this is necessary + // for nested groups) + shouldRemeasure = true; + } + + // fallthrough + + case MODE_BREAK: + if (lineSuffix.length) { + cmds.push([ind, mode, _doc]); + [].push.apply(cmds, lineSuffix.reverse()); + lineSuffix = []; + break; + } + + if (_doc.literal) { + if (ind.root) { + out.push(newLine, ind.root.value); + pos = ind.root.length; + } else { + out.push(newLine); + pos = 0; + } + } else { + pos -= trim$1(out); + out.push(newLine + ind.value); + pos = ind.length; + } + + break; + } + + break; + + default: + } + } + } + + var cursorPlaceholderIndex = out.indexOf(cursor$2.placeholder); + + if (cursorPlaceholderIndex !== -1) { + var otherCursorPlaceholderIndex = out.indexOf(cursor$2.placeholder, cursorPlaceholderIndex + 1); + var beforeCursor = out.slice(0, cursorPlaceholderIndex).join(""); + var aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join(""); + var afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join(""); + return { + formatted: beforeCursor + aroundCursor + afterCursor, + cursorNodeStart: beforeCursor.length, + cursorNodeText: aroundCursor + }; + } + + return { + formatted: out.join("") + }; +} + +var docPrinter = { + printDocToString: printDocToString +}; + +var traverseDocOnExitStackMarker = {}; + +function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { + var docsStack = [doc]; + + while (docsStack.length !== 0) { + var _doc = docsStack.pop(); + + if (_doc === traverseDocOnExitStackMarker) { + onExit(docsStack.pop()); + continue; + } + + var shouldRecurse = true; + + if (onEnter) { + if (onEnter(_doc) === false) { + shouldRecurse = false; + } + } + + if (onExit) { + docsStack.push(_doc); + docsStack.push(traverseDocOnExitStackMarker); + } + + if (shouldRecurse) { + // When there are multiple parts to process, + // the parts need to be pushed onto the stack in reverse order, + // so that they are processed in the original order + // when the stack is popped. + if (_doc.type === "concat" || _doc.type === "fill") { + for (var ic = _doc.parts.length, i = ic - 1; i >= 0; --i) { + docsStack.push(_doc.parts[i]); + } + } else if (_doc.type === "if-break") { + if (_doc.flatContents) { + docsStack.push(_doc.flatContents); + } + + if (_doc.breakContents) { + docsStack.push(_doc.breakContents); + } + } else if (_doc.type === "group" && _doc.expandedStates) { + if (shouldTraverseConditionalGroups) { + for (var _ic = _doc.expandedStates.length, _i = _ic - 1; _i >= 0; --_i) { + docsStack.push(_doc.expandedStates[_i]); + } + } else { + docsStack.push(_doc.contents); + } + } else if (_doc.contents) { + docsStack.push(_doc.contents); + } + } + } +} + +function mapDoc$1(doc, cb) { + if (doc.type === "concat" || doc.type === "fill") { + var parts = doc.parts.map(function (part) { + return mapDoc$1(part, cb); + }); + return cb(Object.assign({}, doc, { + parts: parts + })); + } else if (doc.type === "if-break") { + var breakContents = doc.breakContents && mapDoc$1(doc.breakContents, cb); + var flatContents = doc.flatContents && mapDoc$1(doc.flatContents, cb); + return cb(Object.assign({}, doc, { + breakContents: breakContents, + flatContents: flatContents + })); + } else if (doc.contents) { + var contents = mapDoc$1(doc.contents, cb); + return cb(Object.assign({}, doc, { + contents: contents + })); + } + + return cb(doc); +} + +function findInDoc(doc, fn, defaultValue) { + var result = defaultValue; + var hasStopped = false; + + function findInDocOnEnterFn(doc) { + var maybeResult = fn(doc); + + if (maybeResult !== undefined) { + hasStopped = true; + result = maybeResult; + } + + if (hasStopped) { + return false; + } + } + + traverseDoc(doc, findInDocOnEnterFn); + return result; +} + +function isEmpty(n) { + return typeof n === "string" && n.length === 0; +} + +function isLineNextFn(doc) { + if (typeof doc === "string") { + return false; + } + + if (doc.type === "line") { + return true; + } +} + +function isLineNext(doc) { + return findInDoc(doc, isLineNextFn, false); +} + +function willBreakFn(doc) { + if (doc.type === "group" && doc.break) { + return true; + } + + if (doc.type === "line" && doc.hard) { + return true; + } + + if (doc.type === "break-parent") { + return true; + } +} + +function willBreak(doc) { + return findInDoc(doc, willBreakFn, false); +} + +function breakParentGroup(groupStack) { + if (groupStack.length > 0) { + var parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because + // the user is expected to manually handle what breaks. + + if (!parentGroup.expandedStates) { + parentGroup.break = true; + } + } + + return null; +} + +function propagateBreaks(doc) { + var alreadyVisitedSet = new Set(); + var groupStack = []; + + function propagateBreaksOnEnterFn(doc) { + if (doc.type === "break-parent") { + breakParentGroup(groupStack); + } + + if (doc.type === "group") { + groupStack.push(doc); + + if (alreadyVisitedSet.has(doc)) { + return false; + } + + alreadyVisitedSet.add(doc); + } + } + + function propagateBreaksOnExitFn(doc) { + if (doc.type === "group") { + var group = groupStack.pop(); + + if (group.break) { + breakParentGroup(groupStack); + } + } + } + + traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn, + /* shouldTraverseConditionalGroups */ + true); +} + +function removeLinesFn(doc) { + // Force this doc into flat mode by statically converting all + // lines into spaces (or soft lines into nothing). Hard lines + // should still output because there's too great of a chance + // of breaking existing assumptions otherwise. + if (doc.type === "line" && !doc.hard) { + return doc.soft ? "" : " "; + } else if (doc.type === "if-break") { + return doc.flatContents || ""; + } + + return doc; +} + +function removeLines(doc) { + return mapDoc$1(doc, removeLinesFn); +} + +function stripTrailingHardline(doc) { + // HACK remove ending hardline, original PR: #1984 + if (doc.type === "concat" && doc.parts.length !== 0) { + var lastPart = doc.parts[doc.parts.length - 1]; + + if (lastPart.type === "concat") { + if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") { + return { + type: "concat", + parts: doc.parts.slice(0, -1) + }; + } + + return { + type: "concat", + parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart)) + }; + } + } + + return doc; +} + +var docUtils = { + isEmpty: isEmpty, + willBreak: willBreak, + isLineNext: isLineNext, + traverseDoc: traverseDoc, + mapDoc: mapDoc$1, + propagateBreaks: propagateBreaks, + removeLines: removeLines, + stripTrailingHardline: stripTrailingHardline +}; + +function flattenDoc(doc) { + if (doc.type === "concat") { + var res = []; + + for (var i = 0; i < doc.parts.length; ++i) { + var doc2 = doc.parts[i]; + + if (typeof doc2 !== "string" && doc2.type === "concat") { + [].push.apply(res, flattenDoc(doc2).parts); + } else { + var flattened = flattenDoc(doc2); + + if (flattened !== "") { + res.push(flattened); + } + } + } + + return Object.assign({}, doc, { + parts: res + }); + } else if (doc.type === "if-break") { + return Object.assign({}, doc, { + breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null, + flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null + }); + } else if (doc.type === "group") { + return Object.assign({}, doc, { + contents: flattenDoc(doc.contents), + expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates + }); + } else if (doc.contents) { + return Object.assign({}, doc, { + contents: flattenDoc(doc.contents) + }); + } + + return doc; +} + +function printDoc(doc) { + if (typeof doc === "string") { + return JSON.stringify(doc); + } + + if (doc.type === "line") { + if (doc.literal) { + return "literalline"; + } + + if (doc.hard) { + return "hardline"; + } + + if (doc.soft) { + return "softline"; + } + + return "line"; + } + + if (doc.type === "break-parent") { + return "breakParent"; + } + + if (doc.type === "trim") { + return "trim"; + } + + if (doc.type === "concat") { + return "[" + doc.parts.map(printDoc).join(", ") + "]"; + } + + if (doc.type === "indent") { + return "indent(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "align") { + return doc.n === -Infinity ? "dedentToRoot(" + printDoc(doc.contents) + ")" : doc.n < 0 ? "dedent(" + printDoc(doc.contents) + ")" : doc.n.type === "root" ? "markAsRoot(" + printDoc(doc.contents) + ")" : "align(" + JSON.stringify(doc.n) + ", " + printDoc(doc.contents) + ")"; + } + + if (doc.type === "if-break") { + return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")"; + } + + if (doc.type === "group") { + if (doc.expandedStates) { + return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])"; + } + + return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "fill") { + return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")"; + } + + if (doc.type === "line-suffix") { + return "lineSuffix(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "line-suffix-boundary") { + return "lineSuffixBoundary"; + } + + throw new Error("Unknown doc type " + doc.type); +} + +var docDebug = { + printDocToDebug: function printDocToDebug(doc) { + return printDoc(flattenDoc(doc)); + } +}; + +var doc = { + builders: docBuilders, + printer: docPrinter, + utils: docUtils, + debug: docDebug +}; + +var mapDoc$2 = doc.utils.mapDoc; + +function isNextLineEmpty$1(text, node, options) { + return util.isNextLineEmpty(text, node, options.locEnd); +} + +function isPreviousLineEmpty$2(text, node, options) { + return util.isPreviousLineEmpty(text, node, options.locStart); +} + +function getNextNonSpaceNonCommentCharacterIndex$1(text, node, options) { + return util.getNextNonSpaceNonCommentCharacterIndex(text, node, options.locEnd); +} + +var utilShared = { + getMaxContinuousCount: util.getMaxContinuousCount, + getStringWidth: util.getStringWidth, + getAlignmentSize: util.getAlignmentSize, + getIndentSize: util.getIndentSize, + skip: util.skip, + skipWhitespace: util.skipWhitespace, + skipSpaces: util.skipSpaces, + skipNewline: util.skipNewline, + skipToLineEnd: util.skipToLineEnd, + skipEverythingButNewLine: util.skipEverythingButNewLine, + skipInlineComment: util.skipInlineComment, + skipTrailingComment: util.skipTrailingComment, + hasNewline: util.hasNewline, + hasNewlineInRange: util.hasNewlineInRange, + hasSpaces: util.hasSpaces, + isNextLineEmpty: isNextLineEmpty$1, + isNextLineEmptyAfterIndex: util.isNextLineEmptyAfterIndex, + isPreviousLineEmpty: isPreviousLineEmpty$2, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1, + mapDoc: mapDoc$2, + // TODO: remove in 2.0, we already exposed it in docUtils + makeString: util.makeString, + addLeadingComment: util.addLeadingComment, + addDanglingComment: util.addDanglingComment, + addTrailingComment: util.addTrailingComment +}; + +var assert$3 = ( assert$2 && assert ) || assert$2; + +var _require$$0$builders = doc.builders; +var concat = _require$$0$builders.concat; +var hardline = _require$$0$builders.hardline; +var breakParent = _require$$0$builders.breakParent; +var indent = _require$$0$builders.indent; +var lineSuffix = _require$$0$builders.lineSuffix; +var join = _require$$0$builders.join; +var cursor = _require$$0$builders.cursor; +var hasNewline = util.hasNewline; +var skipNewline = util.skipNewline; +var isPreviousLineEmpty = util.isPreviousLineEmpty; +var addLeadingComment = utilShared.addLeadingComment; +var addDanglingComment = utilShared.addDanglingComment; +var addTrailingComment = utilShared.addTrailingComment; +var childNodesCacheKey = Symbol("child-nodes"); + +function getSortedChildNodes(node, options, resultArray) { + if (!node) { + return; + } + + var printer = options.printer, + locStart = options.locStart, + locEnd = options.locEnd; + + if (resultArray) { + if (node && printer.canAttachComment && printer.canAttachComment(node)) { + // This reverse insertion sort almost always takes constant + // time because we almost always (maybe always?) append the + // nodes in order anyway. + var i; + + for (i = resultArray.length - 1; i >= 0; --i) { + if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) { + break; + } + } + + resultArray.splice(i + 1, 0, node); + return; + } + } else if (node[childNodesCacheKey]) { + return node[childNodesCacheKey]; + } + + var childNodes; + + if (printer.getCommentChildNodes) { + childNodes = printer.getCommentChildNodes(node); + } else if (node && _typeof(node) === "object") { + childNodes = Object.keys(node).filter(function (n) { + return n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode"; + }).map(function (n) { + return node[n]; + }); + } + + if (!childNodes) { + return; + } + + if (!resultArray) { + Object.defineProperty(node, childNodesCacheKey, { + value: resultArray = [], + enumerable: false + }); + } + + childNodes.forEach(function (childNode) { + getSortedChildNodes(childNode, options, resultArray); + }); + return resultArray; +} // As efficiently as possible, decorate the comment object with +// .precedingNode, .enclosingNode, and/or .followingNode properties, at +// least one of which is guaranteed to be defined. + + +function decorateComment(node, comment, options) { + var locStart = options.locStart, + locEnd = options.locEnd; + var childNodes = getSortedChildNodes(node, options); + var precedingNode; + var followingNode; // Time to dust off the old binary search robes and wizard hat. + + var left = 0; + var right = childNodes.length; + + while (left < right) { + var middle = left + right >> 1; + var child = childNodes[middle]; + + if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) { + // The comment is completely contained by this child node. + comment.enclosingNode = child; + decorateComment(child, comment, options); + return; // Abandon the binary search at this level. + } + + if (locEnd(child) - locStart(comment) <= 0) { + // This child node falls completely before the comment. + // Because we will never consider this node or any nodes + // before it again, this node must be the closest preceding + // node we have encountered so far. + precedingNode = child; + left = middle + 1; + continue; + } + + if (locEnd(comment) - locStart(child) <= 0) { + // This child node falls completely after the comment. + // Because we will never consider this node or any nodes after + // it again, this node must be the closest following node we + // have encountered so far. + followingNode = child; + right = middle; + continue; + } + /* istanbul ignore next */ + + + throw new Error("Comment location overlaps with node location"); + } // We don't want comments inside of different expressions inside of the same + // template literal to move to another expression. + + + if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") { + var quasis = comment.enclosingNode.quasis; + var commentIndex = findExpressionIndexForComment(quasis, comment, options); + + if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) { + precedingNode = null; + } + + if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) { + followingNode = null; + } + } + + if (precedingNode) { + comment.precedingNode = precedingNode; + } + + if (followingNode) { + comment.followingNode = followingNode; + } +} + +function attach(comments, ast, text, options) { + if (!Array.isArray(comments)) { + return; + } + + var tiesToBreak = []; + var locStart = options.locStart, + locEnd = options.locEnd; + comments.forEach(function (comment, i) { + if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") { + if (locStart(comment) - locStart(ast) <= 0) { + addLeadingComment(ast, comment); + return; + } + + if (locEnd(comment) - locEnd(ast) >= 0) { + addTrailingComment(ast, comment); + return; + } + } + + decorateComment(ast, comment, options); + var precedingNode = comment.precedingNode, + enclosingNode = comment.enclosingNode, + followingNode = comment.followingNode; + var pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : function () { + return false; + }; + var pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : function () { + return false; + }; + var pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : function () { + return false; + }; + var isLastComment = comments.length - 1 === i; + + if (hasNewline(text, locStart(comment), { + backwards: true + })) { + // If a comment exists on its own line, prefer a leading comment. + // We also need to check if it's the first line of the file. + if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) {// We're good + } else if (followingNode) { + // Always a leading comment. + addLeadingComment(followingNode, comment); + } else if (precedingNode) { + addTrailingComment(precedingNode, comment); + } else if (enclosingNode) { + addDanglingComment(enclosingNode, comment); + } else { + // There are no nodes, let's attach it to the root of the ast + + /* istanbul ignore next */ + addDanglingComment(ast, comment); + } + } else if (hasNewline(text, locEnd(comment))) { + if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) {// We're good + } else if (precedingNode) { + // There is content before this comment on the same line, but + // none after it, so prefer a trailing comment of the previous node. + addTrailingComment(precedingNode, comment); + } else if (followingNode) { + addLeadingComment(followingNode, comment); + } else if (enclosingNode) { + addDanglingComment(enclosingNode, comment); + } else { + // There are no nodes, let's attach it to the root of the ast + + /* istanbul ignore next */ + addDanglingComment(ast, comment); + } + } else { + if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) {// We're good + } else if (precedingNode && followingNode) { + // Otherwise, text exists both before and after the comment on + // the same line. If there is both a preceding and following + // node, use a tie-breaking algorithm to determine if it should + // be attached to the next or previous node. In the last case, + // simply attach the right node; + var tieCount = tiesToBreak.length; + + if (tieCount > 0) { + var lastTie = tiesToBreak[tieCount - 1]; + + if (lastTie.followingNode !== comment.followingNode) { + breakTies(tiesToBreak, text, options); + } + } + + tiesToBreak.push(comment); + } else if (precedingNode) { + addTrailingComment(precedingNode, comment); + } else if (followingNode) { + addLeadingComment(followingNode, comment); + } else if (enclosingNode) { + addDanglingComment(enclosingNode, comment); + } else { + // There are no nodes, let's attach it to the root of the ast + + /* istanbul ignore next */ + addDanglingComment(ast, comment); + } + } + }); + breakTies(tiesToBreak, text, options); + comments.forEach(function (comment) { + // These node references were useful for breaking ties, but we + // don't need them anymore, and they create cycles in the AST that + // may lead to infinite recursion if we don't delete them here. + delete comment.precedingNode; + delete comment.enclosingNode; + delete comment.followingNode; + }); +} + +function breakTies(tiesToBreak, text, options) { + var tieCount = tiesToBreak.length; + + if (tieCount === 0) { + return; + } + + var _tiesToBreak$ = tiesToBreak[0], + precedingNode = _tiesToBreak$.precedingNode, + followingNode = _tiesToBreak$.followingNode; + var gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps + // between the tied comments. In order to qualify as leading, a + // comment must be separated from followingNode by an unbroken series of + // gaps (or other comments). Gaps should only contain whitespace or open + // parentheses. + + var indexOfFirstLeadingComment; + + for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) { + var comment = tiesToBreak[indexOfFirstLeadingComment - 1]; + assert$3.strictEqual(comment.precedingNode, precedingNode); + assert$3.strictEqual(comment.followingNode, followingNode); + var gap = text.slice(options.locEnd(comment), gapEndPos).trim(); + + if (gap === "" || /^\(+$/.test(gap)) { + gapEndPos = options.locStart(comment); + } else { + // The gap string contained something other than whitespace or open + // parentheses. + break; + } + } + + tiesToBreak.forEach(function (comment, i) { + if (i < indexOfFirstLeadingComment) { + addTrailingComment(precedingNode, comment); + } else { + addLeadingComment(followingNode, comment); + } + }); + tiesToBreak.length = 0; +} + +function printComment(commentPath, options) { + var comment = commentPath.getValue(); + comment.printed = true; + return options.printer.printComment(commentPath, options); +} + +function findExpressionIndexForComment(quasis, comment, options) { + var startPos = options.locStart(comment) - 1; + + for (var i = 1; i < quasis.length; ++i) { + if (startPos < getQuasiRange(quasis[i]).start) { + return i - 1; + } + } // We haven't found it, it probably means that some of the locations are off. + // Let's just return the first one. + + /* istanbul ignore next */ + + + return 0; +} + +function getQuasiRange(expr) { + if (expr.start !== undefined) { + // Babel + return { + start: expr.start, + end: expr.end + }; + } // Flow + + + return { + start: expr.range[0], + end: expr.range[1] + }; +} + +function printLeadingComment(commentPath, print, options) { + var comment = commentPath.getValue(); + var contents = printComment(commentPath, options); + + if (!contents) { + return ""; + } + + var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the + // same line or not. + + if (isBlock) { + return concat([contents, hasNewline(options.originalText, options.locEnd(comment)) ? hardline : " "]); + } + + return concat([contents, hardline]); +} + +function printTrailingComment(commentPath, print, options) { + var comment = commentPath.getValue(); + var contents = printComment(commentPath, options); + + if (!contents) { + return ""; + } + + var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break + // when the parentParentNode is a ClassDeclaration/-Expression + // And the parentNode is in the superClass property + + var parentNode = commentPath.getNode(1); + var parentParentNode = commentPath.getNode(2); + var isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode; + + if (hasNewline(options.originalText, options.locStart(comment), { + backwards: true + })) { + // This allows comments at the end of nested structures: + // { + // x: 1, + // y: 2 + // // A comment + // } + // Those kinds of comments are almost always leading comments, but + // here it doesn't go "outside" the block and turns it into a + // trailing comment for `2`. We can simulate the above by checking + // if this a comment on its own line; normal trailing comments are + // always at the end of another expression. + var isLineBeforeEmpty = isPreviousLineEmpty(options.originalText, comment, options.locStart); + return lineSuffix(concat([hardline, isLineBeforeEmpty ? hardline : "", contents])); + } else if (isBlock || isParentSuperClass) { + // Trailing block comments never need a newline + return concat([" ", contents]); + } + + return concat([lineSuffix(" " + contents), !isBlock ? breakParent : ""]); +} + +function printDanglingComments(path, options, sameIndent, filter) { + var parts = []; + var node = path.getValue(); + + if (!node || !node.comments) { + return ""; + } + + path.each(function (commentPath) { + var comment = commentPath.getValue(); + + if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) { + parts.push(printComment(commentPath, options)); + } + }, "comments"); + + if (parts.length === 0) { + return ""; + } + + if (sameIndent) { + return join(hardline, parts); + } + + return indent(concat([hardline, join(hardline, parts)])); +} + +function prependCursorPlaceholder(path, options, printed) { + if (path.getNode() === options.cursorNode && path.getValue()) { + return concat([cursor, printed, cursor]); + } + + return printed; +} + +function printComments(path, print, options, needsSemi) { + var value = path.getValue(); + var printed = print(path); + var comments = value && value.comments; + + if (!comments || comments.length === 0) { + return prependCursorPlaceholder(path, options, printed); + } + + var leadingParts = []; + var trailingParts = [needsSemi ? ";" : "", printed]; + path.each(function (commentPath) { + var comment = commentPath.getValue(); + var leading = comment.leading, + trailing = comment.trailing; + + if (leading) { + var contents = printLeadingComment(commentPath, print, options); + + if (!contents) { + return; + } + + leadingParts.push(contents); + var text = options.originalText; + + if (hasNewline(text, skipNewline(text, options.locEnd(comment)))) { + leadingParts.push(hardline); + } + } else if (trailing) { + trailingParts.push(printTrailingComment(commentPath, print, options)); + } + }, "comments"); + return prependCursorPlaceholder(path, options, concat(leadingParts.concat(trailingParts))); +} + +var comments = { + attach: attach, + printComments: printComments, + printDanglingComments: printDanglingComments, + getSortedChildNodes: getSortedChildNodes +}; + +function FastPath(value) { + assert$3.ok(this instanceof FastPath); + this.stack = [value]; +} // The name of the current property is always the penultimate element of +// this.stack, and always a String. + + +FastPath.prototype.getName = function getName() { + var s = this.stack; + var len = s.length; + + if (len > 1) { + return s[len - 2]; + } // Since the name is always a string, null is a safe sentinel value to + // return if we do not know the name of the (root) value. + + /* istanbul ignore next */ + + + return null; +}; // The value of the current property is always the final element of +// this.stack. + + +FastPath.prototype.getValue = function getValue() { + var s = this.stack; + return s[s.length - 1]; +}; + +function getNodeHelper(path, count) { + var stackIndex = getNodeStackIndexHelper(path.stack, count); + return stackIndex === -1 ? null : path.stack[stackIndex]; +} + +function getNodeStackIndexHelper(stack, count) { + for (var i = stack.length - 1; i >= 0; i -= 2) { + var value = stack[i]; + + if (value && !Array.isArray(value) && --count < 0) { + return i; + } + } + + return -1; +} + +FastPath.prototype.getNode = function getNode(count) { + return getNodeHelper(this, ~~count); +}; + +FastPath.prototype.getParentNode = function getParentNode(count) { + return getNodeHelper(this, ~~count + 1); +}; // Temporarily push properties named by string arguments given after the +// callback function onto this.stack, then call the callback with a +// reference to this (modified) FastPath object. Note that the stack will +// be restored to its original state after the callback is finished, so it +// is probably a mistake to retain a reference to the path. + + +FastPath.prototype.call = function call(callback +/*, name1, name2, ... */ +) { + var s = this.stack; + var origLen = s.length; + var value = s[origLen - 1]; + var argc = arguments.length; + + for (var i = 1; i < argc; ++i) { + var name = arguments[i]; + value = value[name]; + s.push(name, value); + } + + var result = callback(this); + s.length = origLen; + return result; +}; + +FastPath.prototype.callParent = function callParent(callback, count) { + var stackIndex = getNodeStackIndexHelper(this.stack, ~~count + 1); + var parentValues = this.stack.splice(stackIndex + 1); + var result = callback(this); + Array.prototype.push.apply(this.stack, parentValues); + return result; +}; // Similar to FastPath.prototype.call, except that the value obtained by +// accessing this.getValue()[name1][name2]... should be array-like. The +// callback will be called with a reference to this path object for each +// element of the array. + + +FastPath.prototype.each = function each(callback +/*, name1, name2, ... */ +) { + var s = this.stack; + var origLen = s.length; + var value = s[origLen - 1]; + var argc = arguments.length; + + for (var i = 1; i < argc; ++i) { + var name = arguments[i]; + value = value[name]; + s.push(name, value); + } + + for (var _i = 0; _i < value.length; ++_i) { + if (_i in value) { + s.push(_i, value[_i]); // If the callback needs to know the value of i, call + // path.getName(), assuming path is the parameter name. + + callback(this); + s.length -= 2; + } + } + + s.length = origLen; +}; // Similar to FastPath.prototype.each, except that the results of the +// callback function invocations are stored in an array and returned at +// the end of the iteration. + + +FastPath.prototype.map = function map(callback +/*, name1, name2, ... */ +) { + var s = this.stack; + var origLen = s.length; + var value = s[origLen - 1]; + var argc = arguments.length; + + for (var i = 1; i < argc; ++i) { + var name = arguments[i]; + value = value[name]; + s.push(name, value); + } + + var result = new Array(value.length); + + for (var _i2 = 0; _i2 < value.length; ++_i2) { + if (_i2 in value) { + s.push(_i2, value[_i2]); + result[_i2] = callback(this, _i2); + s.length -= 2; + } + } + + s.length = origLen; + return result; +}; + +var fastPath = FastPath; + +var normalize$3 = options.normalize; + +function printSubtree(path, print, options$$1, printAstToDoc) { + if (options$$1.printer.embed) { + return options$$1.printer.embed(path, print, function (text, partialNextOptions) { + return textToDoc(text, partialNextOptions, options$$1, printAstToDoc); + }, options$$1); + } +} + +function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) { + var nextOptions = normalize$3(Object.assign({}, parentOptions, partialNextOptions, { + parentParser: parentOptions.parser, + originalText: text + }), { + passThrough: true + }); + var result = parser.parse(text, nextOptions); + var ast = result.ast; + text = result.text; + var astComments = ast.comments; + delete ast.comments; + comments.attach(astComments, ast, text, nextOptions); + return printAstToDoc(ast, nextOptions); +} + +var multiparser = { + printSubtree: printSubtree +}; + +var doc$2 = doc; +var docBuilders$2 = doc$2.builders; +var concat$3 = docBuilders$2.concat; +var hardline$2 = docBuilders$2.hardline; +var addAlignmentToDoc$1 = docBuilders$2.addAlignmentToDoc; +var docUtils$2 = doc$2.utils; +/** + * Takes an abstract syntax tree (AST) and recursively converts it to a + * document (series of printing primitives). + * + * This is done by descending down the AST recursively. The recursion + * involves two functions that call each other: + * + * 1. printGenerically(), which is defined as an inner function here. + * It basically takes care of node caching. + * 2. callPluginPrintFunction(), which checks for some options, and + * ultimately calls the print() function provided by the plugin. + * + * The plugin function will call printGenerically() again for child nodes + * of the current node, which will do its housekeeping, then call the + * plugin function again, and so on. + * + * All the while, these functions pass a "path" variable around, which + * is a stack-like data structure (FastPath) that maintains the current + * state of the recursion. It is called "path", because it represents + * the path to the current node through the Abstract Syntax Tree. + */ + +function printAstToDoc(ast, options) { + var alignmentSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var printer = options.printer; + + if (printer.preprocess) { + ast = printer.preprocess(ast, options); + } + + var cache = new Map(); + + function printGenerically(path, args) { + var node = path.getValue(); + var shouldCache = node && _typeof(node) === "object" && args === undefined; + + if (shouldCache && cache.has(node)) { + return cache.get(node); + } // We let JSXElement print its comments itself because it adds () around + // UnionTypeAnnotation has to align the child without the comments + + + var res; + + if (printer.willPrintOwnComments && printer.willPrintOwnComments(path)) { + res = callPluginPrintFunction(path, options, printGenerically, args); + } else { + // printComments will call the plugin print function and check for + // comments to print + res = comments.printComments(path, function (p) { + return callPluginPrintFunction(p, options, printGenerically, args); + }, options, args && args.needsSemi); + } + + if (shouldCache) { + cache.set(node, res); + } + + return res; + } + + var doc$$2 = printGenerically(new fastPath(ast)); + + if (alignmentSize > 0) { + // Add a hardline to make the indents take effect + // It should be removed in index.js format() + doc$$2 = addAlignmentToDoc$1(concat$3([hardline$2, doc$$2]), alignmentSize, options.tabWidth); + } + + docUtils$2.propagateBreaks(doc$$2); + return doc$$2; +} + +function callPluginPrintFunction(path, options, printPath, args) { + assert$3.ok(path instanceof fastPath); + var node = path.getValue(); + var printer = options.printer; // Escape hatch + + if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) { + return options.originalText.slice(options.locStart(node), options.locEnd(node)); + } + + if (node) { + try { + // Potentially switch to a different parser + var sub = multiparser.printSubtree(path, printPath, options, printAstToDoc); + + if (sub) { + return sub; + } + } catch (error) { + /* istanbul ignore if */ + if (commonjsGlobal.PRETTIER_DEBUG) { + throw error; + } // Continue with current parser + + } + } + + return printer.print(path, options, printPath, args); +} + +var astToDoc = printAstToDoc; + +function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { + var resultStartNode = startNodeAndParents.node; + var resultEndNode = endNodeAndParents.node; + + if (resultStartNode === resultEndNode) { + return { + startNode: resultStartNode, + endNode: resultEndNode + }; + } + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = endNodeAndParents.parentNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var endParent = _step.value; + + if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) { + resultEndNode = endParent; + } else { + break; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = startNodeAndParents.parentNodes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var startParent = _step2.value; + + if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) { + resultStartNode = startParent; + } else { + break; + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return { + startNode: resultStartNode, + endNode: resultEndNode + }; +} + +function findNodeAtOffset(node, offset, options, predicate, parentNodes) { + predicate = predicate || function () { + return true; + }; + + parentNodes = parentNodes || []; + var start = options.locStart(node, options.locStart); + var end = options.locEnd(node, options.locEnd); + + if (start <= offset && offset <= end) { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = comments.getSortedChildNodes(node, options)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var childNode = _step3.value; + var childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes)); + + if (childResult) { + return childResult; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + if (predicate(node)) { + return { + node: node, + parentNodes: parentNodes + }; + } + } +} // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 + + +function isSourceElement(opts, node) { + if (node == null) { + return false; + } // JS and JS like to avoid repetitions + + + var jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015 + "ImportDeclaration", // Module + "ExportDefaultDeclaration", // Module + "ExportNamedDeclaration", // Module + "ExportAllDeclaration", // Module + "TypeAlias", // Flow + "InterfaceDeclaration", // Flow, TypeScript + "TypeAliasDeclaration", // TypeScript + "ExportAssignment", // TypeScript + "ExportDeclaration" // TypeScript + ]; + var jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"]; + var graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"]; + + switch (opts.parser) { + case "flow": + case "babel": + case "typescript": + return jsSourceElements.indexOf(node.type) > -1; + + case "json": + return jsonSourceElements.indexOf(node.type) > -1; + + case "graphql": + return graphqlSourceElements.indexOf(node.kind) > -1; + + case "vue": + return node.tag !== "root"; + } + + return false; +} + +function calculateRange(text, opts, ast) { + // Contract the range so that it has non-whitespace characters at its endpoints. + // This ensures we can format a range that doesn't end on a node. + var rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd); + var startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart); + var endNonWhitespace; + + for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) { + if (text[endNonWhitespace - 1].match(/\S/)) { + break; + } + } + + var startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, function (node) { + return isSourceElement(opts, node); + }); + var endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, function (node) { + return isSourceElement(opts, node); + }); + + if (!startNodeAndParents || !endNodeAndParents) { + return { + rangeStart: 0, + rangeEnd: 0 + }; + } + + var siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts); + var startNode = siblingAncestors.startNode, + endNode = siblingAncestors.endNode; + var rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart)); + var rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd)); + return { + rangeStart: rangeStart, + rangeEnd: rangeEnd + }; +} + +var rangeUtil = { + calculateRange: calculateRange, + findNodeAtOffset: findNodeAtOffset +}; + +var normalizeOptions = options.normalize; +var guessEndOfLine = endOfLine.guessEndOfLine; +var convertEndOfLineToChars = endOfLine.convertEndOfLineToChars; +var mapDoc = doc.utils.mapDoc; +var _printDocToString = doc.printer.printDocToString; +var printDocToDebug = doc.debug.printDocToDebug; +var UTF8BOM = 0xfeff; +var CURSOR = Symbol("cursor"); +var PLACEHOLDERS = { + cursorOffset: "<<>>", + rangeStart: "<<>>", + rangeEnd: "<<>>" +}; + +function ensureAllCommentsPrinted(astComments) { + if (!astComments) { + return; + } + + for (var i = 0; i < astComments.length; ++i) { + if (astComments[i].value.trim() === "prettier-ignore") { + // If there's a prettier-ignore, we're not printing that sub-tree so we + // don't know if the comments was printed or not. + return; + } + } + + astComments.forEach(function (comment) { + if (!comment.printed) { + throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!'); + } + + delete comment.printed; + }); +} + +function attachComments(text, ast, opts) { + var astComments = ast.comments; + + if (astComments) { + delete ast.comments; + comments.attach(astComments, ast, text, opts); + } + + ast.tokens = []; + opts.originalText = opts.parser === "yaml" ? text : text.trimRight(); + return astComments; +} + +function coreFormat(text, opts, addAlignmentSize) { + if (!text || !text.trim().length) { + return { + formatted: "", + cursorOffset: 0 + }; + } + + addAlignmentSize = addAlignmentSize || 0; + var parsed = parser.parse(text, opts); + var ast = parsed.ast; + text = parsed.text; + + if (opts.cursorOffset >= 0) { + var nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts); + + if (nodeResult && nodeResult.node) { + opts.cursorNode = nodeResult.node; + } + } + + var astComments = attachComments(text, ast, opts); + var doc$$1 = astToDoc(ast, opts, addAlignmentSize); + var eol = convertEndOfLineToChars(opts.endOfLine); + + var result = _printDocToString(opts.endOfLine === "lf" ? doc$$1 : mapDoc(doc$$1, function (currentDoc) { + return typeof currentDoc === "string" && currentDoc.indexOf("\n") !== -1 ? currentDoc.replace(/\n/g, eol) : currentDoc; + }), opts); + + ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline + + if (addAlignmentSize > 0) { + var trimmed = result.formatted.trim(); + + if (result.cursorNodeStart !== undefined) { + result.cursorNodeStart -= result.formatted.indexOf(trimmed); + } + + result.formatted = trimmed + convertEndOfLineToChars(opts.endOfLine); + } + + if (opts.cursorOffset >= 0) { + var oldCursorNodeStart; + var oldCursorNodeText; + var cursorOffsetRelativeToOldCursorNode; + var newCursorNodeStart; + var newCursorNodeText; + + if (opts.cursorNode && result.cursorNodeText) { + oldCursorNodeStart = opts.locStart(opts.cursorNode); + oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode)); + cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart; + newCursorNodeStart = result.cursorNodeStart; + newCursorNodeText = result.cursorNodeText; + } else { + oldCursorNodeStart = 0; + oldCursorNodeText = text; + cursorOffsetRelativeToOldCursorNode = opts.cursorOffset; + newCursorNodeStart = 0; + newCursorNodeText = result.formatted; + } + + if (oldCursorNodeText === newCursorNodeText) { + return { + formatted: result.formatted, + cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode + }; + } // diff old and new cursor node texts, with a special cursor + // symbol inserted to find out where it moves to + + + var oldCursorNodeCharArray = oldCursorNodeText.split(""); + oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR); + var newCursorNodeCharArray = newCursorNodeText.split(""); + var cursorNodeDiff = lib.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray); + var cursorOffset = newCursorNodeStart; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = cursorNodeDiff[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var entry = _step.value; + + if (entry.removed) { + if (entry.value.indexOf(CURSOR) > -1) { + break; + } + } else { + cursorOffset += entry.count; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return { + formatted: result.formatted, + cursorOffset: cursorOffset + }; + } + + return { + formatted: result.formatted + }; +} + +function formatRange(text, opts) { + var parsed = parser.parse(text, opts); + var ast = parsed.ast; + text = parsed.text; + var range = rangeUtil.calculateRange(text, opts, ast); + var rangeStart = range.rangeStart; + var rangeEnd = range.rangeEnd; + var rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. + // This is so we can detect indentation correctly and restore it. + // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 + + var rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1); + var indentString = text.slice(rangeStart2, rangeStart); + var alignmentSize = util.getAlignmentSize(indentString, opts.tabWidth); + var rangeResult = coreFormat(rangeString, Object.assign({}, opts, { + rangeStart: 0, + rangeEnd: Infinity, + printWidth: opts.printWidth - alignmentSize, + // track the cursor offset only if it's within our range + cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1 + }), alignmentSize); // Since the range contracts to avoid trailing whitespace, + // we need to remove the newline that was inserted by the `format` call. + + var rangeTrimmed = rangeResult.formatted.trimRight(); + var rangeLeft = text.slice(0, rangeStart); + var rangeRight = text.slice(rangeEnd); + var cursorOffset = opts.cursorOffset; + + if (opts.cursorOffset >= rangeEnd) { + // handle the case where the cursor was past the end of the range + cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length); + } else if (rangeResult.cursorOffset !== undefined) { + // handle the case where the cursor was in the range + cursorOffset = rangeResult.cursorOffset + rangeStart; + } // keep the cursor as it was if it was before the start of the range + + + var formatted; + + if (opts.endOfLine === "lf") { + formatted = rangeLeft + rangeTrimmed + rangeRight; + } else { + var eol = convertEndOfLineToChars(opts.endOfLine); + + if (cursorOffset >= 0) { + var parts = [rangeLeft, rangeTrimmed, rangeRight]; + var partIndex = 0; + var partOffset = cursorOffset; + + while (partIndex < parts.length) { + var part = parts[partIndex]; + + if (partOffset < part.length) { + parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset); + break; + } + + partIndex++; + partOffset -= part.length; + } + + var newRangeLeft = parts[0], + newRangeTrimmed = parts[1], + newRangeRight = parts[2]; + formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, function (_, index) { + cursorOffset = index; + return ""; + }); + } else { + formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol); + } + } + + return { + formatted: formatted, + cursorOffset: cursorOffset + }; +} + +function format(text, opts) { + var selectedParser = parser.resolveParser(opts); + var hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text); + + if (opts.requirePragma && !hasPragma) { + return { + formatted: text + }; + } + + if (opts.endOfLine === "auto") { + opts.endOfLine = guessEndOfLine(text); + } + + var hasCursor = opts.cursorOffset >= 0; + var hasRangeStart = opts.rangeStart > 0; + var hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing + + if (text.indexOf("\r") !== -1) { + var offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort(function (aKey, bKey) { + return opts[aKey] - opts[bKey]; + }); + + for (var i = offsetKeys.length - 1; i >= 0; i--) { + var key = offsetKeys[i]; + text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]); + } + + text = text.replace(/\r\n?/g, "\n"); + + var _loop = function _loop(_i) { + var key = offsetKeys[_i]; + text = text.replace(PLACEHOLDERS[key], function (_, index) { + opts[key] = index; + return ""; + }); + }; + + for (var _i = 0; _i < offsetKeys.length; _i++) { + _loop(_i); + } + } + + var hasUnicodeBOM = text.charCodeAt(0) === UTF8BOM; + + if (hasUnicodeBOM) { + text = text.substring(1); + + if (hasCursor) { + opts.cursorOffset++; + } + + if (hasRangeStart) { + opts.rangeStart++; + } + + if (hasRangeEnd) { + opts.rangeEnd++; + } + } + + if (!hasCursor) { + opts.cursorOffset = -1; + } + + if (opts.rangeStart < 0) { + opts.rangeStart = 0; + } + + if (opts.rangeEnd > text.length) { + opts.rangeEnd = text.length; + } + + var result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts); + + if (hasUnicodeBOM) { + result.formatted = String.fromCharCode(UTF8BOM) + result.formatted; + + if (hasCursor) { + result.cursorOffset++; + } + } + + return result; +} + +var core = { + formatWithCursor: function formatWithCursor(text, opts) { + opts = normalizeOptions(opts); + return format(text, opts); + }, + parse: function parse(text, opts, massage) { + opts = normalizeOptions(opts); + + if (text.indexOf("\r") !== -1) { + text = text.replace(/\r\n?/g, "\n"); + } + + var parsed = parser.parse(text, opts); + + if (massage) { + parsed.ast = massageAst(parsed.ast, opts); + } + + return parsed; + }, + formatAST: function formatAST(ast, opts) { + opts = normalizeOptions(opts); + var doc$$1 = astToDoc(ast, opts); + return _printDocToString(doc$$1, opts); + }, + // Doesn't handle shebang for now + formatDoc: function formatDoc(doc$$1, opts) { + var debug = printDocToDebug(doc$$1); + opts = normalizeOptions(Object.assign({}, opts, { + parser: "babel" + })); + return format(debug, opts).formatted; + }, + printToDoc: function printToDoc(text, opts) { + opts = normalizeOptions(opts); + var parsed = parser.parse(text, opts); + var ast = parsed.ast; + text = parsed.text; + attachComments(text, ast, opts); + return astToDoc(ast, opts); + }, + printDocToString: function printDocToString(doc$$1, opts) { + return _printDocToString(doc$$1, normalizeOptions(opts)); + } +}; + +var index$11 = ["a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "bgsound", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", "content", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "image", "img", "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li", "link", "listing", "main", "map", "mark", "marquee", "math", "menu", "menuitem", "meta", "meter", "multicol", "nav", "nextid", "nobr", "noembed", "noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "plaintext", "pre", "progress", "q", "rb", "rbc", "rp", "rt", "rtc", "ruby", "s", "samp", "script", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "svg", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr", "xmp"]; + +var htmlTagNames = Object.freeze({ + default: index$11 +}); + +var htmlTagNames$1 = ( htmlTagNames && index$11 ) || htmlTagNames; + +function clean(ast, newObj, parent) { + ["raw", // front-matter + "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(function (name) { + delete newObj[name]; + }); + + if (ast.type === "yaml") { + delete newObj.value; + } // --insert-pragma + + + if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment + parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) { + /** + * something + * + * @format + */ + delete newObj.text; // standalone pragma + + if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) { + return null; + } + } + + if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") { + delete newObj.value; + } + + if (ast.type === "css-rule") { + delete newObj.params; + } + + if (ast.type === "selector-combinator") { + newObj.value = newObj.value.replace(/\s+/g, " "); + } + + if (ast.type === "media-feature") { + newObj.value = newObj.value.replace(/ /g, ""); + } + + if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].indexOf(newObj.value.replace().toLowerCase()) !== -1) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") { + newObj.value = newObj.value.toLowerCase(); + } + + if (ast.type === "css-decl") { + newObj.prop = newObj.prop.toLowerCase(); + } + + if (ast.type === "css-atrule" || ast.type === "css-import") { + newObj.name = newObj.name.toLowerCase(); + } + + if (ast.type === "value-number") { + newObj.unit = newObj.unit.toLowerCase(); + } + + if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) { + newObj.value = cleanCSSStrings(newObj.value); + } + + if (ast.type === "selector-attribute") { + newObj.attribute = newObj.attribute.trim(); + + if (newObj.namespace) { + if (typeof newObj.namespace === "string") { + newObj.namespace = newObj.namespace.trim(); + + if (newObj.namespace.length === 0) { + newObj.namespace = true; + } + } + } + + if (newObj.value) { + newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, ""); + delete newObj.quoted; + } + } + + if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) { + newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, function (match, numStr, unit) { + var num = Number(numStr); + return isNaN(num) ? match : num + unit.toLowerCase(); + }); + } + + if (ast.type === "selector-tag") { + var lowercasedValue = ast.value.toLowerCase(); + + if (htmlTagNames$1.indexOf(lowercasedValue) !== -1) { + newObj.value = lowercasedValue; + } + + if (["from", "to"].indexOf(lowercasedValue) !== -1) { + newObj.value = lowercasedValue; + } + } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func` + + + if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") { + delete newObj.value; + } // Workaround for SCSS nested properties + + + if (ast.type === "selector-unknown") { + delete newObj.value; + } +} + +function cleanCSSStrings(value) { + return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1"); +} + +var clean_1 = clean; + +var _require$$0$builders$1 = doc.builders; +var hardline$4 = _require$$0$builders$1.hardline; +var literalline$1 = _require$$0$builders$1.literalline; +var concat$5 = _require$$0$builders$1.concat; +var markAsRoot$1 = _require$$0$builders$1.markAsRoot; +var mapDoc$3 = doc.utils.mapDoc; + +function embed(path, print, textToDoc +/*, options */ +) { + var node = path.getValue(); + + if (node.type === "yaml") { + return markAsRoot$1(concat$5(["---", hardline$4, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, { + parser: "yaml" + })) : "", "---", hardline$4])); + } + + return null; + + function replaceNewlinesWithLiterallines(doc$$2) { + return mapDoc$3(doc$$2, function (currentDoc) { + return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$5(currentDoc.split(/(\n)/g).map(function (v, i) { + return i % 2 === 0 ? v : literalline$1; + })) : currentDoc; + }); + } +} + +var embed_1 = embed; + +var detectNewline = createCommonjsModule(function (module) { + 'use strict'; + + module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + var newlines = str.match(/(?:\r?\n)/g) || []; + + if (newlines.length === 0) { + return null; + } + + var crlf = newlines.filter(function (el) { + return el === '\r\n'; + }).length; + var lf = newlines.length - crlf; + return crlf > lf ? '\r\n' : '\n'; + }; + + module.exports.graceful = function (str) { + return module.exports(str) || '\n'; + }; +}); + +var build$1 = createCommonjsModule(function (module, exports) { + 'use strict'; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.extract = extract; + exports.strip = strip; + exports.parse = parse; + exports.parseWithComments = parseWithComments; + exports.print = print; + + var _detectNewline; + + function _load_detectNewline() { + return _detectNewline = _interopRequireDefault(detectNewline); + } + + var _os; + + function _load_os() { + return _os = require$$1$1; + } + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + /** + * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + */ + + + var commentEndRe = /\*\/$/; + var commentStartRe = /^\/\*\*/; + var docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; + var lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g; + var ltrimNewlineRe = /^(\r?\n)+/; + var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g; + var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; + var stringStartRe = /(\r?\n|^) *\* ?/g; + + function extract(contents) { + var match = contents.match(docblockRe); + return match ? match[0].trimLeft() : ''; + } + + function strip(contents) { + var match = contents.match(docblockRe); + return match && match[0] ? contents.substring(match[0].length) : contents; + } + + function parse(docblock) { + return parseWithComments(docblock).pragmas; + } + + function parseWithComments(docblock) { + var line = (0, (_detectNewline || _load_detectNewline()).default)(docblock) || (_os || _load_os()).EOL; + + docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives + + var prev = ''; + + while (prev !== docblock) { + prev = docblock; + docblock = docblock.replace(multilineRe, "".concat(line, "$1 $2").concat(line)); + } + + docblock = docblock.replace(ltrimNewlineRe, '').trimRight(); + var result = Object.create(null); + var comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight(); + var match; + + while (match = propertyRe.exec(docblock)) { + // strip linecomments from pragmas + var nextPragma = match[2].replace(lineCommentRe, ''); + + if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) { + result[match[1]] = [].concat(result[match[1]], nextPragma); + } else { + result[match[1]] = nextPragma; + } + } + + return { + comments: comments, + pragmas: result + }; + } + + function print(_ref) { + var _ref$comments = _ref.comments; + var comments = _ref$comments === undefined ? '' : _ref$comments; + var _ref$pragmas = _ref.pragmas; + var pragmas = _ref$pragmas === undefined ? {} : _ref$pragmas; + + var line = (0, (_detectNewline || _load_detectNewline()).default)(comments) || (_os || _load_os()).EOL; + + var head = '/**'; + var start = ' *'; + var tail = ' */'; + var keys = Object.keys(pragmas); + var printedObject = keys.map(function (key) { + return printKeyValues(key, pragmas[key]); + }).reduce(function (arr, next) { + return arr.concat(next); + }, []).map(function (keyValue) { + return start + ' ' + keyValue + line; + }).join(''); + + if (!comments) { + if (keys.length === 0) { + return ''; + } + + if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) { + var value = pragmas[keys[0]]; + return "".concat(head, " ").concat(printKeyValues(keys[0], value)[0]).concat(tail); + } + } + + var printedComments = comments.split(line).map(function (textLine) { + return "".concat(start, " ").concat(textLine); + }).join(line) + line; + return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail; + } + + function printKeyValues(key, valueOrArray) { + return [].concat(valueOrArray).map(function (value) { + return "@".concat(key, " ").concat(value).trim(); + }); + } +}); +unwrapExports(build$1); + +function hasPragma$1(text) { + var pragmas = Object.keys(build$1.parse(build$1.extract(text))); + return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1; +} + +function insertPragma$2(text) { + var parsedDocblock = build$1.parseWithComments(build$1.extract(text)); + var pragmas = Object.assign({ + format: "" + }, parsedDocblock.pragmas); + var newDocblock = build$1.print({ + pragmas: pragmas, + comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines + + }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock) + + var strippedText = build$1.strip(text); + var separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n"; + return newDocblock + separatingNewlines + strippedText; +} + +var pragma$2 = { + hasPragma: hasPragma$1, + insertPragma: insertPragma$2 +}; + +var DELIMITER_MAP = { + "---": "yaml", + "+++": "toml" +}; + +function parse$3(text) { + var delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|"); + var match = text.match( // trailing spaces after delimiters are allowed + new RegExp("^(".concat(delimiterRegex, ")[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)"))); + + if (match === null) { + return { + frontMatter: null, + content: text + }; + } + + var raw = match[0].replace(/\n$/, ""); + var delimiter = match[1]; + var value = match[2]; + return { + frontMatter: { + type: DELIMITER_MAP[delimiter], + value: value, + raw: raw + }, + content: match[0].replace(/[^\n]/g, " ") + text.slice(match[0].length) + }; +} + +var frontMatter = parse$3; + +function hasPragma(text) { + return pragma$2.hasPragma(frontMatter(text).content); +} + +function insertPragma$1(text) { + var _parseFrontMatter = frontMatter(text), + frontMatter$$1 = _parseFrontMatter.frontMatter, + content = _parseFrontMatter.content; + + return (frontMatter$$1 ? frontMatter$$1.raw + "\n\n" : "") + pragma$2.insertPragma(content); +} + +var pragma = { + hasPragma: hasPragma, + insertPragma: insertPragma$1 +}; + +var colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"]; + +function getAncestorCounter(path, typeOrTypes) { + var types = [].concat(typeOrTypes); + var counter = -1; + var ancestorNode; + + while (ancestorNode = path.getParentNode(++counter)) { + if (types.indexOf(ancestorNode.type) !== -1) { + return counter; + } + } + + return -1; +} + +function getAncestorNode$1(path, typeOrTypes) { + var counter = getAncestorCounter(path, typeOrTypes); + return counter === -1 ? null : path.getParentNode(counter); +} + +function getPropOfDeclNode$1(path) { + var declAncestorNode = getAncestorNode$1(path, "css-decl"); + return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase(); +} + +function isSCSS$1(parser, text) { + var hasExplicitParserChoice = parser === "less" || parser === "scss"; + var IS_POSSIBLY_SCSS = /(\w\s*: [^}:]+|#){|@import[^\n]+(url|,)/; + return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text); +} + +function isWideKeywords$1(value) { + return ["initial", "inherit", "unset", "revert"].indexOf(value.toLowerCase()) !== -1; +} + +function isKeyframeAtRuleKeywords$1(path, value) { + var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); + return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].indexOf(value.toLowerCase()) !== -1; +} + +function maybeToLowerCase$1(value) { + return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase(); +} + +function insideValueFunctionNode$1(path, functionName) { + var funcAncestorNode = getAncestorNode$1(path, "value-func"); + return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName; +} + +function insideICSSRuleNode$1(path) { + var ruleAncestorNode = getAncestorNode$1(path, "css-rule"); + return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export")); +} + +function insideAtRuleNode$1(path, atRuleNameOrAtRuleNames) { + var atRuleNames = [].concat(atRuleNameOrAtRuleNames); + var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); + return atRuleAncestorNode && atRuleNames.indexOf(atRuleAncestorNode.name.toLowerCase()) !== -1; +} + +function insideURLFunctionInImportAtRuleNode$1(path) { + var node = path.getValue(); + var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); + return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2; +} + +function isURLFunctionNode$1(node) { + return node.type === "value-func" && node.value.toLowerCase() === "url"; +} + +function isLastNode$1(path, node) { + var parentNode = path.getParentNode(); + + if (!parentNode) { + return false; + } + + var nodes = parentNode.nodes; + return nodes && nodes.indexOf(node) === nodes.length - 1; +} + +function isHTMLTag$1(value) { + return htmlTagNames$1.indexOf(value.toLowerCase()) !== -1; +} + +function isDetachedRulesetDeclarationNode$1(node) { + // If a Less file ends up being parsed with the SCSS parser, Less + // variable declarations will be parsed as atrules with names ending + // with a colon, so keep the original case then. + if (!node.selector) { + return false; + } + + return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value); +} + +function isForKeywordNode$1(node) { + return node.type === "value-word" && ["from", "through", "end"].indexOf(node.value) !== -1; +} + +function isIfElseKeywordNode$1(node) { + return node.type === "value-word" && ["and", "or", "not"].indexOf(node.value) !== -1; +} + +function isEachKeywordNode$1(node) { + return node.type === "value-word" && node.value === "in"; +} + +function isMultiplicationNode$1(node) { + return node.type === "value-operator" && node.value === "*"; +} + +function isDivisionNode$1(node) { + return node.type === "value-operator" && node.value === "/"; +} + +function isAdditionNode$1(node) { + return node.type === "value-operator" && node.value === "+"; +} + +function isSubtractionNode$1(node) { + return node.type === "value-operator" && node.value === "-"; +} + +function isModuloNode(node) { + return node.type === "value-operator" && node.value === "%"; +} + +function isMathOperatorNode$1(node) { + return isMultiplicationNode$1(node) || isDivisionNode$1(node) || isAdditionNode$1(node) || isSubtractionNode$1(node) || isModuloNode(node); +} + +function isEqualityOperatorNode$1(node) { + return node.type === "value-word" && ["==", "!="].indexOf(node.value) !== -1; +} + +function isRelationalOperatorNode$1(node) { + return node.type === "value-word" && ["<", ">", "<=", ">="].indexOf(node.value) !== -1; +} + +function isSCSSControlDirectiveNode$1(node) { + return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].indexOf(node.name) !== -1; +} + +function isSCSSNestedPropertyNode(node) { + if (!node.selector) { + return false; + } + + return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":"); +} + +function isDetachedRulesetCallNode$1(node) { + return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params); +} + +function isTemplatePlaceholderNode$1(node) { + return node.name.startsWith("prettier-placeholder"); +} + +function isTemplatePropNode$1(node) { + return node.prop.startsWith("@prettier-placeholder"); +} + +function isPostcssSimpleVarNode$1(currentNode, nextNode) { + return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before; +} + +function hasComposesNode$1(node) { + return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes"; +} + +function hasParensAroundNode$1(node) { + return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null; +} + +function hasEmptyRawBefore$1(node) { + return node.raws && node.raws.before === ""; +} + +function isKeyValuePairNode$1(node) { + return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon"; +} + +function isKeyValuePairInParenGroupNode(node) { + return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode$1(node.groups[0]); +} + +function isSCSSMapItemNode$1(path) { + var node = path.getValue(); // Ignore empty item (i.e. `$key: ()`) + + if (node.groups.length === 0) { + return false; + } + + var parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`) + + if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) { + return false; + } + + var declNode = getAncestorNode$1(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`) + + if (declNode && declNode.prop && declNode.prop.startsWith("$")) { + return true; + } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`) + + + if (isKeyValuePairInParenGroupNode(parentParentNode)) { + return true; + } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`) + + + if (parentParentNode.type === "value-func") { + return true; + } + + return false; +} + +function isInlineValueCommentNode$1(node) { + return node.type === "value-comment" && node.inline; +} + +function isHashNode$1(node) { + return node.type === "value-word" && node.value === "#"; +} + +function isLeftCurlyBraceNode$1(node) { + return node.type === "value-word" && node.value === "{"; +} + +function isRightCurlyBraceNode$1(node) { + return node.type === "value-word" && node.value === "}"; +} + +function isWordNode$1(node) { + return ["value-word", "value-atword"].indexOf(node.type) !== -1; +} + +function isColonNode$1(node) { + return node.type === "value-colon"; +} + +function isMediaAndSupportsKeywords$1(node) { + return node.value && ["not", "and", "or"].indexOf(node.value.toLowerCase()) !== -1; +} + +function isColorAdjusterFuncNode$1(node) { + if (node.type !== "value-func") { + return false; + } + + return colorAdjusterFunctions.indexOf(node.value.toLowerCase()) !== -1; +} + +var utils$4 = { + getAncestorCounter: getAncestorCounter, + getAncestorNode: getAncestorNode$1, + getPropOfDeclNode: getPropOfDeclNode$1, + maybeToLowerCase: maybeToLowerCase$1, + insideValueFunctionNode: insideValueFunctionNode$1, + insideICSSRuleNode: insideICSSRuleNode$1, + insideAtRuleNode: insideAtRuleNode$1, + insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1, + isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1, + isHTMLTag: isHTMLTag$1, + isWideKeywords: isWideKeywords$1, + isSCSS: isSCSS$1, + isLastNode: isLastNode$1, + isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1, + isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1, + isRelationalOperatorNode: isRelationalOperatorNode$1, + isEqualityOperatorNode: isEqualityOperatorNode$1, + isMultiplicationNode: isMultiplicationNode$1, + isDivisionNode: isDivisionNode$1, + isAdditionNode: isAdditionNode$1, + isSubtractionNode: isSubtractionNode$1, + isModuloNode: isModuloNode, + isMathOperatorNode: isMathOperatorNode$1, + isEachKeywordNode: isEachKeywordNode$1, + isForKeywordNode: isForKeywordNode$1, + isURLFunctionNode: isURLFunctionNode$1, + isIfElseKeywordNode: isIfElseKeywordNode$1, + hasComposesNode: hasComposesNode$1, + hasParensAroundNode: hasParensAroundNode$1, + hasEmptyRawBefore: hasEmptyRawBefore$1, + isSCSSNestedPropertyNode: isSCSSNestedPropertyNode, + isDetachedRulesetCallNode: isDetachedRulesetCallNode$1, + isTemplatePlaceholderNode: isTemplatePlaceholderNode$1, + isTemplatePropNode: isTemplatePropNode$1, + isPostcssSimpleVarNode: isPostcssSimpleVarNode$1, + isKeyValuePairNode: isKeyValuePairNode$1, + isKeyValuePairInParenGroupNode: isKeyValuePairInParenGroupNode, + isSCSSMapItemNode: isSCSSMapItemNode$1, + isInlineValueCommentNode: isInlineValueCommentNode$1, + isHashNode: isHashNode$1, + isLeftCurlyBraceNode: isLeftCurlyBraceNode$1, + isRightCurlyBraceNode: isRightCurlyBraceNode$1, + isWordNode: isWordNode$1, + isColonNode: isColonNode$1, + isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1, + isColorAdjusterFuncNode: isColorAdjusterFuncNode$1 +}; + +var insertPragma = pragma.insertPragma; +var printNumber$1 = util.printNumber; +var printString$1 = util.printString; +var hasIgnoreComment$1 = util.hasIgnoreComment; +var hasNewline$2 = util.hasNewline; +var isNextLineEmpty$2 = utilShared.isNextLineEmpty; +var _require$$3$builders = doc.builders; +var concat$4 = _require$$3$builders.concat; +var join$2 = _require$$3$builders.join; +var line$3 = _require$$3$builders.line; +var hardline$3 = _require$$3$builders.hardline; +var softline$1 = _require$$3$builders.softline; +var group$1 = _require$$3$builders.group; +var fill$2 = _require$$3$builders.fill; +var indent$2 = _require$$3$builders.indent; +var dedent$2 = _require$$3$builders.dedent; +var ifBreak$1 = _require$$3$builders.ifBreak; +var removeLines$1 = doc.utils.removeLines; +var getAncestorNode = utils$4.getAncestorNode; +var getPropOfDeclNode = utils$4.getPropOfDeclNode; +var maybeToLowerCase = utils$4.maybeToLowerCase; +var insideValueFunctionNode = utils$4.insideValueFunctionNode; +var insideICSSRuleNode = utils$4.insideICSSRuleNode; +var insideAtRuleNode = utils$4.insideAtRuleNode; +var insideURLFunctionInImportAtRuleNode = utils$4.insideURLFunctionInImportAtRuleNode; +var isKeyframeAtRuleKeywords = utils$4.isKeyframeAtRuleKeywords; +var isHTMLTag = utils$4.isHTMLTag; +var isWideKeywords = utils$4.isWideKeywords; +var isSCSS = utils$4.isSCSS; +var isLastNode = utils$4.isLastNode; +var isSCSSControlDirectiveNode = utils$4.isSCSSControlDirectiveNode; +var isDetachedRulesetDeclarationNode = utils$4.isDetachedRulesetDeclarationNode; +var isRelationalOperatorNode = utils$4.isRelationalOperatorNode; +var isEqualityOperatorNode = utils$4.isEqualityOperatorNode; +var isMultiplicationNode = utils$4.isMultiplicationNode; +var isDivisionNode = utils$4.isDivisionNode; +var isAdditionNode = utils$4.isAdditionNode; +var isSubtractionNode = utils$4.isSubtractionNode; +var isMathOperatorNode = utils$4.isMathOperatorNode; +var isEachKeywordNode = utils$4.isEachKeywordNode; +var isForKeywordNode = utils$4.isForKeywordNode; +var isURLFunctionNode = utils$4.isURLFunctionNode; +var isIfElseKeywordNode = utils$4.isIfElseKeywordNode; +var hasComposesNode = utils$4.hasComposesNode; +var hasParensAroundNode = utils$4.hasParensAroundNode; +var hasEmptyRawBefore = utils$4.hasEmptyRawBefore; +var isKeyValuePairNode = utils$4.isKeyValuePairNode; +var isDetachedRulesetCallNode = utils$4.isDetachedRulesetCallNode; +var isTemplatePlaceholderNode = utils$4.isTemplatePlaceholderNode; +var isTemplatePropNode = utils$4.isTemplatePropNode; +var isPostcssSimpleVarNode = utils$4.isPostcssSimpleVarNode; +var isSCSSMapItemNode = utils$4.isSCSSMapItemNode; +var isInlineValueCommentNode = utils$4.isInlineValueCommentNode; +var isHashNode = utils$4.isHashNode; +var isLeftCurlyBraceNode = utils$4.isLeftCurlyBraceNode; +var isRightCurlyBraceNode = utils$4.isRightCurlyBraceNode; +var isWordNode = utils$4.isWordNode; +var isColonNode = utils$4.isColonNode; +var isMediaAndSupportsKeywords = utils$4.isMediaAndSupportsKeywords; +var isColorAdjusterFuncNode = utils$4.isColorAdjusterFuncNode; + +function shouldPrintComma(options) { + switch (options.trailingComma) { + case "all": + case "es5": + return true; + + case "none": + default: + return false; + } +} + +function genericPrint(path, options, print) { + var node = path.getValue(); + /* istanbul ignore if */ + + if (!node) { + return ""; + } + + if (typeof node === "string") { + return node; + } + + switch (node.type) { + case "yaml": + case "toml": + return concat$4([node.raw, hardline$3]); + + case "css-root": + { + var nodes = printNodeSequence(path, options, print); + + if (nodes.parts.length) { + return concat$4([nodes, hardline$3]); + } + + return nodes; + } + + case "css-comment": + { + if (node.raws.content) { + return node.raws.content; + } + + var text = options.originalText.slice(options.locStart(node), options.locEnd(node)); + var rawText = node.raws.text || node.text; // Workaround a bug where the location is off. + // https://github.com/postcss/postcss-scss/issues/63 + + if (text.indexOf(rawText) === -1) { + if (node.raws.inline) { + return concat$4(["// ", rawText]); + } + + return concat$4(["/* ", rawText, " */"]); + } + + return text; + } + + case "css-rule": + { + return concat$4([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$4([" {", node.nodes.length > 0 ? indent$2(concat$4([hardline$3, printNodeSequence(path, options, print)])) : "", hardline$3, "}", isDetachedRulesetDeclarationNode(node) ? ";" : ""]) : ";"]); + } + + case "css-decl": + { + var parentNode = path.getParentNode(); + return concat$4([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode(path) ? node.prop : maybeToLowerCase(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode(node) ? removeLines$1(path.call(print, "value")) : path.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$4([" {", indent$2(concat$4([softline$1, printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePropNode(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]); + } + + case "css-atrule": + { + var _parentNode = path.getParentNode(); + + return concat$4(["@", // If a Less file ends up being parsed with the SCSS parser, Less + // variable declarations will be parsed as at-rules with names ending + // with a colon, so keep the original case then. + isDetachedRulesetCallNode(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase(node.name), node.params ? concat$4([isDetachedRulesetCallNode(node) ? "" : isTemplatePlaceholderNode(node) && /^\s*\n/.test(node.raws.afterName) ? /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$4([hardline$3, hardline$3]) : hardline$3 : " ", path.call(print, "params")]) : "", node.selector ? indent$2(concat$4([" ", path.call(print, "selector")])) : "", node.value ? group$1(concat$4([" ", path.call(print, "value"), isSCSSControlDirectiveNode(node) ? hasParensAroundNode(node) ? " " : line$3 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$4([isSCSSControlDirectiveNode(node) ? "" : " ", "{", indent$2(concat$4([node.nodes.length > 0 ? softline$1 : "", printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePlaceholderNode(node) && !_parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]); + } + // postcss-media-query-parser + + case "media-query-list": + { + var parts = []; + path.each(function (childPath) { + var node = childPath.getValue(); + + if (node.type === "media-query" && node.value === "") { + return; + } + + parts.push(childPath.call(print)); + }, "nodes"); + return group$1(indent$2(join$2(line$3, parts))); + } + + case "media-query": + { + return concat$4([join$2(" ", path.map(print, "nodes")), isLastNode(path, node) ? "" : ","]); + } + + case "media-type": + { + return adjustNumbers(adjustStrings(node.value, options)); + } + + case "media-feature-expression": + { + if (!node.nodes) { + return node.value; + } + + return concat$4(["(", concat$4(path.map(print, "nodes")), ")"]); + } + + case "media-feature": + { + return maybeToLowerCase(adjustStrings(node.value.replace(/ +/g, " "), options)); + } + + case "media-colon": + { + return concat$4([node.value, " "]); + } + + case "media-value": + { + return adjustNumbers(adjustStrings(node.value, options)); + } + + case "media-keyword": + { + return adjustStrings(node.value, options); + } + + case "media-url": + { + return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options); + } + + case "media-unknown": + { + return node.value; + } + // postcss-selector-parser + + case "selector-root": + { + return group$1(concat$4([insideAtRuleNode(path, "custom-selector") ? concat$4([getAncestorNode(path, "css-atrule").customSelector, line$3]) : "", join$2(concat$4([",", insideAtRuleNode(path, ["extend", "custom-selector", "nest"]) ? line$3 : hardline$3]), path.map(print, "nodes"))])); + } + + case "selector-selector": + { + return group$1(indent$2(concat$4(path.map(print, "nodes")))); + } + + case "selector-comment": + { + return node.value; + } + + case "selector-string": + { + return adjustStrings(node.value, options); + } + + case "selector-tag": + { + var _parentNode2 = path.getParentNode(); + + var index = _parentNode2 && _parentNode2.nodes.indexOf(node); + + var prevNode = index && _parentNode2.nodes[index - 1]; + return concat$4([node.namespace ? concat$4([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isHTMLTag(node.value) || isKeyframeAtRuleKeywords(path, node.value) ? node.value.toLowerCase() : node.value)]); + } + + case "selector-id": + { + return concat$4(["#", node.value]); + } + + case "selector-class": + { + return concat$4([".", adjustNumbers(adjustStrings(node.value, options))]); + } + + case "selector-attribute": + { + return concat$4(["[", node.namespace ? concat$4([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]); + } + + case "selector-combinator": + { + if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") { + var _parentNode3 = path.getParentNode(); + + var _leading = _parentNode3.type === "selector-selector" && _parentNode3.nodes[0] === node ? "" : line$3; + + return concat$4([_leading, node.value, isLastNode(path, node) ? "" : " "]); + } + + var leading = node.value.trim().startsWith("(") ? line$3 : ""; + var value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$3; + return concat$4([leading, value]); + } + + case "selector-universal": + { + return concat$4([node.namespace ? concat$4([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]); + } + + case "selector-pseudo": + { + return concat$4([maybeToLowerCase(node.value), node.nodes && node.nodes.length > 0 ? concat$4(["(", join$2(", ", path.map(print, "nodes")), ")"]) : ""]); + } + + case "selector-nesting": + { + return node.value; + } + + case "selector-unknown": + { + var ruleAncestorNode = getAncestorNode(path, "css-rule"); // Nested SCSS property + + if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) { + return adjustNumbers(adjustStrings(maybeToLowerCase(node.value), options)); + } + + return node.value; + } + // postcss-values-parser + + case "value-value": + case "value-root": + { + return path.call(print, "group"); + } + + case "value-comment": + { + return concat$4([node.inline ? "//" : "/*", node.value, node.inline ? "" : "*/"]); + } + + case "value-comma_group": + { + var _parentNode4 = path.getParentNode(); + + var parentParentNode = path.getParentNode(1); + var declAncestorProp = getPropOfDeclNode(path); + var isGridValue = declAncestorProp && _parentNode4.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template")); + var atRuleAncestorNode = getAncestorNode(path, "css-atrule"); + var isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode(atRuleAncestorNode); + var printed = path.map(print, "groups"); + var _parts = []; + var insideURLFunction = insideValueFunctionNode(path, "url"); + var insideSCSSInterpolationInString = false; + var didBreak = false; + + for (var i = 0; i < node.groups.length; ++i) { + _parts.push(printed[i]); // Ignore value inside `url()` + + + if (insideURLFunction) { + continue; + } + + var iPrevNode = node.groups[i - 1]; + var iNode = node.groups[i]; + var iNextNode = node.groups[i + 1]; + var iNextNextNode = node.groups[i + 2]; // Ignore after latest node (i.e. before semicolon) + + if (!iNextNode) { + continue; + } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`) + + + var isStartSCSSinterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{"); + var isEndingSCSSinterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}"); + + if (isStartSCSSinterpolationInString || isEndingSCSSinterpolationInString) { + insideSCSSInterpolationInString = !insideSCSSInterpolationInString; + continue; + } + + if (insideSCSSInterpolationInString) { + continue; + } // Ignore colon (i.e. `:`) + + + if (isColonNode(iNode) || isColonNode(iNextNode)) { + continue; + } // Ignore `@` in Less (i.e. `@@var;`) + + + if (iNode.type === "value-atword" && iNode.value === "") { + continue; + } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`) + + + if (iNode.value === "~") { + continue; + } // Ignore escape `\` + + + if (iNode.value && iNode.value.indexOf("\\") !== -1 && iNextNode && iNextNode.type !== "value-comment") { + continue; + } // Ignore escaped `/` + + + if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") { + continue; + } // Ignore `\` (i.e. `$variable: \@small;`) + + + if (iNode.value === "\\") { + continue; + } // Ignore `$$` (i.e. `background-color: $$(style)Color;`) + + + if (isPostcssSimpleVarNode(iNode, iNextNode)) { + continue; + } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`) + + + if (isHashNode(iNode) || isLeftCurlyBraceNode(iNode) || isRightCurlyBraceNode(iNextNode) || isLeftCurlyBraceNode(iNextNode) && hasEmptyRawBefore(iNextNode) || isRightCurlyBraceNode(iNode) && hasEmptyRawBefore(iNextNode)) { + continue; + } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`) + + + if (iNode.value === "--" && isHashNode(iNextNode)) { + continue; + } // Formatting math operations + + + var isMathOperator = isMathOperatorNode(iNode); + var isNextMathOperator = isMathOperatorNode(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is + // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`) + // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`) + + if ((isMathOperator && isHashNode(iNextNode) || isNextMathOperator && isRightCurlyBraceNode(iNode)) && hasEmptyRawBefore(iNextNode)) { + continue; + } // Print spaces before and after addition and subtraction math operators as is in `calc` function + // due to the fact that it is not valid syntax + // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`) + + + if (insideValueFunctionNode(path, "calc") && (isAdditionNode(iNode) || isAdditionNode(iNextNode) || isSubtractionNode(iNode) || isSubtractionNode(iNextNode)) && hasEmptyRawBefore(iNextNode)) { + continue; + } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`) + // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is. + + + var isColorAdjusterNode = (isAdditionNode(iNode) || isSubtractionNode(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode(parentParentNode) && !hasEmptyRawBefore(iNextNode); + var requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode(iNextNextNode) || iNode.type === "value-func" || isWordNode(iNode); + var requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode(iPrevNode); // Formatting `/`, `+`, `-` sign + + if (!(isMultiplicationNode(iNextNode) || isMultiplicationNode(iNode)) && !insideValueFunctionNode(path, "calc") && !isColorAdjusterNode && (isDivisionNode(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode(iNode) && !requireSpaceAfterOperator || isAdditionNode(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode(iNode) && !requireSpaceAfterOperator || isSubtractionNode(iNextNode) || isSubtractionNode(iNode)) && (hasEmptyRawBefore(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode(iPrevNode)))) { + continue; + } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`) + + + if (isInlineValueCommentNode(iNode)) { + _parts.push(hardline$3); + + continue; + } // Handle keywords in SCSS control directive + + + if (isControlDirective && (isEqualityOperatorNode(iNextNode) || isRelationalOperatorNode(iNextNode) || isIfElseKeywordNode(iNextNode) || isEachKeywordNode(iNode) || isForKeywordNode(iNode))) { + _parts.push(" "); + + continue; + } // At-rule `namespace` should be in one line + + + if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") { + _parts.push(" "); + + continue; + } // Formatting `grid` property + + + if (isGridValue) { + if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) { + _parts.push(hardline$3); + + didBreak = true; + } else { + _parts.push(" "); + } + + continue; + } // Add `space` before next math operation + // Note: `grip` property have `/` delimiter and it is not math operation, so + // `grid` property handles above + + + if (isNextMathOperator) { + _parts.push(" "); + + continue; + } // Be default all values go through `line` + + + _parts.push(line$3); + } + + if (didBreak) { + _parts.unshift(hardline$3); + } + + if (isControlDirective) { + return group$1(indent$2(concat$4(_parts))); + } // Indent is not needed for import url when url is very long + // and node has two groups + // when type is value-comma_group + // example @import url("verylongurl") projection,tv + + + if (insideURLFunctionInImportAtRuleNode(path)) { + return group$1(fill$2(_parts)); + } + + return group$1(indent$2(fill$2(_parts))); + } + + case "value-paren_group": + { + var _parentNode5 = path.getParentNode(); + + if (_parentNode5 && isURLFunctionNode(_parentNode5) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) { + return concat$4([node.open ? path.call(print, "open") : "", join$2(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]); + } + + if (!node.open) { + var _printed = path.map(print, "groups"); + + var res = []; + + for (var _i = 0; _i < _printed.length; _i++) { + if (_i !== 0) { + res.push(concat$4([",", line$3])); + } + + res.push(_printed[_i]); + } + + return group$1(indent$2(fill$2(res))); + } + + var isSCSSMapItem = isSCSSMapItemNode(path); + return group$1(concat$4([node.open ? path.call(print, "open") : "", indent$2(concat$4([softline$1, join$2(concat$4([",", line$3]), path.map(function (childPath) { + var node = childPath.getValue(); + var printed = print(childPath); // Key/Value pair in open paren already indented + + if (isKeyValuePairNode(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") { + printed.contents.contents.parts[1] = group$1(printed.contents.contents.parts[1]); + return group$1(dedent$2(printed)); + } + + return printed; + }, "groups"))])), ifBreak$1(isSCSS(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma(options) ? "," : ""), softline$1, node.close ? path.call(print, "close") : ""]), { + shouldBreak: isSCSSMapItem + }); + } + + case "value-func": + { + return concat$4([node.value, insideAtRuleNode(path, "supports") && isMediaAndSupportsKeywords(node) ? " " : "", path.call(print, "group")]); + } + + case "value-paren": + { + return node.value; + } + + case "value-number": + { + return concat$4([printCssNumber(node.value), maybeToLowerCase(node.unit)]); + } + + case "value-operator": + { + return node.value; + } + + case "value-word": + { + if (node.isColor && node.isHex || isWideKeywords(node.value)) { + return node.value.toLowerCase(); + } + + return node.value; + } + + case "value-colon": + { + return concat$4([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`) + insideValueFunctionNode(path, "url") ? "" : line$3]); + } + + case "value-comma": + { + return concat$4([node.value, " "]); + } + + case "value-string": + { + return printString$1(node.raws.quote + node.value + node.raws.quote, options); + } + + case "value-atword": + { + return concat$4(["@", node.value]); + } + + case "value-unicode-range": + { + return node.value; + } + + case "value-unknown": + { + return node.value; + } + + default: + /* istanbul ignore next */ + throw new Error("Unknown postcss type ".concat(JSON.stringify(node.type))); + } +} + +function printNodeSequence(path, options, print) { + var node = path.getValue(); + var parts = []; + var i = 0; + path.map(function (pathChild) { + var prevNode = node.nodes[i - 1]; + + if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") { + var childNode = pathChild.getValue(); + parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode))); + } else { + parts.push(pathChild.call(print)); + } + + if (i !== node.nodes.length - 1) { + if (node.nodes[i + 1].type === "css-comment" && !hasNewline$2(options.originalText, options.locStart(node.nodes[i + 1]), { + backwards: true + }) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml" || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") { + parts.push(" "); + } else { + parts.push(hardline$3); + + if (isNextLineEmpty$2(options.originalText, pathChild.getValue(), options) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") { + parts.push(hardline$3); + } + } + } + + i++; + }, "nodes"); + return concat$4(parts); +} + +var STRING_REGEX = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g; +var NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g; +var STANDARD_UNIT_REGEX = /[a-zA-Z]+/g; +var WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g; +var ADJUST_NUMBERS_REGEX = RegExp(STRING_REGEX.source + "|" + "(".concat(WORD_PART_REGEX.source, ")?") + "(".concat(NUMBER_REGEX.source, ")") + "(".concat(STANDARD_UNIT_REGEX.source, ")?"), "g"); + +function adjustStrings(value, options) { + return value.replace(STRING_REGEX, function (match) { + return printString$1(match, options); + }); +} + +function quoteAttributeValue(value, options) { + var quote = options.singleQuote ? "'" : '"'; + return value.includes('"') || value.includes("'") ? value : quote + value + quote; +} + +function adjustNumbers(value) { + return value.replace(ADJUST_NUMBERS_REGEX, function (match, quote, wordPart, number, unit) { + return !wordPart && number ? (wordPart || "") + printCssNumber(number) + maybeToLowerCase(unit || "") : match; + }); +} + +function printCssNumber(rawNumber) { + return printNumber$1(rawNumber) // Remove trailing `.0`. + .replace(/\.0(?=$|e)/, ""); +} + +var printerPostcss = { + print: genericPrint, + embed: embed_1, + insertPragma: insertPragma, + hasPrettierIgnore: hasIgnoreComment$1, + massageAstNode: clean_1 +}; + +var CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js + +var commonOptions = { + bracketSpacing: { + since: "0.0.0", + category: CATEGORY_COMMON, + type: "boolean", + default: true, + description: "Print spaces between brackets.", + oppositeDescription: "Do not print spaces between brackets." + }, + singleQuote: { + since: "0.0.0", + category: CATEGORY_COMMON, + type: "boolean", + default: false, + description: "Use single quotes instead of double quotes." + }, + proseWrap: { + since: "1.8.2", + category: CATEGORY_COMMON, + type: "choice", + default: [{ + since: "1.8.2", + value: true + }, { + since: "1.9.0", + value: "preserve" + }], + description: "How to wrap prose.", + choices: [{ + since: "1.9.0", + value: "always", + description: "Wrap prose if it exceeds the print width." + }, { + since: "1.9.0", + value: "never", + description: "Do not wrap prose." + }, { + since: "1.9.0", + value: "preserve", + description: "Wrap prose as-is." + }, { + value: false, + deprecated: "1.9.0", + redirect: "never" + }, { + value: true, + deprecated: "1.9.0", + redirect: "always" + }] + } +}; + +var options$3 = { + singleQuote: commonOptions.singleQuote +}; + +var createLanguage = function createLanguage(linguistData, _ref) { + var extend = _ref.extend, + override = _ref.override; + var language = {}; + + for (var key in linguistData) { + var newKey = key === "languageId" ? "linguistLanguageId" : key; + language[newKey] = linguistData[key]; + } + + if (extend) { + for (var _key in extend) { + language[_key] = (language[_key] || []).concat(extend[_key]); + } + } + + for (var _key2 in override) { + language[_key2] = override[_key2]; + } + + return language; +}; + +var name$1 = "CSS"; +var type = "markup"; +var tmScope = "source.css"; +var aceMode = "css"; +var codemirrorMode = "css"; +var codemirrorMimeType = "text/css"; +var color = "#563d7c"; +var extensions = [".css"]; +var languageId = 50; +var css$2 = { + name: name$1, + type: type, + tmScope: tmScope, + aceMode: aceMode, + codemirrorMode: codemirrorMode, + codemirrorMimeType: codemirrorMimeType, + color: color, + extensions: extensions, + languageId: languageId +}; + +var css$3 = Object.freeze({ + name: name$1, + type: type, + tmScope: tmScope, + aceMode: aceMode, + codemirrorMode: codemirrorMode, + codemirrorMimeType: codemirrorMimeType, + color: color, + extensions: extensions, + languageId: languageId, + default: css$2 +}); + +var name$2 = "PostCSS"; +var type$1 = "markup"; +var tmScope$1 = "source.postcss"; +var group$2 = "CSS"; +var extensions$1 = [".pcss"]; +var aceMode$1 = "text"; +var languageId$1 = 262764437; +var postcss = { + name: name$2, + type: type$1, + tmScope: tmScope$1, + group: group$2, + extensions: extensions$1, + aceMode: aceMode$1, + languageId: languageId$1 +}; + +var postcss$1 = Object.freeze({ + name: name$2, + type: type$1, + tmScope: tmScope$1, + group: group$2, + extensions: extensions$1, + aceMode: aceMode$1, + languageId: languageId$1, + default: postcss +}); + +var name$3 = "Less"; +var type$2 = "markup"; +var group$3 = "CSS"; +var extensions$2 = [".less"]; +var tmScope$2 = "source.css.less"; +var aceMode$2 = "less"; +var codemirrorMode$1 = "css"; +var codemirrorMimeType$1 = "text/css"; +var languageId$2 = 198; +var less = { + name: name$3, + type: type$2, + group: group$3, + extensions: extensions$2, + tmScope: tmScope$2, + aceMode: aceMode$2, + codemirrorMode: codemirrorMode$1, + codemirrorMimeType: codemirrorMimeType$1, + languageId: languageId$2 +}; + +var less$1 = Object.freeze({ + name: name$3, + type: type$2, + group: group$3, + extensions: extensions$2, + tmScope: tmScope$2, + aceMode: aceMode$2, + codemirrorMode: codemirrorMode$1, + codemirrorMimeType: codemirrorMimeType$1, + languageId: languageId$2, + default: less +}); + +var name$4 = "SCSS"; +var type$3 = "markup"; +var tmScope$3 = "source.scss"; +var group$4 = "CSS"; +var aceMode$3 = "scss"; +var codemirrorMode$2 = "css"; +var codemirrorMimeType$2 = "text/x-scss"; +var extensions$3 = [".scss"]; +var languageId$3 = 329; +var scss = { + name: name$4, + type: type$3, + tmScope: tmScope$3, + group: group$4, + aceMode: aceMode$3, + codemirrorMode: codemirrorMode$2, + codemirrorMimeType: codemirrorMimeType$2, + extensions: extensions$3, + languageId: languageId$3 +}; + +var scss$1 = Object.freeze({ + name: name$4, + type: type$3, + tmScope: tmScope$3, + group: group$4, + aceMode: aceMode$3, + codemirrorMode: codemirrorMode$2, + codemirrorMimeType: codemirrorMimeType$2, + extensions: extensions$3, + languageId: languageId$3, + default: scss +}); + +var require$$0$17 = ( css$3 && css$2 ) || css$3; + +var require$$1$8 = ( postcss$1 && postcss ) || postcss$1; + +var require$$2$9 = ( less$1 && less ) || less$1; + +var require$$3$4 = ( scss$1 && scss ) || scss$1; + +var languages = [createLanguage(require$$0$17, { + override: { + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["css"] + } +}), createLanguage(require$$1$8, { + override: { + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["postcss"] + }, + extend: { + extensions: [".postcss"] + } +}), createLanguage(require$$2$9, { + override: { + since: "1.4.0", + parsers: ["less"], + vscodeLanguageIds: ["less"] + } +}), createLanguage(require$$3$4, { + override: { + since: "1.4.0", + parsers: ["scss"], + vscodeLanguageIds: ["scss"] + } +})]; +var printers = { + postcss: printerPostcss +}; +var languageCss = { + languages: languages, + options: options$3, + printers: printers +}; + +function hasPragma$2(text) { + return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text); +} + +function insertPragma$4(text) { + return "# @format\n\n" + text; +} + +var pragma$4 = { + hasPragma: hasPragma$2, + insertPragma: insertPragma$4 +}; + +var _require$$0$builders$2 = doc.builders; +var concat$6 = _require$$0$builders$2.concat; +var join$3 = _require$$0$builders$2.join; +var hardline$5 = _require$$0$builders$2.hardline; +var line$4 = _require$$0$builders$2.line; +var softline$2 = _require$$0$builders$2.softline; +var group$5 = _require$$0$builders$2.group; +var indent$3 = _require$$0$builders$2.indent; +var ifBreak$2 = _require$$0$builders$2.ifBreak; +var hasIgnoreComment$2 = util.hasIgnoreComment; +var isNextLineEmpty$3 = utilShared.isNextLineEmpty; +var insertPragma$3 = pragma$4.insertPragma; + +function genericPrint$1(path, options, print) { + var n = path.getValue(); + + if (!n) { + return ""; + } + + if (typeof n === "string") { + return n; + } + + switch (n.kind) { + case "Document": + { + var parts = []; + path.map(function (pathChild, index) { + parts.push(concat$6([pathChild.call(print)])); + + if (index !== n.definitions.length - 1) { + parts.push(hardline$5); + + if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options)) { + parts.push(hardline$5); + } + } + }, "definitions"); + return concat$6([concat$6(parts), hardline$5]); + } + + case "OperationDefinition": + { + var hasOperation = options.originalText[options.locStart(n)] !== "{"; + var hasName = !!n.name; + return concat$6([hasOperation ? n.operation : "", hasOperation && hasName ? concat$6([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]); + } + + case "FragmentDefinition": + { + return concat$6(["fragment ", path.call(print, "name"), " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); + } + + case "SelectionSet": + { + return concat$6(["{", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (selectionsPath) { + return printSequence(selectionsPath, options, print); + }, "selections"))])), hardline$5, "}"]); + } + + case "Field": + { + return group$5(concat$6([n.alias ? concat$6([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(function (argsPath) { + return printSequence(argsPath, options, print); + }, "arguments"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")])); + } + + case "Name": + { + return n.value; + } + + case "StringValue": + { + if (n.block) { + return concat$6(['"""', hardline$5, join$3(hardline$5, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$5, '"""']); + } + + return concat$6(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']); + } + + case "IntValue": + case "FloatValue": + case "EnumValue": + { + return n.value; + } + + case "BooleanValue": + { + return n.value ? "true" : "false"; + } + + case "NullValue": + { + return "null"; + } + + case "Variable": + { + return concat$6(["$", path.call(print, "name")]); + } + + case "ListValue": + { + return group$5(concat$6(["[", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "values"))])), softline$2, "]"])); + } + + case "ObjectValue": + { + return group$5(concat$6(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "fields"))])), softline$2, ifBreak$2("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"])); + } + + case "ObjectField": + case "Argument": + { + return concat$6([path.call(print, "name"), ": ", path.call(print, "value")]); + } + + case "Directive": + { + return concat$6(["@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(function (argsPath) { + return printSequence(argsPath, options, print); + }, "arguments"))])), softline$2, ")"])) : ""]); + } + + case "NamedType": + { + return path.call(print, "name"); + } + + case "VariableDefinition": + { + return concat$6([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : ""]); + } + + case "TypeExtensionDefinition": + { + return concat$6(["extend ", path.call(print, "definition")]); + } + + case "ObjectTypeExtension": + case "ObjectTypeDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$6([" implements ", join$3(determineInterfaceSeparator(options.originalText.substr(options.locStart(n), options.locEnd(n))), path.map(print, "interfaces"))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (fieldsPath) { + return printSequence(fieldsPath, options, print); + }, "fields"))])), hardline$5, "}"]) : ""]); + } + + case "FieldDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(function (argsPath) { + return printSequence(argsPath, options, print); + }, "arguments"))])), softline$2, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]); + } + + case "DirectiveDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(function (argsPath) { + return printSequence(argsPath, options, print); + }, "arguments"))])), softline$2, ")"])) : "", concat$6([" on ", join$3(" | ", path.map(print, "locations"))])]); + } + + case "EnumTypeExtension": + case "EnumTypeDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (valuesPath) { + return printSequence(valuesPath, options, print); + }, "values"))])), hardline$5, "}"]) : ""]); + } + + case "EnumValueDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), printDirectives(path, print, n)]); + } + + case "InputValueDefinition": + { + return concat$6([path.call(print, "description"), n.description ? n.description.block ? hardline$5 : line$4 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]); + } + + case "InputObjectTypeExtension": + case "InputObjectTypeDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (fieldsPath) { + return printSequence(fieldsPath, options, print); + }, "fields"))])), hardline$5, "}"]) : ""]); + } + + case "SchemaDefinition": + { + return concat$6(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (opsPath) { + return printSequence(opsPath, options, print); + }, "operationTypes"))])) : "", hardline$5, "}"]); + } + + case "OperationTypeDefinition": + { + return concat$6([path.call(print, "operation"), ": ", path.call(print, "type")]); + } + + case "InterfaceTypeExtension": + case "InterfaceTypeDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(function (fieldsPath) { + return printSequence(fieldsPath, options, print); + }, "fields"))])), hardline$5, "}"]) : ""]); + } + + case "FragmentSpread": + { + return concat$6(["...", path.call(print, "name"), printDirectives(path, print, n)]); + } + + case "InlineFragment": + { + return concat$6(["...", n.typeCondition ? concat$6([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); + } + + case "UnionTypeExtension": + case "UnionTypeDefinition": + { + return group$5(concat$6([path.call(print, "description"), n.description ? hardline$5 : "", group$5(concat$6([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$6([" =", ifBreak$2("", " "), indent$3(concat$6([ifBreak$2(concat$6([line$4, " "])), join$3(concat$6([line$4, "| "]), path.map(print, "types"))]))]) : ""]))])); + } + + case "ScalarTypeExtension": + case "ScalarTypeDefinition": + { + return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]); + } + + case "NonNullType": + { + return concat$6([path.call(print, "type"), "!"]); + } + + case "ListType": + { + return concat$6(["[", path.call(print, "type"), "]"]); + } + + default: + /* istanbul ignore next */ + throw new Error("unknown graphql type: " + JSON.stringify(n.kind)); + } +} + +function printDirectives(path, print, n) { + if (n.directives.length === 0) { + return ""; + } + + return concat$6([" ", group$5(indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", " "), softline$2]), path.map(print, "directives"))])))]); +} + +function printSequence(sequencePath, options, print) { + var count = sequencePath.getValue().length; + return sequencePath.map(function (path, i) { + var printed = print(path); + + if (isNextLineEmpty$3(options.originalText, path.getValue(), options) && i < count - 1) { + return concat$6([printed, hardline$5]); + } + + return printed; + }); +} + +function canAttachComment(node) { + return node.kind && node.kind !== "Comment"; +} + +function printComment$1(commentPath) { + var comment = commentPath.getValue(); + + if (comment.kind === "Comment") { + return "#" + comment.value.trimRight(); + } + + throw new Error("Not a comment: " + JSON.stringify(comment)); +} + +function determineInterfaceSeparator(originalSource) { + var start = originalSource.indexOf("implements"); + + if (start === -1) { + throw new Error("Must implement interfaces: " + originalSource); + } + + var end = originalSource.indexOf("{"); + + if (end === -1) { + end = originalSource.length; + } + + return originalSource.substr(start, end).includes("&") ? " & " : ", "; +} + +function clean$2(node, newNode +/*, parent*/ +) { + delete newNode.loc; + delete newNode.comments; +} + +var printerGraphql = { + print: genericPrint$1, + massageAstNode: clean$2, + hasPrettierIgnore: hasIgnoreComment$2, + insertPragma: insertPragma$3, + printComment: printComment$1, + canAttachComment: canAttachComment +}; + +var options$6 = { + bracketSpacing: commonOptions.bracketSpacing +}; + +var name$5 = "GraphQL"; +var type$4 = "data"; +var extensions$4 = [".graphql", ".gql"]; +var tmScope$4 = "source.graphql"; +var aceMode$4 = "text"; +var languageId$4 = 139; +var graphql = { + name: name$5, + type: type$4, + extensions: extensions$4, + tmScope: tmScope$4, + aceMode: aceMode$4, + languageId: languageId$4 +}; + +var graphql$1 = Object.freeze({ + name: name$5, + type: type$4, + extensions: extensions$4, + tmScope: tmScope$4, + aceMode: aceMode$4, + languageId: languageId$4, + default: graphql +}); + +var require$$0$18 = ( graphql$1 && graphql ) || graphql$1; + +var languages$1 = [createLanguage(require$$0$18, { + override: { + since: "1.5.0", + parsers: ["graphql"], + vscodeLanguageIds: ["graphql"] + } +})]; +var printers$1 = { + graphql: printerGraphql +}; +var languageGraphql = { + languages: languages$1, + options: options$6, + printers: printers$1 +}; + +var _require$$0$builders$3 = doc.builders; +var concat$7 = _require$$0$builders$3.concat; +var join$4 = _require$$0$builders$3.join; +var softline$3 = _require$$0$builders$3.softline; +var hardline$6 = _require$$0$builders$3.hardline; +var line$5 = _require$$0$builders$3.line; +var group$6 = _require$$0$builders$3.group; +var indent$4 = _require$$0$builders$3.indent; +var ifBreak$3 = _require$$0$builders$3.ifBreak; // http://w3c.github.io/html/single-page.html#void-elements + +var voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]; // Formatter based on @glimmerjs/syntax's built-in test formatter: +// https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts + +function print(path, options, print) { + var n = path.getValue(); + /* istanbul ignore if*/ + + if (!n) { + return ""; + } + + switch (n.type) { + case "Program": + { + return group$6(join$4(softline$3, path.map(print, "body").filter(function (text) { + return text !== ""; + }))); + } + + case "ElementNode": + { + var tagFirstChar = n.tag[0]; + var isLocal = n.tag.indexOf(".") !== -1; + var isGlimmerComponent = tagFirstChar.toUpperCase() === tagFirstChar || isLocal; + var hasChildren = n.children.length > 0; + var isVoid = isGlimmerComponent && !hasChildren || voidTags.indexOf(n.tag) !== -1; + var closeTag = isVoid ? concat$7([" />", softline$3]) : ">"; + + var _getParams = function _getParams(path, print) { + return indent$4(concat$7([n.attributes.length ? line$5 : "", join$4(line$5, path.map(print, "attributes")), n.modifiers.length ? line$5 : "", join$4(line$5, path.map(print, "modifiers")), n.comments.length ? line$5 : "", join$4(line$5, path.map(print, "comments"))])); + }; // The problem here is that I want to not break at all if the children + // would not break but I need to force an indent, so I use a hardline. + + /** + * What happens now: + *
+ * Hello + *
+ * ==> + *
Hello
+ * This is due to me using hasChildren to decide to put the hardline in. + * I would rather use a {DOES THE WHOLE THING NEED TO BREAK} + */ + + + return concat$7([group$6(concat$7(["<", n.tag, _getParams(path, print), n.blockParams.length ? " as |".concat(n.blockParams.join(" "), "|") : "", ifBreak$3(softline$3, ""), closeTag])), group$6(concat$7([indent$4(join$4(softline$3, [""].concat(path.map(print, "children")))), ifBreak$3(hasChildren ? hardline$6 : "", ""), !isVoid ? concat$7([""]) : ""]))]); + } + + case "BlockStatement": + { + var pp = path.getParentNode(1); + var isElseIf = pp && pp.inverse && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if"; + var hasElseIf = n.inverse && n.inverse.body[0] && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if"; + var indentElse = hasElseIf ? function (a) { + return a; + } : indent$4; + + if (n.inverse) { + return concat$7([isElseIf ? concat$7(["{{else ", printPathParams(path, print), "}}"]) : printOpenBlock(path, print), indent$4(concat$7([hardline$6, path.call(print, "program")])), n.inverse && !hasElseIf ? concat$7([hardline$6, "{{else}}"]) : "", n.inverse ? indentElse(concat$7([hardline$6, path.call(print, "inverse")])) : "", isElseIf ? "" : concat$7([hardline$6, printCloseBlock(path, print)])]); + } else if (isElseIf) { + return concat$7([concat$7(["{{else ", printPathParams(path, print), "}}"]), indent$4(concat$7([hardline$6, path.call(print, "program")]))]); + } + /** + * I want this boolean to be: if params are going to cause a break, + * not that it has params. + */ + + + var hasParams = n.params.length > 0 || n.hash.pairs.length > 0; + + var _hasChildren = n.program.body.length > 0; + + return concat$7([printOpenBlock(path, print), group$6(concat$7([indent$4(concat$7([softline$3, path.call(print, "program")])), hasParams && _hasChildren ? hardline$6 : softline$3, printCloseBlock(path, print)]))]); + } + + case "ElementModifierStatement": + case "MustacheStatement": + { + var _pp = path.getParentNode(1); + + var isConcat = _pp && _pp.type === "ConcatStatement"; + return group$6(concat$7([n.escaped === false ? "{{{" : "{{", printPathParams(path, print), isConcat ? "" : softline$3, n.escaped === false ? "}}}" : "}}"])); + } + + case "SubExpression": + { + var params = getParams(path, print); + var printedParams = params.length > 0 ? indent$4(concat$7([line$5, group$6(join$4(line$5, params))])) : ""; + return group$6(concat$7(["(", printPath(path, print), printedParams, softline$3, ")"])); + } + + case "AttrNode": + { + var isText = n.value.type === "TextNode"; + + if (isText && n.value.loc.start.column === n.value.loc.end.column) { + return concat$7([n.name]); + } + + var quote = isText ? '"' : ""; + return concat$7([n.name, "=", quote, path.call(print, "value"), quote]); + } + + case "ConcatStatement": + { + return concat$7(['"', group$6(indent$4(join$4(softline$3, path.map(function (partPath) { + return print(partPath); + }, "parts").filter(function (a) { + return a !== ""; + })))), '"']); + } + + case "Hash": + { + return concat$7([join$4(line$5, path.map(print, "pairs"))]); + } + + case "HashPair": + { + return concat$7([n.key, "=", path.call(print, "value")]); + } + + case "TextNode": + { + var leadingSpace = ""; + var trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present, when next to mustache statement. + + var inAttrNode = path.stack.indexOf("attributes") >= 0; + + if (inAttrNode) { + var parentNode = path.getParentNode(0); + + var _isConcat = parentNode.type === "ConcatStatement"; + + if (_isConcat) { + var parts = parentNode.parts; + var partIndex = parts.indexOf(n); + + if (partIndex > 0) { + var partType = parts[partIndex - 1].type; + var isMustache = partType === "MustacheStatement"; + + if (isMustache) { + leadingSpace = " "; + } + } + + if (partIndex < parts.length - 1) { + var _partType = parts[partIndex + 1].type; + + var _isMustache = _partType === "MustacheStatement"; + + if (_isMustache) { + trailingSpace = " "; + } + } + } + } + + return n.chars.replace(/^\s+/, leadingSpace).replace(/\s+$/, trailingSpace); + } + + case "MustacheCommentStatement": + { + var dashes = n.value.indexOf("}}") > -1 ? "--" : ""; + return concat$7(["{{!", dashes, n.value, dashes, "}}"]); + } + + case "PathExpression": + { + return n.original; + } + + case "BooleanLiteral": + { + return String(n.value); + } + + case "CommentStatement": + { + return concat$7([""]); + } + + case "StringLiteral": + { + return printStringLiteral(n.value, options); + } + + case "NumberLiteral": + { + return String(n.value); + } + + case "UndefinedLiteral": + { + return "undefined"; + } + + case "NullLiteral": + { + return "null"; + } + + /* istanbul ignore next */ + + default: + throw new Error("unknown glimmer type: " + JSON.stringify(n.type)); + } +} +/** + * Prints a string literal with the correct surrounding quotes based on + * `options.singleQuote` and the number of escaped quotes contained in + * the string literal. This function is the glimmer equivalent of `printString` + * in `common/util`, but has differences because of the way escaped characters + * are treated in hbs string literals. + * @param {string} stringLiteral - the string literal value + * @param {object} options - the prettier options object + */ + + +function printStringLiteral(stringLiteral, options) { + var double = { + quote: '"', + regex: /"/g + }; + var single = { + quote: "'", + regex: /'/g + }; + var preferred = options.singleQuote ? single : double; + var alternate = preferred === single ? double : single; + var shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for + // enclosing the string, we might want to enclose with the alternate quote + // instead, to minimize the number of escaped quotes. + + if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) { + var numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length; + var numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length; + shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes; + } + + var enclosingQuote = shouldUseAlternateQuote ? alternate : preferred; + var escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, "\\".concat(enclosingQuote.quote)); + return "".concat(enclosingQuote.quote).concat(escapedStringLiteral).concat(enclosingQuote.quote); +} + +function printPath(path, print) { + return path.call(print, "path"); +} + +function getParams(path, print) { + var node = path.getValue(); + var parts = []; + + if (node.params.length > 0) { + parts = parts.concat(path.map(print, "params")); + } + + if (node.hash && node.hash.pairs.length > 0) { + parts.push(path.call(print, "hash")); + } + + return parts; +} + +function printPathParams(path, print) { + var parts = []; + parts.push(printPath(path, print)); + parts = parts.concat(getParams(path, print)); + return indent$4(group$6(join$4(line$5, parts))); +} + +function printBlockParams(path) { + var block = path.getValue(); + + if (!block.program || !block.program.blockParams.length) { + return ""; + } + + return concat$7([" as |", block.program.blockParams.join(" "), "|"]); +} + +function printOpenBlock(path, print) { + return group$6(concat$7(["{{#", printPathParams(path, print), printBlockParams(path), softline$3, "}}"])); +} + +function printCloseBlock(path, print) { + return concat$7(["{{/", path.call(print, "path"), "}}"]); +} + +function clean$3(ast, newObj) { + delete newObj.loc; // (Glimmer/HTML) ignore TextNode whitespace + + if (ast.type === "TextNode") { + if (ast.chars.replace(/\s+/, "") === "") { + return null; + } + + newObj.chars = ast.chars.replace(/^\s+/, "").replace(/\s+$/, ""); + } +} + +var printerGlimmer = { + print: print, + massageAstNode: clean$3 +}; + +var name$6 = "Handlebars"; +var type$5 = "markup"; +var group$7 = "HTML"; +var aliases = ["hbs", "htmlbars"]; +var extensions$5 = [".handlebars", ".hbs"]; +var tmScope$5 = "text.html.handlebars"; +var aceMode$5 = "handlebars"; +var languageId$5 = 155; +var handlebars = { + name: name$6, + type: type$5, + group: group$7, + aliases: aliases, + extensions: extensions$5, + tmScope: tmScope$5, + aceMode: aceMode$5, + languageId: languageId$5 +}; + +var handlebars$1 = Object.freeze({ + name: name$6, + type: type$5, + group: group$7, + aliases: aliases, + extensions: extensions$5, + tmScope: tmScope$5, + aceMode: aceMode$5, + languageId: languageId$5, + default: handlebars +}); + +var require$$0$19 = ( handlebars$1 && handlebars ) || handlebars$1; + +var languages$2 = [createLanguage(require$$0$19, { + override: { + since: null, + // unreleased + parsers: ["glimmer"], + vscodeLanguageIds: ["handlebars"] + } +})]; +var printers$2 = { + glimmer: printerGlimmer +}; +var languageHandlebars = { + languages: languages$2, + printers: printers$2 +}; + +var clean$4 = function clean(ast, newNode) { + delete newNode.sourceSpan; + delete newNode.startSourceSpan; + delete newNode.endSourceSpan; + delete newNode.nameSpan; + delete newNode.valueSpan; + + if (ast.type === "text" || ast.type === "comment") { + return null; + } // may be formatted by multiparser + + + if (ast.type === "yaml" || ast.type === "toml") { + return null; + } + + if (ast.type === "attribute") { + delete newNode.value; + } + + if (ast.type === "docType") { + delete newNode.value; + } +}; + +var a = ["accesskey", "charset", "coords", "download", "href", "hreflang", "name", "ping", "referrerpolicy", "rel", "rev", "shape", "tabindex", "target", "type"]; +var abbr = ["title"]; +var applet = ["align", "alt", "archive", "code", "codebase", "height", "hspace", "name", "object", "vspace", "width"]; +var area = ["accesskey", "alt", "coords", "download", "href", "hreflang", "nohref", "ping", "referrerpolicy", "rel", "shape", "tabindex", "target", "type"]; +var audio = ["autoplay", "controls", "crossorigin", "loop", "muted", "preload", "src"]; +var base$2 = ["href", "target"]; +var basefont = ["color", "face", "size"]; +var bdo = ["dir"]; +var blockquote = ["cite"]; +var body = ["alink", "background", "bgcolor", "link", "text", "vlink"]; +var br = ["clear"]; +var button = ["accesskey", "autofocus", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "name", "tabindex", "type", "value"]; +var canvas = ["height", "width"]; +var caption = ["align"]; +var col = ["align", "char", "charoff", "span", "valign", "width"]; +var colgroup = ["align", "char", "charoff", "span", "valign", "width"]; +var data = ["value"]; +var del = ["cite", "datetime"]; +var details = ["open"]; +var dfn = ["title"]; +var dialog = ["open"]; +var dir = ["compact"]; +var div = ["align"]; +var dl = ["compact"]; +var embed$3 = ["height", "src", "type", "width"]; +var fieldset = ["disabled", "form", "name"]; +var font = ["color", "face", "size"]; +var form = ["accept", "accept-charset", "action", "autocomplete", "enctype", "method", "name", "novalidate", "target"]; +var frame = ["frameborder", "longdesc", "marginheight", "marginwidth", "name", "noresize", "scrolling", "src"]; +var frameset = ["cols", "rows"]; +var h1 = ["align"]; +var h2 = ["align"]; +var h3 = ["align"]; +var h4 = ["align"]; +var h5 = ["align"]; +var h6 = ["align"]; +var head = ["profile"]; +var hr = ["align", "noshade", "size", "width"]; +var html = ["manifest", "version"]; +var iframe = ["align", "allowfullscreen", "allowpaymentrequest", "allowusermedia", "frameborder", "height", "longdesc", "marginheight", "marginwidth", "name", "referrerpolicy", "sandbox", "scrolling", "src", "srcdoc", "width"]; +var img = ["align", "alt", "border", "crossorigin", "decoding", "height", "hspace", "ismap", "longdesc", "name", "referrerpolicy", "sizes", "src", "srcset", "usemap", "vspace", "width"]; +var input = ["accept", "accesskey", "align", "alt", "autocomplete", "autofocus", "checked", "dirname", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "height", "ismap", "list", "max", "maxlength", "min", "minlength", "multiple", "name", "pattern", "placeholder", "readonly", "required", "size", "src", "step", "tabindex", "title", "type", "usemap", "value", "width"]; +var ins = ["cite", "datetime"]; +var isindex = ["prompt"]; +var label = ["accesskey", "for", "form"]; +var legend = ["accesskey", "align"]; +var li = ["type", "value"]; +var link$1 = ["as", "charset", "color", "crossorigin", "href", "hreflang", "integrity", "media", "nonce", "referrerpolicy", "rel", "rev", "sizes", "target", "title", "type"]; +var map = ["name"]; +var menu = ["compact"]; +var meta = ["charset", "content", "http-equiv", "name", "scheme"]; +var meter = ["high", "low", "max", "min", "optimum", "value"]; +var object = ["align", "archive", "border", "classid", "codebase", "codetype", "data", "declare", "form", "height", "hspace", "name", "standby", "tabindex", "type", "typemustmatch", "usemap", "vspace", "width"]; +var ol = ["compact", "reversed", "start", "type"]; +var optgroup = ["disabled", "label"]; +var option = ["disabled", "label", "selected", "value"]; +var output = ["for", "form", "name"]; +var p = ["align"]; +var param = ["name", "type", "value", "valuetype"]; +var pre = ["width"]; +var progress = ["max", "value"]; +var q = ["cite"]; +var script = ["async", "charset", "crossorigin", "defer", "integrity", "language", "nomodule", "nonce", "referrerpolicy", "src", "type"]; +var select = ["autocomplete", "autofocus", "disabled", "form", "multiple", "name", "required", "size", "tabindex"]; +var slot = ["name"]; +var source = ["media", "sizes", "src", "srcset", "type"]; +var style = ["media", "nonce", "title", "type"]; +var table = ["align", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "rules", "summary", "width"]; +var tbody = ["align", "char", "charoff", "valign"]; +var td = ["abbr", "align", "axis", "bgcolor", "char", "charoff", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width"]; +var textarea = ["accesskey", "autocomplete", "autofocus", "cols", "dirname", "disabled", "form", "maxlength", "minlength", "name", "placeholder", "readonly", "required", "rows", "tabindex", "wrap"]; +var tfoot = ["align", "char", "charoff", "valign"]; +var th = ["abbr", "align", "axis", "bgcolor", "char", "charoff", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width"]; +var thead = ["align", "char", "charoff", "valign"]; +var time = ["datetime"]; +var tr = ["align", "bgcolor", "char", "charoff", "valign"]; +var track = ["default", "kind", "label", "src", "srclang"]; +var ul = ["compact", "type"]; +var video = ["autoplay", "controls", "crossorigin", "height", "loop", "muted", "playsinline", "poster", "preload", "src", "width"]; +var index$13 = { + a: a, + abbr: abbr, + applet: applet, + area: area, + audio: audio, + base: base$2, + basefont: basefont, + bdo: bdo, + blockquote: blockquote, + body: body, + br: br, + button: button, + canvas: canvas, + caption: caption, + col: col, + colgroup: colgroup, + data: data, + del: del, + details: details, + dfn: dfn, + dialog: dialog, + dir: dir, + div: div, + dl: dl, + embed: embed$3, + fieldset: fieldset, + font: font, + form: form, + frame: frame, + frameset: frameset, + h1: h1, + h2: h2, + h3: h3, + h4: h4, + h5: h5, + h6: h6, + head: head, + hr: hr, + html: html, + iframe: iframe, + img: img, + input: input, + ins: ins, + isindex: isindex, + label: label, + legend: legend, + li: li, + link: link$1, + map: map, + menu: menu, + meta: meta, + meter: meter, + object: object, + ol: ol, + optgroup: optgroup, + option: option, + output: output, + p: p, + param: param, + pre: pre, + progress: progress, + q: q, + script: script, + select: select, + slot: slot, + source: source, + style: style, + table: table, + tbody: tbody, + td: td, + textarea: textarea, + tfoot: tfoot, + th: th, + thead: thead, + time: time, + tr: tr, + track: track, + ul: ul, + video: video, + "*": ["accesskey", "autocapitalize", "class", "contenteditable", "dir", "draggable", "hidden", "id", "inputmode", "is", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "nonce", "slot", "spellcheck", "style", "tabindex", "title", "translate"] +}; + +var htmlElementAttributes = Object.freeze({ + a: a, + abbr: abbr, + applet: applet, + area: area, + audio: audio, + base: base$2, + basefont: basefont, + bdo: bdo, + blockquote: blockquote, + body: body, + br: br, + button: button, + canvas: canvas, + caption: caption, + col: col, + colgroup: colgroup, + data: data, + del: del, + details: details, + dfn: dfn, + dialog: dialog, + dir: dir, + div: div, + dl: dl, + embed: embed$3, + fieldset: fieldset, + font: font, + form: form, + frame: frame, + frameset: frameset, + h1: h1, + h2: h2, + h3: h3, + h4: h4, + h5: h5, + h6: h6, + head: head, + hr: hr, + html: html, + iframe: iframe, + img: img, + input: input, + ins: ins, + isindex: isindex, + label: label, + legend: legend, + li: li, + link: link$1, + map: map, + menu: menu, + meta: meta, + meter: meter, + object: object, + ol: ol, + optgroup: optgroup, + option: option, + output: output, + p: p, + param: param, + pre: pre, + progress: progress, + q: q, + script: script, + select: select, + slot: slot, + source: source, + style: style, + table: table, + tbody: tbody, + td: td, + textarea: textarea, + tfoot: tfoot, + th: th, + thead: thead, + time: time, + tr: tr, + track: track, + ul: ul, + video: video, + default: index$13 +}); + +var json$4 = {"CSS_DISPLAY_TAGS":{"area":"none","base":"none","basefont":"none","datalist":"none","head":"none","link":"none","meta":"none","noembed":"none","noframes":"none","param":"none","rp":"none","script":"none","source":"block","style":"none","template":"inline","track":"block","title":"none","html":"block","body":"block","address":"block","blockquote":"block","center":"block","div":"block","figure":"block","figcaption":"block","footer":"block","form":"block","header":"block","hr":"block","legend":"block","listing":"block","main":"block","p":"block","plaintext":"block","pre":"block","xmp":"block","slot":"contents","ruby":"ruby","rt":"ruby-text","article":"block","aside":"block","h1":"block","h2":"block","h3":"block","h4":"block","h5":"block","h6":"block","hgroup":"block","nav":"block","section":"block","dir":"block","dd":"block","dl":"block","dt":"block","ol":"block","ul":"block","li":"list-item","table":"table","caption":"table-caption","colgroup":"table-column-group","col":"table-column","thead":"table-header-group","tbody":"table-row-group","tfoot":"table-footer-group","tr":"table-row","td":"table-cell","th":"table-cell","fieldset":"block","button":"inline-block","video":"inline-block","audio":"inline-block"},"CSS_DISPLAY_DEFAULT":"inline","CSS_WHITE_SPACE_TAGS":{"listing":"pre","plaintext":"pre","pre":"pre","xmp":"pre","nobr":"nowrap","table":"initial","textarea":"pre-wrap"},"CSS_WHITE_SPACE_DEFAULT":"normal"}; + +var htmlElementAttributes$1 = ( htmlElementAttributes && index$13 ) || htmlElementAttributes; + +var CSS_DISPLAY_TAGS = json$4.CSS_DISPLAY_TAGS; +var CSS_DISPLAY_DEFAULT = json$4.CSS_DISPLAY_DEFAULT; +var CSS_WHITE_SPACE_TAGS = json$4.CSS_WHITE_SPACE_TAGS; +var CSS_WHITE_SPACE_DEFAULT = json$4.CSS_WHITE_SPACE_DEFAULT; +var HTML_TAGS = arrayToMap(htmlTagNames$1); +var HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap); + +function arrayToMap(array) { + var map = Object.create(null); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var value = _step.value; + map[value] = true; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return map; +} + +function mapObject(object, fn) { + var newObject = Object.create(null); + + var _arr = Object.keys(object); + + for (var _i = 0; _i < _arr.length; _i++) { + var key = _arr[_i]; + newObject[key] = fn(object[key], key); + } + + return newObject; +} + +function shouldPreserveContent$1(node, options) { + if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") { + return true; + } // unterminated node in ie conditional comment + // e.g. + + + if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) { + return true; + } // incomplete html in ie conditional comment + // e.g. + + + if (node.type === "ieConditionalComment" && !node.complete) { + return true; + } // top-level elements (excluding