http#RequestOptions TypeScript Examples

The following examples show how to use http#RequestOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DifferentialDownloader.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
createRequestOptions(): RequestOptions {
    const result = {
      headers: {
        ...this.options.requestHeaders,
        accept: "*/*"
      }
    };
    configureRequestUrl(this.options.newUrl, result);
    // user-agent, cache-control and other common options
    configureRequestOptions(result);
    return result;
  }
Example #2
Source File: DifferentialDownloader.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
private request(
    requestOptions: RequestOptions,
    dataHandler: (chunk: Buffer) => void
  ): Promise<void> {
    return new Promise((resolve, reject) => {
      const request = this.httpExecutor.createRequest(
        requestOptions,
        response => {
          if (!checkIsRangesSupported(response, reject)) {
            return;
          }

          response.on("data", dataHandler);
          response.on("end", () => resolve());
        }
      );
      this.httpExecutor.addErrorAndTimeoutHandlers(request, reject);
      request.end();
    });
  }
Example #3
Source File: electronHttpExecutor.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
protected addRedirectHandlers(request: ClientRequest, options: RequestOptions, reject: (error: Error) => void, redirectCount: number, handler: (options: RequestOptions) => void): void {
    request.on("redirect", (statusCode: number, method: string, redirectUrl: string) => {
      // no way to modify request options, abort old and make a new one
      // https://github.com/electron/electron/issues/11505
      request.abort()

      if (redirectCount > this.maxRedirects) {
        reject(this.createMaxRedirectError())
      }
      else {
        handler(HttpExecutor.prepareRedirectUrlOptions(redirectUrl, options))
      }
    })
  }
Example #4
Source File: Provider.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
protected createRequestOptions(url: URL, headers?: OutgoingHttpHeaders | null): RequestOptions {
    const result: RequestOptions = {}
    if (this.requestHeaders == null) {
      if (headers != null) {
        result.headers = headers
      }
    }
    else {
      result.headers = headers == null ? this.requestHeaders : {...this.requestHeaders, ...headers}
    }

    configureRequestUrl(url, result)
    return result
  }
Example #5
Source File: fetchSourceMap.ts    From web with MIT License 6 votes vote down vote up
async function doFetchSourceMap(
  code: string,
  browserUrl: string,
  reqOpts: RequestOptions,
): Promise<SourceMapConverter | undefined> {
  try {
    const match = code.match(mapFileCommentRegex);
    if (!match || !match[0]) {
      return;
    }

    const [sourceMapComment] = match;
    const sourceMapUrl = sourceMapComment.replace('//# sourceMappingURL=', '');
    if (sourceMapUrl.startsWith('data')) {
      // this is a data url
      return fromSource(code) ?? undefined;
    }

    // this is a source map pointing to another file, fetch it
    const dir = path.posix.dirname(browserUrl.split('?')[0].split('#')[0]);
    const sourcMapPath = path.join(dir, sourceMapUrl);
    const { response: sourceMapResponse, body: sourceMap } = await request({
      ...reqOpts,
      path: encodeURI(sourcMapPath),
    });

    if (!is2xxResponse(sourceMapResponse.statusCode) || !sourceMap) {
      return;
    }

    return fromJSON(sourceMap);
  } catch (error) {
    console.error(`Error retrieving source map for ${browserUrl}`);
    console.error(error);
  }
}
Example #6
Source File: fetchSourceMap.ts    From web with MIT License 6 votes vote down vote up
/**
 * Fetches the source maps for a file by retreiving the original source code from the server, and
 * reading the source maps if there are any available.
 */
export async function fetchSourceMap(args: FetchCodeArgs): Promise<FetchCodeReturnValue> {
  const headers: Record<string, string> = args.userAgent ? { 'user-agent': args.userAgent } : {};
  const reqOpts: RequestOptions = {
    protocol: args.protocol,
    host: args.host,
    port: String(args.port),
    method: 'GET',
    headers,
    timeout: 5000,
  };

  // fetch the source code used by the browser, using the browser's user agent to
  // account for accurate transformation
  const { response, body: source } = await request({
    ...reqOpts,
    path: encodeURI(args.browserUrl),
  });

  // we couldn't retreive this file, this could be because it is a generated file
  // from a server plugin which no longer exists
  if (!is2xxResponse(response.statusCode) || !source) {
    return {};
  }

  const sourceMap = await doFetchSourceMap(source, args.browserUrl, reqOpts);
  if (!sourceMap) {
    return { source };
  }
  return { source, sourceMap };
}
Example #7
Source File: request.ts    From web with MIT License 6 votes vote down vote up
export function request(options: RequestOptions): Promise<Response> {
  const isHttps = options.protocol === 'https:';

  const requestFn = isHttps ? httpsRequest : httpRequest;

  if (isHttps) {
    (options as HttpsRequestOptions).rejectUnauthorized = false;
  }

  return new Promise((resolve, reject) => {
    const req = requestFn(options, response => {
      let body = '';
      response.on('data', chunk => {
        body += chunk;
      });

      response.on('end', () => {
        resolve({ response, body });
      });
    });

    req.on('error', err => {
      reject(err);
    });

    req.end();
  });
}
Example #8
Source File: PrivateGitHubProvider.ts    From electron-differential-updater with MIT License 5 votes vote down vote up
protected createRequestOptions(url: URL, headers?: OutgoingHttpHeaders | null): RequestOptions {
    const result = super.createRequestOptions(url, headers);
    (result as any).redirect = "manual"
    return result
  }
Example #9
Source File: karma-http-test-run-executor.ts    From karma-test-explorer with MIT License 5 votes vote down vote up
public executeTestRun(karmaPort: number, clientArgs: string[] = []): Execution {
    const deferredTestRunExecution = new DeferredExecution();

    const karmaRequestData = {
      // See: https://github.com/karma-runner/karma/blob/94cf15e8fa4420c8716998873b77f0c4f59b9e94/lib/runner.js#L100-L105
      args: clientArgs,
      refresh: DEFAULT_RUN_OPTIONS.refresh
    };

    const httpRequestOptions: RequestOptions = {
      hostname: DEFAULT_RUN_OPTIONS.hostname,
      path: DEFAULT_RUN_OPTIONS.urlRoot,
      port: karmaPort,
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    };

    const request = httpRequest(httpRequestOptions, responseMessage => {
      responseMessage.resume();

      responseMessage.on('end', () => {
        if (!responseMessage.complete) {
          this.logger.error(() => `Test run http connection was terminated before receiving the full response`);
        }
      });
    });

    request.on('error', err => {
      let errorMsg = `Karma http request error: ${err}`;

      if ((err as any).code === 'ECONNREFUSED') {
        errorMsg = `No karma server listening on port ${httpRequestOptions.port}`;
      }

      this.logger.error(() => errorMsg);
      deferredTestRunExecution.fail(errorMsg);
    });

    request.on('close', () => {
      this.logger.debug(() => 'Karma http request closed');
      deferredTestRunExecution.end();
    });

    const karmaRequestContent = JSON.stringify(karmaRequestData);

    this.logger.debug(() => `Sending karma run http request with data: ${karmaRequestContent}`);

    deferredTestRunExecution.start();

    request.end(karmaRequestContent, () => {
      this.logger.debug(() => 'Finished sending http test run request');
    });

    // TODO: Consider adding auto-fail timeout for when http request taking too long

    return deferredTestRunExecution.execution();
  }
Example #10
Source File: HttpPlugin.ts    From skywalking-nodejs with Apache License 2.0 4 votes vote down vote up
private interceptClientRequest(module: any, protocol: string) {
    const _request = module.request; // BUG! this doesn't work with "import {request} from http", but haven't found an alternative yet

    module.request = function () {
      const url: URL | string | RequestOptions = arguments[0];

      const { host, pathname } =
        url instanceof URL
          ? url
          : typeof url === 'string'
          ? new URL(url) // TODO: this may throw invalid URL
          : {
              host: (url.host || url.hostname || 'unknown') + ':' + (url.port || 80),
              pathname: url.path || '/',
            };

      const operation = pathname.replace(/\?.*$/g, '');
      const method = arguments[url instanceof URL || typeof url === 'string' ? 1 : 0]?.method || 'GET';
      const span = ignoreHttpMethodCheck(method)
        ? DummySpan.create()
        : ContextManager.current.newExitSpan(operation, Component.HTTP);

      if (span.depth)
        // if we inherited from a higher level plugin then do nothing, higher level should do all the work and we don't duplicate here
        return _request.apply(this, arguments);

      span.start();

      try {
        span.component = Component.HTTP;
        span.layer = SpanLayer.HTTP;
        span.peer = host;

        span.tag(Tag.httpURL(protocol + '://' + host + pathname));
        span.tag(Tag.httpMethod(method));

        const copyStatusAndWrapEmit = (res: any) => {
          span.tag(Tag.httpStatusCode(res.statusCode));

          if (res.statusCode && res.statusCode >= 400) span.errored = true;

          if (res.statusMessage) span.tag(Tag.httpStatusMsg(res.statusMessage));

          wrapEmit(span, res, false);
        };

        const responseCB = function (this: any, res: any) {
          // may wrap callback instead of event because it procs first
          span.resync();

          copyStatusAndWrapEmit(res);

          try {
            if (callback) return callback.apply(this, arguments);
          } catch (err) {
            span.error(err);

            throw err;
          } finally {
            span.async();
          }
        };

        const idxCallback = typeof arguments[2] === 'function' ? 2 : typeof arguments[1] === 'function' ? 1 : 0;
        const callback = arguments[idxCallback];

        if (idxCallback) arguments[idxCallback] = responseCB;

        let arg0 = arguments[0];
        const expect = arg0.headers && (arg0.headers.Expect || arg0.headers.expect);

        if (expect === '100-continue') {
          span.inject().items.forEach((item) => {
            arg0.headers[item.key] = item.value;
          });
        }

        const req: ClientRequest = _request.apply(this, arguments);

        span
          .inject()
          .items.filter((item) => expect != '100-continue')
          .forEach((item) => req.setHeader(item.key, item.value));

        wrapEmit(span, req, true, 'close');

        req.on('timeout', () => span.log('Timeout', true));
        req.on('abort', () => span.log('Abort', (span.errored = true)));

        if (!idxCallback) req.on('response', copyStatusAndWrapEmit);

        span.async();

        return req;
      } catch (err) {
        span.error(err);
        span.stop();

        throw err;
      }
    };
  }