id int64 0 3.78k | code stringlengths 13 37.9k | declarations stringlengths 16 64.6k |
|---|---|---|
400 | constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'ReadError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code;
} | type Error = NodeJS.ErrnoException; |
401 | constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'ReadError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code;
} | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUr... |
402 | constructor(request: Request) {
super('Retrying', {}, request);
this.name = 'RetryError';
this.code = 'ERR_RETRYING';
} | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUr... |
403 | constructor(request: Request) {
super('This operation was aborted.', {}, request);
this.code = 'ERR_ABORTED';
this.name = 'AbortError';
} | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUr... |
404 | function timedOut(request: ClientRequest, delays: Delays, options: TimedOutOptions): () => void {
if (reentry in request) {
return noop;
}
request[reentry] = true;
const cancelers: Array<typeof noop> = [];
const {once, unhandleAll} = unhandler();
const addTimeout = (delay: number, callback: (delay: number, ev... | interface ClientRequest {
[reentry]?: boolean;
} |
405 | function timedOut(request: ClientRequest, delays: Delays, options: TimedOutOptions): () => void {
if (reentry in request) {
return noop;
}
request[reentry] = true;
const cancelers: Array<typeof noop> = [];
const {once, unhandleAll} = unhandler();
const addTimeout = (delay: number, callback: (delay: number, ev... | type Delays = {
lookup?: number;
socket?: number;
connect?: number;
secureConnect?: number;
send?: number;
response?: number;
read?: number;
request?: number;
}; |
406 | function timedOut(request: ClientRequest, delays: Delays, options: TimedOutOptions): () => void {
if (reentry in request) {
return noop;
}
request[reentry] = true;
const cancelers: Array<typeof noop> = [];
const {once, unhandleAll} = unhandler();
const addTimeout = (delay: number, callback: (delay: number, ev... | type TimedOutOptions = {
host?: string;
hostname?: string;
protocol?: string;
}; |
407 | (error: Error): void => {
if (error === null) {
once(socket, 'connect', timeConnect());
}
} | type Error = NodeJS.ErrnoException; |
408 | (error: Error): void => {
if (error === null) {
once(socket, 'connect', timeConnect());
}
} | type Error = NodeJS.ErrnoException; |
409 | (url: URL, options: NativeRequestOptions, callback?: (response: AcceptableResponse) => void) => AcceptableRequestResult | type AcceptableResponse = IncomingMessageWithTimings | ResponseLike; |
410 | (url: URL, options: NativeRequestOptions, callback?: (response: AcceptableResponse) => void) => AcceptableRequestResult | type NativeRequestOptions = HttpsRequestOptions & CacheOptions & {checkServerIdentity?: CheckServerIdentityFunction}; |
411 | (response: AcceptableResponse) => void | type AcceptableResponse = IncomingMessageWithTimings | ResponseLike; |
412 | (init: OptionsInit, self: Options) => void | type OptionsInit =
Except<Partial<InternalsType>, 'hooks' | 'retry'>
& {
hooks?: Partial<Hooks>;
retry?: Partial<RetryOptions>;
}; |
413 | (init: OptionsInit, self: Options) => void | class Options {
private _unixOptions?: NativeRequestOptions;
private _internals: InternalsType;
private _merging: boolean;
private readonly _init: OptionsInit[];
constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options) {
assert.any([is.string, is.urlInstance, is.object, is.unde... |
414 | (options: Options) => Promisable<void | Response | ResponseLike> | class Options {
private _unixOptions?: NativeRequestOptions;
private _internals: InternalsType;
private _merging: boolean;
private readonly _init: OptionsInit[];
constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options) {
assert.any([is.string, is.urlInstance, is.object, is.unde... |
415 | (updatedOptions: Options, plainResponse: PlainResponse) => Promisable<void> | type PlainResponse = {
/**
The original request URL.
*/
requestUrl: URL;
/**
The redirect URLs.
*/
redirectUrls: URL[];
/**
- `options` - The Got options that were set on this request.
__Note__: This is not a [http.ClientRequest](https://nodejs.org/api/http.html#http_class_http_clientrequest).
*/
reques... |
416 | (updatedOptions: Options, plainResponse: PlainResponse) => Promisable<void> | class Options {
private _unixOptions?: NativeRequestOptions;
private _internals: InternalsType;
private _merging: boolean;
private readonly _init: OptionsInit[];
constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options) {
assert.any([is.string, is.urlInstance, is.object, is.unde... |
417 | (error: RequestError) => Promisable<RequestError> | class RequestError extends Error {
input?: string;
code: string;
override stack!: string;
declare readonly options: Options;
readonly response?: Response;
readonly request?: Request;
readonly timings?: Timings;
constructor(message: string, error: Partial<Error & {code?: string}>, self: Request | Options) {
... |
418 | (error: RequestError, retryCount: number) => Promisable<void> | class RequestError extends Error {
input?: string;
code: string;
override stack!: string;
declare readonly options: Options;
readonly response?: Response;
readonly request?: Request;
readonly timings?: Timings;
constructor(message: string, error: Partial<Error & {code?: string}>, self: Request | Options) {
... |
419 | (options: OptionsInit) => never | type OptionsInit =
Except<Partial<InternalsType>, 'hooks' | 'retry'>
& {
hooks?: Partial<Hooks>;
retry?: Partial<RetryOptions>;
}; |
420 | (retryObject: RetryObject) => Promisable<number> | type RetryObject = {
attemptCount: number;
retryOptions: RetryOptions;
error: RequestError;
computedValue: number;
retryAfter?: number;
}; |
421 | (options: NativeRequestOptions, oncreate: (error: NodeJS.ErrnoException, socket: Socket) => void) => Socket | type NativeRequestOptions = HttpsRequestOptions & CacheOptions & {checkServerIdentity?: CheckServerIdentityFunction}; |
422 | transform(response: Response) {
if (response.request.options.responseType === 'json') {
return response.body;
}
return JSON.parse(response.body as string);
} | type Response<T = unknown> = {
/**
The result of the request.
*/
body: T;
/**
The raw result of the request.
*/
rawBody: Buffer;
} & PlainResponse; |
423 | (raw: OptionsInit) => {
const {hooks, retry} = raw;
const result: OptionsInit = {...raw};
if (is.object(raw.context)) {
result.context = {...raw.context};
}
if (is.object(raw.cacheOptions)) {
result.cacheOptions = {...raw.cacheOptions};
}
if (is.object(raw.https)) {
result.https = {...raw.https};
}
... | type OptionsInit =
Except<Partial<InternalsType>, 'hooks' | 'retry'>
& {
hooks?: Partial<Hooks>;
retry?: Partial<RetryOptions>;
}; |
424 | (options: OptionsInit, withOptions: OptionsInit, self: Options): void => {
const initHooks = options.hooks?.init;
if (initHooks) {
for (const hook of initHooks) {
hook(withOptions, self);
}
}
} | type OptionsInit =
Except<Partial<InternalsType>, 'hooks' | 'retry'>
& {
hooks?: Partial<Hooks>;
retry?: Partial<RetryOptions>;
}; |
425 | (options: OptionsInit, withOptions: OptionsInit, self: Options): void => {
const initHooks = options.hooks?.init;
if (initHooks) {
for (const hook of initHooks) {
hook(withOptions, self);
}
}
} | class Options {
private _unixOptions?: NativeRequestOptions;
private _internals: InternalsType;
private _merging: boolean;
private readonly _init: OptionsInit[];
constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options) {
assert.any([is.string, is.urlInstance, is.object, is.unde... |
426 | set agent(value: Agents) {
assert.plainObject(value);
// eslint-disable-next-line guard-for-in
for (const key in value) {
if (!(key in this._internals.agent)) {
throw new TypeError(`Unexpected agent option: ${key}`);
}
// @ts-expect-error - No idea why `value[key]` doesn't work here.
assert.any(... | type Agents = {
http?: HttpAgent | false;
https?: HttpsAgent | false;
http2?: unknown | false;
}; |
427 | set timeout(value: Delays) {
assert.plainObject(value);
// eslint-disable-next-line guard-for-in
for (const key in value) {
if (!(key in this._internals.timeout)) {
throw new Error(`Unexpected timeout option: ${key}`);
}
// @ts-expect-error - No idea why `value[key]` doesn't work here.
assert.an... | type Delays = {
lookup?: number;
socket?: number;
connect?: number;
secureConnect?: number;
send?: number;
response?: number;
read?: number;
request?: number;
}; |
428 | set hooks(value: Hooks) {
assert.object(value);
// eslint-disable-next-line guard-for-in
for (const knownHookEvent in value) {
if (!(knownHookEvent in this._internals.hooks)) {
throw new Error(`Unexpected hook event: ${knownHookEvent}`);
}
const typedKnownHookEvent = knownHookEvent as keyof Hooks;
... | type Hooks = {
/**
Called with the plain request options, right before their normalization.
The second argument represents the current `Options` instance.
@default []
**Note:**
> - This hook must be synchronous.
**Note:**
> - This is called every time options are merged.
**Note:**
> - The `options` objec... |
429 | set headers(value: Headers) {
assert.plainObject(value);
if (this._merging) {
Object.assign(this._internals.headers, lowercaseKeys(value));
} else {
this._internals.headers = lowercaseKeys(value);
}
} | type Headers = Record<string, string | string[] | undefined>; |
430 | set dnsLookupIpVersion(value: DnsLookupIpVersion) {
if (value !== undefined && value !== 4 && value !== 6) {
throw new TypeError(`Invalid DNS lookup IP version: ${value as string}`);
}
this._internals.dnsLookupIpVersion = value;
} | type DnsLookupIpVersion = undefined | 4 | 6; |
431 | set parseJson(value: ParseJsonFunction) {
assert.function_(value);
this._internals.parseJson = value;
} | type ParseJsonFunction = (text: string) => unknown; |
432 | set stringifyJson(value: StringifyJsonFunction) {
assert.function_(value);
this._internals.stringifyJson = value;
} | type StringifyJsonFunction = (object: unknown) => string; |
433 | set method(value: Method) {
assert.string(value);
this._internals.method = value.toUpperCase() as Method;
} | type Method =
| 'GET'
| 'POST'
| 'PUT'
| 'PATCH'
| 'HEAD'
| 'DELETE'
| 'OPTIONS'
| 'TRACE'
| 'get'
| 'post'
| 'put'
| 'patch'
| 'head'
| 'delete'
| 'options'
| 'trace'; |
434 | set cacheOptions(value: CacheOptions) {
assert.plainObject(value);
assert.any([is.boolean, is.undefined], value.shared);
assert.any([is.number, is.undefined], value.cacheHeuristic);
assert.any([is.number, is.undefined], value.immutableMinTimeToLive);
assert.any([is.boolean, is.undefined], value.ignoreCargoCu... | type CacheOptions = {
shared?: boolean;
cacheHeuristic?: number;
immutableMinTimeToLive?: number;
ignoreCargoCult?: boolean;
}; |
435 | set https(value: HttpsOptions) {
assert.plainObject(value);
assert.any([is.boolean, is.undefined], value.rejectUnauthorized);
assert.any([is.function_, is.undefined], value.checkServerIdentity);
assert.any([is.string, is.object, is.array, is.undefined], value.certificateAuthority);
assert.any([is.string, is.... | type HttpsOptions = {
alpnProtocols?: string[];
// From `http.RequestOptions` and `tls.CommonConnectionOptions`
rejectUnauthorized?: NativeRequestOptions['rejectUnauthorized'];
// From `tls.ConnectionOptions`
checkServerIdentity?: CheckServerIdentityFunction;
// From `tls.SecureContextOptions`
/**
Override t... |
436 | set responseType(value: ResponseType) {
if (value === undefined) {
this._internals.responseType = 'text';
return;
}
if (value !== 'text' && value !== 'buffer' && value !== 'json') {
throw new Error(`Invalid \`responseType\` option: ${value as string}`);
}
this._internals.responseType = value;
} | type ResponseType = 'json' | 'buffer' | 'text'; |
437 | (origin: Origin, event: Event, fn: Fn) => void | type Origin = EventEmitter; |
438 | (origin: Origin, event: Event, fn: Fn) => void | type Event = string | symbol; |
439 | (origin: Origin, event: Event, fn: Fn) => void | type Fn = (...args: unknown[]) => void; |
440 | (origin: Origin, event: Event, fn: Fn) => void | type Fn = (...args: any[]) => void; |
441 | once(origin: Origin, event: Event, fn: Fn) {
origin.once(event, fn);
handlers.push({origin, event, fn});
} | type Origin = EventEmitter; |
442 | once(origin: Origin, event: Event, fn: Fn) {
origin.once(event, fn);
handlers.push({origin, event, fn});
} | type Event = string | symbol; |
443 | once(origin: Origin, event: Event, fn: Fn) {
origin.once(event, fn);
handlers.push({origin, event, fn});
} | type Fn = (...args: unknown[]) => void; |
444 | once(origin: Origin, event: Event, fn: Fn) {
origin.once(event, fn);
handlers.push({origin, event, fn});
} | type Fn = (...args: any[]) => void; |
445 | constructor(request: Request) {
super('Promise was canceled', {}, request);
this.name = 'CancelError';
this.code = 'ERR_CANCELED';
} | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUr... |
446 | function asPromise<T>(firstRequest?: Request): CancelableRequest<T> {
let globalRequest: Request;
let globalResponse: Response;
let normalizedOptions: Options;
const emitter = new EventEmitter();
const promise = new PCancelable<T>((resolve, reject, onCancel) => {
onCancel(() => {
globalRequest.destroy();
}... | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUr... |
447 | async (response: Response) => {
// Parse body
const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase();
const isCompressed = contentEncoding === 'gzip' || contentEncoding === 'deflate' || contentEncoding === 'br';
const {options} = request;
if (isCompressed && !options.de... | type Response<T = unknown> = {
/**
The result of the request.
*/
body: T;
/**
The raw result of the request.
*/
rawBody: Buffer;
} & PlainResponse; |
448 | (error: RequestError) => {
if (promise.isCanceled) {
return;
}
const {options} = request;
if (error instanceof HTTPError && !options.throwHttpErrors) {
const {response} = error;
request.destroy();
resolve(request.options.resolveBodyOnly ? response.body as T : response as unknown a... | class RequestError extends Error {
input?: string;
code: string;
override stack!: string;
declare readonly options: Options;
readonly response?: Response;
readonly request?: Request;
readonly timings?: Timings;
constructor(message: string, error: Partial<Error & {code?: string}>, self: Request | Options) {
... |
449 | function isGitIgnored(options?: GitignoreOptions): Promise<GlobbyFilterFunction>; | interface GitignoreOptions {
readonly cwd?: URL | string;
} |
450 | function isGitIgnoredSync(options?: GitignoreOptions): GlobbyFilterFunction; | interface GitignoreOptions {
readonly cwd?: URL | string;
} |
451 | function genericsWorker(this: GenericsContext, task: number, cb: fastq.done<string>) {
cb(null, 'the meaning of life is ' + (this.base * task))
} | interface GenericsContext {
base: number;
} |
452 | function createModuleTypeClassifier(
options: ModuleTypeClassifierOptions
) {
const { patterns, basePath: _basePath } = options;
const basePath =
_basePath !== undefined
? normalizeSlashes(_basePath).replace(/\/$/, '')
: undefined;
const patternTypePairs = Object.entries(patterns ?? []).map(
... | interface ModuleTypeClassifierOptions {
basePath?: string;
patterns?: ModuleTypes;
} |
453 | (t: T) => RegExp | type T = ExecutionContext<ctxTsNode.Ctx>; |
454 | setService(service: Service): void | interface Service {
/** @internal */
[TS_NODE_SERVICE_BRAND]: true;
ts: TSCommon;
/** @internal */
compilerPath: string;
config: _ts.ParsedCommandLine;
options: RegisterOptions;
enabled(enabled?: boolean): boolean;
ignored(fileName: string): boolean;
compile(code: string, fileName: string, lineOffse... |
455 | function createRepl(options: CreateReplOptions = {}) {
const { ignoreDiagnosticsThatAreAnnoyingInInteractiveRepl = true } = options;
let service = options.service;
let nodeReplServer: REPLServer;
// If `useGlobal` is not true, then REPL creates a context when started.
// This stores a reference to it or to `g... | interface CreateReplOptions {
service?: Service;
state?: EvalState;
stdin?: NodeJS.ReadableStream;
stdout?: NodeJS.WritableStream;
stderr?: NodeJS.WritableStream;
/** @internal */
composeWithEvalAwarePartialHost?: EvalAwarePartialHost;
/**
* @internal
* Ignore diagnostics that are annoying when in... |
456 | function setService(_service: Service) {
service = _service;
if (ignoreDiagnosticsThatAreAnnoyingInInteractiveRepl) {
service.addDiagnosticFilter({
appliesToAllFiles: false,
filenamesAbsolute: [state.path],
diagnosticsIgnored: [
2393, // Duplicate function implementation:... | interface Service {
/** @internal */
[TS_NODE_SERVICE_BRAND]: true;
ts: TSCommon;
/** @internal */
compilerPath: string;
config: _ts.ParsedCommandLine;
options: RegisterOptions;
enabled(enabled?: boolean): boolean;
ignored(fileName: string): boolean;
compile(code: string, fileName: string, lineOffse... |
457 | function createEvalAwarePartialHost(
state: EvalState,
composeWith?: EvalAwarePartialHost
): EvalAwarePartialHost {
function readFile(path: string) {
if (path === state.path) return state.input;
if (composeWith?.readFile) return composeWith.readFile(path);
try {
return readFileSync(path, 'utf8... | type EvalAwarePartialHost = Pick<
CreateOptions,
'readFile' | 'fileExists'
>; |
458 | function createEvalAwarePartialHost(
state: EvalState,
composeWith?: EvalAwarePartialHost
): EvalAwarePartialHost {
function readFile(path: string) {
if (path === state.path) return state.input;
if (composeWith?.readFile) return composeWith.readFile(path);
try {
return readFileSync(path, 'utf8... | class EvalState {
/** @internal */
input = '';
/** @internal */
output = '';
/** @internal */
version = 0;
/** @internal */
lines = 0;
__tsNodeEvalStateBrand: unknown;
constructor(public path: string) {}
} |
459 | function appendToEvalState(state: EvalState, input: string) {
const undoInput = state.input;
const undoVersion = state.version;
const undoOutput = state.output;
const undoLines = state.lines;
state.input += input;
state.lines += lineCount(input);
state.version++;
return function () {
state.input =... | class EvalState {
/** @internal */
input = '';
/** @internal */
output = '';
/** @internal */
version = 0;
/** @internal */
lines = 0;
__tsNodeEvalStateBrand: unknown;
constructor(public path: string) {}
} |
460 | function isRecoverable(error: TSError) {
return error.diagnosticCodes.every((code) => {
const deps = RECOVERY_CODES.get(code);
return (
deps === null ||
(deps && error.diagnosticCodes.some((code) => deps.has(code)))
);
});
} | class TSError extends BaseError {
name = 'TSError';
diagnosticText!: string;
diagnostics!: ReadonlyArray<_ts.Diagnostic>;
constructor(
diagnosticText: string,
public diagnosticCodes: number[],
diagnostics: ReadonlyArray<_ts.Diagnostic> = []
) {
super(`⨯ Unable to compile TypeScript:\n${diagno... |
461 | (arg: T) => U | type T = ExecutionContext<ctxTsNode.Ctx>; |
462 | (x: T) => {
debug(key, x, ++i);
return fn(x);
} | type T = ExecutionContext<ctxTsNode.Ctx>; |
463 | addDiagnosticFilter(filter: DiagnosticFilter): void | interface DiagnosticFilter {
/** if true, filter applies to all files */
appliesToAllFiles: boolean;
/** Filter applies onto to these filenames. Only used if appliesToAllFiles is false */
filenamesAbsolute: string[];
/** these diagnostic codes are ignored */
diagnosticsIgnored: number[];
} |
464 | function register(opts?: RegisterOptions): Service; | interface RegisterOptions extends CreateOptions {
/**
* Enable experimental features that re-map imports and require calls to support:
* `baseUrl`, `paths`, `rootDirs`, `.js` to `.ts` file extension mappings,
* `outDir` to `rootDir` mappings for composite projects and monorepos.
*
* For details, see ht... |
465 | function register(service: Service): Service; | interface Service {
/** @internal */
[TS_NODE_SERVICE_BRAND]: true;
ts: TSCommon;
/** @internal */
compilerPath: string;
config: _ts.ParsedCommandLine;
options: RegisterOptions;
enabled(enabled?: boolean): boolean;
ignored(fileName: string): boolean;
compile(code: string, fileName: string, lineOffse... |
466 | function create(rawOptions: CreateOptions = {}): Service {
const foundConfigResult = findAndReadConfig(rawOptions);
return createFromPreloadedConfig(foundConfigResult);
} | interface CreateOptions {
/**
* Behave as if invoked within this working directory. Roughly equivalent to `cd $dir && ts-node ...`
*
* @default process.cwd()
*/
cwd?: string;
/**
* Legacy alias for `cwd`
*
* @deprecated use `projectSearchDir` or `cwd`
*/
dir?: string;
/**
* Emit ou... |
467 | function addDiagnosticFilter(filter: DiagnosticFilter) {
diagnosticFilters.push({
...filter,
filenamesAbsolute: filter.filenamesAbsolute.map((f) =>
normalizeSlashes(f)
),
});
} | interface DiagnosticFilter {
/** if true, filter applies to all files */
appliesToAllFiles: boolean;
/** Filter applies onto to these filenames. Only used if appliesToAllFiles is false */
filenamesAbsolute: string[];
/** these diagnostic codes are ignored */
diagnosticsIgnored: number[];
} |
468 | function getTokenAtPosition(
ts: TSCommon,
sourceFile: _ts.SourceFile,
position: number
): _ts.Node {
let current: _ts.Node = sourceFile;
outer: while (true) {
for (const child of current.getChildren(sourceFile)) {
const start = child.getFullStart();
if (start > position) break;
const ... | interface TSCommon {
version: typeof _ts.version;
sys: typeof _ts.sys;
ScriptSnapshot: typeof _ts.ScriptSnapshot;
displayPartsToString: typeof _ts.displayPartsToString;
createLanguageService: typeof _ts.createLanguageService;
getDefaultLibFilePath: typeof _ts.getDefaultLibFilePath;
getPreEmitDiagnostics: ... |
469 | (
tsNodeService: Service
) => (require('./esm') as typeof import('./esm')).createEsmHooks(tsNodeService) | interface Service {
/** @internal */
[TS_NODE_SERVICE_BRAND]: true;
ts: TSCommon;
/** @internal */
compilerPath: string;
config: _ts.ParsedCommandLine;
options: RegisterOptions;
enabled(enabled?: boolean): boolean;
ignored(fileName: string): boolean;
compile(code: string, fileName: string, lineOffse... |
470 | function assign<T extends object>(
initialValue: T,
...sources: Array<T>
): T {
for (const source of sources) {
for (const key of Object.keys(source)) {
const value = (source as any)[key];
if (value !== undefined) (initialValue as any)[key] = value;
}
}
return initialValue;
} | type T = ExecutionContext<ctxTsNode.Ctx>; |
471 | (arg: T) => R | type T = ExecutionContext<ctxTsNode.Ctx>; |
472 | (arg: T): R => {
if (!cache.has(arg)) {
const v = fn(arg);
cache.set(arg, v);
return v;
}
return cache.get(arg)!;
} | type T = ExecutionContext<ctxTsNode.Ctx>; |
473 | function bootstrap(state: BootstrapState) {
if (!state.phase2Result) {
state.phase2Result = phase2(state);
if (state.shouldUseChildProcess && !state.isInChildProcess) {
// Note: When transitioning into the child-process after `phase2`,
// the updated working directory needs to be preserved.
... | interface BootstrapState {
isInChildProcess: boolean;
shouldUseChildProcess: boolean;
/**
* True if bootstrapping the ts-node CLI process or the direct child necessitated by `--esm`.
* false if bootstrapping a subsequently `fork()`ed child.
*/
isCli: boolean;
tsNodeScript: string;
parseArgvResult: ... |
474 | function phase2(payload: BootstrapState) {
const { help, version, cwdArg, esm } = payload.parseArgvResult;
if (help) {
console.log(`
Usage: ts-node [options] [ -e script | script.ts ] [arguments]
Options:
-e, --eval [code] Evaluate code
-p, --print Print result of \`--ev... | interface BootstrapState {
isInChildProcess: boolean;
shouldUseChildProcess: boolean;
/**
* True if bootstrapping the ts-node CLI process or the direct child necessitated by `--esm`.
* false if bootstrapping a subsequently `fork()`ed child.
*/
isCli: boolean;
tsNodeScript: string;
parseArgvResult: ... |
475 | function phase3(payload: BootstrapState) {
const {
emit,
files,
pretty,
transpileOnly,
transpiler,
noExperimentalReplAwait,
typeCheck,
swc,
compilerHost,
ignore,
preferTsExts,
logError,
scriptMode,
cwdMode,
project,
skipProject,
skipIgnore,
compi... | interface BootstrapState {
isInChildProcess: boolean;
shouldUseChildProcess: boolean;
/**
* True if bootstrapping the ts-node CLI process or the direct child necessitated by `--esm`.
* false if bootstrapping a subsequently `fork()`ed child.
*/
isCli: boolean;
tsNodeScript: string;
parseArgvResult: ... |
476 | function getEntryPointInfo(state: BootstrapState) {
const { code, interactive, restArgs } = state.parseArgvResult!;
const { cwd } = state.phase2Result!;
const { isCli } = state;
// Figure out which we are executing: piped stdin, --eval, REPL, and/or entrypoint
// This is complicated because node's behavior i... | interface BootstrapState {
isInChildProcess: boolean;
shouldUseChildProcess: boolean;
/**
* True if bootstrapping the ts-node CLI process or the direct child necessitated by `--esm`.
* false if bootstrapping a subsequently `fork()`ed child.
*/
isCli: boolean;
tsNodeScript: string;
parseArgvResult: ... |
477 | function phase4(payload: BootstrapState) {
const { isInChildProcess, tsNodeScript } = payload;
const { version, showConfig, restArgs, code, print, argv } =
payload.parseArgvResult;
const { cwd } = payload.phase2Result!;
const { preloadedConfig } = payload.phase3Result!;
const {
entryPointPath,
ex... | interface BootstrapState {
isInChildProcess: boolean;
shouldUseChildProcess: boolean;
/**
* True if bootstrapping the ts-node CLI process or the direct child necessitated by `--esm`.
* false if bootstrapping a subsequently `fork()`ed child.
*/
isCli: boolean;
tsNodeScript: string;
parseArgvResult: ... |
478 | function evalAndExitOnTsError(
replService: ReplService,
module: Module,
code: string,
isPrinted: boolean,
filenameAndDirname: 'eval' | 'stdin'
) {
let result: any;
setupContext(global, module, filenameAndDirname);
try {
result = replService.evalCode(code);
} catch (error) {
if (error instanc... | interface ReplService {
readonly state: EvalState;
/**
* Bind this REPL to a ts-node compiler service. A compiler service must be bound before `eval`-ing code or starting the REPL
*/
setService(service: Service): void;
/**
* Append code to the virtual <repl> source file, compile it to JavaScript, thro... |
479 | function registerAndCreateEsmHooks(opts?: RegisterOptions) {
// Automatically performs registration just like `-r ts-node/register`
const tsNodeInstance = register(opts);
return createEsmHooks(tsNodeInstance);
} | interface RegisterOptions extends CreateOptions {
/**
* Enable experimental features that re-map imports and require calls to support:
* `baseUrl`, `paths`, `rootDirs`, `.js` to `.ts` file extension mappings,
* `outDir` to `rootDir` mappings for composite projects and monorepos.
*
* For details, see ht... |
480 | function createEsmHooks(tsNodeService: Service) {
// Custom implementation that considers additional file extensions and automatically adds file extensions
const nodeResolveImplementation = tsNodeService.getNodeEsmResolver();
const nodeGetFormatImplementation = tsNodeService.getNodeEsmGetFormat();
const extensi... | interface Service {
/** @internal */
[TS_NODE_SERVICE_BRAND]: true;
ts: TSCommon;
/** @internal */
compilerPath: string;
config: _ts.ParsedCommandLine;
options: RegisterOptions;
enabled(enabled?: boolean): boolean;
ignored(fileName: string): boolean;
compile(code: string, fileName: string, lineOffse... |
481 | function fixConfig(ts: TSCommon, config: _ts.ParsedCommandLine) {
// Delete options that *should not* be passed through.
delete config.options.out;
delete config.options.outFile;
delete config.options.composite;
delete config.options.declarationDir;
delete config.options.declarationMap;
delete config.opti... | interface TSCommon {
version: typeof _ts.version;
sys: typeof _ts.sys;
ScriptSnapshot: typeof _ts.ScriptSnapshot;
displayPartsToString: typeof _ts.displayPartsToString;
createLanguageService: typeof _ts.createLanguageService;
getDefaultLibFilePath: typeof _ts.getDefaultLibFilePath;
getPreEmitDiagnostics: ... |
482 | function findAndReadConfig(rawOptions: CreateOptions) {
const cwd = resolve(
rawOptions.cwd ?? rawOptions.dir ?? DEFAULTS.cwd ?? process.cwd()
);
const compilerName = rawOptions.compiler ?? DEFAULTS.compiler;
// Compute minimum options to read the config file.
let projectLocalResolveDir = getBasePathForP... | interface CreateOptions {
/**
* Behave as if invoked within this working directory. Roughly equivalent to `cd $dir && ts-node ...`
*
* @default process.cwd()
*/
cwd?: string;
/**
* Legacy alias for `cwd`
*
* @deprecated use `projectSearchDir` or `cwd`
*/
dir?: string;
/**
* Emit ou... |
483 | function createTsInternalsUncached(_ts: TSCommon) {
const ts = _ts as TSCommon & TSInternal;
/**
* Copied from:
* https://github.com/microsoft/TypeScript/blob/v4.3.2/src/compiler/commandLineParser.ts#L2821-L2846
*/
function getExtendsConfigPath(
extendedConfig: string,
host: _ts.ParseConfigHost,
... | interface TSCommon {
version: typeof _ts.version;
sys: typeof _ts.sys;
ScriptSnapshot: typeof _ts.ScriptSnapshot;
displayPartsToString: typeof _ts.displayPartsToString;
createLanguageService: typeof _ts.createLanguageService;
getDefaultLibFilePath: typeof _ts.getDefaultLibFilePath;
getPreEmitDiagnostics: ... |
484 | (value: T) => boolean | type T = ExecutionContext<ctxTsNode.Ctx>; |
485 | function getDefaultTsconfigJsonForNodeVersion(ts: TSCommon): any {
const tsInternal = ts as any as TSInternal;
if (nodeMajor >= 18) {
const config = require('@tsconfig/node18/tsconfig.json');
if (configCompatible(config)) return config;
}
if (nodeMajor >= 16) {
const config = require('@tsconfig/node... | interface TSCommon {
version: typeof _ts.version;
sys: typeof _ts.sys;
ScriptSnapshot: typeof _ts.ScriptSnapshot;
displayPartsToString: typeof _ts.displayPartsToString;
createLanguageService: typeof _ts.createLanguageService;
getDefaultLibFilePath: typeof _ts.getDefaultLibFilePath;
getPreEmitDiagnostics: ... |
486 | function createTsTranspileModule(
ts: TSCommon,
transpileOptions: Pick<
TranspileOptions,
'compilerOptions' | 'reportDiagnostics' | 'transformers'
>
) {
const {
createProgram,
createSourceFile,
getDefaultCompilerOptions,
getImpliedNodeFormatForFile,
fixupCompilerOptions,
transpil... | interface TSCommon {
version: typeof _ts.version;
sys: typeof _ts.sys;
ScriptSnapshot: typeof _ts.ScriptSnapshot;
displayPartsToString: typeof _ts.displayPartsToString;
createLanguageService: typeof _ts.createLanguageService;
getDefaultLibFilePath: typeof _ts.getDefaultLibFilePath;
getPreEmitDiagnostics: ... |
487 | function installCommonjsResolveHooksIfNecessary(tsNodeService: Service) {
const Module = require('module') as ModuleConstructorWithInternals;
const originalResolveFilename = Module._resolveFilename;
const originalFindPath = Module._findPath;
const shouldInstallHook = tsNodeService.options.experimentalResolver;
... | interface Service {
/** @internal */
[TS_NODE_SERVICE_BRAND]: true;
ts: TSCommon;
/** @internal */
compilerPath: string;
config: _ts.ParsedCommandLine;
options: RegisterOptions;
enabled(enabled?: boolean): boolean;
ignored(fileName: string): boolean;
compile(code: string, fileName: string, lineOffse... |
488 | function errorPostprocessor<T extends Function>(fn: T): T {
return async function (this: any) {
try {
return await fn.call(this, arguments);
} catch (error: any) {
delete error?.matcherResult;
// delete error?.matcherResult?.message;
if (error?.message) error.message = `\n${error.messa... | type T = ExecutionContext<ctxTsNode.Ctx>; |
489 | function once<T extends Function>(func: T): T {
let run = false;
let ret: any = undefined;
return function (...args: any[]) {
if (run) return ret;
run = true;
ret = func(...args);
return ret;
} as any as T;
} | type T = ExecutionContext<ctxTsNode.Ctx>; |
490 | function createExec<T extends Partial<ExecOptions>>(
preBoundOptions?: T
) {
/**
* Helper to exec a child process.
* Returns a Promise and a reference to the child process to suite multiple situations.
* Promise resolves with the process's stdout, stderr, and error.
*/
return function exec(
cmd: s... | type T = ExecutionContext<ctxTsNode.Ctx>; |
491 | function createSpawn<T extends Partial<SpawnOptions>>(
preBoundOptions?: T
) {
/**
* Helper to spawn a child process.
* Returns a Promise and a reference to the child process to suite multiple situations.
*
* Should almost always avoid this helper, and instead use `createExec` / `exec`. `spawn`
* ma... | type T = ExecutionContext<ctxTsNode.Ctx>; |
492 | function createExecTester<T extends Partial<ExecTesterOptions>>(
preBoundOptions: T
) {
return async function (
options: Pick<
ExecTesterOptions,
Exclude<keyof ExecTesterOptions, keyof T>
> &
Partial<Pick<ExecTesterOptions, keyof T & keyof ExecTesterOptions>>
) {
const {
cmd,
... | type T = ExecutionContext<ctxTsNode.Ctx>; |
493 | function declareProject(_test: Test, project: Project) {
const test =
project.useTsNodeNext && !tsSupportsStableNodeNextNode16
? _test.skip
: _test;
test(`${project.identifier}`, async (t) => {
t.teardown(() => {
resetNodeEnvironment();
});
const p = fsProject(project.identifier);... | type Test = TestInterface<ctxTsNode.Ctx>; |
494 | function declareProject(_test: Test, project: Project) {
const test =
project.useTsNodeNext && !tsSupportsStableNodeNextNode16
? _test.skip
: _test;
test(`${project.identifier}`, async (t) => {
t.teardown(() => {
resetNodeEnvironment();
});
const p = fsProject(project.identifier);... | type Test = typeof test; |
495 | function declareProject(_test: Test, project: Project) {
const test =
project.useTsNodeNext && !tsSupportsStableNodeNextNode16
? _test.skip
: _test;
test(`${project.identifier}`, async (t) => {
t.teardown(() => {
resetNodeEnvironment();
});
const p = fsProject(project.identifier);... | interface Project {
identifier: string;
allowJs: boolean;
preferSrc: boolean;
typeModule: boolean;
/** Use TS's new module: `nodenext` option */
useTsNodeNext: boolean;
experimentalSpecifierResolutionNode: boolean;
skipIgnore: boolean;
} |
496 | function declareProject(_test: Test, project: Project) {
const test =
project.useTsNodeNext && !tsSupportsStableNodeNextNode16
? _test.skip
: _test;
test(`${project.identifier}`, async (t) => {
t.teardown(() => {
resetNodeEnvironment();
});
const p = fsProject(project.identifier);... | type Project = ReturnType<typeof project>; |
497 | function generateTargets(project: Project, p: FsProject) {
/** Array of metadata about target files to be imported */
const targets: Array<Target> = [];
// TODO does allowJs matter?
for (const inOut of [false, true]) {
for (const inSrc of [false, true]) {
for (const srcExt of [
'ts',
'... | interface Project {
identifier: string;
allowJs: boolean;
preferSrc: boolean;
typeModule: boolean;
/** Use TS's new module: `nodenext` option */
useTsNodeNext: boolean;
experimentalSpecifierResolutionNode: boolean;
skipIgnore: boolean;
} |
498 | function generateTargets(project: Project, p: FsProject) {
/** Array of metadata about target files to be imported */
const targets: Array<Target> = [];
// TODO does allowJs matter?
for (const inOut of [false, true]) {
for (const inSrc of [false, true]) {
for (const srcExt of [
'ts',
'... | type Project = ReturnType<typeof project>; |
499 | function generateTarget(
project: Project,
p: FsProject,
options: GenerateTargetOptions
) {
const {
inSrc,
inOut,
srcExt,
targetPackageStyle,
packageTypeModule,
isIndex,
} = options;
const outExt = srcExt.replace('ts', 'js').replace('x', '');
let targetIdentifier = `target-${targe... | interface GenerateTargetOptions {
inSrc: boolean;
inOut: boolean;
srcExt: string;
/** If true, is an index.* file within a directory */
isIndex: boolean;
targetPackageStyle: TargetPackageStyle;
packageTypeModule: boolean;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.