node-runtime.mjs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import * as nf from 'node-fetch';
  2. import * as fd from 'formdata-node';
  3. import KeepAliveAgent from 'agentkeepalive';
  4. import { AbortController as AbortControllerPolyfill } from 'abort-controller';
  5. import { ReadStream as FsReadStream } from 'node:fs';
  6. import { FormDataEncoder } from 'form-data-encoder';
  7. import { Readable } from 'node:stream';
  8. import { MultipartBody } from "./MultipartBody.mjs";
  9. import { ReadableStream } from 'node:stream/web';
  10. let fileFromPathWarned = false;
  11. async function fileFromPath(path, ...args) {
  12. // this import fails in environments that don't handle export maps correctly, like old versions of Jest
  13. const { fileFromPath: _fileFromPath } = await import('formdata-node/file-from-path');
  14. if (!fileFromPathWarned) {
  15. console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`);
  16. fileFromPathWarned = true;
  17. }
  18. // @ts-ignore
  19. return await _fileFromPath(path, ...args);
  20. }
  21. const defaultHttpAgent = new KeepAliveAgent({ keepAlive: true, timeout: 5 * 60 * 1000 });
  22. const defaultHttpsAgent = new KeepAliveAgent.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 });
  23. async function getMultipartRequestOptions(form, opts) {
  24. const encoder = new FormDataEncoder(form);
  25. const readable = Readable.from(encoder);
  26. const body = new MultipartBody(readable);
  27. const headers = {
  28. ...opts.headers,
  29. ...encoder.headers,
  30. 'Content-Length': encoder.contentLength,
  31. };
  32. return { ...opts, body: body, headers };
  33. }
  34. export function getRuntime() {
  35. // Polyfill global object if needed.
  36. if (typeof AbortController === 'undefined') {
  37. // @ts-expect-error (the types are subtly different, but compatible in practice)
  38. globalThis.AbortController = AbortControllerPolyfill;
  39. }
  40. return {
  41. kind: 'node',
  42. fetch: nf.default,
  43. Request: nf.Request,
  44. Response: nf.Response,
  45. Headers: nf.Headers,
  46. FormData: fd.FormData,
  47. Blob: fd.Blob,
  48. File: fd.File,
  49. ReadableStream,
  50. getMultipartRequestOptions,
  51. getDefaultAgent: (url) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent),
  52. fileFromPath,
  53. isFsReadStream: (value) => value instanceof FsReadStream,
  54. };
  55. }
  56. //# sourceMappingURL=node-runtime.mjs.map