{"type":"module","name":"form-data-encoder","version":"2.1.4","description":"Encode FormData content into the multipart/form-data format","repository":{"type":"git","url":"git+https://github.com/octet-stream/form-data-encoder.git"},"sideEffects":false,"engines":{"node":">= 14.17"},"keywords":["form-data","encoder","multipart","files-upload","async-iterator","spec-compatible","form"],"main":"./lib/index.js","module":"./lib/index.js","exports":{"types":"./@type/index.d.ts","default":"./lib/index.js"},"types":"./@type/index.d.ts","scripts":{"eslint":"eslint src/**/*.ts","staged":"lint-staged","coverage":"c8 npm test","ci":"c8 npm test && c8 report --reporter=json","build:types":"tsc --project tsconfig.d.ts.json","build":"tsc && npm run build:types","test":"ava --fail-fast","cleanup":"del-cli @type lib","prepare":"npm run cleanup && npm run build","_postinstall":"husky install","prepublishOnly":"pinst --disable","postpublish":"pinst --enable"},"author":{"name":"Nick K."},"license":"MIT","devDependencies":{"@octetstream/eslint-config":"6.2.2","@types/mime-types":"2.1.1","@types/node":"18.11.9","@types/sinon":"^10.0.13","@typescript-eslint/eslint-plugin":"5.44.0","@typescript-eslint/parser":"5.44.0","ava":"5.1.0","c8":"7.12.0","del-cli":"5.0.0","eslint":"8.28.0","eslint-config-airbnb-typescript":"17.0.0","eslint-import-resolver-typescript":"3.5.2","eslint-plugin-ava":"13.2.0","eslint-plugin-import":"^2.26.0","eslint-plugin-jsx-a11y":"6.6.1","eslint-plugin-react":"7.31.11","formdata-node":"5.0.0","husky":"8.0.2","lint-staged":"13.0.3","pinst":"3.0.0","sinon":"^14.0.2","ts-node":"10.9.1","ttypescript":"1.5.13","typescript":"4.9.3","web-streams-polyfill":"4.0.0-beta.3"},"gitHead":"9d92640f60586592dc35d3ff6dd3c2f6c4abdfd2","bugs":{"url":"https://github.com/octet-stream/form-data-encoder/issues"},"homepage":"https://github.com/octet-stream/form-data-encoder#readme","_id":"form-data-encoder@2.1.4","_nodeVersion":"19.1.0","_npmVersion":"8.19.3","dist":{"integrity":"sha512-yDYSgNMraqvnxiEXO4hi88+YZxaHC6QKzb5N84iRCTDeRO7ZALpir/lVmf/uXUhnwUr2O4HU8s/n6x+yNjQkHw==","shasum":"261ea35d2a70d48d30ec7a9603130fa5515e9cd5","tarball":"http://registry-npm.ywwl.com/form-data-encoder/download/form-data-encoder-2.1.4.tgz","fileCount":31,"unpackedSize":37571,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCyRqDsY/3rfuZv+RpSdT5y4i7OexHawHty/p6Tq7OjrAIgDbo+dkrwcfaW1YBDwUJ2Jo3NDvMyy8ewd8Vz8U9q/ug="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjf3wAACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmr79A/+I5A7dCf4UtJI0iAwjQbJOA4UuwY5nWnGPjRS3l7AYl5wHB8B\r\nuhaNIXdsWgXK9BZs5lArqDbddmKSW5CZf3Sxj/ES+0LmOW1O9/OfJYcULhWX\r\n8xxTDuKyuS5tcG9ZnDh5tZhs59hQ8y35l/5E1XWmdcw2MQkjisJmDRjzgcX8\r\nPyQLiVKqzST22BjK7CFPIojcynh6VW0Pepw/1DCZAEwhv3MZFpe+e5neyPyM\r\ng8t5xPSrUFNLN7ZYWiSxCYIU7p4DMmg1tdwTakK/1SWuQobgRfb5vs/hQgYW\r\ndAwvEdHmxjN6ZIe45t6rpTjeoMYXoQQq9dU/f3iURaL/wSLDyleKznJJ/XD/\r\nSV05F48HJ+1EUZUYrD6zhh9UNexPc0gdjSZlJ6ADPgOEj35u2zmNGoZwrvXm\r\nEg936v+D1s3mx9JJWtYSqN6TYCsYu0m2TaVjt6dC7750K7b4NhCN+eldF2as\r\nJi0qo8kECKc+KCiBvzQoh4ZUVweEWuqznxMK+YNLZZjT9TcpQasBtsHZq9IL\r\neXiotjhVsqlJob/fR0t4inqRRXgFsstm4M2+VpiPJ2tbH5TmqciEgJFEQQ+Y\r\nHUhwaZLPuUvvhPhIdamVOZi9pR2vfinndoikUtAVUepNJeQSd10c3rX4OQBI\r\nO3okcf1lAWLYg/GCRwJtcI8EjgPzrqBTKPc=\r\n=dtAj\r\n-----END PGP SIGNATURE-----\r\n","size":10231,"noattachment":false,"key":"/form-data-encoder/-/form-data-encoder-2.1.4.tgz"},"_npmUser":{"name":"octetstream","email":"nick.kruchinin@gmail.com"},"directories":{},"maintainers":[{"name":"octetstream","email":"nick.kruchinin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/form-data-encoder_2.1.4_1669299200065_0.5747677375185671"},"_hasShrinkwrap":false,"readme":"# form-data-encoder\n\nEncode `FormData` content into the `multipart/form-data` format\n\n[![Code Coverage](https://codecov.io/github/octet-stream/form-data-encoder/coverage.svg?branch=main)](https://codecov.io/github/octet-stream/form-data-encoder?branch=main)\n[![CI](https://github.com/octet-stream/form-data-encoder/workflows/CI/badge.svg)](https://github.com/octet-stream/form-data-encoder/actions/workflows/ci.yml)\n[![ESLint](https://github.com/octet-stream/form-data-encoder/workflows/ESLint/badge.svg)](https://github.com/octet-stream/form-data-encoder/actions/workflows/eslint.yml)\n[![TypeScript Types](https://github.com/octet-stream/form-data-encoder/actions/workflows/typescript.yml/badge.svg)](https://github.com/octet-stream/form-data-encoder/actions/workflows/typescript.yml)\n\n## Requirements\n\n- Node.js v18.0.0 or higher;\n- Runtime should support `TextEncoder`, `TextDecoder`, `WeakMap`, `WeakSet` and async generator functions;\n- For TypeScript users: tsc v4.3 or higher.\n\n## Installation\n\nYou can install this package using npm:\n\n```sh\nnpm install form-data-encoder\n```\n\nOr yarn:\n\n```sh\nyarn add form-data-encoder\n```\n\nOr pnpm:\n\n```sh\npnpm add form-data-encoder\n```\n\n## Usage\n\n1. To start the encoding process, you need to create a new Encoder instance with the FormData you want to encode:\n\n```js\nimport {Readable} from \"stream\"\n\nimport {FormData, File} from \"formdata-node\"\nimport {FormDataEncoder} from \"form-data-encoder\"\n\nimport fetch from \"node-fetch\"\n\nconst form = new FormData()\n\nform.set(\"greeting\", \"Hello, World!\")\nform.set(\"file\", new File([\"On Soviet Moon landscape see binoculars through YOU\"], \"file.txt\"))\n\nconst encoder = new FormDataEncoder(form)\n\nconst options = {\n  method: \"post\",\n\n  // Set request headers provided by the Encoder.\n  // The `headers` property has `Content-Type` and `Content-Length` headers.\n  headers: encoder.headers,\n\n  // Create a Readable stream from the Encoder.\n  // You can omit usage of `Readable.from` for HTTP clients whose support async iterables in request body.\n  // The Encoder will yield FormData content portions encoded into the multipart/form-data format as node-fetch consumes the stream.\n  body: Readable.from(encoder.encode()) // or just Readable.from(encoder)\n}\n\nconst response = await fetch(\"https://httpbin.org/post\", options)\n\nconsole.log(await response.json())\n```\n\n2. Encoder support different spec-compatible FormData implementations. Let's try it with [`formdata-polyfill`](https://github.com/jimmywarting/FormData):\n\n```js\nimport {Readable} from \"stream\"\n\nimport {FormDataEncoder} from \"form-data-encoder\"\nimport {FormData} from \"formdata-polyfill/esm-min.js\"\nimport {File} from \"fetch-blob\" // v3\n\nconst form = new FormData()\n\nform.set(\"field\", \"Some value\")\nform.set(\"file\", new File([\"File content goes here\"], \"file.txt\"))\n\nconst encoder = new FormDataEncoder(form)\n\nconst options = {\n  method: \"post\",\n  headers: encoder.headers,\n  body: Readable.from(encoder)\n}\n\nawait fetch(\"https://httpbin.org/post\", options)\n```\n\n3. Because the Encoder is iterable (it has both Symbol.asyncIterator and Symbol.iterator methods), you can use it with different targets. Let's say you want to convert FormData content into `Blob`, for that you can write a function like this:\n\n```js\nimport {Readable} from \"stream\"\n\nimport {FormDataEncoder} from \"form-data-encoder\"\nimport {FormData, File, Blob} from \"formdata-node\"\nimport {fileFromPath} from \"formdata-node/file-from-path\"\n\nimport fetch from \"node-fetch\"\n\nconst form = new FormData()\n\nform.set(\"field\", \"Just a random string\")\nform.set(\"file\", new File([\"Using files is class amazing\"], \"file.txt\"))\nform.set(\"fileFromPath\", await fileFromPath(\"path/to/a/file.txt\"))\n\n// Note 1: When using with native Blob or fetch-blob@2 you might also need to generate boundary string for your FormDataEncoder instance\n// because Blob will lowercase value of the `type` option and default boundary generator produces a string with both lower and upper cased alphabetical characters. Math.random() should be enough to fix this:\n// const encoder = new FormDataEncoder(form, String(Math.random()))\nconst encoder = new FormDataEncoder(form)\n\nconst options = {\n  method: \"post\",\n\n  // Note 2: To use this approach with fetch-blob@2 you probably gonna need to convert the encoder parts output to an array first:\n  // new Blob([...encoder], {type: encoder.contentType})\n  body: new Blob(encoder, {type: encoder.contentType})\n}\n\nconst response = await fetch(\"https://httpbin.org/post\", options)\n\nconsole.log(await response.json())\n```\n\n4. Here's FormData to Blob conversion with async-iterator approach:\n\n```js\nimport {FormData} from \"formdata-polyfill/esm-min.js\"\nimport {FormDataEncoder} from \"form-data-encoder\"\nimport {blobFrom} from \"fetch-blob/from.js\"\n\nimport Blob from \"fetch-blob\"\nimport fetch from \"node-fetch\"\n\n// This approach may require much more RAM compared to the previous one, but it works too.\nasync function toBlob(form) {\n  const encoder = new Encoder(form)\n  const chunks = []\n\n  for await (const chunk of encoder) {\n    chunks.push(chunk)\n  }\n\n  return new Blob(chunks, {type: encoder.contentType})\n}\n\nconst form = new FormData()\n\nform.set(\"name\", \"John Doe\")\nform.set(\"avatar\", await blobFrom(\"path/to/an/avatar.png\"), \"avatar.png\")\n\nconst options = {\n  method: \"post\",\n  body: await toBlob(form)\n}\n\nawait fetch(\"https://httpbin.org/post\", options)\n```\n\n5. Another way to convert FormData parts to blob using `form-data-encoder` is making a Blob-ish class:\n\n```js\nimport {Readable} from \"stream\"\n\nimport {FormDataEncoder} from \"form-data-encoder\"\nimport {FormData} from \"formdata-polyfill/esm-min.js\"\nimport {blobFrom} from \"fetch-blob/from.js\"\n\nimport Blob from \"fetch-blob\"\nimport fetch from \"node-fetch\"\n\nclass BlobDataItem {\n  constructor(encoder) {\n    this.#encoder = encoder\n    this.#size = encoder.headers[\"Content-Length\"]\n    this.#type = encoder.headers[\"Content-Type\"]\n  }\n\n  get type() {\n    return this.#type\n  }\n\n  get size() {\n    return this.#size\n  }\n\n  stream() {\n    return Readable.from(this.#encoder)\n  }\n\n  get [Symbol.toStringTag]() {\n    return \"Blob\"\n  }\n}\n\nconst form = new FormData()\n\nform.set(\"name\", \"John Doe\")\nform.set(\"avatar\", await blobFrom(\"path/to/an/avatar.png\"), \"avatar.png\")\n\nconst encoder = new FormDataEncoder(form)\n\n// Note that node-fetch@2 performs more strictness tests for Blob objects, so you may need to do extra steps before you set up request body (like, maybe you'll need to instaniate a Blob with BlobDataItem as one of its blobPart)\nconst blob = new BlobDataItem(enocoder) // or new Blob([new BlobDataItem(enocoder)], {type: encoder.contentType})\n\nconst options = {\n  method: \"post\",\n  body: blob\n}\n\nawait fetch(\"https://httpbin.org/post\", options)\n```\n\n6. In this example we will pull FormData content into the ReadableStream:\n\n```js\n // This module is only necessary when you targeting Node.js or need web streams that implement Symbol.asyncIterator\nimport {ReadableStream} from \"web-streams-polyfill/ponyfill/es2018\"\n\nimport {FormDataEncoder} from \"form-data-encoder\"\nimport {FormData} from \"formdata-node\"\n\nimport fetch from \"node-fetch\"\n\nfunction toReadableStream(encoder) {\n  const iterator = encoder.encode()\n\n  return new ReadableStream({\n    async pull(controller) {\n      const {value, done} = await iterator.next()\n\n      if (done) {\n        return controller.close()\n      }\n\n      controller.enqueue(value)\n    }\n  })\n}\n\nconst form = new FormData()\n\nform.set(\"field\", \"My hovercraft is full of eels\")\n\nconst encoder = new FormDataEncoder(form)\n\nconst options = {\n  method: \"post\",\n  headers: encoder.headers,\n  body: toReadableStream(encoder)\n}\n\n// Note that this example requires `fetch` to support Symbol.asyncIterator, which node-fetch lacks of (but will support eventually)\nawait fetch(\"https://httpbin.org/post\", options)\n```\n\n7. Speaking of async iterables - if HTTP client supports them, you can use encoder like this:\n\n```js\nimport {FormDataEncoder} from \"form-data-encoder\"\nimport {FormData} from \"formdata-node\"\n\nimport fetch from \"node-fetch\"\n\nconst form = new FormData()\n\nform.set(\"field\", \"My hovercraft is full of eels\")\n\nconst encoder = new FormDataEncoder(form)\n\nconst options = {\n  method: \"post\",\n  headers: encoder.headers,\n  body: encoder\n}\n\nawait fetch(\"https://httpbin.org/post\", options)\n```\n\n8. ...And for those client whose supporting form-data-encoder out of the box, the usage will be much, much more simpler:\n\n```js\nimport {FormData} from \"formdata-node\" // Or any other spec-compatible implementation\n\nimport fetch from \"node-fetch\"\n\nconst form = new FormData()\n\nform.set(\"field\", \"My hovercraft is full of eels\")\n\nconst options = {\n  method: \"post\",\n  body: form\n}\n\n// Note that node-fetch does NOT support form-data-encoder\nawait fetch(\"https://httpbin.org/post\", options)\n```\n\n## API\n\n### `class FormDataEncoder`\n\n##### `constructor(form[, boundary, options]) -> {FormDataEncoder}`\n\n  - **{FormDataLike}** form - FormData object to encode. This object must be a spec-compatible FormData implementation.\n  - **{string}** [boundary] - An optional boundary string that will be used by the encoder. If there's no boundary string is present, FormDataEncoder will generate it automatically.\n  - **{object}** [options] - FormDataEncoder options.\n  - **{boolean}** [options.enableAdditionalHeaders = false] - When enabled, the encoder will emit additional per part headers, such as `Content-Length`. Please note that the web clients do not include these, so when enabled this option might cause an error if `multipart/form-data` does not consider additional headers.\n\nCreates a `multipart/form-data` encoder.\n\n#### Instance properties\n\n##### `boundary -> {string}`\n\nReturns boundary string.\n\n##### `contentType -> {string}`\n\nReturns Content-Type header.\n\n##### `contentLength -> {string}`\n\nReturn Content-Length header.\n\n##### `headers -> {object}`\n\nReturns headers object with Content-Type and Content-Length header.\n\n#### Instance methods\n\n##### `values() -> {Generator<Uint8Array | FileLike, void, undefined>}`\n\nCreates an iterator allowing to go through form-data parts (with metadata).\nThis method **will not** read the files and **will not** split values big into smaller chunks.\n\n##### `encode() -> {AsyncGenerator<Uint8Array, void, undefined>}`\n\nCreates an async iterator allowing to perform the encoding by portions.\nThis method reads through files and splits big values into smaller pieces (65536 bytes per each).\n\n##### `[Symbol.iterator]() -> {Generator<Uint8Array | FileLike, void, undefined>}`\n\nAn alias for `Encoder#values()` method.\n\n##### `[Symbol.asyncIterator]() -> {AsyncGenerator<Uint8Array, void, undefined>}`\n\nAn alias for `Encoder#encode()` method.\n\n### `isFile(value) -> {boolean}`\n\nCheck if a value is File-ish object.\n\n  - **{unknown}** value - a value to test\n\n### `isFormData(value) -> {boolean}`\n\nCheck if a value is FormData-ish object.\n\n  - **{unknown}** value - a value to test\n","publish_time":1669299200211,"_cnpm_publish_time":1669299200211,"dist-tags":{"cjs":"1.9.0","latest":"4.1.0"}}