{"_id":"@dfihub/ts-proto","_rev":"2-725ab02f953b2417fdfd9e082fb2fc1a","name":"@dfihub/ts-proto","dist-tags":{"latest":"1.83.1-intenum"},"versions":{"1.83.1-intenum":{"name":"@dfihub/ts-proto","version":"1.83.1-intenum","description":"> `ts-proto` transforms your `.proto` files into strongly-typed, idiomatic TypeScript files!","main":"build/plugin.js","repository":{"type":"git","url":"https://github.com/DFIhub/ts-proto.git"},"bin":{"protoc-gen-ts_proto":"protoc-gen-ts_proto"},"scripts":{"build":"yarn tsc","setup":"cd ./integration && ./pbjs.sh && ./update-bins.sh && ./codegen.sh","test":"yarn jest -c jest.config.js --maxWorkers=2","prettier":"prettier --write {src,tests}/**/*.ts","prettier:check":"prettier --list-different {src,tests}/**/*.ts"},"keywords":[],"author":{},"license":"ISC","devDependencies":{"@grpc/grpc-js":"^1.2.12","@grpc/proto-loader":"^0.5.6","@improbable-eng/grpc-web":"^0.14.0","@improbable-eng/grpc-web-node-http-transport":"^0.14.0","@nestjs/common":"^7.6.15","@nestjs/core":"^7.6.15","@nestjs/microservices":"^7.6.15","@semantic-release/changelog":"^5.0.1","@semantic-release/commit-analyzer":"^8.0.1","@semantic-release/git":"^9.0.0","@semantic-release/github":"^7.2.0","@semantic-release/npm":"^7.1.0","@semantic-release/release-notes-generator":"^9.0.2","@types/jest":"^26.0.22","@types/node":"^14.14.37","grpc":"^1.24.6","jest":"^26.6.3","prettier":"^2.2.1","reflect-metadata":"^0.1.13","rxjs":"^6.6.7","semantic-release":"^17.4.2","ts-jest":"^26.5.4","ts-node":"^9.1.1","typescript":"^4.2.3","uglify-js":"^3.13.3"},"dependencies":{"@types/object-hash":"^1.3.0","dataloader":"^1.4.0","object-hash":"^1.3.1","protobufjs":"^6.8.8","ts-poet":"^4.5.0","ts-proto-descriptors":"^1.2.1"},"licenseText":"                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n","_id":"@dfihub/ts-proto@1.83.1-intenum","dist":{"shasum":"11cadd81f512008d5bb8753772f2ceff3480f790","integrity":"sha512-JOKG6I4LOGlzbSyLskh+PB2mIoeX87uoR+HuvicNLIbONi2OknZXu/NFHgYnel9m+xfk20nIXK40jdTTDdaPbg==","tarball":"https://registry.npmjs.org/@dfihub/ts-proto/-/ts-proto-1.83.1-intenum.tgz","fileCount":24,"unpackedSize":211886,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJhzwasCRA9TVsSAnZWagAAxO4P/0hXWk+XHPDNM47Lpz2o\nnXKT41ZRaWbVO2JQHwDPL3TL4+IBV7Ii2enwsurHMfuP7VSDwv/eP5Z2LjDz\nbL4VI5lAMBw0tnRozg0Fxmr8HkI1nVkHfXacD0Sp6m5bazOz8ao2qTp6MIyp\nM+W7QFlXJT9hfuLotuLyuYbvaJZkOYQxSpddPoEXCwjdWldCr1Sm+OdzbuT5\nJvVzEkvM92lB33hRwMRvcoA5Ac2dcVsipeVMWDZ2iJk6aN3d+Rts7VLT63ZE\nBYwKIegqRwpF2RCg0vRrO9gC7xNXiebGzQDIA4s4UkQ5fP+pXMMU/7bQJbu9\noVcrbG3zrFiJLRVnxfLVVdBxh5l3Z5Sm4vzjMox+2G2op53yntwiC72X49Rr\nvFyNF/bbWMDiR6v9imIdPlgsKMoujAO6HueyM9UPeulmG5lllsyQMbSiOa3v\nOOivLVLlKch7I9fCn+Ya5ciJRbr5YXvg5VUBP2vZGuwZ/vRYJf3lqrB9bnjj\nnrWSJajbxaaKGFImyf8gnbm/YajeNwe47HaXiQa3VYzSKD8iXjP461tHfE4i\nUVQ2jehq+p+ZglCNLdnjMzn6BRbgxrATDLxzqK2+pjjpMiCYft2HHMC8AhZq\n+naRftYw6EHxpNXwUCUHpXvOXqbiRwx9zFqQcaYHoMRuEUzJbj1OVKLnpiQt\ncneh\r\n=ggDm\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCU1GNfyrA+GLfS142pLgFyT2cc8auLmwscasy/ecQW3wIhAO3DRteXHViJu5muJoN87rhz1qjbin2qtrlDch5Gquq5"}]},"_npmUser":{"name":"botafi","email":"botaifilip@gmail.com"},"directories":{},"maintainers":[{"name":"botafi","email":"botaifilip@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-proto_1.83.1-intenum_1633980295208_0.04085520392139874"},"_hasShrinkwrap":false}},"time":{"created":"2021-10-11T19:24:55.169Z","1.83.1-intenum":"2021-10-11T19:24:55.375Z","modified":"2022-04-05T04:17:03.479Z"},"maintainers":[{"name":"botafi","email":"botaifilip@gmail.com"}],"description":"> `ts-proto` transforms your `.proto` files into strongly-typed, idiomatic TypeScript files!","keywords":[],"repository":{"type":"git","url":"https://github.com/DFIhub/ts-proto.git"},"author":{},"license":"ISC","readme":"[![npm](https://img.shields.io/npm/v/ts-proto)](https://www.npmjs.com/package/ts-proto)\n[![build](https://github.com/stephenh/ts-proto/workflows/Build/badge.svg)](https://github.com/stephenh/ts-proto/actions)\n\n# ts-proto\n\n> `ts-proto` transforms your `.proto` files into strongly-typed, idiomatic TypeScript files!\n\n(Note, if you're a new user of ts-proto and using a modern TS setup with `esModuleInterop`, you need to also pass that as a `ts_proto_opt`.)\n\n## Table of contents\n\n- [QuickStart](#quickstart)\n- [Goals](#goals)\n- [Example Types](#example-types)\n- [Highlights](#highlights)\n- [Auto-Batching / N+1 Prevention](#auto-batching--n1-prevention)\n- [Usage](#usage)\n  - [Supported options](#supported-options)\n  - [Only Types](#only-types)\n  - [NestJS Support](NESTJS.markdown)\n- [Building](#building)\n- [Assumptions](#assumptions)\n- [Todo](#todo)\n- [OneOf Handling](#oneof-handling)\n- [Primitive Types](#primitive-types)\n- [Wrapper Types](#wrapper-types)\n- [Number Types](#number-types)\n- [Timestamps](#timestamps)\n- [Current Status of Optional Values](#current-status-of-optional-values)\n\n# Overview\n\nts-proto generates TypeScript types from protobuf schemas.\n\nI.e. given a `person.proto` schema like:\n\n```proto\nmessage Person {\n  string name = 1;\n}\n```\n\nts-proto will generate a `person.ts` file like:\n\n```typescript\ninterface Person {\n  name: string\n}\n\nconst Person = {\n  encode(person): Writer { ... }\n  decode(reader): Person { ... }\n  toJSON(person): unknown { ... }\n  fromJSON(data): Person { ... }\n}\n```\n\nIt also knows about services and will generate types for them as well, i.e.:\n\n```typescript\nexport interface PingService {\n  ping(request: PingRequest): Promise<PingResponse>;\n}\n```\n\nIt will also generate client implementations of `PingService`; currently [Twirp](https://github.com/twitchtv/twirp), [grpc-web](./integration/grpc-web), [grpc-js](./integration/grpc-js) and [nestjs](./NESTJS.markdown) are supported.\n\n# QuickStart\n\n- `npm install ts-proto`\n- `protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_out=. ./simple.proto`\n  - (Note that the output parameter name, `ts_proto_out`, is named based on the suffix of the plugin's name, i.e. \"ts_proto\" suffix in the `--plugin=./node_modules/.bin/protoc-gen-ts_proto` parameter becomes the `_out` prefix, per `protoc`'s CLI conventions.)\n  - On Windows, use `protoc --plugin=protoc-gen-ts_proto=.\\node_modules\\.bin\\protoc-gen-ts_proto.cmd --ts_proto_out=. ./simple.proto`\n  - Ensure you're using a modern `protoc`, i.e. the original `protoc` `3.0.0` doesn't support the `_opt` flag\n\nThis will generate `*.ts` source files for the given `*.proto` types.\n\nIf you want to package these source files into an npm package to distribute to clients, just run `tsc` on them as usual to generate the `.js`/`.d.ts` files, and deploy the output as a regular npm package.\n\n# Goals\n\n- Idiomatic TypeScript/ES6 types\n  - `ts-proto` is a clean break from either the built-in Google/Java-esque JS code of `protoc` or the \"make `.d.ts` files the `*.js` comments\" approach of `protobufjs`\n  - (Techically the `protobufjs/minimal` package is used for actually reading/writing bytes.)\n- TypeScript-first output\n- Interfaces over classes\n  - As much as possible, types are just interfaces, so you can work with messages just like regular hashes/data structures.\n- Only supports codegen `*.proto`-to-`*.ts` workflow, currently no runtime reflection/loading of dynamic `.proto` files\n\n# Example Types\n\nThe generated types are \"just data\", i.e.:\n\n```typescript\nexport interface Simple {\n  name: string;\n  age: number;\n  createdAt: Date | undefined;\n  child: Child | undefined;\n  state: StateEnum;\n  grandChildren: Child[];\n  coins: number[];\n}\n```\n\nAlong with `encode`/`decode` factory methods:\n\n```typescript\nexport const Simple = {\n  encode(message: Simple, writer: Writer = Writer.create()): Writer {\n    ...\n  },\n\n  decode(reader: Reader, length?: number): Simple {\n    ...\n  },\n\n  fromJSON(object: any): Simple {\n    ...\n  },\n\n  fromPartial(object: DeepPartial<Simple>): Simple {\n    ...\n  },\n\n  toJSON(message: Simple): unknown {\n    ...\n  },\n};\n```\n\nThis allows idiomatic TS/JS usage like:\n\n```typescript\nconst bytes = Simple.encode({ name: ..., age: ..., ... }).finish();\nconst simple = Simple.decode(Reader.create(bytes));\nconst { name, age } = simple;\n```\n\nWhich can dramatically ease integration when converting to/from other layers without\ncreating a class and calling the right getters/setters.\n\n# Highlights\n\n- A poor man's attempt at \"please give us back optional types\"\n\n  The canonical protobuf wrapper types, i.e. `google.protobuf.StringValue`, are mapped as optional values, i.e. `string | undefined`, which means for primitives we can kind of pretend the protobuf type system has optional types.\n\n  (**Update**: ts-proto now also supports the proto3 `optional` keyword.)\n\n- Timestamps are mapped as `Date`\n\n  (Configurable with the `useDate` parameter.)\n\n- `fromJSON`/`toJSON` support the [canonical Protobuf JS](https://developers.google.com/protocol-buffers/docs/proto3#json) format (i.e. timestamps are ISO strings)\n\n# Auto-Batching / N+1 Prevention\n\n(Note: this is currently only supported by the Twirp clients.)\n\nIf you're using ts-proto's clients to call backend micro-services, similar to the N+1 problem in SQL applications, it is easy for micro-service clients to (when serving an individual request) inadvertantly trigger multiple separate RPC calls for \"get book 1\", \"get book 2\", \"get book 3\", that should really be batched into a single \"get books [1, 2, 3]\" (assuming the backend supports a batch-oriented RPC method).\n\nts-proto can help with this, and essentially auto-batch your individual \"get book\" calls into batched \"get books\" calls.\n\nFor ts-proto to do this, you need to implement your service's RPC methods with the batching convention of:\n\n- A method name of `Batch<OperationName>`\n- The `Batch<OperationName>` input type has a single repeated field (i.e. `repeated string ids = 1`)\n- The `Batch<OperationName>` output type has either a:\n  - A single repeated field (i.e. `repeated Foo foos = 1`) _where the output order is the same as the input `ids` order_, or\n  - A map of the input to an output (i.e. `map<string, Entity> entities = 1;`)\n\nWhen ts-proto recognizes methods of this pattern, it will automatically create a \"non-batch\" version of `<OperationName>` for the client, i.e. `client.Get<OperationName>`, that takes a single id and returns a single result.\n\nThis provides the client code with the illusion that it can make individual `Get<OperationName>` calls (which is generally preferrable/easier when implementing the client's business logic), but the actual implementation that ts-proto provides will end up making `Batch<OperationName>` calls to the backend service.\n\nYou also need to enable the `useContext=true` build-time parameter, which gives all client methods a Go-style `ctx` parameter, with a `getDataLoaders` method that lets ts-proto cache/resolve request-scoped [DataLoaders](https://github.com/graphql/dataloader), which provide the fundamental auto-batch detection/flushing behavior.\n\nSee the `batching.proto` file and related tests for examples/more details.\n\nBut the net effect is that ts-proto can provide SQL-/ORM-style N+1 prevention for clients calls, which can be critical especially in high-volume / highly-parallel implementations like GraphQL front-end gateways calling backend micro-services.\n\n# Usage\n\n`ts-proto` is a `protoc` plugin, so you run it by (either directly in your project, or more likely in your mono-repo schema pipeline, i.e. like [Ibotta](https://medium.com/building-ibotta/building-a-scaleable-protocol-buffers-grpc-artifact-pipeline-5265c5118c9d) or [Namely](https://medium.com/namely-labs/how-we-build-grpc-services-at-namely-52a3ae9e7c35)):\n\n- Add `ts-proto` to your `package.json`\n- Run `npm install` to download it\n- Invoke `protoc` with a `plugin` parameter like:\n\n```bash\nprotoc --plugin=node_modules/ts-proto/protoc-gen-ts_proto ./batching.proto -I.\n```\n\n`ts-proto` can also be invoked with [Gradle](https://gradle.org) using the [protobuf-gradle-plugin](https://github.com/google/protobuf-gradle-plugin):\n\n``` groovy\nprotobuf {\n    plugins {\n        // `ts` can be replaced by any unused plugin name, e.g. `tsproto`\n        ts {\n            path = 'path/to/plugin'\n        }\n    }\n\n    // This section only needed if you provide plugin options\n    generateProtoTasks {\n        all().each { task ->\n            task.plugins {\n                // Must match plugin ID declared above\n                ts {\n                    option 'foo=bar'\n                }\n            }\n        }\n    }\n}\n```\n\nGenerated code will be placed in the Gradle build directory.\n\n### Supported options\n\n- With `--ts_proto_opt=context=true`, the services will have a Go-style `ctx` parameter, which is useful for tracing/logging/etc. if you're not using node's `async_hooks` api due to performance reasons.\n\n- With `--ts_proto_opt=forceLong=long`, all 64-bit numbers will be parsed as instances of `Long` (using the [long](https://www.npmjs.com/package/long) library).\n\n  Alternatively, if you pass `--ts_proto_opt=forceLong=string`, all 64-bit numbers will be outputted as strings.\n\n  The default behavior is `forceLong=number`, which will internally still use the `long` library to encode/decode values on the wire (so you will still see a `util.Long = Long` line in your output), but will convert the `long` values to `number` automatically for you. Note that a runtime error is thrown if, while doing this conversion, a 64-bit value is larger than can be correctly stored as a `number`.\n\n- With `--ts_proto_opt=esModuleInterop=true` changes output to be `esModuleInterop` compliant.\n\n  Specifically the `Long` imports will be generated as `import Long from 'long'` instead of `import * as Long from 'long'`.\n\n- With `--ts_proto_opt=env=node` or `browser` or `both`, ts-proto will make environment-specific assumptions in your output. This defaults to `both`, which makes no environment-specific assumptions.\n\n  Using `node` changes the types of `bytes` from `Uint8Array` to `Buffer` for easier integration with the node ecosystem which generally uses `Buffer`.\n\n  Currently `browser` doesn't have any specific behavior other than being \"not `node`\". It probably will soon/at some point.\n\n- With `--ts_proto_opt=useOptionals=true`, non-scalar fields are declared as optional TypeScript properties, e.g. `field?: Message` instead of the default `field: Message | undefined`.\n\n  ts-proto defaults to `useOptionals=false`, e.g. `field: Message | undefined`, because it is the most safe for use cases like:\n\n  ```typescript\n  interface SomeMessage {\n    firstName: string | undefined;\n    lastName: string | undefined;\n  }\n\n  const data = { firstName: 'a', lastTypo: 'b' };\n\n  // This would compile if `lastName` was `lastName?`, even though the\n  // `lastTypo` key above means that `lastName` is not assigned.\n  const message: SomeMessage = {\n    ...data,\n  };\n  ```\n\n  However, the type-safety of `useOptionals=false` is admittedly tedious if you have many inherently-unused fields, so you can use `useOptionals=true` if that trade-off makes sense for your project.\n\n  You can also use the generated `SomeMessage.fromPartial` methods to opt into the optionality on a per-call-site basis. The `fromPartial` allows the creator/writer to have default values applied (i.e. `undefined` --> `0`), and the return value will still be the non-optional type that provides a consistent view (i.e. always `0`) to clients.\n\n  Eventually if TypeScript supports [Exact Types](https://github.com/microsoft/TypeScript/issues/12936), that should allow ts-proto to switch to `useOptionals=true` as the default/only behavior, have the generated `Message.encode`/`Message.toPartial`/etc. methods accept `Exact<T>` versions of the message types, and the result would be both safe + succinct.\n\n  Also see the comment in [this issue](https://github.com/stephenh/ts-proto/issues/120#issuecomment-678375833) which explains the nuance behind making all fields optional (currently `useOptionals` only makes message fields optional), specifically that a message created with `const message: Message = { ...key not set... }` (so `key` is `undefined`) vs. `const message = Message.decode(...key not set...)` (so `key` is the default value) would look different to clients.\n\n  Note that RPC methods, like `service.ping({ key: ... })`, accept `DeepPartial` versions of the request messages, because of the same rationale that it makes it easy for the writer call-site to get default values for free, and because the \"reader\" is the internal ts-proto serialization code, it can apply the defaults as necessary.\n\n- With `--ts_proto_opt=exportCommonSymbols=false`, utility types like `DeepPartial` won't be `export`d.\n\n  This should make it possible to use create barrel imports of the generated output, i.e. `import * from ./foo` and `import * from ./bar`.\n\n  Note that if you have the same message name used in multiple `*.proto` files, you will still get import conflicts.\n\n- With `--ts_proto_opt=oneof=unions`, `oneof` fields will be generated as ADTs.\n\n  See the \"OneOf Handling\" section.\n\n- With `--ts_proto_opt=unrecognizedEnum=false` enums will not contain an `UNRECOGNIZED` key with value of -1.\n\n- With `--ts_proto_opt=lowerCaseServiceMethods=true`, the method names of service methods will be lowered/camel-case, i.e. `service.findFoo` instead of `service.FindFoo`.\n\n- With `--ts_proto_opt=snakeToCamel=false`, fields will be kept snake case.\n\n  Defaults to `true`.\n\n- With `--ts_proto_opt=outputEncodeMethods=false`, the `Message.encode` and `Message.decode` methods for working with protobuf-encoded/binary data will not be output.\n\n  This is useful if you want \"only types\".\n\n- With `--ts_proto_opt=outputJsonMethods=false`, the `Message.fromJSON` and `Message.toJSON` methods for working with JSON-coded data will not be output.\n\n  This is also useful if you want \"only types\".\n\n- With `--ts_proto_opt=outputPartialMethods=false`, the `Message.fromPartial` methods for accepting partially-formed objects/object literals will not be output.\n\n- With `--ts_proto_opt=stringEnums=true`, the generated enum types will be string-based instead of int-based.\n\n  This is useful if you want \"only types\" and are using a gRPC REST Gateway configured to serialize enums as strings.\n\n  (Requires `outputEncodeMethods=false`.)\n\n- With `--ts_proto_opt=outputClientImpl=false`, the client implementations, i.e. `FooServiceClientImpl`, that implement the client-side (in Twirp, see next option for `grpc-web`) RPC interfaces will not be output.\n\n- With `--ts_proto_opt=outputClientImpl=grpc-web`, the client implementations, i.e. `FooServiceClientImpl`, will use the [@improbable-eng/grpc-web](https://github.com/improbable-eng/grpc-web) library at runtime to send grpc messages to a grpc-web backend.\n\n  (Note that this only uses the grpc-web runtime, you don't need to use any of their generated code, i.e. the ts-proto output replaces their `ts-protoc-gen` output.)\n\n  You'll need to add the `@improbable-eng/grpc-web` and a transport to your project's `package.json`; see the `integration/grpc-web` directory for a working example.\n\n- With `--ts_proto_opt=returnObservable=true`, the return type of service methods will be `Observable<T>` instead of `Promise<T>`.\n\n- With`--ts_proto_opt=addGrpcMetadata=true`, the last argument of service methods will accept the grpc `Metadata` type, which contains additional information with the call (i.e. access tokens/etc.).\n\n  (Requires `nestJs=true`.)\n\n- With`--ts_proto_opt=addNestjsRestParameter=true`, the last argument of service methods will be an rest parameter with type any. This way you can use custom decorators you could normally use in nestjs.\n\n  (Requires `nestJs=true`.)\n\n- With `--ts_proto_opt=nestJs=true`, the defaults will change to generate [NestJS protobuf](https://docs.nestjs.com/microservices/grpc) friendly types & service interfaces that can be used in both the client-side and server-side of NestJS protobuf implementations. See the [nestjs readme](NESTJS.markdown) for more information and implementation examples.\n\n  Specifically `outputEncodeMethods`, `outputJsonMethods`, and `outputClientImpl` will all be false, and `lowerCaseServiceMethods` will be true.\n\n  Note that `addGrpcMetadata`, `addNestjsRestParameter` and `returnObservable` will still be false.\n\n- With `--ts_proto_opt=useDate=false`, fields of type `google.protobuf.Timestamp` will not be mapped to type `Date` in the generated types. See [Timestamps](#timestamps) for more details.\n\n- With `--ts_proto_opt=outputSchema=true`, meta typings will be generated that can later be used in other code generators.\n\n- With `--ts_proto_opt=outputTypeRegistry=true`, the type registry will be generated that can be used to resolve message types by fully-qualified name. Also, each message will get extra `$type` field containing fully-qualified name.\n\n- With `--ts_proto_opt=outputServices=grpc-js`, ts-proto will output service definitions and server / client stubs in [grpc-js](https://github.com/grpc/grpc-node/tree/master/packages/grpc-js) format.\n\n- With `--ts_proto_opt=outputServices=generic-definitions`, ts-proto will output generic (framework-agnostic) service definitions.\n\n- With `--ts_proto_opt=outputServices=false`, or `=none`, ts-proto will output NO service definitions.\n\n- With `--ts_proto_opt=emitImportedFiles=false`, ts-proto will not emit `google/protobuf/*` files unless you explicit add files to `protoc` like this\n`protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto my_message.proto google/protobuf/duration.proto`\n\n### Only Types\n\nIf you're looking for `ts-proto` to generate only types for your Protobuf types then passing all three of `outputEncodeMethods`, `outputJsonMethods`, and `outputClientImpl` as `false` is probably what you want, i.e.:\n\n`--ts_proto_opt=outputEncodeMethods=false,outputJsonMethods=false,outputClientImpl=false`.\n\n### NestJS Support\n\nWe have a great way of working together with [nestjs](https://docs.nestjs.com/microservices/grpc). `ts-proto` generates `interfaces` and `decorators` for you controller, client. For more information see the [nestjs readme](NESTJS.markdown).\n\n# Sponsors\n\nKudos to our sponsors:\n\n* [ngrok](https://ngrok.com) funded ts-proto's initial grpc-web support.\n\nIf you need ts-proto customizations or priority support for your company, you can ping me at [via email](mailto:stephen.haberman@gmail.com).\n\n# Building\n\nAfter running `yarn install`, run `./integration/pbjs.sh` to create the integration test types. These pbjs-generated files are not currently checked in.\n\nAfter this, the tests should pass.\n\nAfter making changes to `ts-proto`, you can run `cd integration` and `./codegen.sh` to re-generate the test case `*.ts` output files that are in each `integration/<test-case>/` directory.\n\nThe test suite's proto files (i.e. `simple.proto`, `batching.proto`, etc.) currently have serialized/`.bin` copies checked into git (i.e. `simple.bin`, `batching.bin`, etc.), so that the test suite can run without having to invoke the `protoc` build chain. I.e. if you change the `simple.proto`/etc. files, you'll need to run `./integration/update-bins.sh`, which does require having the `protoc` executable available.\n\n# Assumptions\n\n- TS/ES6 module name is the proto package\n\n# Todo\n\n- Support the string-based encoding of duration in `fromJSON`/`toJSON`\n- Support the `json_name` annotation\n- Make `oneof=unions` the default behavior in 2.0\n- Probably change `forceLong` default in 2.0, should default to `forceLong=long`\n- Make `esModuleInterop=true` the default in 2.0\n\n# OneOf Handling\n\nBy default, `oneof` fields are modeled \"flatly\" in the message, i.e. `oneof either_field { string field_a; string field_b }` means that the message will have `field_a: string | undefined; field_b: string | undefined`.\n\nWith this output, you'll have to check both `if object.field_a` and `if object.field_b`, and if you set one, you'll have to remember to unset the other.\n\nWe recommend using the `oneof=unions` option, which will change the output to be an Abstract Data Type/ADT like:\n\n```typescript\ninterface YourMessage {\n  eitherField: { $case: 'field_a'; field_a: string } | { $case: 'field_b'; field_b: string };\n}\n```\n\nAs this will automatically enforce only one of `field_a` or `field_b` \"being set\" at a time, because the values are stored in the `eitherField` field that can only have a single value at a time.\n\nIn ts-proto's currently-unscheduled 2.x release, `oneof=unions` will become the default behavior.\n\n# Primitive Types\n\nProtobuf has the somewhat annoying behavior that primitives types cannot differentiate between set-to-defalut-value and unset.\n\nI.e. if you have a `string name = 1`, and set `object.name = ''`, Protobuf will skip sending the tagged `name` field over the wire, because its understood that readers on the other end will, when they see `name` is not included in the payload, return empty string.\n\n`ts-proto` models this behavior, of \"unset\" values being the primitive's default. (Technically by setting up an object prototype that knows the default values of the message's primitive fields.)\n\nIf you want fields where you can model set/unset, see Wrapper Types.\n\n# Wrapper Types\n\nIn core Protobuf, unset primitive fields become their respective default values (so you loose ability to distinguish \"unset\" from \"default\").\n\nHowever, unset message fields stay `null`.\n\nThis allows a cute hack where you can model a logical `string | unset` by creating a field that is technically a message (i.e. so it can stay `null` for the unset case), but the message only has a single string field (i.e for storing the value in the set case).\n\nProtobuf has already \"blessed\" this pattern with several built-in types, i.e. `google.protobuf.StringValue`, `google.protobuf.Int32Value`, etc.\n\n`ts-proto` understands these wrapper types and \"re-idiomizes\" them by generating a `google.protobuf.StringValue name = 1` field as a `name: string | undefined`, and hides the `StringValue` implementation detail from your code (i.e. during `encode`/`decode` of the `name` field on the wire to external consumers, it's still read/written as a `StringValue` message field).\n\nThis makes dealing with `string | unset` in your code much nicer, albeit it's unfortunate that, in Protobuf core, this is not as simple as marking a `string name = 1` field as `optional`, i.e. you have to \"dirty\" your proto files a bit by knowing to use the `StringValue` convention.\n\n# Number Types\n\nNumbers are by default assumed to be plain JavaScript `number`s.\n\nThis is fine for Protobuf types like `int32` and `float`, but 64-bit types like `int64` can't be 100% represented by JavaScript's `number` type, because `int64` can have larger/smaller values than `number`.\n\nts-proto's default configuration (which is `forceLong=number`) is to still use `number` for 64-bit fields, and then throw an error if a value (at runtime) is larger than `Number.MAX_SAFE_INTEGER`.\n\nIf you expect to use 64-bit / higher-than-`MAX_SAFE_INTEGER` values, then you can use the ts-proto `forceLong` option, which uses the [long](https://www.npmjs.com/package/long) npm package to support the entire range of 64-bit values.\n\nThe protobuf number types map to JavaScript types based on the `forceLong` config option:\n\n| Protobuf number types | Default/`forceLong=number` | `forceLong=long` | `forceLong=string` |\n| --------------------- | -------------------------- | ---------------- | ------------------ |\n| double                | number                     | number           | number             |\n| float                 | number                     | number           | number             |\n| int32                 | number                     | number           | number             |\n| int64                 | number\\*                   | Long             | string             |\n| uint32                | number                     | number           | number             |\n| uint64                | number\\*                   | Unsigned Long    | string             |\n| sint32                | number                     | number           | number             |\n| sint64                | number\\*                   | Long             | string             |\n| fixed32               | number                     | number           | number             |\n| fixed64               | number\\*                   | Unsigned Long    | string             |\n| sfixed32              | number                     | number           | number             |\n| sfixed64              | number\\*                   | Long             | string             |\n\nWhere (\\*) indicates they might throw an error at runtime.\n\n# Timestamps\n\nThe representation of `google.protobuf.Timestamp` is configurable by the `useDate` flag.\n\n| Protobuf well-known type    | Default/`useDate=true` | `useDate=false`                      | `useDate=string` |\n| --------------------------- | ---------------------- | ------------------------------------ | ---------------- |\n| `google.protobuf.Timestamp` | `Date`                 | `{ seconds: number, nanos: number }` | `string`         |\n\n# Current Status of Optional Values\n\n- Required primitives: use as-is, i.e. `string name = 1`.\n- Optional primitives: use wrapper types, i.e. `StringValue name = 1`.\n- Required messages: not available\n- Optional primitives: use as-is, i.e. `SubMessage message = 1`.\n","readmeFilename":"README.markdown"}