{"id":20424283,"url":"https://github.com/writer/writer-node","last_synced_at":"2025-06-29T01:37:27.772Z","repository":{"id":242720932,"uuid":"810299159","full_name":"writer/writer-node","owner":"writer","description":"The official Node library for the Writer API","archived":false,"fork":false,"pushed_at":"2025-06-23T19:20:53.000Z","size":1086,"stargazers_count":12,"open_issues_count":1,"forks_count":1,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-06-23T20:27:05.127Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/writer.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-06-04T12:28:57.000Z","updated_at":"2025-05-07T23:32:57.000Z","dependencies_parsed_at":"2024-08-14T11:20:22.930Z","dependency_job_id":"c22d5fd9-19ca-4774-96b5-a53a220adade","html_url":"https://github.com/writer/writer-node","commit_stats":null,"previous_names":["writerai/writer-node","writer/writer-node"],"tags_count":21,"template":false,"template_full_name":null,"purl":"pkg:github/writer/writer-node","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/writer%2Fwriter-node","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/writer%2Fwriter-node/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/writer%2Fwriter-node/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/writer%2Fwriter-node/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/writer","download_url":"https://codeload.github.com/writer/writer-node/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/writer%2Fwriter-node/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262520579,"owners_count":23323732,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-15T07:09:06.171Z","updated_at":"2025-06-29T01:37:27.762Z","avatar_url":"https://github.com/writer.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Writer TypeScript API Library\n\n[![NPM version](https://img.shields.io/npm/v/writer-sdk.svg)](https://npmjs.org/package/writer-sdk) ![npm bundle size](https://img.shields.io/bundlephobia/minzip/writer-sdk)\n\nThis library provides access to the Writer REST API from server-side TypeScript(\u003e=4.9) or JavaScript.\n\nThe REST API documentation can be found on [dev.writer.com](https://dev.writer.com/api-guides/introduction). The full API of this library can be found in [api.md](api.md).\n\nIt is generated with [Stainless](https://www.stainless.com/).\n\n## Installation\n\n```sh\nnpm install writer-sdk\n```\n\n## Requirements\n\nYou need a [Writer API](https://dev.writer.com/api-guides/quickstart#generate-a-new-api-key) key to use this library.\n\n### Supported runtimes\n\n- Web browsers (Up-to-date Chrome, Firefox, Safari, Edge, and more)\n- Node.js 18 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions.\n- Deno v1.28.0 or higher.\n- Bun 1.0 or later.\n- Cloudflare Workers.\n- Vercel Edge Runtime.\n- Jest 28 or greater with the `\"node\"` environment (`\"jsdom\"` is not supported at this time).\n- Nitro v2.6 or greater.\n\n\u003e React Native is not supported at this time.\n\nIf you are interested in other runtime environments, please open or upvote an issue on GitHub.\n\n## Authentication\n\nTo authenticate with the Writer API, set the `WRITER_API_KEY` environment variable.\n\n```shell\n$ export WRITER_API_KEY=\"my-api-key\"\n```\n\nThe `Writer` class automatically infers your API key from the `WRITER_API_KEY` environment variable.\n\n```js\nimport Writer from 'writer-sdk';\n\nconst client = new Writer();\n```\n\nYou can also explicitly set the API key with the `apiKey` parameter:\n\n```js\nimport Writer from 'writer-sdk';\n\nconst client = new Writer({\n  apiKey: 'my-api-key',\n});\n```\n\n\u003e Never hard-code your API keys in source code or commit them to version control systems like GitHub.\n\u003e We recommend adding `WRITER_API_KEY=\"My API Key\"` to your `.env` file so that your API Key is not stored in source control. \n\n## Usage\n\nYou can find the full API for this library in [api.md](api.md).\n\n\u003c!-- prettier-ignore --\u003e\n```js\nimport Writer from 'writer-sdk';\n\nconst client = new Writer();\n\nasync function main() {\n  const chatCompletion = await client.chat.chat({\n    messages: [{ content: 'Write a haiku about programming', role: 'user' }],\n    model: 'palmyra-x5',\n  });\n\n  console.log(chatCompletion.choices[0].message.content);\n}\n\nmain();\n```\n\n### Streaming Helpers\n\nThe SDK also includes helpers to process streams and handle the incoming events.\n\n```ts\nconst runner = writer.chat\n  .stream({\n    model: 'palmyra-x5',\n    messages: [{ role: 'user', content: 'Hi, today I want to write about' }],\n  })\n  .on('message', (msg) =\u003e console.log(msg))\n  .on('content', (diff) =\u003e process.stdout.write(diff));\n\nconst result = await runner.finalChatCompletion();\nconsole.log(result);\n```\n\nMore information on streaming helpers can be found in the dedicated documentation: [helpers.md](helpers.md)\n\n## Streaming responses\n\nWe provide support for streaming responses using Server Sent Events (SSE).\n\n```ts\nimport Writer from 'writer-sdk';\n\nconst client = new Writer();\n\nconst stream = await client.chat.chat({\n  messages: [{ content: 'Write a haiku about programming', role: 'user' }],\n  model: 'palmyra-x5',\n  stream: true,\n});\nlet outputText = \"\";\nfor await (const chunk of stream) {\n    if (chunk.choices[0]?.delta?.content) {\n        outputText += chunk.choices[0].delta.content;\n    } else {\n        continue;\n    }\n}\nconsole.log(outputText);\n```\n\nIf you need to cancel a stream, you can `break` from the loop\nor call `stream.controller.abort()`.\n\n### Request and response types\n\nThis library includes TypeScript definitions for all request params and response fields. Import and use them like so:\n\n\u003c!-- prettier-ignore --\u003e\n```ts\nimport Writer from 'writer-sdk';\n\nconst client = new Writer();\n\nasync function main() {\n  const params: Writer.ChatChatParams = {\n    messages: [{ content: 'Write a haiku about programming', role: 'user' }],\n    model: 'palmyra-x5',\n  };\n  const chatCompletion: Writer.ChatCompletion = await client.chat.chat(params);\n}\n\nmain();\n```\n\nDocumentation for each method, request parameter, and response field are available in docstrings and will appear on hover in most modern editors.\n\n## File uploads\n\nRequest parameters that correspond to file uploads can be passed in many different forms:\n\n- `File` (or an object with the same structure)\n- a `fetch` `Response` (or an object with the same structure)\n- an `fs.ReadStream`\n- the return value of our `toFile` helper\n\nThe `Content-Type` parameter is the [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types/Common_types) of the file being uploaded. The file upload supports `txt`, `doc`, `docx`, `ppt`, `pptx`, `jpg`, `png`, `eml`, `html`, `pdf`, `srt`, `csv`, `xls`, and `xlsx` file extensions.\n\n```ts\nimport fs from 'fs';\nimport Writer, { toFile } from 'writer-sdk';\n\nconst client = new Writer();\n\n// If you have access to Node `fs` we recommend using `fs.createReadStream()`:\nawait client.files.upload({\n  content: fs.createReadStream('/path/to/file.pdf'),\n  'Content-Disposition': 'attachment; filename=\"example.pdf\"',\n  'Content-Type': 'application/pdf',\n});\n\n// If you have the web `File` API you can pass a `File` instance:\nawait client.files.upload({\n  content: new File(['my bytes'], 'example.txt'),\n  'Content-Disposition': 'attachment; filename=\"example.txt\"',\n  'Content-Type': 'text/plain',\n});\n\n// You can also pass a `fetch` `Response`:\nawait client.files.upload({\n  content: await fetch('https://example.com/example.pdf'),\n  'Content-Disposition': 'attachment; filename=\"example.pdf\"',\n  'Content-Type': 'application/pdf',\n});\n\n// Finally, if none of the above are convenient, you can use our `toFile` helper:\nawait client.files.upload({\n  content: await toFile(Buffer.from('my bytes'), 'example.txt'),\n  'Content-Disposition': 'attachment; filename=\"example.txt\"',\n  'Content-Type': 'text/plain',\n});\nawait client.files.upload({\n  content: await toFile(new Uint8Array([0, 1, 2]), 'example.txt'),\n  'Content-Disposition': 'attachment; filename=\"example.txt\"',\n  'Content-Type': 'text/plain',\n});\n```\n\n## Error handling\n\nWhen the library is unable to connect to the API (for example, due to a network connectivity problem or a firewall that doesn't allow the connection),\nor if the API returns a non-success status code (`4xx` or `5xx` response),\na subclass of `APIError` will be thrown.\n\n\u003e If you are behind a firewall, you may need to configure it to allow connections to the Writer API at `https://api.writer.com/v1.`\n\n\u003c!-- prettier-ignore --\u003e\n```ts\nasync function main() {\n  const chatCompletion = await client.chat\n    .chat({ messages: [{ content: 'Write a haiku about programming', role: 'user' }], model: 'palmyra-x5' })\n    .catch(async (err) =\u003e {\n      if (err instanceof Writer.APIError) {\n        console.log(err.status); // 400\n        console.log(err.name); // BadRequestError\n        console.log(err.headers); // {server: 'nginx', ...}\n      } else {\n        throw err;\n      }\n    });\n}\n\nmain();\n```\n\nError codes are as follows:\n\n| Status Code | Error Type                 |\n| ----------- | -------------------------- |\n| 400         | `BadRequestError`          |\n| 401         | `AuthenticationError`      |\n| 403         | `PermissionDeniedError`    |\n| 404         | `NotFoundError`            |\n| 422         | `UnprocessableEntityError` |\n| 429         | `RateLimitError`           |\n| \u003e=500       | `InternalServerError`      |\n| N/A         | `APIConnectionError`       |\n\n### Retries\n\nThe library automatically retries certain errors two times by default, with a short exponential backoff. Connection errors, `408 Request Timeout`, `409 Conflict`, `429 Rate Limit`, and `\u003e=500 Internal errors` are all retried by default.\n\nYou can use the `maxRetries` option to configure or disable this:\n\n\u003c!-- prettier-ignore --\u003e\n```js\n// Configure the default for all requests:\nconst client = new Writer({\n  maxRetries: 0, // default is 2\n});\n\n// Or, configure per-request:\nawait client.chat.chat({ messages: [{ content: 'Write a haiku about programming', role: 'user' }], model: 'palmyra-x5' }, {\n\n  maxRetries: 5,\n});\n```\n\n### Timeouts\n\nRequests time out after three minutes by default. You can configure this with a `timeout` option:\n\n\u003c!-- prettier-ignore --\u003e\n```ts\n// Configure the default for all requests:\nconst client = new Writer({\n  timeout: 20 * 1000, // 20 seconds (default is 3 minutes)\n});\n\n// Override per-request:\nawait client.chat.chat({ messages: [{ content: 'Write a haiku about programming', role: 'user' }], model: 'palmyra-x5' }, {\n  timeout: 5 * 1000,\n});\n```\n\nOn timeout, an `APIConnectionTimeoutError` is thrown.\n\nRequests that time out will be [retried twice by default](#retries).\n\n## Pagination\n\nList methods in the Writer API are paginated.\nYou can use the `for await … of` syntax to iterate through items across all pages:\n\n```ts\nasync function fetchAllGraphs(params) {\n  const allGraphs = [];\n  // Automatically fetches more pages as needed.\n  for await (const graph of client.graphs.list()) {\n    allGraphs.push(graph);\n  }\n  return allGraphs;\n}\n```\n\nAlternatively, you can request a single page at a time:\n\n```ts\nlet page = await client.graphs.list();\nfor (const graph of page.data) {\n  console.log(graph);\n}\n\n// Convenience methods are provided for manually paginating:\nwhile (page.hasNextPage()) {\n  page = await page.getNextPage();\n  // ...\n}\n```\n\n## Advanced Usage\n\n### Accessing raw response data\n\nWhen you use `fetch()` to make requests, you can access the raw `Response` through the `.asResponse()` method on the `APIPromise` type that all methods return.\nThis method returns as soon as the headers for a successful response are received and does not consume the response body, so you are free to write custom parsing or streaming logic.\n\nYou can also use the `.withResponse()` method to get the raw `Response` along with the parsed data.\nUnlike `.asResponse()` this method consumes the body, returning once it is parsed.\n\n\u003c!-- prettier-ignore --\u003e\n```ts\nconst client = new Writer();\n\nconst response = await client.chat\n  .chat({ messages: [{ content: 'Write a haiku about programming', role: 'user' }], model: 'palmyra-x5' })\n  .asResponse();\nconsole.log(response.headers.get('X-My-Header'));\nconsole.log(response.statusText); // access the underlying Response object\n\nconst { data: chatCompletion, response: raw } = await client.chat\n  .chat({ messages: [{ content: 'Write a haiku about programming', role: 'user' }], model: 'palmyra-x5' })\n  .withResponse();\nconsole.log(raw.headers.get('X-My-Header'));\nconsole.log(chatCompletion.id);\n```\n\n### Logging\n\n\u003e [!IMPORTANT]\n\u003e All log messages are intended for debugging only. The format and content of log messages\n\u003e may change between releases.\n\n#### Log levels\n\nThe log level can be configured in two ways:\n\n1. Via the `WRITER_LOG` environment variable\n2. Using the `logLevel` client option (overrides the environment variable if set)\n\n```ts\nimport Writer from 'writer-sdk';\n\nconst client = new Writer({\n  logLevel: 'debug', // Show all log messages\n});\n```\n\nAvailable log levels, from most to least verbose:\n\n- `'debug'` - Show debug messages, info, warnings, and errors\n- `'info'` - Show info messages, warnings, and errors\n- `'warn'` - Show warnings and errors (default)\n- `'error'` - Show only errors\n- `'off'` - Disable all logging\n\nAt the `'debug'` level, all HTTP requests and responses are logged, including headers and bodies.\nSome authentication-related headers are redacted, but sensitive data in request and response bodies\nmay still be visible.\n\n#### Custom logger\n\nBy default, this library logs to `globalThis.console`. You can also provide a custom logger.\nMost logging libraries are supported, including [pino](https://www.npmjs.com/package/pino), [winston](https://www.npmjs.com/package/winston), [bunyan](https://www.npmjs.com/package/bunyan), [consola](https://www.npmjs.com/package/consola), [signale](https://www.npmjs.com/package/signale), and [@std/log](https://jsr.io/@std/log). If your logger doesn't work, please open an issue.\n\nWhen providing a custom logger, the `logLevel` option still controls which messages are emitted, messages\nbelow the configured level will not be sent to your logger.\n\n```ts\nimport Writer from 'writer-sdk';\nimport pino from 'pino';\n\nconst logger = pino();\n\nconst client = new Writer({\n  logger: logger.child({ name: 'Writer' }),\n  logLevel: 'debug', // Send all messages to pino, allowing it to filter\n});\n```\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API. If you need to access undocumented\nendpoints, parameters, or response properties, you can still use the library.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, use `client.get`, `client.post`, and other HTTP verbs.\nOptions on the client, such as retries, will be respected when making these requests.\n\n```ts\nawait client.post('/some/path', {\n  body: { some_prop: 'foo' },\n  query: { some_query_arg: 'bar' },\n});\n```\n\n#### Undocumented request parameters\n\nTo make requests using undocumented parameters, you may use `// @ts-expect-error` on the undocumented\nparameter. This library doesn't validate at runtime that the request matches the type, so any extra values you\nsend will be sent as-is.\n\n```ts\nclient.foo.create({\n  foo: 'my_param',\n  bar: 12,\n  // @ts-expect-error baz is not yet public\n  baz: 'undocumented option',\n});\n```\n\nFor requests with the `GET` verb, any extra parameters will be in the query. All other requests will send the\nextra parameter in the body of the request.\n\nIf you want to explicitly send an extra argument, you can do so with the `query`, `body`, and `headers` request\noptions.\n\n#### Undocumented response properties\n\nTo access undocumented response properties, access the response object with `// @ts-expect-error` on\nthe response object, or cast the response object to the requisite type. Like the request parameters, we do not\nvalidate or strip extra properties from the response from the API.\n\n### Customizing the fetch client\n\nBy default, this library expects a global `fetch` function is defined.\n\nIf you want to use a different `fetch` function, you can either polyfill the global:\n\n```ts\nimport fetch from 'my-fetch';\n\nglobalThis.fetch = fetch;\n```\n\nOr pass it to the client:\n\n```ts\nimport Writer from 'writer-sdk';\nimport fetch from 'my-fetch';\n\nconst client = new Writer({ fetch });\n```\n\n### Fetch options\n\nIf you want to set custom `fetch` options without overriding the `fetch` function, you can provide a `fetchOptions` object when instantiating the client or making a request. (Request-specific options override client options.)\n\n```ts\nimport Writer from 'writer-sdk';\n\nconst client = new Writer({\n  fetchOptions: {\n    // `RequestInit` options\n  },\n});\n```\n\n#### Configuring proxies\n\nTo modify proxy behavior, you can provide custom `fetchOptions` that add runtime-specific proxy\noptions to requests:\n\n\u003cimg src=\"https://raw.githubusercontent.com/stainless-api/sdk-assets/refs/heads/main/node.svg\" align=\"top\" width=\"18\" height=\"21\"\u003e **Node** \u003csup\u003e[[docs](https://github.com/nodejs/undici/blob/main/docs/docs/api/ProxyAgent.md#example---proxyagent-with-fetch)]\u003c/sup\u003e\n\n```ts\nimport Writer from 'writer-sdk';\nimport * as undici from 'undici';\n\nconst proxyAgent = new undici.ProxyAgent('http://localhost:8888');\nconst client = new Writer({\n  fetchOptions: {\n    dispatcher: proxyAgent,\n  },\n});\n```\n\n\u003cimg src=\"https://raw.githubusercontent.com/stainless-api/sdk-assets/refs/heads/main/bun.svg\" align=\"top\" width=\"18\" height=\"21\"\u003e **Bun** \u003csup\u003e[[docs](https://bun.sh/guides/http/proxy)]\u003c/sup\u003e\n\n```ts\nimport Writer from 'writer-sdk';\n\nconst client = new Writer({\n  fetchOptions: {\n    proxy: 'http://localhost:8888',\n  },\n});\n```\n\n\u003cimg src=\"https://raw.githubusercontent.com/stainless-api/sdk-assets/refs/heads/main/deno.svg\" align=\"top\" width=\"18\" height=\"21\"\u003e **Deno** \u003csup\u003e[[docs](https://docs.deno.com/api/deno/~/Deno.createHttpClient)]\u003c/sup\u003e\n\n```ts\nimport Writer from 'npm:writer-sdk';\n\nconst httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });\nconst client = new Writer({\n  fetchOptions: {\n    client: httpClient,\n  },\n});\n```\n\n## Frequently Asked Questions\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes that only affect static types, without breaking runtime behavior.\n2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n3. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\n## Feedback\n\nWe welcome feedback! Please open an [issue](https://www.github.com/writer/writer-node/issues) with questions, bugs, or suggestions.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwriter%2Fwriter-node","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwriter%2Fwriter-node","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwriter%2Fwriter-node/lists"}