From 68e8fbbe289d95e3b7c8b84de68c636327a814bb Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Fri, 12 Jul 2024 15:40:24 +0900 Subject: [PATCH 01/20] Add http support --- .gitignore | 1 + HTTP.markdown | 112 ++ Makefile | 12 + README.markdown | 14 +- integration/http/google/api/annotations.proto | 31 + integration/http/google/api/annotations.ts | 6 + integration/http/google/api/http.proto | 379 ++++++ integration/http/google/api/http.ts | 376 ++++++ .../http/google/protobuf/descriptor.proto | 872 ++++++++++++++ .../http/google/protobuf/descriptor.ts | 924 +++++++++++++++ integration/http/http-test.ts | 40 + integration/http/parameters.txt | 1 + integration/http/simple.proto | 37 + integration/http/simple.ts | 48 + package.json | 2 + src/context.ts | 6 +- src/generate-http.ts | 83 ++ src/main.ts | 5 + src/options.ts | 13 + src/plugin.ts | 18 +- tests/options-test.ts | 1 + vendor/google/api/annotations_pb.js | 54 + vendor/google/api/http_pb.js | 1012 +++++++++++++++++ yarn.lock | 16 + 24 files changed, 4053 insertions(+), 10 deletions(-) create mode 100644 HTTP.markdown create mode 100644 Makefile create mode 100644 integration/http/google/api/annotations.proto create mode 100644 integration/http/google/api/annotations.ts create mode 100644 integration/http/google/api/http.proto create mode 100644 integration/http/google/api/http.ts create mode 100644 integration/http/google/protobuf/descriptor.proto create mode 100644 integration/http/google/protobuf/descriptor.ts create mode 100644 integration/http/http-test.ts create mode 100644 integration/http/parameters.txt create mode 100644 integration/http/simple.proto create mode 100644 integration/http/simple.ts create mode 100644 src/generate-http.ts create mode 100644 vendor/google/api/annotations_pb.js create mode 100644 vendor/google/api/http_pb.js diff --git a/.gitignore b/.gitignore index 0ef7311a0..46fc89438 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ build/ coverage/ yarn-error.log .DS_Store +third_party # Yarn .pnp.* diff --git a/HTTP.markdown b/HTTP.markdown new file mode 100644 index 000000000..f42cc063d --- /dev/null +++ b/HTTP.markdown @@ -0,0 +1,112 @@ +# Http + +If we have to following `.proto` file: + +```protobuf +syntax = "proto3"; + +import "google/api/annotations.proto"; + +service Messaging { + rpc GetMessage(GetMessageRequest) returns (GetMessageResponse) { + option (google.api.http) = { + get:"/v1/messages/{message_id}" + }; + } + rpc CreateMessage(CreateMessageRequest) returns (CreateMessageResponse) { + option (google.api.http) = { + post:"/v1/messages/{message_id}" + body: "message" + }; + } + rpc UpdateMessage(CreateMessageRequest) returns (CreateMessageResponse) { + option (google.api.http) = { + post:"/v1/messages/{message_id}" + body: "*" + }; + } +} + +message GetMessageRequest { + string message_id = 1; +} +message GetMessageResponse { + string message = 1; +} + +message CreateMessageRequest { + string message_id = 1; + string message = 2; // mapped to the body +} + +message CreateMessageResponse {} +``` + +The output will be + +```typescript +// ... +export interface GetMessageRequest { + messageId: string; +} + +export interface GetMessageResponse { + message: string; +} + +export interface CreateMessageRequest { + messageId: string; + /** mapped to the body */ + message: string; +} + +export interface CreateMessageResponse {} + +export const Messaging = { + getMessage: { + path: "/v1/messages/{message_id}", + method: "get", + request: undefined as GetMessageRequest | undefined, + response: undefined as GetMessageResponse | undefined, + }, + + createMessage: { + path: "/v1/messages/{message_id}", + method: "post", + body: "message", + request: undefined as CreateMessageRequest | undefined, + response: undefined as CreateMessageResponse | undefined, + }, + + updateMessage: { + path: "/v1/messages/{message_id}", + method: "post", + body: "*", + request: undefined as CreateMessageRequest | undefined, + response: undefined as CreateMessageResponse | undefined, + }, +}; +``` + +## Client implementation example + +```typescript +// This is just an example, do not use it directly. +function createApi(config: T) { + return function api(request: NonNullable): Promise> { + const path = config.path.replace("{message_id}", request.messageId); + const method = config.method; + const body = method === "get" ? undefined : JSON.stringify({ message: request.message }); + + return fetch(path, { method, body }); + }; +} + +const getMessage = createApi(Messaging.getMessage); + +getMessage({ + messageId: "123", +}).then((res) => { + // ... +}); +``` diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..e954ce8cd --- /dev/null +++ b/Makefile @@ -0,0 +1,12 @@ +.PHONY: build-vendor +build-vendor: + @rm -rf third_party + @mkdir third_party + @cd third_party && git clone git@github.com:googleapis/googleapis.git --depth=1 && cd .. + @rm -rf vendor + @mkdir vendor + @protoc \ + --js_out=import_style=commonjs,binary:vendor \ + -I third_party/googleapis \ + third_party/googleapis/google/api/http.proto third_party/googleapis/google/api/annotations.proto + @rm -rf third_party diff --git a/README.markdown b/README.markdown index 62f95452a..7af322386 100644 --- a/README.markdown +++ b/README.markdown @@ -28,6 +28,7 @@ - [Assumptions](#assumptions) - [Todo](#todo) - [OneOf Handling](#oneof-handling) + - [OneOf Type Helpers](#oneof-type-helpers) - [Default values and unset fields](#default-values-and-unset-fields) - [Well-Known Types](#well-known-types) - [Wrapper Types](#wrapper-types) @@ -147,8 +148,6 @@ If you'd like an out-of-the-box RPC framework built on top of ts-proto, there ar (Note for potential contributors, if you develop other frameworks/mini-frameworks, or even blog posts/tutorials, on using `ts-proto`, we're happy to link to them.) -We also don't support clients for `google.api.http`-based [Google Cloud](https://cloud.google.com/endpoints/docs/grpc/transcoding) APIs, see [#948](https://github.com/stephenh/ts-proto/issues/948) if you'd like to submit a PR. - # Example Types The generated types are "just data", i.e.: @@ -428,6 +427,10 @@ Generated code will be placed in the Gradle build directory. Note that `addGrpcMetadata`, `addNestjsRestParameter` and `returnObservable` will still be false. +- With `--ts_proto_opt=http=true`, the defaults will change to generate http friendly types & service metadata that can be used to create your own http client. See the [http readme](HTTP.markdown) for more information and implementation examples. + + Specifically `outputEncodeMethods`, `outputJsonMethods`, and `outputClientImpl` will all be false, `lowerCaseServiceMethods` will be true and `outputServices` will be ignored. + - With `--ts_proto_opt=useDate=false`, fields of type `google.protobuf.Timestamp` will not be mapped to type `Date` in the generated types. See [Timestamp](#timestamp) for more details. - With `--ts_proto_opt=useMongoObjectId=true`, fields of a type called ObjectId where the message is constructed to have on field called value that is a string will be mapped to type `mongodb.ObjectId` in the generated types. This will require your project to install the mongodb npm package. See [ObjectId](#objectid) for more details. @@ -609,11 +612,10 @@ export interface User { } ``` -- With `--ts_proto_opt=noDefaultsForOptionals=true`, `undefined` primitive values will not be defaulted as per the protobuf spec. Additionally unlike the standard behavior, when a field is set to it's standard default value, it *will* be encoded allowing it to be sent over the wire and distinguished from undefined values. For example if a message does not set a boolean value, ordinarily this would be defaulted to `false` which is different to it being undefined. +- With `--ts_proto_opt=noDefaultsForOptionals=true`, `undefined` primitive values will not be defaulted as per the protobuf spec. Additionally unlike the standard behavior, when a field is set to it's standard default value, it _will_ be encoded allowing it to be sent over the wire and distinguished from undefined values. For example if a message does not set a boolean value, ordinarily this would be defaulted to `false` which is different to it being undefined. This option allows the library to act in a compatible way with the [Wire implementation](https://square.github.io/wire/) maintained and used by Square/Block. Note: this option should only be used in combination with other client/server code generated using Wire or ts-proto with this option enabled. - ### NestJS Support We 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). @@ -832,10 +834,10 @@ For comparison, the equivalents for `oneof=unions-value`: ```ts /** Extracts all the case names from a oneOf field. */ -type OneOfCases = T['$case']; +type OneOfCases = T["$case"]; /** Extracts a union of all the value types from a oneOf field */ -type OneOfValues = T['value']; +type OneOfValues = T["value"]; /** Extracts the specific type of a oneOf case based on its field name */ type OneOfCase> = T extends { diff --git a/integration/http/google/api/annotations.proto b/integration/http/google/api/annotations.proto new file mode 100644 index 000000000..b17b34560 --- /dev/null +++ b/integration/http/google/api/annotations.proto @@ -0,0 +1,31 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/http.proto"; +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "AnnotationsProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.MethodOptions { + // See `HttpRule`. + HttpRule http = 72295728; +} \ No newline at end of file diff --git a/integration/http/google/api/annotations.ts b/integration/http/google/api/annotations.ts new file mode 100644 index 000000000..a2f11e8e5 --- /dev/null +++ b/integration/http/google/api/annotations.ts @@ -0,0 +1,6 @@ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// source: google/api/annotations.proto + +/* eslint-disable */ + +export const protobufPackage = "google.api"; diff --git a/integration/http/google/api/http.proto b/integration/http/google/api/http.proto new file mode 100644 index 000000000..cc6ba3c9d --- /dev/null +++ b/integration/http/google/api/http.proto @@ -0,0 +1,379 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "HttpProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Defines the HTTP configuration for an API service. It contains a list of +// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method +// to one or more HTTP REST API methods. +message Http { + // A list of HTTP configuration rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated HttpRule rules = 1; + + // When set to true, URL path parameters will be fully URI-decoded except in + // cases of single segment matches in reserved expansion, where "%2F" will be + // left encoded. + // + // The default behavior is to not decode RFC 6570 reserved characters in multi + // segment matches. + bool fully_decode_reserved_expansion = 2; +} + +// # gRPC Transcoding +// +// gRPC Transcoding is a feature for mapping between a gRPC method and one or +// more HTTP REST endpoints. It allows developers to build a single API service +// that supports both gRPC APIs and REST APIs. Many systems, including [Google +// APIs](https://github.com/googleapis/googleapis), +// [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC +// Gateway](https://github.com/grpc-ecosystem/grpc-gateway), +// and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature +// and use it for large scale production services. +// +// `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies +// how different portions of the gRPC request message are mapped to the URL +// path, URL query parameters, and HTTP request body. It also controls how the +// gRPC response message is mapped to the HTTP response body. `HttpRule` is +// typically specified as an `google.api.http` annotation on the gRPC method. +// +// Each mapping specifies a URL path template and an HTTP method. The path +// template may refer to one or more fields in the gRPC request message, as long +// as each field is a non-repeated field with a primitive (non-message) type. +// The path template controls how fields of the request message are mapped to +// the URL path. +// +// Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/{name=messages/*}" +// }; +// } +// } +// message GetMessageRequest { +// string name = 1; // Mapped to URL path. +// } +// message Message { +// string text = 1; // The resource content. +// } +// +// This enables an HTTP REST to gRPC mapping as below: +// +// HTTP | gRPC +// -----|----- +// `GET /v1/messages/123456` | `GetMessage(name: "messages/123456")` +// +// Any fields in the request message which are not bound by the path template +// automatically become HTTP query parameters if there is no HTTP request body. +// For example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get:"/v1/messages/{message_id}" +// }; +// } +// } +// message GetMessageRequest { +// message SubMessage { +// string subfield = 1; +// } +// string message_id = 1; // Mapped to URL path. +// int64 revision = 2; // Mapped to URL query parameter `revision`. +// SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`. +// } +// +// This enables a HTTP JSON to RPC mapping as below: +// +// HTTP | gRPC +// -----|----- +// `GET /v1/messages/123456?revision=2&sub.subfield=foo` | +// `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: +// "foo"))` +// +// Note that fields which are mapped to URL query parameters must have a +// primitive type or a repeated primitive type or a non-repeated message type. +// In the case of a repeated type, the parameter can be repeated in the URL +// as `...?param=A¶m=B`. In the case of a message type, each field of the +// message is mapped to a separate parameter, such as +// `...?foo.a=A&foo.b=B&foo.c=C`. +// +// For HTTP methods that allow a request body, the `body` field +// specifies the mapping. Consider a REST update method on the +// message resource collection: +// +// service Messaging { +// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "message" +// }; +// } +// } +// message UpdateMessageRequest { +// string message_id = 1; // mapped to the URL +// Message message = 2; // mapped to the body +// } +// +// The following HTTP JSON to RPC mapping is enabled, where the +// representation of the JSON in the request body is determined by +// protos JSON encoding: +// +// HTTP | gRPC +// -----|----- +// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: +// "123456" message { text: "Hi!" })` +// +// The special name `*` can be used in the body mapping to define that +// every field not bound by the path template should be mapped to the +// request body. This enables the following alternative definition of +// the update method: +// +// service Messaging { +// rpc UpdateMessage(Message) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "*" +// }; +// } +// } +// message Message { +// string message_id = 1; +// string text = 2; +// } +// +// +// The following HTTP JSON to RPC mapping is enabled: +// +// HTTP | gRPC +// -----|----- +// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: +// "123456" text: "Hi!")` +// +// Note that when using `*` in the body mapping, it is not possible to +// have HTTP parameters, as all fields not bound by the path end in +// the body. This makes this option more rarely used in practice when +// defining REST APIs. The common usage of `*` is in custom methods +// which don't use the URL at all for transferring data. +// +// It is possible to define multiple HTTP methods for one RPC by using +// the `additional_bindings` option. Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/messages/{message_id}" +// additional_bindings { +// get: "/v1/users/{user_id}/messages/{message_id}" +// } +// }; +// } +// } +// message GetMessageRequest { +// string message_id = 1; +// string user_id = 2; +// } +// +// This enables the following two alternative HTTP JSON to RPC mappings: +// +// HTTP | gRPC +// -----|----- +// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` +// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: +// "123456")` +// +// ## Rules for HTTP mapping +// +// 1. Leaf request fields (recursive expansion nested messages in the request +// message) are classified into three categories: +// - Fields referred by the path template. They are passed via the URL path. +// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They +// are passed via the HTTP +// request body. +// - All other fields are passed via the URL query parameters, and the +// parameter name is the field path in the request message. A repeated +// field can be represented as multiple query parameters under the same +// name. +// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL +// query parameter, all fields +// are passed via URL path and HTTP request body. +// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP +// request body, all +// fields are passed via URL path and URL query parameters. +// +// ### Path template syntax +// +// Template = "/" Segments [ Verb ] ; +// Segments = Segment { "/" Segment } ; +// Segment = "*" | "**" | LITERAL | Variable ; +// Variable = "{" FieldPath [ "=" Segments ] "}" ; +// FieldPath = IDENT { "." IDENT } ; +// Verb = ":" LITERAL ; +// +// The syntax `*` matches a single URL path segment. The syntax `**` matches +// zero or more URL path segments, which must be the last part of the URL path +// except the `Verb`. +// +// The syntax `Variable` matches part of the URL path as specified by its +// template. A variable template must not contain other variables. If a variable +// matches a single path segment, its template may be omitted, e.g. `{var}` +// is equivalent to `{var=*}`. +// +// The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL` +// contains any reserved character, such characters should be percent-encoded +// before the matching. +// +// If a variable contains exactly one path segment, such as `"{var}"` or +// `"{var=*}"`, when such a variable is expanded into a URL path on the client +// side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The +// server side does the reverse decoding. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{var}`. +// +// If a variable contains multiple path segments, such as `"{var=foo/*}"` +// or `"{var=**}"`, when such a variable is expanded into a URL path on the +// client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. +// The server side does the reverse decoding, except "%2F" and "%2f" are left +// unchanged. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{+var}`. +// +// ## Using gRPC API Service Configuration +// +// gRPC API Service Configuration (service config) is a configuration language +// for configuring a gRPC service to become a user-facing product. The +// service config is simply the YAML representation of the `google.api.Service` +// proto message. +// +// As an alternative to annotating your proto file, you can configure gRPC +// transcoding in your service config YAML files. You do this by specifying a +// `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same +// effect as the proto annotation. This can be particularly useful if you +// have a proto that is reused in multiple services. Note that any transcoding +// specified in the service config will override any matching transcoding +// configuration in the proto. +// +// Example: +// +// http: +// rules: +// # Selects a gRPC method and applies HttpRule to it. +// - selector: example.v1.Messaging.GetMessage +// get: /v1/messages/{message_id}/{sub.subfield} +// +// ## Special notes +// +// When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the +// proto to JSON conversion must follow the [proto3 +// specification](https://developers.google.com/protocol-buffers/docs/proto3#json). +// +// While the single segment variable follows the semantics of +// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String +// Expansion, the multi segment variable **does not** follow RFC 6570 Section +// 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion +// does not expand special characters like `?` and `#`, which would lead +// to invalid URLs. As the result, gRPC Transcoding uses a custom encoding +// for multi segment variables. +// +// The path variables **must not** refer to any repeated or mapped field, +// because client libraries are not capable of handling such variable expansion. +// +// The path variables **must not** capture the leading "/" character. The reason +// is that the most common use case "{var}" does not capture the leading "/" +// character. For consistency, all path variables must share the same behavior. +// +// Repeated message fields must not be mapped to URL query parameters, because +// no client library can support such complicated mapping. +// +// If an API needs to use a JSON array for request or response body, it can map +// the request or response body to a repeated field. However, some gRPC +// Transcoding implementations may not support this feature. +message HttpRule { + // Selects a method to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // Determines the URL pattern is matched by this rules. This pattern can be + // used with any of the {get|put|post|delete|patch} methods. A custom method + // can be defined using the 'custom' field. + oneof pattern { + // Maps to HTTP GET. Used for listing and getting information about + // resources. + string get = 2; + + // Maps to HTTP PUT. Used for replacing a resource. + string put = 3; + + // Maps to HTTP POST. Used for creating a resource or performing an action. + string post = 4; + + // Maps to HTTP DELETE. Used for deleting a resource. + string delete = 5; + + // Maps to HTTP PATCH. Used for updating a resource. + string patch = 6; + + // The custom pattern is used for specifying an HTTP method that is not + // included in the `pattern` field, such as HEAD, or "*" to leave the + // HTTP method unspecified for this rule. The wild-card rule is useful + // for services that provide content to Web (HTML) clients. + CustomHttpPattern custom = 8; + } + + // The name of the request field whose value is mapped to the HTTP request + // body, or `*` for mapping all request fields not captured by the path + // pattern to the HTTP body, or omitted for not having any HTTP request body. + // + // NOTE: the referred field must be present at the top-level of the request + // message type. + string body = 7; + + // Optional. The name of the response field whose value is mapped to the HTTP + // response body. When omitted, the entire response message will be used + // as the HTTP response body. + // + // NOTE: The referred field must be present at the top-level of the response + // message type. + string response_body = 12; + + // Additional HTTP bindings for the selector. Nested bindings must + // not contain an `additional_bindings` field themselves (that is, + // the nesting may only be one level deep). + repeated HttpRule additional_bindings = 11; +} + +// A custom pattern is used for defining custom HTTP verb. +message CustomHttpPattern { + // The name of this custom HTTP verb. + string kind = 1; + + // The path matched by this custom verb. + string path = 2; +} \ No newline at end of file diff --git a/integration/http/google/api/http.ts b/integration/http/google/api/http.ts new file mode 100644 index 000000000..23260bab8 --- /dev/null +++ b/integration/http/google/api/http.ts @@ -0,0 +1,376 @@ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// source: google/api/http.proto + +/* eslint-disable */ + +export const protobufPackage = "google.api"; + +/** + * Defines the HTTP configuration for an API service. It contains a list of + * [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method + * to one or more HTTP REST API methods. + */ +export interface Http { + /** + * A list of HTTP configuration rules that apply to individual API methods. + * + * **NOTE:** All service configuration rules follow "last one wins" order. + */ + rules: HttpRule[]; + /** + * When set to true, URL path parameters will be fully URI-decoded except in + * cases of single segment matches in reserved expansion, where "%2F" will be + * left encoded. + * + * The default behavior is to not decode RFC 6570 reserved characters in multi + * segment matches. + */ + fullyDecodeReservedExpansion: boolean; +} + +/** + * # gRPC Transcoding + * + * gRPC Transcoding is a feature for mapping between a gRPC method and one or + * more HTTP REST endpoints. It allows developers to build a single API service + * that supports both gRPC APIs and REST APIs. Many systems, including [Google + * APIs](https://github.com/googleapis/googleapis), + * [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC + * Gateway](https://github.com/grpc-ecosystem/grpc-gateway), + * and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature + * and use it for large scale production services. + * + * `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies + * how different portions of the gRPC request message are mapped to the URL + * path, URL query parameters, and HTTP request body. It also controls how the + * gRPC response message is mapped to the HTTP response body. `HttpRule` is + * typically specified as an `google.api.http` annotation on the gRPC method. + * + * Each mapping specifies a URL path template and an HTTP method. The path + * template may refer to one or more fields in the gRPC request message, as long + * as each field is a non-repeated field with a primitive (non-message) type. + * The path template controls how fields of the request message are mapped to + * the URL path. + * + * Example: + * + * service Messaging { + * rpc GetMessage(GetMessageRequest) returns (Message) { + * option (google.api.http) = { + * get: "/v1/{name=messages/*}" + * }; + * } + * } + * message GetMessageRequest { + * string name = 1; // Mapped to URL path. + * } + * message Message { + * string text = 1; // The resource content. + * } + * + * This enables an HTTP REST to gRPC mapping as below: + * + * HTTP | gRPC + * -----|----- + * `GET /v1/messages/123456` | `GetMessage(name: "messages/123456")` + * + * Any fields in the request message which are not bound by the path template + * automatically become HTTP query parameters if there is no HTTP request body. + * For example: + * + * service Messaging { + * rpc GetMessage(GetMessageRequest) returns (Message) { + * option (google.api.http) = { + * get:"/v1/messages/{message_id}" + * }; + * } + * } + * message GetMessageRequest { + * message SubMessage { + * string subfield = 1; + * } + * string message_id = 1; // Mapped to URL path. + * int64 revision = 2; // Mapped to URL query parameter `revision`. + * SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`. + * } + * + * This enables a HTTP JSON to RPC mapping as below: + * + * HTTP | gRPC + * -----|----- + * `GET /v1/messages/123456?revision=2&sub.subfield=foo` | + * `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: + * "foo"))` + * + * Note that fields which are mapped to URL query parameters must have a + * primitive type or a repeated primitive type or a non-repeated message type. + * In the case of a repeated type, the parameter can be repeated in the URL + * as `...?param=A¶m=B`. In the case of a message type, each field of the + * message is mapped to a separate parameter, such as + * `...?foo.a=A&foo.b=B&foo.c=C`. + * + * For HTTP methods that allow a request body, the `body` field + * specifies the mapping. Consider a REST update method on the + * message resource collection: + * + * service Messaging { + * rpc UpdateMessage(UpdateMessageRequest) returns (Message) { + * option (google.api.http) = { + * patch: "/v1/messages/{message_id}" + * body: "message" + * }; + * } + * } + * message UpdateMessageRequest { + * string message_id = 1; // mapped to the URL + * Message message = 2; // mapped to the body + * } + * + * The following HTTP JSON to RPC mapping is enabled, where the + * representation of the JSON in the request body is determined by + * protos JSON encoding: + * + * HTTP | gRPC + * -----|----- + * `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: + * "123456" message { text: "Hi!" })` + * + * The special name `*` can be used in the body mapping to define that + * every field not bound by the path template should be mapped to the + * request body. This enables the following alternative definition of + * the update method: + * + * service Messaging { + * rpc UpdateMessage(Message) returns (Message) { + * option (google.api.http) = { + * patch: "/v1/messages/{message_id}" + * body: "*" + * }; + * } + * } + * message Message { + * string message_id = 1; + * string text = 2; + * } + * + * The following HTTP JSON to RPC mapping is enabled: + * + * HTTP | gRPC + * -----|----- + * `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: + * "123456" text: "Hi!")` + * + * Note that when using `*` in the body mapping, it is not possible to + * have HTTP parameters, as all fields not bound by the path end in + * the body. This makes this option more rarely used in practice when + * defining REST APIs. The common usage of `*` is in custom methods + * which don't use the URL at all for transferring data. + * + * It is possible to define multiple HTTP methods for one RPC by using + * the `additional_bindings` option. Example: + * + * service Messaging { + * rpc GetMessage(GetMessageRequest) returns (Message) { + * option (google.api.http) = { + * get: "/v1/messages/{message_id}" + * additional_bindings { + * get: "/v1/users/{user_id}/messages/{message_id}" + * } + * }; + * } + * } + * message GetMessageRequest { + * string message_id = 1; + * string user_id = 2; + * } + * + * This enables the following two alternative HTTP JSON to RPC mappings: + * + * HTTP | gRPC + * -----|----- + * `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` + * `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: + * "123456")` + * + * ## Rules for HTTP mapping + * + * 1. Leaf request fields (recursive expansion nested messages in the request + * message) are classified into three categories: + * - Fields referred by the path template. They are passed via the URL path. + * - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They + * are passed via the HTTP + * request body. + * - All other fields are passed via the URL query parameters, and the + * parameter name is the field path in the request message. A repeated + * field can be represented as multiple query parameters under the same + * name. + * 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL + * query parameter, all fields + * are passed via URL path and HTTP request body. + * 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP + * request body, all + * fields are passed via URL path and URL query parameters. + * + * ### Path template syntax + * + * Template = "/" Segments [ Verb ] ; + * Segments = Segment { "/" Segment } ; + * Segment = "*" | "**" | LITERAL | Variable ; + * Variable = "{" FieldPath [ "=" Segments ] "}" ; + * FieldPath = IDENT { "." IDENT } ; + * Verb = ":" LITERAL ; + * + * The syntax `*` matches a single URL path segment. The syntax `**` matches + * zero or more URL path segments, which must be the last part of the URL path + * except the `Verb`. + * + * The syntax `Variable` matches part of the URL path as specified by its + * template. A variable template must not contain other variables. If a variable + * matches a single path segment, its template may be omitted, e.g. `{var}` + * is equivalent to `{var=*}`. + * + * The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL` + * contains any reserved character, such characters should be percent-encoded + * before the matching. + * + * If a variable contains exactly one path segment, such as `"{var}"` or + * `"{var=*}"`, when such a variable is expanded into a URL path on the client + * side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The + * server side does the reverse decoding. Such variables show up in the + * [Discovery + * Document](https://developers.google.com/discovery/v1/reference/apis) as + * `{var}`. + * + * If a variable contains multiple path segments, such as `"{var=foo/*}"` + * or `"{var=**}"`, when such a variable is expanded into a URL path on the + * client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. + * The server side does the reverse decoding, except "%2F" and "%2f" are left + * unchanged. Such variables show up in the + * [Discovery + * Document](https://developers.google.com/discovery/v1/reference/apis) as + * `{+var}`. + * + * ## Using gRPC API Service Configuration + * + * gRPC API Service Configuration (service config) is a configuration language + * for configuring a gRPC service to become a user-facing product. The + * service config is simply the YAML representation of the `google.api.Service` + * proto message. + * + * As an alternative to annotating your proto file, you can configure gRPC + * transcoding in your service config YAML files. You do this by specifying a + * `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same + * effect as the proto annotation. This can be particularly useful if you + * have a proto that is reused in multiple services. Note that any transcoding + * specified in the service config will override any matching transcoding + * configuration in the proto. + * + * Example: + * + * http: + * rules: + * # Selects a gRPC method and applies HttpRule to it. + * - selector: example.v1.Messaging.GetMessage + * get: /v1/messages/{message_id}/{sub.subfield} + * + * ## Special notes + * + * When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the + * proto to JSON conversion must follow the [proto3 + * specification](https://developers.google.com/protocol-buffers/docs/proto3#json). + * + * While the single segment variable follows the semantics of + * [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String + * Expansion, the multi segment variable **does not** follow RFC 6570 Section + * 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion + * does not expand special characters like `?` and `#`, which would lead + * to invalid URLs. As the result, gRPC Transcoding uses a custom encoding + * for multi segment variables. + * + * The path variables **must not** refer to any repeated or mapped field, + * because client libraries are not capable of handling such variable expansion. + * + * The path variables **must not** capture the leading "/" character. The reason + * is that the most common use case "{var}" does not capture the leading "/" + * character. For consistency, all path variables must share the same behavior. + * + * Repeated message fields must not be mapped to URL query parameters, because + * no client library can support such complicated mapping. + * + * If an API needs to use a JSON array for request or response body, it can map + * the request or response body to a repeated field. However, some gRPC + * Transcoding implementations may not support this feature. + */ +export interface HttpRule { + /** + * Selects a method to which this rule applies. + * + * Refer to [selector][google.api.DocumentationRule.selector] for syntax + * details. + */ + selector: string; + /** + * Maps to HTTP GET. Used for listing and getting information about + * resources. + */ + get?: + | string + | undefined; + /** Maps to HTTP PUT. Used for replacing a resource. */ + put?: + | string + | undefined; + /** Maps to HTTP POST. Used for creating a resource or performing an action. */ + post?: + | string + | undefined; + /** Maps to HTTP DELETE. Used for deleting a resource. */ + delete?: + | string + | undefined; + /** Maps to HTTP PATCH. Used for updating a resource. */ + patch?: + | string + | undefined; + /** + * The custom pattern is used for specifying an HTTP method that is not + * included in the `pattern` field, such as HEAD, or "*" to leave the + * HTTP method unspecified for this rule. The wild-card rule is useful + * for services that provide content to Web (HTML) clients. + */ + custom?: + | CustomHttpPattern + | undefined; + /** + * The name of the request field whose value is mapped to the HTTP request + * body, or `*` for mapping all request fields not captured by the path + * pattern to the HTTP body, or omitted for not having any HTTP request body. + * + * NOTE: the referred field must be present at the top-level of the request + * message type. + */ + body: string; + /** + * Optional. The name of the response field whose value is mapped to the HTTP + * response body. When omitted, the entire response message will be used + * as the HTTP response body. + * + * NOTE: The referred field must be present at the top-level of the response + * message type. + */ + responseBody: string; + /** + * Additional HTTP bindings for the selector. Nested bindings must + * not contain an `additional_bindings` field themselves (that is, + * the nesting may only be one level deep). + */ + additionalBindings: HttpRule[]; +} + +/** A custom pattern is used for defining custom HTTP verb. */ +export interface CustomHttpPattern { + /** The name of this custom HTTP verb. */ + kind: string; + /** The path matched by this custom verb. */ + path: string; +} diff --git a/integration/http/google/protobuf/descriptor.proto b/integration/http/google/protobuf/descriptor.proto new file mode 100644 index 000000000..4f027647b --- /dev/null +++ b/integration/http/google/protobuf/descriptor.proto @@ -0,0 +1,872 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// The messages in this file describe the definitions found in .proto files. +// A valid .proto file can be translated directly to a FileDescriptorProto +// without any other information (e.g. without reading its imports). + +syntax = "proto2"; + +package google.protobuf; +option go_package = "google.golang.org/protobuf/types/descriptorpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DescriptorProtos"; +option csharp_namespace = "Google.Protobuf.Reflection"; +option objc_class_prefix = "GPB"; +option cc_enable_arenas = true; +option php_namespace = "Google\\Protobuf\\Internal"; + +// descriptor.proto must be optimized for speed because reflection-based +// algorithms don't work during bootstrapping. +option optimize_for = SPEED; + +// The protocol compiler can output a FileDescriptorSet containing the .proto +// files it parses. +message FileDescriptorSet { + repeated FileDescriptorProto file = 1; +} + +// Describes a complete .proto file. +message FileDescriptorProto { + optional string name = 1; // file name, relative to root of source tree + optional string package = 2; // e.g. "foo", "foo.bar", etc. + + // Names of files imported by this file. + repeated string dependency = 3; + // Indexes of the public imported files in the dependency list above. + repeated int32 public_dependency = 10; + // Indexes of the weak imported files in the dependency list. + // For Google-internal migration only. Do not use. + repeated int32 weak_dependency = 11; + + // All top-level definitions in this file. + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; + + optional FileOptions options = 8; + + // This field contains optional information about the original source code. + // You may safely remove this entire field without harming runtime + // functionality of the descriptors -- the information is needed only by + // development tools. + optional SourceCodeInfo source_code_info = 9; + + // The syntax of the proto file. + // The supported values are "proto2" and "proto3". + optional string syntax = 12; +} + +// Describes a message type. +message DescriptorProto { + optional string name = 1; + + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; + + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; + + message ExtensionRange { + optional int32 start = 1; + optional int32 end = 2; + + optional ExtensionRangeOptions options = 3; + } + repeated ExtensionRange extension_range = 5; + + repeated OneofDescriptorProto oneof_decl = 8; + + optional MessageOptions options = 7; + + // Range of reserved tag numbers. Reserved tag numbers may not be used by + // fields or extension ranges in the same message. Reserved ranges may + // not overlap. + message ReservedRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. + } + repeated ReservedRange reserved_range = 9; + // Reserved field names, which may not be used by fields in the same message. + // A given name may only be reserved once. + repeated string reserved_name = 10; +} + +message ExtensionRangeOptions { + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +// Describes a field within a message. +message FieldDescriptorProto { + enum Type { + // 0 is reserved for errors. + // Order is weird for historical reasons. + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + // Tag-delimited aggregate. + // Group type is deprecated and not supported in proto3. However, Proto3 + // implementations should still be able to parse the group wire format and + // treat group fields as unknown fields. + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; // Length-delimited aggregate. + + // New in version 2. + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; // Uses ZigZag encoding. + TYPE_SINT64 = 18; // Uses ZigZag encoding. + }; + + enum Label { + // 0 is reserved for errors + LABEL_OPTIONAL = 1; + LABEL_REQUIRED = 2; + LABEL_REPEATED = 3; + }; + + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; + + // If type_name is set, this need not be set. If both this and type_name + // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + optional Type type = 5; + + // For message and enum types, this is the name of the type. If the name + // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + // rules are used to find the type (i.e. first the nested types within this + // message are searched, then within the parent, on up to the root + // namespace). + optional string type_name = 6; + + // For extensions, this is the name of the type being extended. It is + // resolved in the same manner as type_name. + optional string extendee = 2; + + // For numeric types, contains the original text representation of the value. + // For booleans, "true" or "false". + // For strings, contains the default text contents (not escaped in any way). + // For bytes, contains the C escaped value. All bytes >= 128 are escaped. + // TODO(kenton): Base-64 encode? + optional string default_value = 7; + + // If set, gives the index of a oneof in the containing type's oneof_decl + // list. This field is a member of that oneof. + optional int32 oneof_index = 9; + + // JSON name of this field. The value is set by protocol compiler. If the + // user has set a "json_name" option on this field, that option's value + // will be used. Otherwise, it's deduced from the field's name by converting + // it to camelCase. + optional string json_name = 10; + + optional FieldOptions options = 8; +} + +// Describes a oneof. +message OneofDescriptorProto { + optional string name = 1; + optional OneofOptions options = 2; +} + +// Describes an enum type. +message EnumDescriptorProto { + optional string name = 1; + + repeated EnumValueDescriptorProto value = 2; + + optional EnumOptions options = 3; + + // Range of reserved numeric values. Reserved values may not be used by + // entries in the same enum. Reserved ranges may not overlap. + // + // Note that this is distinct from DescriptorProto.ReservedRange in that it + // is inclusive such that it can appropriately represent the entire int32 + // domain. + message EnumReservedRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Inclusive. + } + + // Range of reserved numeric values. Reserved numeric values may not be used + // by enum values in the same enum declaration. Reserved ranges may not + // overlap. + repeated EnumReservedRange reserved_range = 4; + + // Reserved enum value names, which may not be reused. A given name may only + // be reserved once. + repeated string reserved_name = 5; +} + +// Describes a value within an enum. +message EnumValueDescriptorProto { + optional string name = 1; + optional int32 number = 2; + + optional EnumValueOptions options = 3; +} + +// Describes a service. +message ServiceDescriptorProto { + optional string name = 1; + repeated MethodDescriptorProto method = 2; + + optional ServiceOptions options = 3; +} + +// Describes a method of a service. +message MethodDescriptorProto { + optional string name = 1; + + // Input and output type names. These are resolved in the same way as + // FieldDescriptorProto.type_name, but must refer to a message type. + optional string input_type = 2; + optional string output_type = 3; + + optional MethodOptions options = 4; + + // Identifies if client streams multiple client messages + optional bool client_streaming = 5 [ default = false ]; + // Identifies if server streams multiple server messages + optional bool server_streaming = 6 [ default = false ]; +} + +// =================================================================== +// Options + +// Each of the definitions above may have "options" attached. These are +// just annotations which may cause code to be generated slightly differently +// or may contain hints for code that manipulates protocol messages. +// +// Clients may define custom options as extensions of the *Options messages. +// These extensions may not yet be known at parsing time, so the parser cannot +// store the values in them. Instead it stores them in a field in the *Options +// message called uninterpreted_option. This field must have the same name +// across all *Options messages. We then use this field to populate the +// extensions when we build a descriptor, at which point all protos have been +// parsed and so all extensions are known. +// +// Extension numbers for custom options may be chosen as follows: +// * For options which will only be used within a single application or +// organization, or for experimental options, use field numbers 50000 +// through 99999. It is up to you to ensure that you do not use the +// same number for multiple options. +// * For options which will be published and used publicly by multiple +// independent entities, e-mail protobuf-global-extension-registry@google.com +// to reserve extension numbers. Simply provide your project name (e.g. +// Objective-C plugin) and your project website (if available) -- there's no +// need to explain how you intend to use them. Usually you only need one +// extension number. You can declare multiple options with only one extension +// number by putting them in a sub-message. See the Custom Options section of +// the docs for examples: +// https://developers.google.com/protocol-buffers/docs/proto#options +// If this turns out to be popular, a web service will be set up +// to automatically assign option numbers. + +message FileOptions { + + // Sets the Java package where classes generated from this .proto will be + // placed. By default, the proto package is used, but this is often + // inappropriate because proto packages do not normally start with backwards + // domain names. + optional string java_package = 1; + + // If set, all the classes from the .proto file are wrapped in a single + // outer class with the given name. This applies to both Proto1 + // (equivalent to the old "--one_java_file" option) and Proto2 (where + // a .proto always translates to a single class, but you may want to + // explicitly choose the class name). + optional string java_outer_classname = 8; + + // If set true, then the Java code generator will generate a separate .java + // file for each top-level message, enum, and service defined in the .proto + // file. Thus, these types will *not* be nested inside the outer class + // named by java_outer_classname. However, the outer class will still be + // generated to contain the file's getDescriptor() method as well as any + // top-level extensions defined in the file. + optional bool java_multiple_files = 10 [ default = false ]; + + // This option does nothing. + optional bool java_generate_equals_and_hash = 20 [ deprecated = true ]; + + // If set true, then the Java2 code generator will generate code that + // throws an exception whenever an attempt is made to assign a non-UTF-8 + // byte sequence to a string field. + // Message reflection will do the same. + // However, an extension field still accepts non-UTF-8 byte sequences. + // This option has no effect on when used with the lite runtime. + optional bool java_string_check_utf8 = 27 [ default = false ]; + + // Generated classes can be optimized for speed or code size. + enum OptimizeMode { + SPEED = 1; // Generate complete code for parsing, serialization, + // etc. + CODE_SIZE = 2; // Use ReflectionOps to implement these methods. + LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. + } + optional OptimizeMode optimize_for = 9 [ default = SPEED ]; + + // Sets the Go package where structs generated from this .proto will be + // placed. If omitted, the Go package will be derived from the following: + // - The basename of the package import path, if provided. + // - Otherwise, the package statement in the .proto file, if present. + // - Otherwise, the basename of the .proto file, without extension. + optional string go_package = 11; + + // Should generic services be generated in each language? "Generic" services + // are not specific to any particular RPC system. They are generated by the + // main code generators in each language (without additional plugins). + // Generic services were the only kind of service generation supported by + // early versions of google.protobuf. + // + // Generic services are now considered deprecated in favor of using plugins + // that generate code specific to your particular RPC system. Therefore, + // these default to false. Old code which depends on generic services should + // explicitly set them to true. + optional bool cc_generic_services = 16 [ default = false ]; + optional bool java_generic_services = 17 [ default = false ]; + optional bool py_generic_services = 18 [ default = false ]; + optional bool php_generic_services = 42 [ default = false ]; + + // Is this file deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for everything in the file, or it will be completely ignored; in the very + // least, this is a formalization for deprecating files. + optional bool deprecated = 23 [ default = false ]; + + // Enables the use of arenas for the proto messages in this file. This applies + // only to generated classes for C++. + optional bool cc_enable_arenas = 31 [ default = false ]; + + // Sets the objective c class prefix which is prepended to all objective c + // generated classes from this .proto. There is no default. + optional string objc_class_prefix = 36; + + // Namespace for generated classes; defaults to the package. + optional string csharp_namespace = 37; + + // By default Swift generators will take the proto package and CamelCase it + // replacing '.' with underscore and use that to prefix the types/symbols + // defined. When this options is provided, they will use this value instead + // to prefix the types/symbols defined. + optional string swift_prefix = 39; + + // Sets the php class prefix which is prepended to all php generated classes + // from this .proto. Default is empty. + optional string php_class_prefix = 40; + + // Use this option to change the namespace of php generated classes. Default + // is empty. When this option is empty, the package name will be used for + // determining the namespace. + optional string php_namespace = 41; + + // Use this option to change the namespace of php generated metadata classes. + // Default is empty. When this option is empty, the proto file name will be used + // for determining the namespace. + optional string php_metadata_namespace = 44; + + // Use this option to change the package of ruby generated classes. Default + // is empty. When this option is not set, the package name will be used for + // determining the ruby package. + optional string ruby_package = 45; + + // The parser stores options it doesn't recognize here. + // See the documentation for the "Options" section above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. + // See the documentation for the "Options" section above. + extensions 1000 to max; + + reserved 38; +} + +message MessageOptions { + // Set true to use the old proto1 MessageSet wire format for extensions. + // This is provided for backwards-compatibility with the MessageSet wire + // format. You should not use this for any other reason: It's less + // efficient, has fewer features, and is more complicated. + // + // The message must be defined exactly as follows: + // message Foo { + // option message_set_wire_format = true; + // extensions 4 to max; + // } + // Note that the message cannot have any defined fields; MessageSets only + // have extensions. + // + // All extensions of your type must be singular messages; e.g. they cannot + // be int32s, enums, or repeated messages. + // + // Because this is an option, the above two restrictions are not enforced by + // the protocol compiler. + optional bool message_set_wire_format = 1 [ default = false ]; + + // Disables the generation of the standard "descriptor()" accessor, which can + // conflict with a field of the same name. This is meant to make migration + // from proto1 easier; new code should avoid fields named "descriptor". + optional bool no_standard_descriptor_accessor = 2 [ default = false ]; + + // Is this message deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the message, or it will be completely ignored; in the very least, + // this is a formalization for deprecating messages. + optional bool deprecated = 3 [ default = false ]; + + // Whether the message is an automatically generated map entry type for the + // maps field. + // + // For maps fields: + // map map_field = 1; + // The parsed descriptor looks like: + // message MapFieldEntry { + // option map_entry = true; + // optional KeyType key = 1; + // optional ValueType value = 2; + // } + // repeated MapFieldEntry map_field = 1; + // + // Implementations may choose not to generate the map_entry=true message, but + // use a native map in the target language to hold the keys and values. + // The reflection APIs in such implementions still need to work as + // if the field is a repeated message field. + // + // NOTE: Do not set the option in .proto files. Always use the maps syntax + // instead. The option should only be implicitly set by the proto compiler + // parser. + optional bool map_entry = 7; + + reserved 8; // javalite_serializable + reserved 9; // javanano_as_lite + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message FieldOptions { + // The ctype option instructs the C++ code generator to use a different + // representation of the field than it normally would. See the specific + // options below. This option is not yet implemented in the open source + // release -- sorry, we'll try to include it in a future version! + optional CType ctype = 1 [ default = STRING ]; + enum CType { + // Default mode. + STRING = 0; + + CORD = 1; + + STRING_PIECE = 2; + } + // The packed option can be enabled for repeated primitive fields to enable + // a more efficient representation on the wire. Rather than repeatedly + // writing the tag and type for each element, the entire array is encoded as + // a single length-delimited blob. In proto3, only explicit setting it to + // false will avoid using packed encoding. + optional bool packed = 2; + + // The jstype option determines the JavaScript type used for values of the + // field. The option is permitted only for 64 bit integral and fixed types + // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + // is represented as JavaScript string, which avoids loss of precision that + // can happen when a large value is converted to a floating point JavaScript. + // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + // use the JavaScript "number" type. The behavior of the default option + // JS_NORMAL is implementation dependent. + // + // This option is an enum to permit additional types to be added, e.g. + // goog.math.Integer. + optional JSType jstype = 6 [ default = JS_NORMAL ]; + enum JSType { + // Use the default type. + JS_NORMAL = 0; + + // Use JavaScript strings. + JS_STRING = 1; + + // Use JavaScript numbers. + JS_NUMBER = 2; + } + + // Should this field be parsed lazily? Lazy applies only to message-type + // fields. It means that when the outer message is initially parsed, the + // inner message's contents will not be parsed but instead stored in encoded + // form. The inner message will actually be parsed when it is first accessed. + // + // This is only a hint. Implementations are free to choose whether to use + // eager or lazy parsing regardless of the value of this option. However, + // setting this option true suggests that the protocol author believes that + // using lazy parsing on this field is worth the additional bookkeeping + // overhead typically needed to implement it. + // + // This option does not affect the public interface of any generated code; + // all method signatures remain the same. Furthermore, thread-safety of the + // interface is not affected by this option; const methods remain safe to + // call from multiple threads concurrently, while non-const methods continue + // to require exclusive access. + // + // + // Note that implementations may choose not to check required fields within + // a lazy sub-message. That is, calling IsInitialized() on the outer message + // may return true even if the inner message has missing required fields. + // This is necessary because otherwise the inner message would have to be + // parsed in order to perform the check, defeating the purpose of lazy + // parsing. An implementation which chooses not to check required fields + // must be consistent about it. That is, for any particular sub-message, the + // implementation must either *always* check its required fields, or *never* + // check its required fields, regardless of whether or not the message has + // been parsed. + optional bool lazy = 5 [ default = false ]; + + // Is this field deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for accessors, or it will be completely ignored; in the very least, this + // is a formalization for deprecating fields. + optional bool deprecated = 3 [ default = false ]; + + // For Google-internal migration only. Do not use. + optional bool weak = 10 [ default = false ]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; + + reserved 4; // removed jtype +} + +message OneofOptions { + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumOptions { + + // Set this option to true to allow mapping different tag names to the same + // value. + optional bool allow_alias = 2; + + // Is this enum deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum, or it will be completely ignored; in the very least, this + // is a formalization for deprecating enums. + optional bool deprecated = 3 [ default = false ]; + + reserved 5; // javanano_as_lite + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumValueOptions { + // Is this enum value deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum value, or it will be completely ignored; in the very least, + // this is a formalization for deprecating enum values. + optional bool deprecated = 1 [ default = false ]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message ServiceOptions { + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this service deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the service, or it will be completely ignored; in the very least, + // this is a formalization for deprecating services. + optional bool deprecated = 33 [ default = false ]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message MethodOptions { + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this method deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the method, or it will be completely ignored; in the very least, + // this is a formalization for deprecating methods. + optional bool deprecated = 33 [ default = false ]; + + // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + // or neither? HTTP based RPC implementation may choose GET verb for safe + // methods, and PUT verb for idempotent methods instead of the default POST. + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0; + NO_SIDE_EFFECTS = 1; // implies idempotent + IDEMPOTENT = 2; // idempotent, but may have side effects + } + optional IdempotencyLevel idempotency_level = 34 [ default = IDEMPOTENCY_UNKNOWN ]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +// A message representing a option the parser does not recognize. This only +// appears in options protos created by the compiler::Parser class. +// DescriptorPool resolves these when building Descriptor objects. Therefore, +// options protos in descriptor objects (e.g. returned by Descriptor::options(), +// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions +// in them. +message UninterpretedOption { + // The name of the uninterpreted option. Each string represents a segment in + // a dot-separated name. is_extension is true iff a segment represents an + // extension (denoted with parentheses in options specs in .proto files). + // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents + // "foo.(bar.baz).qux". + message NamePart { + required string name_part = 1; + required bool is_extension = 2; + } + repeated NamePart name = 2; + + // The value of the uninterpreted option, in whatever type the tokenizer + // identified it as during parsing. Exactly one of these should be set. + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; +} + +// =================================================================== +// Optional source code info + +// Encapsulates information about the original source file from which a +// FileDescriptorProto was generated. +message SourceCodeInfo { + // A Location identifies a piece of source code in a .proto file which + // corresponds to a particular definition. This information is intended + // to be useful to IDEs, code indexers, documentation generators, and similar + // tools. + // + // For example, say we have a file like: + // message Foo { + // optional string foo = 1; + // } + // Let's look at just the field definition: + // optional string foo = 1; + // ^ ^^ ^^ ^ ^^^ + // a bc de f ghi + // We have the following locations: + // span path represents + // [a,i) [ 4, 0, 2, 0 ] The whole field definition. + // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + // + // Notes: + // - A location may refer to a repeated field itself (i.e. not to any + // particular index within it). This is used whenever a set of elements are + // logically enclosed in a single code segment. For example, an entire + // extend block (possibly containing multiple extension definitions) will + // have an outer location whose path refers to the "extensions" repeated + // field without an index. + // - Multiple locations may have the same path. This happens when a single + // logical declaration is spread out across multiple places. The most + // obvious example is the "extend" block again -- there may be multiple + // extend blocks in the same scope, each of which will have the same path. + // - A location's span is not always a subset of its parent's span. For + // example, the "extendee" of an extension declaration appears at the + // beginning of the "extend" block and is shared by all extensions within + // the block. + // - Just because a location's span is a subset of some other location's span + // does not mean that it is a descendent. For example, a "group" defines + // both a type and a field in a single declaration. Thus, the locations + // corresponding to the type and field and their components will overlap. + // - Code which tries to interpret locations should probably be designed to + // ignore those that it doesn't understand, as more types of locations could + // be recorded in the future. + repeated Location location = 1; + message Location { + // Identifies which part of the FileDescriptorProto was defined at this + // location. + // + // Each element is a field number or an index. They form a path from + // the root FileDescriptorProto to the place where the definition. For + // example, this path: + // [ 4, 3, 2, 7, 1 ] + // refers to: + // file.message_type(3) // 4, 3 + // .field(7) // 2, 7 + // .name() // 1 + // This is because FileDescriptorProto.message_type has field number 4: + // repeated DescriptorProto message_type = 4; + // and DescriptorProto.field has field number 2: + // repeated FieldDescriptorProto field = 2; + // and FieldDescriptorProto.name has field number 1: + // optional string name = 1; + // + // Thus, the above path gives the location of a field name. If we removed + // the last element: + // [ 4, 3, 2, 7 ] + // this path refers to the whole field declaration (from the beginning + // of the label to the terminating semicolon). + repeated int32 path = 1 [ packed = true ]; + + // Always has exactly three or four elements: start line, start column, + // end line (optional, otherwise assumed same as start line), end column. + // These are packed into a single field for efficiency. Note that line + // and column numbers are zero-based -- typically you will want to add + // 1 to each before displaying to a user. + repeated int32 span = 2 [ packed = true ]; + + // If this SourceCodeInfo represents a complete declaration, these are any + // comments appearing before and after the declaration which appear to be + // attached to the declaration. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // leading_detached_comments will keep paragraphs of comments that appear + // before (but not connected to) the current element. Each paragraph, + // separated by empty lines, will be one comment element in the repeated + // field. + // + // Only the comment content is provided; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk + // will be stripped from the beginning of each line other than the first. + // Newlines are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to qux. + // // + // // Another line attached to qux. + // optional double qux = 4; + // + // // Detached comment for corge. This is not leading or trailing comments + // // to qux or corge because there are blank lines separating it from + // // both. + // + // // Detached comment for corge paragraph 2. + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + // + // // ignored detached comments. + optional string leading_comments = 3; + optional string trailing_comments = 4; + repeated string leading_detached_comments = 6; + } +} + +// Describes the relationship between generated code and its original source +// file. A GeneratedCodeInfo message is associated with only one generated +// source file, but may contain references to different source .proto files. +message GeneratedCodeInfo { + // An Annotation connects some span of text in generated code to an element + // of its generating .proto file. + repeated Annotation annotation = 1; + message Annotation { + // Identifies the element in the original source .proto file. This field + // is formatted the same as SourceCodeInfo.Location.path. + repeated int32 path = 1 [ packed = true ]; + + // Identifies the filesystem path to the original source .proto. + optional string source_file = 2; + + // Identifies the starting offset in bytes in the generated code + // that relates to the identified object. + optional int32 begin = 3; + + // Identifies the ending offset in bytes in the generated code that + // relates to the identified offset. The end offset should be one past + // the last relevant byte (so the length of the text = end - begin). + optional int32 end = 4; + } +} \ No newline at end of file diff --git a/integration/http/google/protobuf/descriptor.ts b/integration/http/google/protobuf/descriptor.ts new file mode 100644 index 000000000..021b960ba --- /dev/null +++ b/integration/http/google/protobuf/descriptor.ts @@ -0,0 +1,924 @@ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// source: google/protobuf/descriptor.proto + +/* eslint-disable */ + +export const protobufPackage = "google.protobuf"; + +/** + * The protocol compiler can output a FileDescriptorSet containing the .proto + * files it parses. + */ +export interface FileDescriptorSet { + file: FileDescriptorProto[]; +} + +/** Describes a complete .proto file. */ +export interface FileDescriptorProto { + /** file name, relative to root of source tree */ + name?: + | string + | undefined; + /** e.g. "foo", "foo.bar", etc. */ + package?: + | string + | undefined; + /** Names of files imported by this file. */ + dependency: string[]; + /** Indexes of the public imported files in the dependency list above. */ + publicDependency: number[]; + /** + * Indexes of the weak imported files in the dependency list. + * For Google-internal migration only. Do not use. + */ + weakDependency: number[]; + /** All top-level definitions in this file. */ + messageType: DescriptorProto[]; + enumType: EnumDescriptorProto[]; + service: ServiceDescriptorProto[]; + extension: FieldDescriptorProto[]; + options?: + | FileOptions + | undefined; + /** + * This field contains optional information about the original source code. + * You may safely remove this entire field without harming runtime + * functionality of the descriptors -- the information is needed only by + * development tools. + */ + sourceCodeInfo?: + | SourceCodeInfo + | undefined; + /** + * The syntax of the proto file. + * The supported values are "proto2" and "proto3". + */ + syntax?: string | undefined; +} + +/** Describes a message type. */ +export interface DescriptorProto { + name?: string | undefined; + field: FieldDescriptorProto[]; + extension: FieldDescriptorProto[]; + nestedType: DescriptorProto[]; + enumType: EnumDescriptorProto[]; + extensionRange: DescriptorProto_ExtensionRange[]; + oneofDecl: OneofDescriptorProto[]; + options?: MessageOptions | undefined; + reservedRange: DescriptorProto_ReservedRange[]; + /** + * Reserved field names, which may not be used by fields in the same message. + * A given name may only be reserved once. + */ + reservedName: string[]; +} + +export interface DescriptorProto_ExtensionRange { + start?: number | undefined; + end?: number | undefined; + options?: ExtensionRangeOptions | undefined; +} + +/** + * Range of reserved tag numbers. Reserved tag numbers may not be used by + * fields or extension ranges in the same message. Reserved ranges may + * not overlap. + */ +export interface DescriptorProto_ReservedRange { + /** Inclusive. */ + start?: + | number + | undefined; + /** Exclusive. */ + end?: number | undefined; +} + +export interface ExtensionRangeOptions { + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} + +/** Describes a field within a message. */ +export interface FieldDescriptorProto { + name?: string | undefined; + number?: number | undefined; + label?: + | FieldDescriptorProto_Label + | undefined; + /** + * If type_name is set, this need not be set. If both this and type_name + * are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + */ + type?: + | FieldDescriptorProto_Type + | undefined; + /** + * For message and enum types, this is the name of the type. If the name + * starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + * rules are used to find the type (i.e. first the nested types within this + * message are searched, then within the parent, on up to the root + * namespace). + */ + typeName?: + | string + | undefined; + /** + * For extensions, this is the name of the type being extended. It is + * resolved in the same manner as type_name. + */ + extendee?: + | string + | undefined; + /** + * For numeric types, contains the original text representation of the value. + * For booleans, "true" or "false". + * For strings, contains the default text contents (not escaped in any way). + * For bytes, contains the C escaped value. All bytes >= 128 are escaped. + * TODO(kenton): Base-64 encode? + */ + defaultValue?: + | string + | undefined; + /** + * If set, gives the index of a oneof in the containing type's oneof_decl + * list. This field is a member of that oneof. + */ + oneofIndex?: + | number + | undefined; + /** + * JSON name of this field. The value is set by protocol compiler. If the + * user has set a "json_name" option on this field, that option's value + * will be used. Otherwise, it's deduced from the field's name by converting + * it to camelCase. + */ + jsonName?: string | undefined; + options?: FieldOptions | undefined; +} + +export enum FieldDescriptorProto_Type { + /** + * TYPE_DOUBLE - 0 is reserved for errors. + * Order is weird for historical reasons. + */ + TYPE_DOUBLE = 1, + TYPE_FLOAT = 2, + /** + * TYPE_INT64 - Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + * negative values are likely. + */ + TYPE_INT64 = 3, + TYPE_UINT64 = 4, + /** + * TYPE_INT32 - Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + * negative values are likely. + */ + TYPE_INT32 = 5, + TYPE_FIXED64 = 6, + TYPE_FIXED32 = 7, + TYPE_BOOL = 8, + TYPE_STRING = 9, + /** + * TYPE_GROUP - Tag-delimited aggregate. + * Group type is deprecated and not supported in proto3. However, Proto3 + * implementations should still be able to parse the group wire format and + * treat group fields as unknown fields. + */ + TYPE_GROUP = 10, + /** TYPE_MESSAGE - Length-delimited aggregate. */ + TYPE_MESSAGE = 11, + /** TYPE_BYTES - New in version 2. */ + TYPE_BYTES = 12, + TYPE_UINT32 = 13, + TYPE_ENUM = 14, + TYPE_SFIXED32 = 15, + TYPE_SFIXED64 = 16, + /** TYPE_SINT32 - Uses ZigZag encoding. */ + TYPE_SINT32 = 17, + /** TYPE_SINT64 - Uses ZigZag encoding. */ + TYPE_SINT64 = 18, + UNRECOGNIZED = -1, +} + +export enum FieldDescriptorProto_Label { + /** LABEL_OPTIONAL - 0 is reserved for errors */ + LABEL_OPTIONAL = 1, + LABEL_REQUIRED = 2, + LABEL_REPEATED = 3, + UNRECOGNIZED = -1, +} + +/** Describes a oneof. */ +export interface OneofDescriptorProto { + name?: string | undefined; + options?: OneofOptions | undefined; +} + +/** Describes an enum type. */ +export interface EnumDescriptorProto { + name?: string | undefined; + value: EnumValueDescriptorProto[]; + options?: + | EnumOptions + | undefined; + /** + * Range of reserved numeric values. Reserved numeric values may not be used + * by enum values in the same enum declaration. Reserved ranges may not + * overlap. + */ + reservedRange: EnumDescriptorProto_EnumReservedRange[]; + /** + * Reserved enum value names, which may not be reused. A given name may only + * be reserved once. + */ + reservedName: string[]; +} + +/** + * Range of reserved numeric values. Reserved values may not be used by + * entries in the same enum. Reserved ranges may not overlap. + * + * Note that this is distinct from DescriptorProto.ReservedRange in that it + * is inclusive such that it can appropriately represent the entire int32 + * domain. + */ +export interface EnumDescriptorProto_EnumReservedRange { + /** Inclusive. */ + start?: + | number + | undefined; + /** Inclusive. */ + end?: number | undefined; +} + +/** Describes a value within an enum. */ +export interface EnumValueDescriptorProto { + name?: string | undefined; + number?: number | undefined; + options?: EnumValueOptions | undefined; +} + +/** Describes a service. */ +export interface ServiceDescriptorProto { + name?: string | undefined; + method: MethodDescriptorProto[]; + options?: ServiceOptions | undefined; +} + +/** Describes a method of a service. */ +export interface MethodDescriptorProto { + name?: + | string + | undefined; + /** + * Input and output type names. These are resolved in the same way as + * FieldDescriptorProto.type_name, but must refer to a message type. + */ + inputType?: string | undefined; + outputType?: string | undefined; + options?: + | MethodOptions + | undefined; + /** Identifies if client streams multiple client messages */ + clientStreaming?: + | boolean + | undefined; + /** Identifies if server streams multiple server messages */ + serverStreaming?: boolean | undefined; +} + +export interface FileOptions { + /** + * Sets the Java package where classes generated from this .proto will be + * placed. By default, the proto package is used, but this is often + * inappropriate because proto packages do not normally start with backwards + * domain names. + */ + javaPackage?: + | string + | undefined; + /** + * If set, all the classes from the .proto file are wrapped in a single + * outer class with the given name. This applies to both Proto1 + * (equivalent to the old "--one_java_file" option) and Proto2 (where + * a .proto always translates to a single class, but you may want to + * explicitly choose the class name). + */ + javaOuterClassname?: + | string + | undefined; + /** + * If set true, then the Java code generator will generate a separate .java + * file for each top-level message, enum, and service defined in the .proto + * file. Thus, these types will *not* be nested inside the outer class + * named by java_outer_classname. However, the outer class will still be + * generated to contain the file's getDescriptor() method as well as any + * top-level extensions defined in the file. + */ + javaMultipleFiles?: + | boolean + | undefined; + /** + * This option does nothing. + * + * @deprecated + */ + javaGenerateEqualsAndHash?: + | boolean + | undefined; + /** + * If set true, then the Java2 code generator will generate code that + * throws an exception whenever an attempt is made to assign a non-UTF-8 + * byte sequence to a string field. + * Message reflection will do the same. + * However, an extension field still accepts non-UTF-8 byte sequences. + * This option has no effect on when used with the lite runtime. + */ + javaStringCheckUtf8?: boolean | undefined; + optimizeFor?: + | FileOptions_OptimizeMode + | undefined; + /** + * Sets the Go package where structs generated from this .proto will be + * placed. If omitted, the Go package will be derived from the following: + * - The basename of the package import path, if provided. + * - Otherwise, the package statement in the .proto file, if present. + * - Otherwise, the basename of the .proto file, without extension. + */ + goPackage?: + | string + | undefined; + /** + * Should generic services be generated in each language? "Generic" services + * are not specific to any particular RPC system. They are generated by the + * main code generators in each language (without additional plugins). + * Generic services were the only kind of service generation supported by + * early versions of google.protobuf. + * + * Generic services are now considered deprecated in favor of using plugins + * that generate code specific to your particular RPC system. Therefore, + * these default to false. Old code which depends on generic services should + * explicitly set them to true. + */ + ccGenericServices?: boolean | undefined; + javaGenericServices?: boolean | undefined; + pyGenericServices?: boolean | undefined; + phpGenericServices?: + | boolean + | undefined; + /** + * Is this file deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for everything in the file, or it will be completely ignored; in the very + * least, this is a formalization for deprecating files. + */ + deprecated?: + | boolean + | undefined; + /** + * Enables the use of arenas for the proto messages in this file. This applies + * only to generated classes for C++. + */ + ccEnableArenas?: + | boolean + | undefined; + /** + * Sets the objective c class prefix which is prepended to all objective c + * generated classes from this .proto. There is no default. + */ + objcClassPrefix?: + | string + | undefined; + /** Namespace for generated classes; defaults to the package. */ + csharpNamespace?: + | string + | undefined; + /** + * By default Swift generators will take the proto package and CamelCase it + * replacing '.' with underscore and use that to prefix the types/symbols + * defined. When this options is provided, they will use this value instead + * to prefix the types/symbols defined. + */ + swiftPrefix?: + | string + | undefined; + /** + * Sets the php class prefix which is prepended to all php generated classes + * from this .proto. Default is empty. + */ + phpClassPrefix?: + | string + | undefined; + /** + * Use this option to change the namespace of php generated classes. Default + * is empty. When this option is empty, the package name will be used for + * determining the namespace. + */ + phpNamespace?: + | string + | undefined; + /** + * Use this option to change the namespace of php generated metadata classes. + * Default is empty. When this option is empty, the proto file name will be used + * for determining the namespace. + */ + phpMetadataNamespace?: + | string + | undefined; + /** + * Use this option to change the package of ruby generated classes. Default + * is empty. When this option is not set, the package name will be used for + * determining the ruby package. + */ + rubyPackage?: + | string + | undefined; + /** + * The parser stores options it doesn't recognize here. + * See the documentation for the "Options" section above. + */ + uninterpretedOption: UninterpretedOption[]; +} + +/** Generated classes can be optimized for speed or code size. */ +export enum FileOptions_OptimizeMode { + /** SPEED - Generate complete code for parsing, serialization, */ + SPEED = 1, + /** CODE_SIZE - etc. */ + CODE_SIZE = 2, + /** LITE_RUNTIME - Generate code using MessageLite and the lite runtime. */ + LITE_RUNTIME = 3, + UNRECOGNIZED = -1, +} + +export interface MessageOptions { + /** + * Set true to use the old proto1 MessageSet wire format for extensions. + * This is provided for backwards-compatibility with the MessageSet wire + * format. You should not use this for any other reason: It's less + * efficient, has fewer features, and is more complicated. + * + * The message must be defined exactly as follows: + * message Foo { + * option message_set_wire_format = true; + * extensions 4 to max; + * } + * Note that the message cannot have any defined fields; MessageSets only + * have extensions. + * + * All extensions of your type must be singular messages; e.g. they cannot + * be int32s, enums, or repeated messages. + * + * Because this is an option, the above two restrictions are not enforced by + * the protocol compiler. + */ + messageSetWireFormat?: + | boolean + | undefined; + /** + * Disables the generation of the standard "descriptor()" accessor, which can + * conflict with a field of the same name. This is meant to make migration + * from proto1 easier; new code should avoid fields named "descriptor". + */ + noStandardDescriptorAccessor?: + | boolean + | undefined; + /** + * Is this message deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for the message, or it will be completely ignored; in the very least, + * this is a formalization for deprecating messages. + */ + deprecated?: + | boolean + | undefined; + /** + * Whether the message is an automatically generated map entry type for the + * maps field. + * + * For maps fields: + * map map_field = 1; + * The parsed descriptor looks like: + * message MapFieldEntry { + * option map_entry = true; + * optional KeyType key = 1; + * optional ValueType value = 2; + * } + * repeated MapFieldEntry map_field = 1; + * + * Implementations may choose not to generate the map_entry=true message, but + * use a native map in the target language to hold the keys and values. + * The reflection APIs in such implementions still need to work as + * if the field is a repeated message field. + * + * NOTE: Do not set the option in .proto files. Always use the maps syntax + * instead. The option should only be implicitly set by the proto compiler + * parser. + */ + mapEntry?: + | boolean + | undefined; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} + +export interface FieldOptions { + /** + * The ctype option instructs the C++ code generator to use a different + * representation of the field than it normally would. See the specific + * options below. This option is not yet implemented in the open source + * release -- sorry, we'll try to include it in a future version! + */ + ctype?: + | FieldOptions_CType + | undefined; + /** + * The packed option can be enabled for repeated primitive fields to enable + * a more efficient representation on the wire. Rather than repeatedly + * writing the tag and type for each element, the entire array is encoded as + * a single length-delimited blob. In proto3, only explicit setting it to + * false will avoid using packed encoding. + */ + packed?: + | boolean + | undefined; + /** + * The jstype option determines the JavaScript type used for values of the + * field. The option is permitted only for 64 bit integral and fixed types + * (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + * is represented as JavaScript string, which avoids loss of precision that + * can happen when a large value is converted to a floating point JavaScript. + * Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + * use the JavaScript "number" type. The behavior of the default option + * JS_NORMAL is implementation dependent. + * + * This option is an enum to permit additional types to be added, e.g. + * goog.math.Integer. + */ + jstype?: + | FieldOptions_JSType + | undefined; + /** + * Should this field be parsed lazily? Lazy applies only to message-type + * fields. It means that when the outer message is initially parsed, the + * inner message's contents will not be parsed but instead stored in encoded + * form. The inner message will actually be parsed when it is first accessed. + * + * This is only a hint. Implementations are free to choose whether to use + * eager or lazy parsing regardless of the value of this option. However, + * setting this option true suggests that the protocol author believes that + * using lazy parsing on this field is worth the additional bookkeeping + * overhead typically needed to implement it. + * + * This option does not affect the public interface of any generated code; + * all method signatures remain the same. Furthermore, thread-safety of the + * interface is not affected by this option; const methods remain safe to + * call from multiple threads concurrently, while non-const methods continue + * to require exclusive access. + * + * Note that implementations may choose not to check required fields within + * a lazy sub-message. That is, calling IsInitialized() on the outer message + * may return true even if the inner message has missing required fields. + * This is necessary because otherwise the inner message would have to be + * parsed in order to perform the check, defeating the purpose of lazy + * parsing. An implementation which chooses not to check required fields + * must be consistent about it. That is, for any particular sub-message, the + * implementation must either *always* check its required fields, or *never* + * check its required fields, regardless of whether or not the message has + * been parsed. + */ + lazy?: + | boolean + | undefined; + /** + * Is this field deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for accessors, or it will be completely ignored; in the very least, this + * is a formalization for deprecating fields. + */ + deprecated?: + | boolean + | undefined; + /** For Google-internal migration only. Do not use. */ + weak?: + | boolean + | undefined; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} + +export enum FieldOptions_CType { + /** STRING - Default mode. */ + STRING = 0, + CORD = 1, + STRING_PIECE = 2, + UNRECOGNIZED = -1, +} + +export enum FieldOptions_JSType { + /** JS_NORMAL - Use the default type. */ + JS_NORMAL = 0, + /** JS_STRING - Use JavaScript strings. */ + JS_STRING = 1, + /** JS_NUMBER - Use JavaScript numbers. */ + JS_NUMBER = 2, + UNRECOGNIZED = -1, +} + +export interface OneofOptions { + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} + +export interface EnumOptions { + /** + * Set this option to true to allow mapping different tag names to the same + * value. + */ + allowAlias?: + | boolean + | undefined; + /** + * Is this enum deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for the enum, or it will be completely ignored; in the very least, this + * is a formalization for deprecating enums. + */ + deprecated?: + | boolean + | undefined; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} + +export interface EnumValueOptions { + /** + * Is this enum value deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for the enum value, or it will be completely ignored; in the very least, + * this is a formalization for deprecating enum values. + */ + deprecated?: + | boolean + | undefined; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} + +export interface ServiceOptions { + /** + * Is this service deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for the service, or it will be completely ignored; in the very least, + * this is a formalization for deprecating services. + */ + deprecated?: + | boolean + | undefined; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} + +export interface MethodOptions { + /** + * Is this method deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for the method, or it will be completely ignored; in the very least, + * this is a formalization for deprecating methods. + */ + deprecated?: boolean | undefined; + idempotencyLevel?: + | MethodOptions_IdempotencyLevel + | undefined; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} + +/** + * Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + * or neither? HTTP based RPC implementation may choose GET verb for safe + * methods, and PUT verb for idempotent methods instead of the default POST. + */ +export enum MethodOptions_IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0, + /** NO_SIDE_EFFECTS - implies idempotent */ + NO_SIDE_EFFECTS = 1, + /** IDEMPOTENT - idempotent, but may have side effects */ + IDEMPOTENT = 2, + UNRECOGNIZED = -1, +} + +/** + * A message representing a option the parser does not recognize. This only + * appears in options protos created by the compiler::Parser class. + * DescriptorPool resolves these when building Descriptor objects. Therefore, + * options protos in descriptor objects (e.g. returned by Descriptor::options(), + * or produced by Descriptor::CopyTo()) will never have UninterpretedOptions + * in them. + */ +export interface UninterpretedOption { + name: UninterpretedOption_NamePart[]; + /** + * The value of the uninterpreted option, in whatever type the tokenizer + * identified it as during parsing. Exactly one of these should be set. + */ + identifierValue?: string | undefined; + positiveIntValue?: number | undefined; + negativeIntValue?: number | undefined; + doubleValue?: number | undefined; + stringValue?: Uint8Array | undefined; + aggregateValue?: string | undefined; +} + +/** + * The name of the uninterpreted option. Each string represents a segment in + * a dot-separated name. is_extension is true iff a segment represents an + * extension (denoted with parentheses in options specs in .proto files). + * E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents + * "foo.(bar.baz).qux". + */ +export interface UninterpretedOption_NamePart { + namePart: string; + isExtension: boolean; +} + +/** + * Encapsulates information about the original source file from which a + * FileDescriptorProto was generated. + */ +export interface SourceCodeInfo { + /** + * A Location identifies a piece of source code in a .proto file which + * corresponds to a particular definition. This information is intended + * to be useful to IDEs, code indexers, documentation generators, and similar + * tools. + * + * For example, say we have a file like: + * message Foo { + * optional string foo = 1; + * } + * Let's look at just the field definition: + * optional string foo = 1; + * ^ ^^ ^^ ^ ^^^ + * a bc de f ghi + * We have the following locations: + * span path represents + * [a,i) [ 4, 0, 2, 0 ] The whole field definition. + * [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + * [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + * [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + * [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + * + * Notes: + * - A location may refer to a repeated field itself (i.e. not to any + * particular index within it). This is used whenever a set of elements are + * logically enclosed in a single code segment. For example, an entire + * extend block (possibly containing multiple extension definitions) will + * have an outer location whose path refers to the "extensions" repeated + * field without an index. + * - Multiple locations may have the same path. This happens when a single + * logical declaration is spread out across multiple places. The most + * obvious example is the "extend" block again -- there may be multiple + * extend blocks in the same scope, each of which will have the same path. + * - A location's span is not always a subset of its parent's span. For + * example, the "extendee" of an extension declaration appears at the + * beginning of the "extend" block and is shared by all extensions within + * the block. + * - Just because a location's span is a subset of some other location's span + * does not mean that it is a descendent. For example, a "group" defines + * both a type and a field in a single declaration. Thus, the locations + * corresponding to the type and field and their components will overlap. + * - Code which tries to interpret locations should probably be designed to + * ignore those that it doesn't understand, as more types of locations could + * be recorded in the future. + */ + location: SourceCodeInfo_Location[]; +} + +export interface SourceCodeInfo_Location { + /** + * Identifies which part of the FileDescriptorProto was defined at this + * location. + * + * Each element is a field number or an index. They form a path from + * the root FileDescriptorProto to the place where the definition. For + * example, this path: + * [ 4, 3, 2, 7, 1 ] + * refers to: + * file.message_type(3) // 4, 3 + * .field(7) // 2, 7 + * .name() // 1 + * This is because FileDescriptorProto.message_type has field number 4: + * repeated DescriptorProto message_type = 4; + * and DescriptorProto.field has field number 2: + * repeated FieldDescriptorProto field = 2; + * and FieldDescriptorProto.name has field number 1: + * optional string name = 1; + * + * Thus, the above path gives the location of a field name. If we removed + * the last element: + * [ 4, 3, 2, 7 ] + * this path refers to the whole field declaration (from the beginning + * of the label to the terminating semicolon). + */ + path: number[]; + /** + * Always has exactly three or four elements: start line, start column, + * end line (optional, otherwise assumed same as start line), end column. + * These are packed into a single field for efficiency. Note that line + * and column numbers are zero-based -- typically you will want to add + * 1 to each before displaying to a user. + */ + span: number[]; + /** + * If this SourceCodeInfo represents a complete declaration, these are any + * comments appearing before and after the declaration which appear to be + * attached to the declaration. + * + * A series of line comments appearing on consecutive lines, with no other + * tokens appearing on those lines, will be treated as a single comment. + * + * leading_detached_comments will keep paragraphs of comments that appear + * before (but not connected to) the current element. Each paragraph, + * separated by empty lines, will be one comment element in the repeated + * field. + * + * Only the comment content is provided; comment markers (e.g. //) are + * stripped out. For block comments, leading whitespace and an asterisk + * will be stripped from the beginning of each line other than the first. + * Newlines are included in the output. + * + * Examples: + * + * optional int32 foo = 1; // Comment attached to foo. + * // Comment attached to bar. + * optional int32 bar = 2; + * + * optional string baz = 3; + * // Comment attached to baz. + * // Another line attached to baz. + * + * // Comment attached to qux. + * // + * // Another line attached to qux. + * optional double qux = 4; + * + * // Detached comment for corge. This is not leading or trailing comments + * // to qux or corge because there are blank lines separating it from + * // both. + * + * // Detached comment for corge paragraph 2. + * + * optional string corge = 5; + * /* Block comment attached + * * to corge. Leading asterisks + * * will be removed. * / + * /* Block comment attached to + * * grault. * / + * optional int32 grault = 6; + * + * // ignored detached comments. + */ + leadingComments?: string | undefined; + trailingComments?: string | undefined; + leadingDetachedComments: string[]; +} + +/** + * Describes the relationship between generated code and its original source + * file. A GeneratedCodeInfo message is associated with only one generated + * source file, but may contain references to different source .proto files. + */ +export interface GeneratedCodeInfo { + /** + * An Annotation connects some span of text in generated code to an element + * of its generating .proto file. + */ + annotation: GeneratedCodeInfo_Annotation[]; +} + +export interface GeneratedCodeInfo_Annotation { + /** + * Identifies the element in the original source .proto file. This field + * is formatted the same as SourceCodeInfo.Location.path. + */ + path: number[]; + /** Identifies the filesystem path to the original source .proto. */ + sourceFile?: + | string + | undefined; + /** + * Identifies the starting offset in bytes in the generated code + * that relates to the identified object. + */ + begin?: + | number + | undefined; + /** + * Identifies the ending offset in bytes in the generated code that + * relates to the identified offset. The end offset should be one past + * the last relevant byte (so the length of the text = end - begin). + */ + end?: number | undefined; +} diff --git a/integration/http/http-test.ts b/integration/http/http-test.ts new file mode 100644 index 000000000..2935f76e2 --- /dev/null +++ b/integration/http/http-test.ts @@ -0,0 +1,40 @@ +/** + * @jest-environment node + */ +import { Messaging, GetMessageRequest, GetMessageResponse } from "./simple"; + +describe("http-test", () => { + it("compiles", () => { + expect(Messaging.getMessage).toStrictEqual({ + path: "/v1/messages/{message_id}", + method: "get", + request: undefined, + response: undefined, + }); + expect(Messaging.createMessage).toStrictEqual({ + path: "/v1/messages/{message_id}", + method: "post", + body: "message", + request: undefined, + response: undefined, + }); + expect(Messaging.updateMessage).toStrictEqual({ + path: "/v1/messages/{message_id}", + method: "post", + body: "*", + request: undefined, + response: undefined, + }); + + // Test that the request and response types are correctly typed + const copy = { ...Messaging.getMessage }; + const request: GetMessageRequest = { + messageId: "1", + }; + const response: GetMessageResponse = { + message: "hello", + }; + copy.request = request; + copy.response = response; + }); +}); diff --git a/integration/http/parameters.txt b/integration/http/parameters.txt new file mode 100644 index 000000000..ed86a6878 --- /dev/null +++ b/integration/http/parameters.txt @@ -0,0 +1 @@ +http=true \ No newline at end of file diff --git a/integration/http/simple.proto b/integration/http/simple.proto new file mode 100644 index 000000000..2b6a25efd --- /dev/null +++ b/integration/http/simple.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; + +import "google/api/annotations.proto"; + +service Messaging { + rpc GetMessage(GetMessageRequest) returns (GetMessageResponse) { + option (google.api.http) = { + get:"/v1/messages/{message_id}" + }; + } + rpc CreateMessage(CreateMessageRequest) returns (CreateMessageResponse) { + option (google.api.http) = { + post:"/v1/messages/{message_id}" + body: "message" + }; + } + rpc UpdateMessage(CreateMessageRequest) returns (CreateMessageResponse) { + option (google.api.http) = { + post:"/v1/messages/{message_id}" + body: "*" + }; + } +} + +message GetMessageRequest { + string message_id = 1; +} +message GetMessageResponse { + string message = 1; +} + +message CreateMessageRequest { + string message_id = 1; + string message = 2; // mapped to the body +} + +message CreateMessageResponse {} \ No newline at end of file diff --git a/integration/http/simple.ts b/integration/http/simple.ts new file mode 100644 index 000000000..e63e9295e --- /dev/null +++ b/integration/http/simple.ts @@ -0,0 +1,48 @@ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// source: simple.proto + +/* eslint-disable */ + +export const protobufPackage = ""; + +export interface GetMessageRequest { + messageId: string; +} + +export interface GetMessageResponse { + message: string; +} + +export interface CreateMessageRequest { + messageId: string; + /** mapped to the body */ + message: string; +} + +export interface CreateMessageResponse { +} + +export const Messaging = { + getMessage: { + path: "/v1/messages/{message_id}", + method: "get", + request: undefined as GetMessageRequest | undefined, + response: undefined as GetMessageResponse | undefined, + }, + + createMessage: { + path: "/v1/messages/{message_id}", + method: "post", + body: "message", + request: undefined as CreateMessageRequest | undefined, + response: undefined as CreateMessageResponse | undefined, + }, + + updateMessage: { + path: "/v1/messages/{message_id}", + method: "post", + body: "*", + request: undefined as CreateMessageRequest | undefined, + response: undefined as CreateMessageResponse | undefined, + }, +}; diff --git a/package.json b/package.json index 37b6c5cc6..91bda43ce 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,7 @@ "@semantic-release/npm": "^10.0.4", "@semantic-release/release-notes-generator": "^11.0.4", "@tsconfig/strictest": "^2.0.1", + "@types/google-protobuf": "^3.15.12", "@types/jest": "^29.5.3", "@types/node": "^16.18.38", "@types/object-hash": "^3.0.2", @@ -66,6 +67,7 @@ }, "dependencies": { "case-anything": "^2.1.13", + "google-protobuf": "^3.21.2", "protobufjs": "^7.2.4", "ts-poet": "^6.7.0", "ts-proto-descriptors": "1.16.0" diff --git a/src/context.ts b/src/context.ts index f0045a70c..36a22d743 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,13 +1,15 @@ import { TypeMap } from "./types"; import { Utils } from "./main"; import { Options } from "./options"; -import { FileDescriptorProto } from "ts-proto-descriptors"; +import { FileDescriptorProto as TsProtoFileDescriptorProto } from "ts-proto-descriptors"; +import { FileDescriptorProto as GoogleFileDescriptorProto } from "google-protobuf/google/protobuf/descriptor_pb"; /** Provides a parameter object for passing around the various context/config data. */ export interface BaseContext { options: Options; typeMap: TypeMap; utils: Utils; + fileDescriptorProtoMap?: Record; } export interface Context extends BaseContext { @@ -18,6 +20,6 @@ export interface FileContext { isProto3Syntax: boolean; } -export function createFileContext(file: FileDescriptorProto) { +export function createFileContext(file: TsProtoFileDescriptorProto) { return { isProto3Syntax: file.syntax === "proto3" }; } diff --git a/src/generate-http.ts b/src/generate-http.ts new file mode 100644 index 000000000..49c885feb --- /dev/null +++ b/src/generate-http.ts @@ -0,0 +1,83 @@ +import { FileDescriptorProto, ServiceDescriptorProto } from "ts-proto-descriptors"; +import { Code, code, joinCode } from "ts-poet"; +import { requestType, responseType } from "./types"; +import SourceInfo from "./sourceInfo"; +import { assertInstanceOf, FormattedMethodDescriptor } from "./utils"; +import { Context } from "./context"; +require("../vendor/google/api/annotations_pb"); + +interface HTTPRule { + get: string; + put: string; + post: string; + pb_delete: string; + patch: string; + body: "*" | string; +} + +function mapHTTPOptions(http: HTTPRule) { + for (const method of ["post", "put", "get", "pb_delete", "patch"] as const) { + if (http[method]) { + return { + method: method, + path: http[method], + body: http.body, + }; + } + } + + throw new Error("No HTTP method found"); +} + +export function generateHttpService( + ctx: Context, + fileDesc: FileDescriptorProto, + _sourceInfo: SourceInfo, + serviceDesc: ServiceDescriptorProto, +): Code { + const chunks: Code[] = []; + + const methodList = ctx.fileDescriptorProtoMap![fileDesc.name].toObject().serviceList.find((service) => { + return service.name === serviceDesc.name; + })?.methodList; + + const httpOptions: Record> = {}; + let hasHttpOptions = false; + + if (methodList) { + serviceDesc.method.forEach((methodDesc, i) => { + // @ts-expect-error + const http = methodList[i]?.options?.http as HTTPRule | undefined; + + if (http) { + hasHttpOptions = true; + assertInstanceOf(methodDesc, FormattedMethodDescriptor); + httpOptions[methodDesc.formattedName] = mapHTTPOptions(http); + } + }); + } + + if (hasHttpOptions) { + chunks.push(code` + export const ${serviceDesc.name} = { + `); + + serviceDesc.method.forEach((methodDesc) => { + assertInstanceOf(methodDesc, FormattedMethodDescriptor); + const httpMethod = httpOptions[methodDesc.formattedName]; + chunks.push(code` + ${methodDesc.formattedName}: { + path: "${httpMethod.path}", + method: "${httpMethod.method}",${httpMethod.body ? `\nbody: "${httpMethod.body}",` : ""} + request: undefined as ${requestType(ctx, methodDesc)} | undefined, + response: undefined as ${responseType(ctx, methodDesc)} | undefined, + }, + `); + }); + + chunks.push(code`}`); + return joinCode(chunks, { on: "\n\n" }); + } + + return code``; +} diff --git a/src/main.ts b/src/main.ts index a2de98b32..8387173c0 100644 --- a/src/main.ts +++ b/src/main.ts @@ -108,6 +108,7 @@ import { withOrMaybeCheckIsNull, } from "./utils"; import { visit, visitServices } from "./visit"; +import { generateHttpService } from "./generate-http"; export function generateFile(ctx: Context, fileDesc: FileDescriptorProto): [string, Code] { const { options, utils } = ctx; @@ -332,6 +333,10 @@ export function generateFile(ctx: Context, fileDesc: FileDescriptorProto): [stri chunks.push(code`export const ${serviceConstName} = "${serviceDesc.name}";`); } + if (options.http) { + chunks.push(generateHttpService(ctx, fileDesc, sInfo, serviceDesc)); + } + const uniqueServices = [...new Set(options.outputServices)].sort(); uniqueServices.forEach((outputService) => { if (outputService === ServiceOption.GRPC) { diff --git a/src/options.ts b/src/options.ts index c98ffc1bd..12575bbf5 100644 --- a/src/options.ts +++ b/src/options.ts @@ -71,6 +71,7 @@ export type Options = { returnObservable: boolean; lowerCaseServiceMethods: boolean; nestJs: boolean; + http: boolean; env: EnvOption; unrecognizedEnum: boolean; unrecognizedEnumName: string; @@ -141,6 +142,7 @@ export function defaultOptions(): Options { metadataType: undefined, addNestjsRestParameter: false, nestJs: false, + http: false, env: EnvOption.BOTH, unrecognizedEnum: true, unrecognizedEnumName: "UNRECOGNIZED", @@ -188,12 +190,23 @@ const nestJsOptions: Partial = { useDate: DateOption.TIMESTAMP, }; +const httpOptions: Partial = { + lowerCaseServiceMethods: true, + outputEncodeMethods: false, + outputJsonMethods: false, + outputPartialMethods: false, + outputClientImpl: false, + outputServices: false as any, +}; + export function optionsFromParameter(parameter: string | undefined): Options { const options = defaultOptions(); if (parameter) { const parsed = parseParameter(parameter); if (parsed.nestJs) { Object.assign(options, nestJsOptions); + } else if (parsed.http) { + Object.assign(options, httpOptions); } Object.assign(options, parsed); } diff --git a/src/plugin.ts b/src/plugin.ts index e0df00540..8c080847d 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -4,6 +4,7 @@ import { CodeGeneratorResponse_Feature, FileDescriptorProto, } from "ts-proto-descriptors"; +import { CodeGeneratorRequest as GoogleCodeGeneratorRequest } from "google-protobuf/google/protobuf/compiler/plugin_pb"; import { promisify } from "util"; import { generateIndexFiles, getVersions, protoFilesToGenerate, readToBuffer } from "./utils"; import { generateFile, makeUtils } from "./main"; @@ -24,7 +25,20 @@ async function main() { const options = optionsFromParameter(request.parameter); const typeMap = createTypeMap(request, options); const utils = makeUtils(options); - const ctx: BaseContext = { typeMap, options, utils }; + let fileDescriptorProtoMap: BaseContext["fileDescriptorProtoMap"] = undefined; + + if (options.http) { + const input = new Uint8Array(stdin.length); + input.set(stdin); + fileDescriptorProtoMap = {}; + GoogleCodeGeneratorRequest.deserializeBinary(input) + .getProtoFileList() + .forEach((descriptor) => { + fileDescriptorProtoMap![descriptor.getName()!] = descriptor; + }); + } + + const ctx: BaseContext = { typeMap, options, utils, fileDescriptorProtoMap }; let filesToGenerate: FileDescriptorProto[]; @@ -58,7 +72,7 @@ async function main() { if (options.outputTypeRegistry) { const utils = makeUtils(options); - const ctx: BaseContext = { options, typeMap, utils }; + const ctx: BaseContext = { options, typeMap, utils, fileDescriptorProtoMap }; const path = "typeRegistry.ts"; const code = generateTypeRegistry(ctx); diff --git a/tests/options-test.ts b/tests/options-test.ts index e30b4a373..7e55b6f29 100644 --- a/tests/options-test.ts +++ b/tests/options-test.ts @@ -23,6 +23,7 @@ describe("options", () => { "fileSuffix": "", "forceLong": "number", "globalThisPolyfill": false, + "http": false, "importSuffix": "", "initializeFieldsAsUndefined": false, "lowerCaseServiceMethods": true, diff --git a/vendor/google/api/annotations_pb.js b/vendor/google/api/annotations_pb.js new file mode 100644 index 000000000..53c05ed02 --- /dev/null +++ b/vendor/google/api/annotations_pb.js @@ -0,0 +1,54 @@ +// source: google/api/annotations.proto +/** + * @fileoverview + * @enhanceable + * @suppress {missingRequire} reports error on implicit type usages. + * @suppress {messageConventions} JS Compiler reports an error if a variable or + * field starts with 'MSG_' and isn't a translatable message. + * @public + */ +// GENERATED CODE -- DO NOT EDIT! +/* eslint-disable */ +// @ts-nocheck + +var jspb = require('google-protobuf'); +var goog = jspb; +var global = + (typeof globalThis !== 'undefined' && globalThis) || + (typeof window !== 'undefined' && window) || + (typeof global !== 'undefined' && global) || + (typeof self !== 'undefined' && self) || + (function () { return this; }).call(null) || + Function('return this')(); + +var google_api_http_pb = require('../../google/api/http_pb.js'); +goog.object.extend(proto, google_api_http_pb); +var google_protobuf_descriptor_pb = require('google-protobuf/google/protobuf/descriptor_pb.js'); +goog.object.extend(proto, google_protobuf_descriptor_pb); +goog.exportSymbol('proto.google.api.http', null, global); + +/** + * A tuple of {field number, class constructor} for the extension + * field named `http`. + * @type {!jspb.ExtensionFieldInfo} + */ +proto.google.api.http = new jspb.ExtensionFieldInfo( + 72295728, + {http: 0}, + google_api_http_pb.HttpRule, + /** @type {?function((boolean|undefined),!jspb.Message=): !Object} */ ( + google_api_http_pb.HttpRule.toObject), + 0); + +google_protobuf_descriptor_pb.MethodOptions.extensionsBinary[72295728] = new jspb.ExtensionFieldBinaryInfo( + proto.google.api.http, + jspb.BinaryReader.prototype.readMessage, + jspb.BinaryWriter.prototype.writeMessage, + google_api_http_pb.HttpRule.serializeBinaryToWriter, + google_api_http_pb.HttpRule.deserializeBinaryFromReader, + false); +// This registers the extension field with the extended class, so that +// toObject() will function correctly. +google_protobuf_descriptor_pb.MethodOptions.extensions[72295728] = proto.google.api.http; + +goog.object.extend(exports, proto.google.api); diff --git a/vendor/google/api/http_pb.js b/vendor/google/api/http_pb.js new file mode 100644 index 000000000..9fc6ee730 --- /dev/null +++ b/vendor/google/api/http_pb.js @@ -0,0 +1,1012 @@ +// source: google/api/http.proto +/** + * @fileoverview + * @enhanceable + * @suppress {missingRequire} reports error on implicit type usages. + * @suppress {messageConventions} JS Compiler reports an error if a variable or + * field starts with 'MSG_' and isn't a translatable message. + * @public + */ +// GENERATED CODE -- DO NOT EDIT! +/* eslint-disable */ +// @ts-nocheck + +var jspb = require('google-protobuf'); +var goog = jspb; +var global = + (typeof globalThis !== 'undefined' && globalThis) || + (typeof window !== 'undefined' && window) || + (typeof global !== 'undefined' && global) || + (typeof self !== 'undefined' && self) || + (function () { return this; }).call(null) || + Function('return this')(); + +goog.exportSymbol('proto.google.api.CustomHttpPattern', null, global); +goog.exportSymbol('proto.google.api.Http', null, global); +goog.exportSymbol('proto.google.api.HttpRule', null, global); +goog.exportSymbol('proto.google.api.HttpRule.PatternCase', null, global); +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.google.api.Http = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, proto.google.api.Http.repeatedFields_, null); +}; +goog.inherits(proto.google.api.Http, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.google.api.Http.displayName = 'proto.google.api.Http'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.google.api.HttpRule = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, proto.google.api.HttpRule.repeatedFields_, proto.google.api.HttpRule.oneofGroups_); +}; +goog.inherits(proto.google.api.HttpRule, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.google.api.HttpRule.displayName = 'proto.google.api.HttpRule'; +} +/** + * Generated by JsPbCodeGenerator. + * @param {Array=} opt_data Optional initial data array, typically from a + * server response, or constructed directly in Javascript. The array is used + * in place and becomes part of the constructed object. It is not cloned. + * If no data is provided, the constructed object will be empty, but still + * valid. + * @extends {jspb.Message} + * @constructor + */ +proto.google.api.CustomHttpPattern = function(opt_data) { + jspb.Message.initialize(this, opt_data, 0, -1, null, null); +}; +goog.inherits(proto.google.api.CustomHttpPattern, jspb.Message); +if (goog.DEBUG && !COMPILED) { + /** + * @public + * @override + */ + proto.google.api.CustomHttpPattern.displayName = 'proto.google.api.CustomHttpPattern'; +} + +/** + * List of repeated fields within this message type. + * @private {!Array} + * @const + */ +proto.google.api.Http.repeatedFields_ = [1]; + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.google.api.Http.prototype.toObject = function(opt_includeInstance) { + return proto.google.api.Http.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.google.api.Http} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.google.api.Http.toObject = function(includeInstance, msg) { + var f, obj = { + rulesList: jspb.Message.toObjectList(msg.getRulesList(), + proto.google.api.HttpRule.toObject, includeInstance), + fullyDecodeReservedExpansion: jspb.Message.getBooleanFieldWithDefault(msg, 2, false) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.google.api.Http} + */ +proto.google.api.Http.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.google.api.Http; + return proto.google.api.Http.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.google.api.Http} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.google.api.Http} + */ +proto.google.api.Http.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = new proto.google.api.HttpRule; + reader.readMessage(value,proto.google.api.HttpRule.deserializeBinaryFromReader); + msg.addRules(value); + break; + case 2: + var value = /** @type {boolean} */ (reader.readBool()); + msg.setFullyDecodeReservedExpansion(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.google.api.Http.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.google.api.Http.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.google.api.Http} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.google.api.Http.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getRulesList(); + if (f.length > 0) { + writer.writeRepeatedMessage( + 1, + f, + proto.google.api.HttpRule.serializeBinaryToWriter + ); + } + f = message.getFullyDecodeReservedExpansion(); + if (f) { + writer.writeBool( + 2, + f + ); + } +}; + + +/** + * repeated HttpRule rules = 1; + * @return {!Array} + */ +proto.google.api.Http.prototype.getRulesList = function() { + return /** @type{!Array} */ ( + jspb.Message.getRepeatedWrapperField(this, proto.google.api.HttpRule, 1)); +}; + + +/** + * @param {!Array} value + * @return {!proto.google.api.Http} returns this +*/ +proto.google.api.Http.prototype.setRulesList = function(value) { + return jspb.Message.setRepeatedWrapperField(this, 1, value); +}; + + +/** + * @param {!proto.google.api.HttpRule=} opt_value + * @param {number=} opt_index + * @return {!proto.google.api.HttpRule} + */ +proto.google.api.Http.prototype.addRules = function(opt_value, opt_index) { + return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.google.api.HttpRule, opt_index); +}; + + +/** + * Clears the list making it empty but non-null. + * @return {!proto.google.api.Http} returns this + */ +proto.google.api.Http.prototype.clearRulesList = function() { + return this.setRulesList([]); +}; + + +/** + * optional bool fully_decode_reserved_expansion = 2; + * @return {boolean} + */ +proto.google.api.Http.prototype.getFullyDecodeReservedExpansion = function() { + return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false)); +}; + + +/** + * @param {boolean} value + * @return {!proto.google.api.Http} returns this + */ +proto.google.api.Http.prototype.setFullyDecodeReservedExpansion = function(value) { + return jspb.Message.setProto3BooleanField(this, 2, value); +}; + + + +/** + * List of repeated fields within this message type. + * @private {!Array} + * @const + */ +proto.google.api.HttpRule.repeatedFields_ = [11]; + +/** + * Oneof group definitions for this message. Each group defines the field + * numbers belonging to that group. When of these fields' value is set, all + * other fields in the group are cleared. During deserialization, if multiple + * fields are encountered for a group, only the last value seen will be kept. + * @private {!Array>} + * @const + */ +proto.google.api.HttpRule.oneofGroups_ = [[2,3,4,5,6,8]]; + +/** + * @enum {number} + */ +proto.google.api.HttpRule.PatternCase = { + PATTERN_NOT_SET: 0, + GET: 2, + PUT: 3, + POST: 4, + DELETE: 5, + PATCH: 6, + CUSTOM: 8 +}; + +/** + * @return {proto.google.api.HttpRule.PatternCase} + */ +proto.google.api.HttpRule.prototype.getPatternCase = function() { + return /** @type {proto.google.api.HttpRule.PatternCase} */(jspb.Message.computeOneofCase(this, proto.google.api.HttpRule.oneofGroups_[0])); +}; + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.google.api.HttpRule.prototype.toObject = function(opt_includeInstance) { + return proto.google.api.HttpRule.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.google.api.HttpRule} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.google.api.HttpRule.toObject = function(includeInstance, msg) { + var f, obj = { + selector: jspb.Message.getFieldWithDefault(msg, 1, ""), + get: jspb.Message.getFieldWithDefault(msg, 2, ""), + put: jspb.Message.getFieldWithDefault(msg, 3, ""), + post: jspb.Message.getFieldWithDefault(msg, 4, ""), + pb_delete: jspb.Message.getFieldWithDefault(msg, 5, ""), + patch: jspb.Message.getFieldWithDefault(msg, 6, ""), + custom: (f = msg.getCustom()) && proto.google.api.CustomHttpPattern.toObject(includeInstance, f), + body: jspb.Message.getFieldWithDefault(msg, 7, ""), + responseBody: jspb.Message.getFieldWithDefault(msg, 12, ""), + additionalBindingsList: jspb.Message.toObjectList(msg.getAdditionalBindingsList(), + proto.google.api.HttpRule.toObject, includeInstance) + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.google.api.HttpRule} + */ +proto.google.api.HttpRule.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.google.api.HttpRule; + return proto.google.api.HttpRule.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.google.api.HttpRule} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.google.api.HttpRule} + */ +proto.google.api.HttpRule.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setSelector(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setGet(value); + break; + case 3: + var value = /** @type {string} */ (reader.readString()); + msg.setPut(value); + break; + case 4: + var value = /** @type {string} */ (reader.readString()); + msg.setPost(value); + break; + case 5: + var value = /** @type {string} */ (reader.readString()); + msg.setDelete(value); + break; + case 6: + var value = /** @type {string} */ (reader.readString()); + msg.setPatch(value); + break; + case 8: + var value = new proto.google.api.CustomHttpPattern; + reader.readMessage(value,proto.google.api.CustomHttpPattern.deserializeBinaryFromReader); + msg.setCustom(value); + break; + case 7: + var value = /** @type {string} */ (reader.readString()); + msg.setBody(value); + break; + case 12: + var value = /** @type {string} */ (reader.readString()); + msg.setResponseBody(value); + break; + case 11: + var value = new proto.google.api.HttpRule; + reader.readMessage(value,proto.google.api.HttpRule.deserializeBinaryFromReader); + msg.addAdditionalBindings(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.google.api.HttpRule.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.google.api.HttpRule.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.google.api.HttpRule} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.google.api.HttpRule.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getSelector(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = /** @type {string} */ (jspb.Message.getField(message, 2)); + if (f != null) { + writer.writeString( + 2, + f + ); + } + f = /** @type {string} */ (jspb.Message.getField(message, 3)); + if (f != null) { + writer.writeString( + 3, + f + ); + } + f = /** @type {string} */ (jspb.Message.getField(message, 4)); + if (f != null) { + writer.writeString( + 4, + f + ); + } + f = /** @type {string} */ (jspb.Message.getField(message, 5)); + if (f != null) { + writer.writeString( + 5, + f + ); + } + f = /** @type {string} */ (jspb.Message.getField(message, 6)); + if (f != null) { + writer.writeString( + 6, + f + ); + } + f = message.getCustom(); + if (f != null) { + writer.writeMessage( + 8, + f, + proto.google.api.CustomHttpPattern.serializeBinaryToWriter + ); + } + f = message.getBody(); + if (f.length > 0) { + writer.writeString( + 7, + f + ); + } + f = message.getResponseBody(); + if (f.length > 0) { + writer.writeString( + 12, + f + ); + } + f = message.getAdditionalBindingsList(); + if (f.length > 0) { + writer.writeRepeatedMessage( + 11, + f, + proto.google.api.HttpRule.serializeBinaryToWriter + ); + } +}; + + +/** + * optional string selector = 1; + * @return {string} + */ +proto.google.api.HttpRule.prototype.getSelector = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.setSelector = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string get = 2; + * @return {string} + */ +proto.google.api.HttpRule.prototype.getGet = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.setGet = function(value) { + return jspb.Message.setOneofField(this, 2, proto.google.api.HttpRule.oneofGroups_[0], value); +}; + + +/** + * Clears the field making it undefined. + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.clearGet = function() { + return jspb.Message.setOneofField(this, 2, proto.google.api.HttpRule.oneofGroups_[0], undefined); +}; + + +/** + * Returns whether this field is set. + * @return {boolean} + */ +proto.google.api.HttpRule.prototype.hasGet = function() { + return jspb.Message.getField(this, 2) != null; +}; + + +/** + * optional string put = 3; + * @return {string} + */ +proto.google.api.HttpRule.prototype.getPut = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); +}; + + +/** + * @param {string} value + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.setPut = function(value) { + return jspb.Message.setOneofField(this, 3, proto.google.api.HttpRule.oneofGroups_[0], value); +}; + + +/** + * Clears the field making it undefined. + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.clearPut = function() { + return jspb.Message.setOneofField(this, 3, proto.google.api.HttpRule.oneofGroups_[0], undefined); +}; + + +/** + * Returns whether this field is set. + * @return {boolean} + */ +proto.google.api.HttpRule.prototype.hasPut = function() { + return jspb.Message.getField(this, 3) != null; +}; + + +/** + * optional string post = 4; + * @return {string} + */ +proto.google.api.HttpRule.prototype.getPost = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); +}; + + +/** + * @param {string} value + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.setPost = function(value) { + return jspb.Message.setOneofField(this, 4, proto.google.api.HttpRule.oneofGroups_[0], value); +}; + + +/** + * Clears the field making it undefined. + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.clearPost = function() { + return jspb.Message.setOneofField(this, 4, proto.google.api.HttpRule.oneofGroups_[0], undefined); +}; + + +/** + * Returns whether this field is set. + * @return {boolean} + */ +proto.google.api.HttpRule.prototype.hasPost = function() { + return jspb.Message.getField(this, 4) != null; +}; + + +/** + * optional string delete = 5; + * @return {string} + */ +proto.google.api.HttpRule.prototype.getDelete = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); +}; + + +/** + * @param {string} value + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.setDelete = function(value) { + return jspb.Message.setOneofField(this, 5, proto.google.api.HttpRule.oneofGroups_[0], value); +}; + + +/** + * Clears the field making it undefined. + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.clearDelete = function() { + return jspb.Message.setOneofField(this, 5, proto.google.api.HttpRule.oneofGroups_[0], undefined); +}; + + +/** + * Returns whether this field is set. + * @return {boolean} + */ +proto.google.api.HttpRule.prototype.hasDelete = function() { + return jspb.Message.getField(this, 5) != null; +}; + + +/** + * optional string patch = 6; + * @return {string} + */ +proto.google.api.HttpRule.prototype.getPatch = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 6, "")); +}; + + +/** + * @param {string} value + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.setPatch = function(value) { + return jspb.Message.setOneofField(this, 6, proto.google.api.HttpRule.oneofGroups_[0], value); +}; + + +/** + * Clears the field making it undefined. + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.clearPatch = function() { + return jspb.Message.setOneofField(this, 6, proto.google.api.HttpRule.oneofGroups_[0], undefined); +}; + + +/** + * Returns whether this field is set. + * @return {boolean} + */ +proto.google.api.HttpRule.prototype.hasPatch = function() { + return jspb.Message.getField(this, 6) != null; +}; + + +/** + * optional CustomHttpPattern custom = 8; + * @return {?proto.google.api.CustomHttpPattern} + */ +proto.google.api.HttpRule.prototype.getCustom = function() { + return /** @type{?proto.google.api.CustomHttpPattern} */ ( + jspb.Message.getWrapperField(this, proto.google.api.CustomHttpPattern, 8)); +}; + + +/** + * @param {?proto.google.api.CustomHttpPattern|undefined} value + * @return {!proto.google.api.HttpRule} returns this +*/ +proto.google.api.HttpRule.prototype.setCustom = function(value) { + return jspb.Message.setOneofWrapperField(this, 8, proto.google.api.HttpRule.oneofGroups_[0], value); +}; + + +/** + * Clears the message field making it undefined. + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.clearCustom = function() { + return this.setCustom(undefined); +}; + + +/** + * Returns whether this field is set. + * @return {boolean} + */ +proto.google.api.HttpRule.prototype.hasCustom = function() { + return jspb.Message.getField(this, 8) != null; +}; + + +/** + * optional string body = 7; + * @return {string} + */ +proto.google.api.HttpRule.prototype.getBody = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 7, "")); +}; + + +/** + * @param {string} value + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.setBody = function(value) { + return jspb.Message.setProto3StringField(this, 7, value); +}; + + +/** + * optional string response_body = 12; + * @return {string} + */ +proto.google.api.HttpRule.prototype.getResponseBody = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 12, "")); +}; + + +/** + * @param {string} value + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.setResponseBody = function(value) { + return jspb.Message.setProto3StringField(this, 12, value); +}; + + +/** + * repeated HttpRule additional_bindings = 11; + * @return {!Array} + */ +proto.google.api.HttpRule.prototype.getAdditionalBindingsList = function() { + return /** @type{!Array} */ ( + jspb.Message.getRepeatedWrapperField(this, proto.google.api.HttpRule, 11)); +}; + + +/** + * @param {!Array} value + * @return {!proto.google.api.HttpRule} returns this +*/ +proto.google.api.HttpRule.prototype.setAdditionalBindingsList = function(value) { + return jspb.Message.setRepeatedWrapperField(this, 11, value); +}; + + +/** + * @param {!proto.google.api.HttpRule=} opt_value + * @param {number=} opt_index + * @return {!proto.google.api.HttpRule} + */ +proto.google.api.HttpRule.prototype.addAdditionalBindings = function(opt_value, opt_index) { + return jspb.Message.addToRepeatedWrapperField(this, 11, opt_value, proto.google.api.HttpRule, opt_index); +}; + + +/** + * Clears the list making it empty but non-null. + * @return {!proto.google.api.HttpRule} returns this + */ +proto.google.api.HttpRule.prototype.clearAdditionalBindingsList = function() { + return this.setAdditionalBindingsList([]); +}; + + + + + +if (jspb.Message.GENERATE_TO_OBJECT) { +/** + * Creates an object representation of this proto. + * Field names that are reserved in JavaScript and will be renamed to pb_name. + * Optional fields that are not set will be set to undefined. + * To access a reserved field use, foo.pb_, eg, foo.pb_default. + * For the list of reserved names please see: + * net/proto2/compiler/js/internal/generator.cc#kKeyword. + * @param {boolean=} opt_includeInstance Deprecated. whether to include the + * JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @return {!Object} + */ +proto.google.api.CustomHttpPattern.prototype.toObject = function(opt_includeInstance) { + return proto.google.api.CustomHttpPattern.toObject(opt_includeInstance, this); +}; + + +/** + * Static version of the {@see toObject} method. + * @param {boolean|undefined} includeInstance Deprecated. Whether to include + * the JSPB instance for transitional soy proto support: + * http://goto/soy-param-migration + * @param {!proto.google.api.CustomHttpPattern} msg The msg instance to transform. + * @return {!Object} + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.google.api.CustomHttpPattern.toObject = function(includeInstance, msg) { + var f, obj = { + kind: jspb.Message.getFieldWithDefault(msg, 1, ""), + path: jspb.Message.getFieldWithDefault(msg, 2, "") + }; + + if (includeInstance) { + obj.$jspbMessageInstance = msg; + } + return obj; +}; +} + + +/** + * Deserializes binary data (in protobuf wire format). + * @param {jspb.ByteSource} bytes The bytes to deserialize. + * @return {!proto.google.api.CustomHttpPattern} + */ +proto.google.api.CustomHttpPattern.deserializeBinary = function(bytes) { + var reader = new jspb.BinaryReader(bytes); + var msg = new proto.google.api.CustomHttpPattern; + return proto.google.api.CustomHttpPattern.deserializeBinaryFromReader(msg, reader); +}; + + +/** + * Deserializes binary data (in protobuf wire format) from the + * given reader into the given message object. + * @param {!proto.google.api.CustomHttpPattern} msg The message object to deserialize into. + * @param {!jspb.BinaryReader} reader The BinaryReader to use. + * @return {!proto.google.api.CustomHttpPattern} + */ +proto.google.api.CustomHttpPattern.deserializeBinaryFromReader = function(msg, reader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + var field = reader.getFieldNumber(); + switch (field) { + case 1: + var value = /** @type {string} */ (reader.readString()); + msg.setKind(value); + break; + case 2: + var value = /** @type {string} */ (reader.readString()); + msg.setPath(value); + break; + default: + reader.skipField(); + break; + } + } + return msg; +}; + + +/** + * Serializes the message to binary data (in protobuf wire format). + * @return {!Uint8Array} + */ +proto.google.api.CustomHttpPattern.prototype.serializeBinary = function() { + var writer = new jspb.BinaryWriter(); + proto.google.api.CustomHttpPattern.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); +}; + + +/** + * Serializes the given message to binary data (in protobuf wire + * format), writing to the given BinaryWriter. + * @param {!proto.google.api.CustomHttpPattern} message + * @param {!jspb.BinaryWriter} writer + * @suppress {unusedLocalVariables} f is only used for nested messages + */ +proto.google.api.CustomHttpPattern.serializeBinaryToWriter = function(message, writer) { + var f = undefined; + f = message.getKind(); + if (f.length > 0) { + writer.writeString( + 1, + f + ); + } + f = message.getPath(); + if (f.length > 0) { + writer.writeString( + 2, + f + ); + } +}; + + +/** + * optional string kind = 1; + * @return {string} + */ +proto.google.api.CustomHttpPattern.prototype.getKind = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); +}; + + +/** + * @param {string} value + * @return {!proto.google.api.CustomHttpPattern} returns this + */ +proto.google.api.CustomHttpPattern.prototype.setKind = function(value) { + return jspb.Message.setProto3StringField(this, 1, value); +}; + + +/** + * optional string path = 2; + * @return {string} + */ +proto.google.api.CustomHttpPattern.prototype.getPath = function() { + return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); +}; + + +/** + * @param {string} value + * @return {!proto.google.api.CustomHttpPattern} returns this + */ +proto.google.api.CustomHttpPattern.prototype.setPath = function(value) { + return jspb.Message.setProto3StringField(this, 2, value); +}; + + +goog.object.extend(exports, proto.google.api); diff --git a/yarn.lock b/yarn.lock index 99dff097e..568252973 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1796,6 +1796,13 @@ __metadata: languageName: node linkType: hard +"@types/google-protobuf@npm:^3.15.12": + version: 3.15.12 + resolution: "@types/google-protobuf@npm:3.15.12" + checksum: c64efd268170eac0865a42c9616b05100e5ac07e7fa1ed87c827c9d2a58eb02cb2d01cb3248c7ddd563468ecb079295b81ab966e399ba08858f525896631e961 + languageName: node + linkType: hard + "@types/graceful-fs@npm:^4.1.3": version: 4.1.5 resolution: "@types/graceful-fs@npm:4.1.5" @@ -3822,6 +3829,13 @@ __metadata: languageName: node linkType: hard +"google-protobuf@npm:^3.21.2": + version: 3.21.2 + resolution: "google-protobuf@npm:3.21.2" + checksum: 3caa2e1e2654714cc1a201ac5e5faabcaa48f5fba3d8ff9b64ca66fe19e4e0506b94053f32eddc77bf3a7a47ac1660315c6744185c1e2bb27654fd76fe91b988 + languageName: node + linkType: hard + "graceful-fs@npm:4.2.10": version: 4.2.10 resolution: "graceful-fs@npm:4.2.10" @@ -7865,12 +7879,14 @@ __metadata: "@semantic-release/npm": ^10.0.4 "@semantic-release/release-notes-generator": ^11.0.4 "@tsconfig/strictest": ^2.0.1 + "@types/google-protobuf": ^3.15.12 "@types/jest": ^29.5.3 "@types/node": ^16.18.38 "@types/object-hash": ^3.0.2 case-anything: ^2.1.13 chokidar: ^3.5.3 dataloader: ^2.2.2 + google-protobuf: ^3.21.2 jest: ^29.6.1 jest-ts-webcompat-resolver: ^1.0.0 mongodb: ^5.7.0 From 709b03e7ed8d32739c29ddd70830a9f65317f990 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Fri, 12 Jul 2024 15:58:19 +0900 Subject: [PATCH 02/20] Format readme --- HTTP.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/HTTP.markdown b/HTTP.markdown index f42cc063d..6b30f5ba2 100644 --- a/HTTP.markdown +++ b/HTTP.markdown @@ -10,19 +10,19 @@ import "google/api/annotations.proto"; service Messaging { rpc GetMessage(GetMessageRequest) returns (GetMessageResponse) { option (google.api.http) = { - get:"/v1/messages/{message_id}" + get:"/v1/messages/{message_id}" }; } rpc CreateMessage(CreateMessageRequest) returns (CreateMessageResponse) { option (google.api.http) = { - post:"/v1/messages/{message_id}" - body: "message" + post:"/v1/messages/{message_id}" + body: "message" }; } rpc UpdateMessage(CreateMessageRequest) returns (CreateMessageResponse) { option (google.api.http) = { - post:"/v1/messages/{message_id}" - body: "*" + post:"/v1/messages/{message_id}" + body: "*" }; } } From b0778af4ce0c9364a68a5ec2471dc72b8ccf8f99 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Fri, 12 Jul 2024 16:20:51 +0900 Subject: [PATCH 03/20] Update vendor generator --- Makefile | 9 +++++++-- README.markdown | 16 ++++++++++++---- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index e954ce8cd..60bbcc76f 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,13 @@ .PHONY: build-vendor build-vendor: @rm -rf third_party - @mkdir third_party - @cd third_party && git clone git@github.com:googleapis/googleapis.git --depth=1 && cd .. + @mkdir -p third_party/googleapis + @cd third_party/googleapis && \ + git init && \ + git remote add origin git@github.com:googleapis/googleapis.git && \ + git fetch origin 47947b2fb9bdde9b02a7dd173a5077a1cc2beb25 && \ + git checkout FETCH_HEAD && \ + cd ../.. @rm -rf vendor @mkdir vendor @protoc \ diff --git a/README.markdown b/README.markdown index 7af322386..cb5c1329c 100644 --- a/README.markdown +++ b/README.markdown @@ -19,10 +19,10 @@ - [Highlights](#highlights) - [Auto-Batching / N+1 Prevention](#auto-batching--n1-prevention) - [Usage](#usage) - - [Supported options](#supported-options) - - [NestJS Support](#nestjs-support) - - [Watch Mode](#watch-mode) - - [Basic gRPC implementation](#basic-grpc-implementation) + - [Supported options](#supported-options) + - [NestJS Support](#nestjs-support) + - [Watch Mode](#watch-mode) + - [Basic gRPC implementation](#basic-grpc-implementation) - [Sponsors](#sponsors) - [Development](#development) - [Assumptions](#assumptions) @@ -704,6 +704,14 @@ The commands below assume you have **Docker** installed. If you are using OS X, > - `proto2pbjs` — Generates a reference implementation using `pbjs` for testing compatibility. - Run `yarn test` +**Vendor** + +To update [vendor](./vendor/) code + +1. Install [Code Generator Plugins](https://github.com/grpc/grpc-web?tab=readme-ov-file#code-generator-plugins) +2. Update the commit id in [Makefile](./Makefile). +3. Run `make build-vendor`. + **Workflow** - Add/update an integration test for your use case From 3a3ef40209b12a4ea73a3be5095b4a6a1acc7a21 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Fri, 12 Jul 2024 16:22:34 +0900 Subject: [PATCH 04/20] Update readme --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index cb5c1329c..e49ef87c9 100644 --- a/README.markdown +++ b/README.markdown @@ -709,7 +709,7 @@ The commands below assume you have **Docker** installed. If you are using OS X, To update [vendor](./vendor/) code 1. Install [Code Generator Plugins](https://github.com/grpc/grpc-web?tab=readme-ov-file#code-generator-plugins) -2. Update the commit id in [Makefile](./Makefile). +2. Update the commit id in [Makefile](./Makefile#L8). 3. Run `make build-vendor`. **Workflow** From b9d0a5530ce10f6af06d4d4880493281ac9ca1e5 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Fri, 12 Jul 2024 16:32:04 +0900 Subject: [PATCH 05/20] Update package.json --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 91bda43ce..ddd7e45a6 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,8 @@ "watch": "tsx integration/watch.ts" }, "files": [ - "build" + "build", + "vendor" ], "keywords": [], "author": "", From b04e1a08260e3dbe734973aa269903a6087bd044 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Tue, 16 Jul 2024 11:28:13 +0900 Subject: [PATCH 06/20] Refine HTTP implementation --- .gitignore | 2 +- HTTP.markdown | 22 +++++++-------- Makefile | 12 ++++----- integration/http/http-test.ts | 51 ++++++++++++++++++++--------------- integration/http/simple.proto | 16 +++++++---- integration/http/simple.ts | 22 ++++++++++----- src/generate-http.ts | 27 ++++++++++--------- src/google-protobuf.ts | 2 ++ src/plugin.ts | 4 +-- 9 files changed, 93 insertions(+), 65 deletions(-) create mode 100644 src/google-protobuf.ts diff --git a/.gitignore b/.gitignore index 46fc89438..57a8e6ef7 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,7 @@ build/ coverage/ yarn-error.log .DS_Store -third_party +tmp/ # Yarn .pnp.* diff --git a/HTTP.markdown b/HTTP.markdown index 6b30f5ba2..a94205d0a 100644 --- a/HTTP.markdown +++ b/HTTP.markdown @@ -21,7 +21,7 @@ service Messaging { } rpc UpdateMessage(CreateMessageRequest) returns (CreateMessageResponse) { option (google.api.http) = { - post:"/v1/messages/{message_id}" + patch:"/v1/messages/{message_id}" body: "*" }; } @@ -66,24 +66,24 @@ export const Messaging = { getMessage: { path: "/v1/messages/{message_id}", method: "get", - request: undefined as GetMessageRequest | undefined, - response: undefined as GetMessageResponse | undefined, + requestType: undefined as GetMessageRequest, + responseType: undefined as GetMessageResponse, }, createMessage: { path: "/v1/messages/{message_id}", method: "post", body: "message", - request: undefined as CreateMessageRequest | undefined, - response: undefined as CreateMessageResponse | undefined, + requestType: undefined as CreateMessageRequest, + responseType: undefined as CreateMessageResponse, }, updateMessage: { path: "/v1/messages/{message_id}", - method: "post", + method: "patch", body: "*", - request: undefined as CreateMessageRequest | undefined, - response: undefined as CreateMessageResponse | undefined, + requestType: undefined as CreateMessageRequest, + responseType: undefined as CreateMessageResponse, }, }; ``` @@ -93,10 +93,10 @@ export const Messaging = { ```typescript // This is just an example, do not use it directly. function createApi(config: T) { - return function api(request: NonNullable): Promise> { - const path = config.path.replace("{message_id}", request.messageId); + return function api(payload: T["requestType"]): Promise { + const path = config.path.replace("{message_id}", payload.messageId); const method = config.method; - const body = method === "get" ? undefined : JSON.stringify({ message: request.message }); + const body = method === "get" ? undefined : JSON.stringify({ message: payload.message }); return fetch(path, { method, body }); }; diff --git a/Makefile b/Makefile index 60bbcc76f..8642b530c 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,8 @@ .PHONY: build-vendor build-vendor: - @rm -rf third_party - @mkdir -p third_party/googleapis - @cd third_party/googleapis && \ + @rm -rf tmp + @mkdir -p tmp/googleapis + @cd tmp/googleapis && \ git init && \ git remote add origin git@github.com:googleapis/googleapis.git && \ git fetch origin 47947b2fb9bdde9b02a7dd173a5077a1cc2beb25 && \ @@ -12,6 +12,6 @@ build-vendor: @mkdir vendor @protoc \ --js_out=import_style=commonjs,binary:vendor \ - -I third_party/googleapis \ - third_party/googleapis/google/api/http.proto third_party/googleapis/google/api/annotations.proto - @rm -rf third_party + -I tmp/googleapis \ + tmp/googleapis/google/api/http.proto tmp/googleapis/google/api/annotations.proto + @rm -rf tmp diff --git a/integration/http/http-test.ts b/integration/http/http-test.ts index 2935f76e2..e57ea1dc4 100644 --- a/integration/http/http-test.ts +++ b/integration/http/http-test.ts @@ -5,25 +5,34 @@ import { Messaging, GetMessageRequest, GetMessageResponse } from "./simple"; describe("http-test", () => { it("compiles", () => { - expect(Messaging.getMessage).toStrictEqual({ - path: "/v1/messages/{message_id}", - method: "get", - request: undefined, - response: undefined, - }); - expect(Messaging.createMessage).toStrictEqual({ - path: "/v1/messages/{message_id}", - method: "post", - body: "message", - request: undefined, - response: undefined, - }); - expect(Messaging.updateMessage).toStrictEqual({ - path: "/v1/messages/{message_id}", - method: "post", - body: "*", - request: undefined, - response: undefined, + expect(Messaging).toStrictEqual({ + getMessage: { + path: "/v1/messages/{message_id}", + method: "get", + requestType: undefined, + responseType: undefined, + }, + createMessage: { + path: "/v1/messages/{message_id}", + method: "post", + body: "message", + requestType: undefined, + responseType: undefined, + }, + updateMessage: { + path: "/v1/messages/{message_id}", + method: "patch", + body: "*", + requestType: undefined, + responseType: undefined, + }, + deleteMessage: { + path: "/v1/messages/{message_id}", + method: "delete", + body: "*", + requestType: undefined, + responseType: undefined, + }, }); // Test that the request and response types are correctly typed @@ -34,7 +43,7 @@ describe("http-test", () => { const response: GetMessageResponse = { message: "hello", }; - copy.request = request; - copy.response = response; + copy.requestType = request; + copy.responseType = response; }); }); diff --git a/integration/http/simple.proto b/integration/http/simple.proto index 2b6a25efd..c5d273017 100644 --- a/integration/http/simple.proto +++ b/integration/http/simple.proto @@ -5,19 +5,25 @@ import "google/api/annotations.proto"; service Messaging { rpc GetMessage(GetMessageRequest) returns (GetMessageResponse) { option (google.api.http) = { - get:"/v1/messages/{message_id}" + get:"/v1/messages/{message_id}" }; } rpc CreateMessage(CreateMessageRequest) returns (CreateMessageResponse) { option (google.api.http) = { - post:"/v1/messages/{message_id}" - body: "message" + post:"/v1/messages/{message_id}" + body: "message" }; } rpc UpdateMessage(CreateMessageRequest) returns (CreateMessageResponse) { option (google.api.http) = { - post:"/v1/messages/{message_id}" - body: "*" + patch:"/v1/messages/{message_id}" + body: "*" + }; + } + rpc DeleteMessage(GetMessageRequest) returns (CreateMessageResponse) { + option (google.api.http) = { + delete:"/v1/messages/{message_id}" + body: "*" }; } } diff --git a/integration/http/simple.ts b/integration/http/simple.ts index e63e9295e..ee05e844f 100644 --- a/integration/http/simple.ts +++ b/integration/http/simple.ts @@ -26,23 +26,31 @@ export const Messaging = { getMessage: { path: "/v1/messages/{message_id}", method: "get", - request: undefined as GetMessageRequest | undefined, - response: undefined as GetMessageResponse | undefined, + requestType: undefined as unknown as GetMessageRequest, + responseType: undefined as unknown as GetMessageResponse, }, createMessage: { path: "/v1/messages/{message_id}", method: "post", body: "message", - request: undefined as CreateMessageRequest | undefined, - response: undefined as CreateMessageResponse | undefined, + requestType: undefined as unknown as CreateMessageRequest, + responseType: undefined as unknown as CreateMessageResponse, }, updateMessage: { path: "/v1/messages/{message_id}", - method: "post", + method: "patch", + body: "*", + requestType: undefined as unknown as CreateMessageRequest, + responseType: undefined as unknown as CreateMessageResponse, + }, + + deleteMessage: { + path: "/v1/messages/{message_id}", + method: "delete", body: "*", - request: undefined as CreateMessageRequest | undefined, - response: undefined as CreateMessageResponse | undefined, + requestType: undefined as unknown as GetMessageRequest, + responseType: undefined as unknown as CreateMessageResponse, }, }; diff --git a/src/generate-http.ts b/src/generate-http.ts index 49c885feb..87395902e 100644 --- a/src/generate-http.ts +++ b/src/generate-http.ts @@ -4,7 +4,6 @@ import { requestType, responseType } from "./types"; import SourceInfo from "./sourceInfo"; import { assertInstanceOf, FormattedMethodDescriptor } from "./utils"; import { Context } from "./context"; -require("../vendor/google/api/annotations_pb"); interface HTTPRule { get: string; @@ -12,21 +11,20 @@ interface HTTPRule { post: string; pb_delete: string; patch: string; + option: string; body: "*" | string; } function mapHTTPOptions(http: HTTPRule) { - for (const method of ["post", "put", "get", "pb_delete", "patch"] as const) { + for (const method of ["get", "post", "put", "pb_delete", "patch", "option"] as const) { if (http[method]) { return { - method: method, + method: method === "pb_delete" ? "delete" : method, path: http[method], body: http.body, }; } } - - throw new Error("No HTTP method found"); } export function generateHttpService( @@ -41,18 +39,18 @@ export function generateHttpService( return service.name === serviceDesc.name; })?.methodList; - const httpOptions: Record> = {}; + const httpOptions: Record | undefined> = {}; let hasHttpOptions = false; if (methodList) { serviceDesc.method.forEach((methodDesc, i) => { - // @ts-expect-error - const http = methodList[i]?.options?.http as HTTPRule | undefined; + const http = (methodList[i]?.options as { http?: HTTPRule } | undefined)?.http as HTTPRule | undefined; + const httpOption = http ? mapHTTPOptions(http) : undefined; - if (http) { + if (httpOption) { hasHttpOptions = true; assertInstanceOf(methodDesc, FormattedMethodDescriptor); - httpOptions[methodDesc.formattedName] = mapHTTPOptions(http); + httpOptions[methodDesc.formattedName] = httpOption; } }); } @@ -65,12 +63,17 @@ export function generateHttpService( serviceDesc.method.forEach((methodDesc) => { assertInstanceOf(methodDesc, FormattedMethodDescriptor); const httpMethod = httpOptions[methodDesc.formattedName]; + + if (!httpMethod) { + return; + } + chunks.push(code` ${methodDesc.formattedName}: { path: "${httpMethod.path}", method: "${httpMethod.method}",${httpMethod.body ? `\nbody: "${httpMethod.body}",` : ""} - request: undefined as ${requestType(ctx, methodDesc)} | undefined, - response: undefined as ${responseType(ctx, methodDesc)} | undefined, + requestType: undefined as unknown as ${requestType(ctx, methodDesc)}, + responseType: undefined as unknown as ${responseType(ctx, methodDesc)}, }, `); }); diff --git a/src/google-protobuf.ts b/src/google-protobuf.ts new file mode 100644 index 000000000..3a1ab3026 --- /dev/null +++ b/src/google-protobuf.ts @@ -0,0 +1,2 @@ +export { CodeGeneratorRequest } from "google-protobuf/google/protobuf/compiler/plugin_pb"; +require("../vendor/google/api/annotations_pb"); diff --git a/src/plugin.ts b/src/plugin.ts index 8c080847d..1226e8984 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -4,7 +4,6 @@ import { CodeGeneratorResponse_Feature, FileDescriptorProto, } from "ts-proto-descriptors"; -import { CodeGeneratorRequest as GoogleCodeGeneratorRequest } from "google-protobuf/google/protobuf/compiler/plugin_pb"; import { promisify } from "util"; import { generateIndexFiles, getVersions, protoFilesToGenerate, readToBuffer } from "./utils"; import { generateFile, makeUtils } from "./main"; @@ -31,7 +30,8 @@ async function main() { const input = new Uint8Array(stdin.length); input.set(stdin); fileDescriptorProtoMap = {}; - GoogleCodeGeneratorRequest.deserializeBinary(input) + const PluginPb = await import("./google-protobuf"); + PluginPb.CodeGeneratorRequest.deserializeBinary(input) .getProtoFileList() .forEach((descriptor) => { fileDescriptorProtoMap![descriptor.getName()!] = descriptor; From 54ef26c2c34dc9fc7699ca54ad34a96424392d40 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Tue, 16 Jul 2024 11:35:30 +0900 Subject: [PATCH 07/20] Fix Readme --- README.markdown | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/README.markdown b/README.markdown index e49ef87c9..1c1f56cda 100644 --- a/README.markdown +++ b/README.markdown @@ -19,10 +19,10 @@ - [Highlights](#highlights) - [Auto-Batching / N+1 Prevention](#auto-batching--n1-prevention) - [Usage](#usage) - - [Supported options](#supported-options) - - [NestJS Support](#nestjs-support) - - [Watch Mode](#watch-mode) - - [Basic gRPC implementation](#basic-grpc-implementation) + - [Supported options](#supported-options) + - [NestJS Support](#nestjs-support) + - [Watch Mode](#watch-mode) + - [Basic gRPC implementation](#basic-grpc-implementation) - [Sponsors](#sponsors) - [Development](#development) - [Assumptions](#assumptions) @@ -612,10 +612,11 @@ export interface User { } ``` -- With `--ts_proto_opt=noDefaultsForOptionals=true`, `undefined` primitive values will not be defaulted as per the protobuf spec. Additionally unlike the standard behavior, when a field is set to it's standard default value, it _will_ be encoded allowing it to be sent over the wire and distinguished from undefined values. For example if a message does not set a boolean value, ordinarily this would be defaulted to `false` which is different to it being undefined. +- With `--ts_proto_opt=noDefaultsForOptionals=true`, `undefined` primitive values will not be defaulted as per the protobuf spec. Additionally unlike the standard behavior, when a field is set to it's standard default value, it *will* be encoded allowing it to be sent over the wire and distinguished from undefined values. For example if a message does not set a boolean value, ordinarily this would be defaulted to `false` which is different to it being undefined. This option allows the library to act in a compatible way with the [Wire implementation](https://square.github.io/wire/) maintained and used by Square/Block. Note: this option should only be used in combination with other client/server code generated using Wire or ts-proto with this option enabled. + ### NestJS Support We 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). @@ -842,10 +843,10 @@ For comparison, the equivalents for `oneof=unions-value`: ```ts /** Extracts all the case names from a oneOf field. */ -type OneOfCases = T["$case"]; +type OneOfCases = T['$case']; /** Extracts a union of all the value types from a oneOf field */ -type OneOfValues = T["value"]; +type OneOfValues = T['value']; /** Extracts the specific type of a oneOf case based on its field name */ type OneOfCase> = T extends { From 56693fe2f520ffe3e56fab26198f45c8edfccc81 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Tue, 16 Jul 2024 13:23:02 +0900 Subject: [PATCH 08/20] Fix Readme --- README.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/README.markdown b/README.markdown index 1c1f56cda..41adb14a8 100644 --- a/README.markdown +++ b/README.markdown @@ -28,7 +28,6 @@ - [Assumptions](#assumptions) - [Todo](#todo) - [OneOf Handling](#oneof-handling) - - [OneOf Type Helpers](#oneof-type-helpers) - [Default values and unset fields](#default-values-and-unset-fields) - [Well-Known Types](#well-known-types) - [Wrapper Types](#wrapper-types) From a1c3d5de7ca98c194389567532ef23b825f20d0b Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Wed, 24 Jul 2024 10:12:58 +0900 Subject: [PATCH 09/20] Use ts-proto-descriptors --- .gitignore | 1 - Makefile | 17 - README.markdown | 8 - package.json | 5 +- protos/build.sh | 9 +- protos/extend-descriptor.cjs | 32 + protos/google/api/annotations.proto | 31 + protos/google/api/http.proto | 371 ++++++++ protos/google/api/http.ts | 814 +++++++++++++++++ protos/google/protobuf/compiler/plugin.ts | 2 +- protos/google/protobuf/descriptor.ts | 11 +- src/context.ts | 6 +- src/generate-http.ts | 65 +- src/google-protobuf.ts | 2 - src/plugin.ts | 18 +- vendor/google/api/annotations_pb.js | 54 -- vendor/google/api/http_pb.js | 1012 --------------------- yarn.lock | 16 - 18 files changed, 1297 insertions(+), 1177 deletions(-) delete mode 100644 Makefile create mode 100644 protos/extend-descriptor.cjs create mode 100644 protos/google/api/annotations.proto create mode 100644 protos/google/api/http.proto create mode 100644 protos/google/api/http.ts delete mode 100644 src/google-protobuf.ts delete mode 100644 vendor/google/api/annotations_pb.js delete mode 100644 vendor/google/api/http_pb.js diff --git a/.gitignore b/.gitignore index 57a8e6ef7..0ef7311a0 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,6 @@ build/ coverage/ yarn-error.log .DS_Store -tmp/ # Yarn .pnp.* diff --git a/Makefile b/Makefile deleted file mode 100644 index 8642b530c..000000000 --- a/Makefile +++ /dev/null @@ -1,17 +0,0 @@ -.PHONY: build-vendor -build-vendor: - @rm -rf tmp - @mkdir -p tmp/googleapis - @cd tmp/googleapis && \ - git init && \ - git remote add origin git@github.com:googleapis/googleapis.git && \ - git fetch origin 47947b2fb9bdde9b02a7dd173a5077a1cc2beb25 && \ - git checkout FETCH_HEAD && \ - cd ../.. - @rm -rf vendor - @mkdir vendor - @protoc \ - --js_out=import_style=commonjs,binary:vendor \ - -I tmp/googleapis \ - tmp/googleapis/google/api/http.proto tmp/googleapis/google/api/annotations.proto - @rm -rf tmp diff --git a/README.markdown b/README.markdown index 41adb14a8..870db912f 100644 --- a/README.markdown +++ b/README.markdown @@ -704,14 +704,6 @@ The commands below assume you have **Docker** installed. If you are using OS X, > - `proto2pbjs` — Generates a reference implementation using `pbjs` for testing compatibility. - Run `yarn test` -**Vendor** - -To update [vendor](./vendor/) code - -1. Install [Code Generator Plugins](https://github.com/grpc/grpc-web?tab=readme-ov-file#code-generator-plugins) -2. Update the commit id in [Makefile](./Makefile#L8). -3. Run `make build-vendor`. - **Workflow** - Add/update an integration test for your use case diff --git a/package.json b/package.json index ddd7e45a6..37b6c5cc6 100644 --- a/package.json +++ b/package.json @@ -22,8 +22,7 @@ "watch": "tsx integration/watch.ts" }, "files": [ - "build", - "vendor" + "build" ], "keywords": [], "author": "", @@ -44,7 +43,6 @@ "@semantic-release/npm": "^10.0.4", "@semantic-release/release-notes-generator": "^11.0.4", "@tsconfig/strictest": "^2.0.1", - "@types/google-protobuf": "^3.15.12", "@types/jest": "^29.5.3", "@types/node": "^16.18.38", "@types/object-hash": "^3.0.2", @@ -68,7 +66,6 @@ }, "dependencies": { "case-anything": "^2.1.13", - "google-protobuf": "^3.21.2", "protobufjs": "^7.2.4", "ts-poet": "^6.7.0", "ts-proto-descriptors": "1.16.0" diff --git a/protos/build.sh b/protos/build.sh index 17cee40d1..1da499ef0 100755 --- a/protos/build.sh +++ b/protos/build.sh @@ -3,12 +3,17 @@ # Generates TS objects of the protoc plugin descriptors, which ts-proto # uses to understand the incoming protoc codegen request objects. +rm -rf dist + protoc \ --plugin=./node_modules/ts-proto/protoc-gen-ts_proto \ --ts_proto_out=. \ --ts_proto_opt=esModuleInterop=true,useExactTypes=false,initializeFieldsAsUndefined=false,exportCommonSymbols=false,unknownFields=true,usePrototypeForDefaults=true,outputExtensions=true,disableProto2Optionals=true \ ./google/protobuf/descriptor.proto \ - ./google/protobuf/compiler/plugin.proto + ./google/protobuf/compiler/plugin.proto \ + ./google/api/http.proto \ + ./google/api/annotations.proto +node ./extend-descriptor.cjs +rm ./google/api/annotations.ts ./node_modules/.bin/tsc -p tsconfig.json - diff --git a/protos/extend-descriptor.cjs b/protos/extend-descriptor.cjs new file mode 100644 index 000000000..dee33faae --- /dev/null +++ b/protos/extend-descriptor.cjs @@ -0,0 +1,32 @@ +const fs = require("node:fs"); + +const annotations = "./google/api/annotations.ts"; +const descriptor = "./google/protobuf/descriptor.ts"; + +const tag = /tag: (\d+)/.exec(fs.readFileSync(annotations, "utf8").toString())[1]; + +fs.writeFileSync( + descriptor, + fs + .readFileSync(descriptor, "utf8") + .toString() + .replace('import _m0 from "protobufjs/minimal";', (target) => { + return target + `\nimport { HttpRule } from "../api/http";`; + }) + .replace("export interface MethodOptions {", (target) => { + return target + `\n httpRule?: HttpRule;`; + }) + .replace("message.idempotencyLevel = reader.int32() as any;", (target) => { + return ( + target + + ` + continue; + case ${tag >>> 3}: + if (tag !== ${tag}) { + break; + } + + message.httpRule = HttpRule.decode(reader, reader.uint32());` + ); + }), +); diff --git a/protos/google/api/annotations.proto b/protos/google/api/annotations.proto new file mode 100644 index 000000000..b17b34560 --- /dev/null +++ b/protos/google/api/annotations.proto @@ -0,0 +1,31 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +import "google/api/http.proto"; +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "AnnotationsProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.MethodOptions { + // See `HttpRule`. + HttpRule http = 72295728; +} \ No newline at end of file diff --git a/protos/google/api/http.proto b/protos/google/api/http.proto new file mode 100644 index 000000000..c9b7fdc3f --- /dev/null +++ b/protos/google/api/http.proto @@ -0,0 +1,371 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package google.api; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "HttpProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Defines the HTTP configuration for an API service. It contains a list of +// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method +// to one or more HTTP REST API methods. +message Http { + // A list of HTTP configuration rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated HttpRule rules = 1; + + // When set to true, URL path parameters will be fully URI-decoded except in + // cases of single segment matches in reserved expansion, where "%2F" will be + // left encoded. + // + // The default behavior is to not decode RFC 6570 reserved characters in multi + // segment matches. + bool fully_decode_reserved_expansion = 2; +} + +// gRPC Transcoding +// +// gRPC Transcoding is a feature for mapping between a gRPC method and one or +// more HTTP REST endpoints. It allows developers to build a single API service +// that supports both gRPC APIs and REST APIs. Many systems, including [Google +// APIs](https://github.com/googleapis/googleapis), +// [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC +// Gateway](https://github.com/grpc-ecosystem/grpc-gateway), +// and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature +// and use it for large scale production services. +// +// `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies +// how different portions of the gRPC request message are mapped to the URL +// path, URL query parameters, and HTTP request body. It also controls how the +// gRPC response message is mapped to the HTTP response body. `HttpRule` is +// typically specified as an `google.api.http` annotation on the gRPC method. +// +// Each mapping specifies a URL path template and an HTTP method. The path +// template may refer to one or more fields in the gRPC request message, as long +// as each field is a non-repeated field with a primitive (non-message) type. +// The path template controls how fields of the request message are mapped to +// the URL path. +// +// Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/{name=messages/*}" +// }; +// } +// } +// message GetMessageRequest { +// string name = 1; // Mapped to URL path. +// } +// message Message { +// string text = 1; // The resource content. +// } +// +// This enables an HTTP REST to gRPC mapping as below: +// +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(name: "messages/123456")` +// +// Any fields in the request message which are not bound by the path template +// automatically become HTTP query parameters if there is no HTTP request body. +// For example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get:"/v1/messages/{message_id}" +// }; +// } +// } +// message GetMessageRequest { +// message SubMessage { +// string subfield = 1; +// } +// string message_id = 1; // Mapped to URL path. +// int64 revision = 2; // Mapped to URL query parameter `revision`. +// SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`. +// } +// +// This enables a HTTP JSON to RPC mapping as below: +// +// - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo` +// - gRPC: `GetMessage(message_id: "123456" revision: 2 sub: +// SubMessage(subfield: "foo"))` +// +// Note that fields which are mapped to URL query parameters must have a +// primitive type or a repeated primitive type or a non-repeated message type. +// In the case of a repeated type, the parameter can be repeated in the URL +// as `...?param=A¶m=B`. In the case of a message type, each field of the +// message is mapped to a separate parameter, such as +// `...?foo.a=A&foo.b=B&foo.c=C`. +// +// For HTTP methods that allow a request body, the `body` field +// specifies the mapping. Consider a REST update method on the +// message resource collection: +// +// service Messaging { +// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "message" +// }; +// } +// } +// message UpdateMessageRequest { +// string message_id = 1; // mapped to the URL +// Message message = 2; // mapped to the body +// } +// +// The following HTTP JSON to RPC mapping is enabled, where the +// representation of the JSON in the request body is determined by +// protos JSON encoding: +// +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })` +// +// The special name `*` can be used in the body mapping to define that +// every field not bound by the path template should be mapped to the +// request body. This enables the following alternative definition of +// the update method: +// +// service Messaging { +// rpc UpdateMessage(Message) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "*" +// }; +// } +// } +// message Message { +// string message_id = 1; +// string text = 2; +// } +// +// +// The following HTTP JSON to RPC mapping is enabled: +// +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")` +// +// Note that when using `*` in the body mapping, it is not possible to +// have HTTP parameters, as all fields not bound by the path end in +// the body. This makes this option more rarely used in practice when +// defining REST APIs. The common usage of `*` is in custom methods +// which don't use the URL at all for transferring data. +// +// It is possible to define multiple HTTP methods for one RPC by using +// the `additional_bindings` option. Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/messages/{message_id}" +// additional_bindings { +// get: "/v1/users/{user_id}/messages/{message_id}" +// } +// }; +// } +// } +// message GetMessageRequest { +// string message_id = 1; +// string user_id = 2; +// } +// +// This enables the following two alternative HTTP JSON to RPC mappings: +// +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(message_id: "123456")` +// +// - HTTP: `GET /v1/users/me/messages/123456` +// - gRPC: `GetMessage(user_id: "me" message_id: "123456")` +// +// Rules for HTTP mapping +// +// 1. Leaf request fields (recursive expansion nested messages in the request +// message) are classified into three categories: +// - Fields referred by the path template. They are passed via the URL path. +// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They +// are passed via the HTTP +// request body. +// - All other fields are passed via the URL query parameters, and the +// parameter name is the field path in the request message. A repeated +// field can be represented as multiple query parameters under the same +// name. +// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL +// query parameter, all fields +// are passed via URL path and HTTP request body. +// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP +// request body, all +// fields are passed via URL path and URL query parameters. +// +// Path template syntax +// +// Template = "/" Segments [ Verb ] ; +// Segments = Segment { "/" Segment } ; +// Segment = "*" | "**" | LITERAL | Variable ; +// Variable = "{" FieldPath [ "=" Segments ] "}" ; +// FieldPath = IDENT { "." IDENT } ; +// Verb = ":" LITERAL ; +// +// The syntax `*` matches a single URL path segment. The syntax `**` matches +// zero or more URL path segments, which must be the last part of the URL path +// except the `Verb`. +// +// The syntax `Variable` matches part of the URL path as specified by its +// template. A variable template must not contain other variables. If a variable +// matches a single path segment, its template may be omitted, e.g. `{var}` +// is equivalent to `{var=*}`. +// +// The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL` +// contains any reserved character, such characters should be percent-encoded +// before the matching. +// +// If a variable contains exactly one path segment, such as `"{var}"` or +// `"{var=*}"`, when such a variable is expanded into a URL path on the client +// side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The +// server side does the reverse decoding. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{var}`. +// +// If a variable contains multiple path segments, such as `"{var=foo/*}"` +// or `"{var=**}"`, when such a variable is expanded into a URL path on the +// client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. +// The server side does the reverse decoding, except "%2F" and "%2f" are left +// unchanged. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{+var}`. +// +// Using gRPC API Service Configuration +// +// gRPC API Service Configuration (service config) is a configuration language +// for configuring a gRPC service to become a user-facing product. The +// service config is simply the YAML representation of the `google.api.Service` +// proto message. +// +// As an alternative to annotating your proto file, you can configure gRPC +// transcoding in your service config YAML files. You do this by specifying a +// `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same +// effect as the proto annotation. This can be particularly useful if you +// have a proto that is reused in multiple services. Note that any transcoding +// specified in the service config will override any matching transcoding +// configuration in the proto. +// +// The following example selects a gRPC method and applies an `HttpRule` to it: +// +// http: +// rules: +// - selector: example.v1.Messaging.GetMessage +// get: /v1/messages/{message_id}/{sub.subfield} +// +// Special notes +// +// When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the +// proto to JSON conversion must follow the [proto3 +// specification](https://developers.google.com/protocol-buffers/docs/proto3#json). +// +// While the single segment variable follows the semantics of +// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String +// Expansion, the multi segment variable **does not** follow RFC 6570 Section +// 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion +// does not expand special characters like `?` and `#`, which would lead +// to invalid URLs. As the result, gRPC Transcoding uses a custom encoding +// for multi segment variables. +// +// The path variables **must not** refer to any repeated or mapped field, +// because client libraries are not capable of handling such variable expansion. +// +// The path variables **must not** capture the leading "/" character. The reason +// is that the most common use case "{var}" does not capture the leading "/" +// character. For consistency, all path variables must share the same behavior. +// +// Repeated message fields must not be mapped to URL query parameters, because +// no client library can support such complicated mapping. +// +// If an API needs to use a JSON array for request or response body, it can map +// the request or response body to a repeated field. However, some gRPC +// Transcoding implementations may not support this feature. +message HttpRule { + // Selects a method to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // Determines the URL pattern is matched by this rules. This pattern can be + // used with any of the {get|put|post|delete|patch} methods. A custom method + // can be defined using the 'custom' field. + oneof pattern { + // Maps to HTTP GET. Used for listing and getting information about + // resources. + string get = 2; + + // Maps to HTTP PUT. Used for replacing a resource. + string put = 3; + + // Maps to HTTP POST. Used for creating a resource or performing an action. + string post = 4; + + // Maps to HTTP DELETE. Used for deleting a resource. + string delete = 5; + + // Maps to HTTP PATCH. Used for updating a resource. + string patch = 6; + + // The custom pattern is used for specifying an HTTP method that is not + // included in the `pattern` field, such as HEAD, or "*" to leave the + // HTTP method unspecified for this rule. The wild-card rule is useful + // for services that provide content to Web (HTML) clients. + CustomHttpPattern custom = 8; + } + + // The name of the request field whose value is mapped to the HTTP request + // body, or `*` for mapping all request fields not captured by the path + // pattern to the HTTP body, or omitted for not having any HTTP request body. + // + // NOTE: the referred field must be present at the top-level of the request + // message type. + string body = 7; + + // Optional. The name of the response field whose value is mapped to the HTTP + // response body. When omitted, the entire response message will be used + // as the HTTP response body. + // + // NOTE: The referred field must be present at the top-level of the response + // message type. + string response_body = 12; + + // Additional HTTP bindings for the selector. Nested bindings must + // not contain an `additional_bindings` field themselves (that is, + // the nesting may only be one level deep). + repeated HttpRule additional_bindings = 11; +} + +// A custom pattern is used for defining custom HTTP verb. +message CustomHttpPattern { + // The name of this custom HTTP verb. + string kind = 1; + + // The path matched by this custom verb. + string path = 2; +} \ No newline at end of file diff --git a/protos/google/api/http.ts b/protos/google/api/http.ts new file mode 100644 index 000000000..4e4f4a496 --- /dev/null +++ b/protos/google/api/http.ts @@ -0,0 +1,814 @@ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// versions: +// protoc-gen-ts_proto v1.175.1 +// protoc v5.26.1 +// source: google/api/http.proto + +/* eslint-disable */ +import _m0 from "protobufjs/minimal"; + +/** + * Defines the HTTP configuration for an API service. It contains a list of + * [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method + * to one or more HTTP REST API methods. + */ +export interface Http { + /** + * A list of HTTP configuration rules that apply to individual API methods. + * + * **NOTE:** All service configuration rules follow "last one wins" order. + */ + rules: HttpRule[]; + /** + * When set to true, URL path parameters will be fully URI-decoded except in + * cases of single segment matches in reserved expansion, where "%2F" will be + * left encoded. + * + * The default behavior is to not decode RFC 6570 reserved characters in multi + * segment matches. + */ + fullyDecodeReservedExpansion: boolean; + _unknownFields?: { [key: number]: Uint8Array[] } | undefined; +} + +/** + * gRPC Transcoding + * + * gRPC Transcoding is a feature for mapping between a gRPC method and one or + * more HTTP REST endpoints. It allows developers to build a single API service + * that supports both gRPC APIs and REST APIs. Many systems, including [Google + * APIs](https://github.com/googleapis/googleapis), + * [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC + * Gateway](https://github.com/grpc-ecosystem/grpc-gateway), + * and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature + * and use it for large scale production services. + * + * `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies + * how different portions of the gRPC request message are mapped to the URL + * path, URL query parameters, and HTTP request body. It also controls how the + * gRPC response message is mapped to the HTTP response body. `HttpRule` is + * typically specified as an `google.api.http` annotation on the gRPC method. + * + * Each mapping specifies a URL path template and an HTTP method. The path + * template may refer to one or more fields in the gRPC request message, as long + * as each field is a non-repeated field with a primitive (non-message) type. + * The path template controls how fields of the request message are mapped to + * the URL path. + * + * Example: + * + * service Messaging { + * rpc GetMessage(GetMessageRequest) returns (Message) { + * option (google.api.http) = { + * get: "/v1/{name=messages/*}" + * }; + * } + * } + * message GetMessageRequest { + * string name = 1; // Mapped to URL path. + * } + * message Message { + * string text = 1; // The resource content. + * } + * + * This enables an HTTP REST to gRPC mapping as below: + * + * - HTTP: `GET /v1/messages/123456` + * - gRPC: `GetMessage(name: "messages/123456")` + * + * Any fields in the request message which are not bound by the path template + * automatically become HTTP query parameters if there is no HTTP request body. + * For example: + * + * service Messaging { + * rpc GetMessage(GetMessageRequest) returns (Message) { + * option (google.api.http) = { + * get:"/v1/messages/{message_id}" + * }; + * } + * } + * message GetMessageRequest { + * message SubMessage { + * string subfield = 1; + * } + * string message_id = 1; // Mapped to URL path. + * int64 revision = 2; // Mapped to URL query parameter `revision`. + * SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`. + * } + * + * This enables a HTTP JSON to RPC mapping as below: + * + * - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo` + * - gRPC: `GetMessage(message_id: "123456" revision: 2 sub: + * SubMessage(subfield: "foo"))` + * + * Note that fields which are mapped to URL query parameters must have a + * primitive type or a repeated primitive type or a non-repeated message type. + * In the case of a repeated type, the parameter can be repeated in the URL + * as `...?param=A¶m=B`. In the case of a message type, each field of the + * message is mapped to a separate parameter, such as + * `...?foo.a=A&foo.b=B&foo.c=C`. + * + * For HTTP methods that allow a request body, the `body` field + * specifies the mapping. Consider a REST update method on the + * message resource collection: + * + * service Messaging { + * rpc UpdateMessage(UpdateMessageRequest) returns (Message) { + * option (google.api.http) = { + * patch: "/v1/messages/{message_id}" + * body: "message" + * }; + * } + * } + * message UpdateMessageRequest { + * string message_id = 1; // mapped to the URL + * Message message = 2; // mapped to the body + * } + * + * The following HTTP JSON to RPC mapping is enabled, where the + * representation of the JSON in the request body is determined by + * protos JSON encoding: + * + * - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` + * - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })` + * + * The special name `*` can be used in the body mapping to define that + * every field not bound by the path template should be mapped to the + * request body. This enables the following alternative definition of + * the update method: + * + * service Messaging { + * rpc UpdateMessage(Message) returns (Message) { + * option (google.api.http) = { + * patch: "/v1/messages/{message_id}" + * body: "*" + * }; + * } + * } + * message Message { + * string message_id = 1; + * string text = 2; + * } + * + * The following HTTP JSON to RPC mapping is enabled: + * + * - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` + * - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")` + * + * Note that when using `*` in the body mapping, it is not possible to + * have HTTP parameters, as all fields not bound by the path end in + * the body. This makes this option more rarely used in practice when + * defining REST APIs. The common usage of `*` is in custom methods + * which don't use the URL at all for transferring data. + * + * It is possible to define multiple HTTP methods for one RPC by using + * the `additional_bindings` option. Example: + * + * service Messaging { + * rpc GetMessage(GetMessageRequest) returns (Message) { + * option (google.api.http) = { + * get: "/v1/messages/{message_id}" + * additional_bindings { + * get: "/v1/users/{user_id}/messages/{message_id}" + * } + * }; + * } + * } + * message GetMessageRequest { + * string message_id = 1; + * string user_id = 2; + * } + * + * This enables the following two alternative HTTP JSON to RPC mappings: + * + * - HTTP: `GET /v1/messages/123456` + * - gRPC: `GetMessage(message_id: "123456")` + * + * - HTTP: `GET /v1/users/me/messages/123456` + * - gRPC: `GetMessage(user_id: "me" message_id: "123456")` + * + * Rules for HTTP mapping + * + * 1. Leaf request fields (recursive expansion nested messages in the request + * message) are classified into three categories: + * - Fields referred by the path template. They are passed via the URL path. + * - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They + * are passed via the HTTP + * request body. + * - All other fields are passed via the URL query parameters, and the + * parameter name is the field path in the request message. A repeated + * field can be represented as multiple query parameters under the same + * name. + * 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL + * query parameter, all fields + * are passed via URL path and HTTP request body. + * 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP + * request body, all + * fields are passed via URL path and URL query parameters. + * + * Path template syntax + * + * Template = "/" Segments [ Verb ] ; + * Segments = Segment { "/" Segment } ; + * Segment = "*" | "**" | LITERAL | Variable ; + * Variable = "{" FieldPath [ "=" Segments ] "}" ; + * FieldPath = IDENT { "." IDENT } ; + * Verb = ":" LITERAL ; + * + * The syntax `*` matches a single URL path segment. The syntax `**` matches + * zero or more URL path segments, which must be the last part of the URL path + * except the `Verb`. + * + * The syntax `Variable` matches part of the URL path as specified by its + * template. A variable template must not contain other variables. If a variable + * matches a single path segment, its template may be omitted, e.g. `{var}` + * is equivalent to `{var=*}`. + * + * The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL` + * contains any reserved character, such characters should be percent-encoded + * before the matching. + * + * If a variable contains exactly one path segment, such as `"{var}"` or + * `"{var=*}"`, when such a variable is expanded into a URL path on the client + * side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The + * server side does the reverse decoding. Such variables show up in the + * [Discovery + * Document](https://developers.google.com/discovery/v1/reference/apis) as + * `{var}`. + * + * If a variable contains multiple path segments, such as `"{var=foo/*}"` + * or `"{var=**}"`, when such a variable is expanded into a URL path on the + * client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. + * The server side does the reverse decoding, except "%2F" and "%2f" are left + * unchanged. Such variables show up in the + * [Discovery + * Document](https://developers.google.com/discovery/v1/reference/apis) as + * `{+var}`. + * + * Using gRPC API Service Configuration + * + * gRPC API Service Configuration (service config) is a configuration language + * for configuring a gRPC service to become a user-facing product. The + * service config is simply the YAML representation of the `google.api.Service` + * proto message. + * + * As an alternative to annotating your proto file, you can configure gRPC + * transcoding in your service config YAML files. You do this by specifying a + * `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same + * effect as the proto annotation. This can be particularly useful if you + * have a proto that is reused in multiple services. Note that any transcoding + * specified in the service config will override any matching transcoding + * configuration in the proto. + * + * The following example selects a gRPC method and applies an `HttpRule` to it: + * + * http: + * rules: + * - selector: example.v1.Messaging.GetMessage + * get: /v1/messages/{message_id}/{sub.subfield} + * + * Special notes + * + * When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the + * proto to JSON conversion must follow the [proto3 + * specification](https://developers.google.com/protocol-buffers/docs/proto3#json). + * + * While the single segment variable follows the semantics of + * [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String + * Expansion, the multi segment variable **does not** follow RFC 6570 Section + * 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion + * does not expand special characters like `?` and `#`, which would lead + * to invalid URLs. As the result, gRPC Transcoding uses a custom encoding + * for multi segment variables. + * + * The path variables **must not** refer to any repeated or mapped field, + * because client libraries are not capable of handling such variable expansion. + * + * The path variables **must not** capture the leading "/" character. The reason + * is that the most common use case "{var}" does not capture the leading "/" + * character. For consistency, all path variables must share the same behavior. + * + * Repeated message fields must not be mapped to URL query parameters, because + * no client library can support such complicated mapping. + * + * If an API needs to use a JSON array for request or response body, it can map + * the request or response body to a repeated field. However, some gRPC + * Transcoding implementations may not support this feature. + */ +export interface HttpRule { + /** + * Selects a method to which this rule applies. + * + * Refer to [selector][google.api.DocumentationRule.selector] for syntax + * details. + */ + selector: string; + /** + * Maps to HTTP GET. Used for listing and getting information about + * resources. + */ + get?: + | string + | undefined; + /** Maps to HTTP PUT. Used for replacing a resource. */ + put?: + | string + | undefined; + /** Maps to HTTP POST. Used for creating a resource or performing an action. */ + post?: + | string + | undefined; + /** Maps to HTTP DELETE. Used for deleting a resource. */ + delete?: + | string + | undefined; + /** Maps to HTTP PATCH. Used for updating a resource. */ + patch?: + | string + | undefined; + /** + * The custom pattern is used for specifying an HTTP method that is not + * included in the `pattern` field, such as HEAD, or "*" to leave the + * HTTP method unspecified for this rule. The wild-card rule is useful + * for services that provide content to Web (HTML) clients. + */ + custom?: + | CustomHttpPattern + | undefined; + /** + * The name of the request field whose value is mapped to the HTTP request + * body, or `*` for mapping all request fields not captured by the path + * pattern to the HTTP body, or omitted for not having any HTTP request body. + * + * NOTE: the referred field must be present at the top-level of the request + * message type. + */ + body: string; + /** + * Optional. The name of the response field whose value is mapped to the HTTP + * response body. When omitted, the entire response message will be used + * as the HTTP response body. + * + * NOTE: The referred field must be present at the top-level of the response + * message type. + */ + responseBody: string; + /** + * Additional HTTP bindings for the selector. Nested bindings must + * not contain an `additional_bindings` field themselves (that is, + * the nesting may only be one level deep). + */ + additionalBindings: HttpRule[]; + _unknownFields?: { [key: number]: Uint8Array[] } | undefined; +} + +/** A custom pattern is used for defining custom HTTP verb. */ +export interface CustomHttpPattern { + /** The name of this custom HTTP verb. */ + kind: string; + /** The path matched by this custom verb. */ + path: string; + _unknownFields?: { [key: number]: Uint8Array[] } | undefined; +} + +function createBaseHttp(): Http { + return { rules: [], fullyDecodeReservedExpansion: false }; +} + +export const Http = { + encode(message: Http, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + for (const v of message.rules) { + HttpRule.encode(v!, writer.uint32(10).fork()).ldelim(); + } + if (message.fullyDecodeReservedExpansion !== false) { + writer.uint32(16).bool(message.fullyDecodeReservedExpansion); + } + if (message._unknownFields !== undefined) { + for (const [key, values] of Object.entries(message._unknownFields)) { + const tag = parseInt(key, 10); + for (const value of values) { + writer.uint32(tag); + (writer as any)["_push"]( + (val: Uint8Array, buf: Buffer, pos: number) => buf.set(val, pos), + value.length, + value, + ); + } + } + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): Http { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = Object.create(createBaseHttp()) as Http; + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.rules.push(HttpRule.decode(reader, reader.uint32())); + continue; + case 2: + if (tag !== 16) { + break; + } + + message.fullyDecodeReservedExpansion = reader.bool(); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + const startPos = reader.pos; + reader.skipType(tag & 7); + const buf = reader.buf.slice(startPos, reader.pos); + + if (message._unknownFields === undefined) { + message._unknownFields = {}; + } + + const list = message._unknownFields[tag]; + + if (list === undefined) { + message._unknownFields[tag] = [buf]; + } else { + list.push(buf); + } + } + return message; + }, + + fromJSON(object: any): Http { + return { + rules: globalThis.Array.isArray(object?.rules) ? object.rules.map((e: any) => HttpRule.fromJSON(e)) : [], + fullyDecodeReservedExpansion: isSet(object.fullyDecodeReservedExpansion) + ? globalThis.Boolean(object.fullyDecodeReservedExpansion) + : false, + }; + }, + + toJSON(message: Http): unknown { + const obj: any = {}; + if (message.rules?.length) { + obj.rules = message.rules.map((e) => HttpRule.toJSON(e)); + } + if (message.fullyDecodeReservedExpansion !== false) { + obj.fullyDecodeReservedExpansion = message.fullyDecodeReservedExpansion; + } + return obj; + }, + + create(base?: DeepPartial): Http { + return Http.fromPartial(base ?? {}); + }, + fromPartial(object: DeepPartial): Http { + const message = Object.create(createBaseHttp()) as Http; + message.rules = object.rules?.map((e) => HttpRule.fromPartial(e)) || []; + message.fullyDecodeReservedExpansion = object.fullyDecodeReservedExpansion ?? false; + return message; + }, +}; + +function createBaseHttpRule(): HttpRule { + return { selector: "", body: "", responseBody: "", additionalBindings: [] }; +} + +export const HttpRule = { + encode(message: HttpRule, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.selector !== "") { + writer.uint32(10).string(message.selector); + } + if (message.get !== undefined) { + writer.uint32(18).string(message.get); + } + if (message.put !== undefined) { + writer.uint32(26).string(message.put); + } + if (message.post !== undefined) { + writer.uint32(34).string(message.post); + } + if (message.delete !== undefined) { + writer.uint32(42).string(message.delete); + } + if (message.patch !== undefined) { + writer.uint32(50).string(message.patch); + } + if (message.custom !== undefined) { + CustomHttpPattern.encode(message.custom, writer.uint32(66).fork()).ldelim(); + } + if (message.body !== "") { + writer.uint32(58).string(message.body); + } + if (message.responseBody !== "") { + writer.uint32(98).string(message.responseBody); + } + for (const v of message.additionalBindings) { + HttpRule.encode(v!, writer.uint32(90).fork()).ldelim(); + } + if (message._unknownFields !== undefined) { + for (const [key, values] of Object.entries(message._unknownFields)) { + const tag = parseInt(key, 10); + for (const value of values) { + writer.uint32(tag); + (writer as any)["_push"]( + (val: Uint8Array, buf: Buffer, pos: number) => buf.set(val, pos), + value.length, + value, + ); + } + } + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): HttpRule { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = Object.create(createBaseHttpRule()) as HttpRule; + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.selector = reader.string(); + continue; + case 2: + if (tag !== 18) { + break; + } + + message.get = reader.string(); + continue; + case 3: + if (tag !== 26) { + break; + } + + message.put = reader.string(); + continue; + case 4: + if (tag !== 34) { + break; + } + + message.post = reader.string(); + continue; + case 5: + if (tag !== 42) { + break; + } + + message.delete = reader.string(); + continue; + case 6: + if (tag !== 50) { + break; + } + + message.patch = reader.string(); + continue; + case 8: + if (tag !== 66) { + break; + } + + message.custom = CustomHttpPattern.decode(reader, reader.uint32()); + continue; + case 7: + if (tag !== 58) { + break; + } + + message.body = reader.string(); + continue; + case 12: + if (tag !== 98) { + break; + } + + message.responseBody = reader.string(); + continue; + case 11: + if (tag !== 90) { + break; + } + + message.additionalBindings.push(HttpRule.decode(reader, reader.uint32())); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + const startPos = reader.pos; + reader.skipType(tag & 7); + const buf = reader.buf.slice(startPos, reader.pos); + + if (message._unknownFields === undefined) { + message._unknownFields = {}; + } + + const list = message._unknownFields[tag]; + + if (list === undefined) { + message._unknownFields[tag] = [buf]; + } else { + list.push(buf); + } + } + return message; + }, + + fromJSON(object: any): HttpRule { + return { + selector: isSet(object.selector) ? globalThis.String(object.selector) : "", + get: isSet(object.get) ? globalThis.String(object.get) : undefined, + put: isSet(object.put) ? globalThis.String(object.put) : undefined, + post: isSet(object.post) ? globalThis.String(object.post) : undefined, + delete: isSet(object.delete) ? globalThis.String(object.delete) : undefined, + patch: isSet(object.patch) ? globalThis.String(object.patch) : undefined, + custom: isSet(object.custom) ? CustomHttpPattern.fromJSON(object.custom) : undefined, + body: isSet(object.body) ? globalThis.String(object.body) : "", + responseBody: isSet(object.responseBody) ? globalThis.String(object.responseBody) : "", + additionalBindings: globalThis.Array.isArray(object?.additionalBindings) + ? object.additionalBindings.map((e: any) => HttpRule.fromJSON(e)) + : [], + }; + }, + + toJSON(message: HttpRule): unknown { + const obj: any = {}; + if (message.selector !== "") { + obj.selector = message.selector; + } + if (message.get !== undefined) { + obj.get = message.get; + } + if (message.put !== undefined) { + obj.put = message.put; + } + if (message.post !== undefined) { + obj.post = message.post; + } + if (message.delete !== undefined) { + obj.delete = message.delete; + } + if (message.patch !== undefined) { + obj.patch = message.patch; + } + if (message.custom !== undefined) { + obj.custom = CustomHttpPattern.toJSON(message.custom); + } + if (message.body !== "") { + obj.body = message.body; + } + if (message.responseBody !== "") { + obj.responseBody = message.responseBody; + } + if (message.additionalBindings?.length) { + obj.additionalBindings = message.additionalBindings.map((e) => HttpRule.toJSON(e)); + } + return obj; + }, + + create(base?: DeepPartial): HttpRule { + return HttpRule.fromPartial(base ?? {}); + }, + fromPartial(object: DeepPartial): HttpRule { + const message = Object.create(createBaseHttpRule()) as HttpRule; + message.selector = object.selector ?? ""; + message.get = object.get ?? undefined; + message.put = object.put ?? undefined; + message.post = object.post ?? undefined; + message.delete = object.delete ?? undefined; + message.patch = object.patch ?? undefined; + message.custom = (object.custom !== undefined && object.custom !== null) + ? CustomHttpPattern.fromPartial(object.custom) + : undefined; + message.body = object.body ?? ""; + message.responseBody = object.responseBody ?? ""; + message.additionalBindings = object.additionalBindings?.map((e) => HttpRule.fromPartial(e)) || []; + return message; + }, +}; + +function createBaseCustomHttpPattern(): CustomHttpPattern { + return { kind: "", path: "" }; +} + +export const CustomHttpPattern = { + encode(message: CustomHttpPattern, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.kind !== "") { + writer.uint32(10).string(message.kind); + } + if (message.path !== "") { + writer.uint32(18).string(message.path); + } + if (message._unknownFields !== undefined) { + for (const [key, values] of Object.entries(message._unknownFields)) { + const tag = parseInt(key, 10); + for (const value of values) { + writer.uint32(tag); + (writer as any)["_push"]( + (val: Uint8Array, buf: Buffer, pos: number) => buf.set(val, pos), + value.length, + value, + ); + } + } + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): CustomHttpPattern { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = Object.create(createBaseCustomHttpPattern()) as CustomHttpPattern; + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.kind = reader.string(); + continue; + case 2: + if (tag !== 18) { + break; + } + + message.path = reader.string(); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + const startPos = reader.pos; + reader.skipType(tag & 7); + const buf = reader.buf.slice(startPos, reader.pos); + + if (message._unknownFields === undefined) { + message._unknownFields = {}; + } + + const list = message._unknownFields[tag]; + + if (list === undefined) { + message._unknownFields[tag] = [buf]; + } else { + list.push(buf); + } + } + return message; + }, + + fromJSON(object: any): CustomHttpPattern { + return { + kind: isSet(object.kind) ? globalThis.String(object.kind) : "", + path: isSet(object.path) ? globalThis.String(object.path) : "", + }; + }, + + toJSON(message: CustomHttpPattern): unknown { + const obj: any = {}; + if (message.kind !== "") { + obj.kind = message.kind; + } + if (message.path !== "") { + obj.path = message.path; + } + return obj; + }, + + create(base?: DeepPartial): CustomHttpPattern { + return CustomHttpPattern.fromPartial(base ?? {}); + }, + fromPartial(object: DeepPartial): CustomHttpPattern { + const message = Object.create(createBaseCustomHttpPattern()) as CustomHttpPattern; + message.kind = object.kind ?? ""; + message.path = object.path ?? ""; + return message; + }, +}; + +type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined; + +type DeepPartial = T extends Builtin ? T + : T extends globalThis.Array ? globalThis.Array> + : T extends ReadonlyArray ? ReadonlyArray> + : T extends {} ? { [K in keyof T]?: DeepPartial } + : Partial; + +function isSet(value: any): boolean { + return value !== null && value !== undefined; +} diff --git a/protos/google/protobuf/compiler/plugin.ts b/protos/google/protobuf/compiler/plugin.ts index aed0b6eaf..635ff9e27 100644 --- a/protos/google/protobuf/compiler/plugin.ts +++ b/protos/google/protobuf/compiler/plugin.ts @@ -1,7 +1,7 @@ // Code generated by protoc-gen-ts_proto. DO NOT EDIT. // versions: // protoc-gen-ts_proto v1.175.1 -// protoc v3.21.12 +// protoc v5.26.1 // source: google/protobuf/compiler/plugin.proto /* eslint-disable */ diff --git a/protos/google/protobuf/descriptor.ts b/protos/google/protobuf/descriptor.ts index 5795cf7b0..c867983af 100644 --- a/protos/google/protobuf/descriptor.ts +++ b/protos/google/protobuf/descriptor.ts @@ -1,12 +1,13 @@ // Code generated by protoc-gen-ts_proto. DO NOT EDIT. // versions: // protoc-gen-ts_proto v1.175.1 -// protoc v3.21.12 +// protoc v5.26.1 // source: google/protobuf/descriptor.proto /* eslint-disable */ import Long from "long"; import _m0 from "protobufjs/minimal"; +import { HttpRule } from "../api/http"; /** * The protocol compiler can output a FileDescriptorSet containing the .proto @@ -883,6 +884,7 @@ export interface ServiceOptions { } export interface MethodOptions { + httpRule?: HttpRule; /** * Is this method deprecated? * Depending on the target platform, this can emit Deprecated annotations @@ -4776,6 +4778,13 @@ export const MethodOptions = { message.idempotencyLevel = reader.int32() as any; continue; + case 72295728: + if (tag !== 578365826) { + break; + } + + message.httpRule = HttpRule.decode(reader, reader.uint32()); + continue; case 999: if (tag !== 7994) { break; diff --git a/src/context.ts b/src/context.ts index 36a22d743..f0045a70c 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,15 +1,13 @@ import { TypeMap } from "./types"; import { Utils } from "./main"; import { Options } from "./options"; -import { FileDescriptorProto as TsProtoFileDescriptorProto } from "ts-proto-descriptors"; -import { FileDescriptorProto as GoogleFileDescriptorProto } from "google-protobuf/google/protobuf/descriptor_pb"; +import { FileDescriptorProto } from "ts-proto-descriptors"; /** Provides a parameter object for passing around the various context/config data. */ export interface BaseContext { options: Options; typeMap: TypeMap; utils: Utils; - fileDescriptorProtoMap?: Record; } export interface Context extends BaseContext { @@ -20,6 +18,6 @@ export interface FileContext { isProto3Syntax: boolean; } -export function createFileContext(file: TsProtoFileDescriptorProto) { +export function createFileContext(file: FileDescriptorProto) { return { isProto3Syntax: file.syntax === "proto3" }; } diff --git a/src/generate-http.ts b/src/generate-http.ts index 87395902e..32c3ddd63 100644 --- a/src/generate-http.ts +++ b/src/generate-http.ts @@ -1,27 +1,21 @@ -import { FileDescriptorProto, ServiceDescriptorProto } from "ts-proto-descriptors"; +import { FileDescriptorProto, ServiceDescriptorProto, MethodOptions } from "ts-proto-descriptors"; import { Code, code, joinCode } from "ts-poet"; import { requestType, responseType } from "./types"; import SourceInfo from "./sourceInfo"; import { assertInstanceOf, FormattedMethodDescriptor } from "./utils"; import { Context } from "./context"; -interface HTTPRule { - get: string; - put: string; - post: string; - pb_delete: string; - patch: string; - option: string; - body: "*" | string; -} +function findHttpRule(httpRule: MethodOptions["httpRule"]) { + if (!httpRule) { + return; + } -function mapHTTPOptions(http: HTTPRule) { - for (const method of ["get", "post", "put", "pb_delete", "patch", "option"] as const) { - if (http[method]) { + for (const method of ["get", "post", "put", "delete", "patch"] as const) { + if (httpRule[method]) { return { - method: method === "pb_delete" ? "delete" : method, - path: http[method], - body: http.body, + method: method, + path: httpRule[method], + body: httpRule.body, }; } } @@ -29,49 +23,42 @@ function mapHTTPOptions(http: HTTPRule) { export function generateHttpService( ctx: Context, - fileDesc: FileDescriptorProto, + _fileDesc: FileDescriptorProto, _sourceInfo: SourceInfo, serviceDesc: ServiceDescriptorProto, ): Code { const chunks: Code[] = []; - const methodList = ctx.fileDescriptorProtoMap![fileDesc.name].toObject().serviceList.find((service) => { - return service.name === serviceDesc.name; - })?.methodList; + const httpRules: Record | undefined> = {}; + let hasHttpRule = false; - const httpOptions: Record | undefined> = {}; - let hasHttpOptions = false; + serviceDesc.method.forEach((methodDesc) => { + const httpRule = findHttpRule(methodDesc.options?.httpRule); - if (methodList) { - serviceDesc.method.forEach((methodDesc, i) => { - const http = (methodList[i]?.options as { http?: HTTPRule } | undefined)?.http as HTTPRule | undefined; - const httpOption = http ? mapHTTPOptions(http) : undefined; - - if (httpOption) { - hasHttpOptions = true; - assertInstanceOf(methodDesc, FormattedMethodDescriptor); - httpOptions[methodDesc.formattedName] = httpOption; - } - }); - } + if (httpRule) { + hasHttpRule = true; + assertInstanceOf(methodDesc, FormattedMethodDescriptor); + httpRules[methodDesc.formattedName] = httpRule; + } + }); - if (hasHttpOptions) { + if (hasHttpRule) { chunks.push(code` export const ${serviceDesc.name} = { `); serviceDesc.method.forEach((methodDesc) => { assertInstanceOf(methodDesc, FormattedMethodDescriptor); - const httpMethod = httpOptions[methodDesc.formattedName]; + const httpRule = httpRules[methodDesc.formattedName]; - if (!httpMethod) { + if (!httpRule) { return; } chunks.push(code` ${methodDesc.formattedName}: { - path: "${httpMethod.path}", - method: "${httpMethod.method}",${httpMethod.body ? `\nbody: "${httpMethod.body}",` : ""} + path: "${httpRule.path}", + method: "${httpRule.method}",${httpRule.body ? `\nbody: "${httpRule.body}",` : ""} requestType: undefined as unknown as ${requestType(ctx, methodDesc)}, responseType: undefined as unknown as ${responseType(ctx, methodDesc)}, }, diff --git a/src/google-protobuf.ts b/src/google-protobuf.ts deleted file mode 100644 index 3a1ab3026..000000000 --- a/src/google-protobuf.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { CodeGeneratorRequest } from "google-protobuf/google/protobuf/compiler/plugin_pb"; -require("../vendor/google/api/annotations_pb"); diff --git a/src/plugin.ts b/src/plugin.ts index 1226e8984..e0df00540 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -24,21 +24,7 @@ async function main() { const options = optionsFromParameter(request.parameter); const typeMap = createTypeMap(request, options); const utils = makeUtils(options); - let fileDescriptorProtoMap: BaseContext["fileDescriptorProtoMap"] = undefined; - - if (options.http) { - const input = new Uint8Array(stdin.length); - input.set(stdin); - fileDescriptorProtoMap = {}; - const PluginPb = await import("./google-protobuf"); - PluginPb.CodeGeneratorRequest.deserializeBinary(input) - .getProtoFileList() - .forEach((descriptor) => { - fileDescriptorProtoMap![descriptor.getName()!] = descriptor; - }); - } - - const ctx: BaseContext = { typeMap, options, utils, fileDescriptorProtoMap }; + const ctx: BaseContext = { typeMap, options, utils }; let filesToGenerate: FileDescriptorProto[]; @@ -72,7 +58,7 @@ async function main() { if (options.outputTypeRegistry) { const utils = makeUtils(options); - const ctx: BaseContext = { options, typeMap, utils, fileDescriptorProtoMap }; + const ctx: BaseContext = { options, typeMap, utils }; const path = "typeRegistry.ts"; const code = generateTypeRegistry(ctx); diff --git a/vendor/google/api/annotations_pb.js b/vendor/google/api/annotations_pb.js deleted file mode 100644 index 53c05ed02..000000000 --- a/vendor/google/api/annotations_pb.js +++ /dev/null @@ -1,54 +0,0 @@ -// source: google/api/annotations.proto -/** - * @fileoverview - * @enhanceable - * @suppress {missingRequire} reports error on implicit type usages. - * @suppress {messageConventions} JS Compiler reports an error if a variable or - * field starts with 'MSG_' and isn't a translatable message. - * @public - */ -// GENERATED CODE -- DO NOT EDIT! -/* eslint-disable */ -// @ts-nocheck - -var jspb = require('google-protobuf'); -var goog = jspb; -var global = - (typeof globalThis !== 'undefined' && globalThis) || - (typeof window !== 'undefined' && window) || - (typeof global !== 'undefined' && global) || - (typeof self !== 'undefined' && self) || - (function () { return this; }).call(null) || - Function('return this')(); - -var google_api_http_pb = require('../../google/api/http_pb.js'); -goog.object.extend(proto, google_api_http_pb); -var google_protobuf_descriptor_pb = require('google-protobuf/google/protobuf/descriptor_pb.js'); -goog.object.extend(proto, google_protobuf_descriptor_pb); -goog.exportSymbol('proto.google.api.http', null, global); - -/** - * A tuple of {field number, class constructor} for the extension - * field named `http`. - * @type {!jspb.ExtensionFieldInfo} - */ -proto.google.api.http = new jspb.ExtensionFieldInfo( - 72295728, - {http: 0}, - google_api_http_pb.HttpRule, - /** @type {?function((boolean|undefined),!jspb.Message=): !Object} */ ( - google_api_http_pb.HttpRule.toObject), - 0); - -google_protobuf_descriptor_pb.MethodOptions.extensionsBinary[72295728] = new jspb.ExtensionFieldBinaryInfo( - proto.google.api.http, - jspb.BinaryReader.prototype.readMessage, - jspb.BinaryWriter.prototype.writeMessage, - google_api_http_pb.HttpRule.serializeBinaryToWriter, - google_api_http_pb.HttpRule.deserializeBinaryFromReader, - false); -// This registers the extension field with the extended class, so that -// toObject() will function correctly. -google_protobuf_descriptor_pb.MethodOptions.extensions[72295728] = proto.google.api.http; - -goog.object.extend(exports, proto.google.api); diff --git a/vendor/google/api/http_pb.js b/vendor/google/api/http_pb.js deleted file mode 100644 index 9fc6ee730..000000000 --- a/vendor/google/api/http_pb.js +++ /dev/null @@ -1,1012 +0,0 @@ -// source: google/api/http.proto -/** - * @fileoverview - * @enhanceable - * @suppress {missingRequire} reports error on implicit type usages. - * @suppress {messageConventions} JS Compiler reports an error if a variable or - * field starts with 'MSG_' and isn't a translatable message. - * @public - */ -// GENERATED CODE -- DO NOT EDIT! -/* eslint-disable */ -// @ts-nocheck - -var jspb = require('google-protobuf'); -var goog = jspb; -var global = - (typeof globalThis !== 'undefined' && globalThis) || - (typeof window !== 'undefined' && window) || - (typeof global !== 'undefined' && global) || - (typeof self !== 'undefined' && self) || - (function () { return this; }).call(null) || - Function('return this')(); - -goog.exportSymbol('proto.google.api.CustomHttpPattern', null, global); -goog.exportSymbol('proto.google.api.Http', null, global); -goog.exportSymbol('proto.google.api.HttpRule', null, global); -goog.exportSymbol('proto.google.api.HttpRule.PatternCase', null, global); -/** - * Generated by JsPbCodeGenerator. - * @param {Array=} opt_data Optional initial data array, typically from a - * server response, or constructed directly in Javascript. The array is used - * in place and becomes part of the constructed object. It is not cloned. - * If no data is provided, the constructed object will be empty, but still - * valid. - * @extends {jspb.Message} - * @constructor - */ -proto.google.api.Http = function(opt_data) { - jspb.Message.initialize(this, opt_data, 0, -1, proto.google.api.Http.repeatedFields_, null); -}; -goog.inherits(proto.google.api.Http, jspb.Message); -if (goog.DEBUG && !COMPILED) { - /** - * @public - * @override - */ - proto.google.api.Http.displayName = 'proto.google.api.Http'; -} -/** - * Generated by JsPbCodeGenerator. - * @param {Array=} opt_data Optional initial data array, typically from a - * server response, or constructed directly in Javascript. The array is used - * in place and becomes part of the constructed object. It is not cloned. - * If no data is provided, the constructed object will be empty, but still - * valid. - * @extends {jspb.Message} - * @constructor - */ -proto.google.api.HttpRule = function(opt_data) { - jspb.Message.initialize(this, opt_data, 0, -1, proto.google.api.HttpRule.repeatedFields_, proto.google.api.HttpRule.oneofGroups_); -}; -goog.inherits(proto.google.api.HttpRule, jspb.Message); -if (goog.DEBUG && !COMPILED) { - /** - * @public - * @override - */ - proto.google.api.HttpRule.displayName = 'proto.google.api.HttpRule'; -} -/** - * Generated by JsPbCodeGenerator. - * @param {Array=} opt_data Optional initial data array, typically from a - * server response, or constructed directly in Javascript. The array is used - * in place and becomes part of the constructed object. It is not cloned. - * If no data is provided, the constructed object will be empty, but still - * valid. - * @extends {jspb.Message} - * @constructor - */ -proto.google.api.CustomHttpPattern = function(opt_data) { - jspb.Message.initialize(this, opt_data, 0, -1, null, null); -}; -goog.inherits(proto.google.api.CustomHttpPattern, jspb.Message); -if (goog.DEBUG && !COMPILED) { - /** - * @public - * @override - */ - proto.google.api.CustomHttpPattern.displayName = 'proto.google.api.CustomHttpPattern'; -} - -/** - * List of repeated fields within this message type. - * @private {!Array} - * @const - */ -proto.google.api.Http.repeatedFields_ = [1]; - - - -if (jspb.Message.GENERATE_TO_OBJECT) { -/** - * Creates an object representation of this proto. - * Field names that are reserved in JavaScript and will be renamed to pb_name. - * Optional fields that are not set will be set to undefined. - * To access a reserved field use, foo.pb_, eg, foo.pb_default. - * For the list of reserved names please see: - * net/proto2/compiler/js/internal/generator.cc#kKeyword. - * @param {boolean=} opt_includeInstance Deprecated. whether to include the - * JSPB instance for transitional soy proto support: - * http://goto/soy-param-migration - * @return {!Object} - */ -proto.google.api.Http.prototype.toObject = function(opt_includeInstance) { - return proto.google.api.Http.toObject(opt_includeInstance, this); -}; - - -/** - * Static version of the {@see toObject} method. - * @param {boolean|undefined} includeInstance Deprecated. Whether to include - * the JSPB instance for transitional soy proto support: - * http://goto/soy-param-migration - * @param {!proto.google.api.Http} msg The msg instance to transform. - * @return {!Object} - * @suppress {unusedLocalVariables} f is only used for nested messages - */ -proto.google.api.Http.toObject = function(includeInstance, msg) { - var f, obj = { - rulesList: jspb.Message.toObjectList(msg.getRulesList(), - proto.google.api.HttpRule.toObject, includeInstance), - fullyDecodeReservedExpansion: jspb.Message.getBooleanFieldWithDefault(msg, 2, false) - }; - - if (includeInstance) { - obj.$jspbMessageInstance = msg; - } - return obj; -}; -} - - -/** - * Deserializes binary data (in protobuf wire format). - * @param {jspb.ByteSource} bytes The bytes to deserialize. - * @return {!proto.google.api.Http} - */ -proto.google.api.Http.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.google.api.Http; - return proto.google.api.Http.deserializeBinaryFromReader(msg, reader); -}; - - -/** - * Deserializes binary data (in protobuf wire format) from the - * given reader into the given message object. - * @param {!proto.google.api.Http} msg The message object to deserialize into. - * @param {!jspb.BinaryReader} reader The BinaryReader to use. - * @return {!proto.google.api.Http} - */ -proto.google.api.Http.deserializeBinaryFromReader = function(msg, reader) { - while (reader.nextField()) { - if (reader.isEndGroup()) { - break; - } - var field = reader.getFieldNumber(); - switch (field) { - case 1: - var value = new proto.google.api.HttpRule; - reader.readMessage(value,proto.google.api.HttpRule.deserializeBinaryFromReader); - msg.addRules(value); - break; - case 2: - var value = /** @type {boolean} */ (reader.readBool()); - msg.setFullyDecodeReservedExpansion(value); - break; - default: - reader.skipField(); - break; - } - } - return msg; -}; - - -/** - * Serializes the message to binary data (in protobuf wire format). - * @return {!Uint8Array} - */ -proto.google.api.Http.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); - proto.google.api.Http.serializeBinaryToWriter(this, writer); - return writer.getResultBuffer(); -}; - - -/** - * Serializes the given message to binary data (in protobuf wire - * format), writing to the given BinaryWriter. - * @param {!proto.google.api.Http} message - * @param {!jspb.BinaryWriter} writer - * @suppress {unusedLocalVariables} f is only used for nested messages - */ -proto.google.api.Http.serializeBinaryToWriter = function(message, writer) { - var f = undefined; - f = message.getRulesList(); - if (f.length > 0) { - writer.writeRepeatedMessage( - 1, - f, - proto.google.api.HttpRule.serializeBinaryToWriter - ); - } - f = message.getFullyDecodeReservedExpansion(); - if (f) { - writer.writeBool( - 2, - f - ); - } -}; - - -/** - * repeated HttpRule rules = 1; - * @return {!Array} - */ -proto.google.api.Http.prototype.getRulesList = function() { - return /** @type{!Array} */ ( - jspb.Message.getRepeatedWrapperField(this, proto.google.api.HttpRule, 1)); -}; - - -/** - * @param {!Array} value - * @return {!proto.google.api.Http} returns this -*/ -proto.google.api.Http.prototype.setRulesList = function(value) { - return jspb.Message.setRepeatedWrapperField(this, 1, value); -}; - - -/** - * @param {!proto.google.api.HttpRule=} opt_value - * @param {number=} opt_index - * @return {!proto.google.api.HttpRule} - */ -proto.google.api.Http.prototype.addRules = function(opt_value, opt_index) { - return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.google.api.HttpRule, opt_index); -}; - - -/** - * Clears the list making it empty but non-null. - * @return {!proto.google.api.Http} returns this - */ -proto.google.api.Http.prototype.clearRulesList = function() { - return this.setRulesList([]); -}; - - -/** - * optional bool fully_decode_reserved_expansion = 2; - * @return {boolean} - */ -proto.google.api.Http.prototype.getFullyDecodeReservedExpansion = function() { - return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false)); -}; - - -/** - * @param {boolean} value - * @return {!proto.google.api.Http} returns this - */ -proto.google.api.Http.prototype.setFullyDecodeReservedExpansion = function(value) { - return jspb.Message.setProto3BooleanField(this, 2, value); -}; - - - -/** - * List of repeated fields within this message type. - * @private {!Array} - * @const - */ -proto.google.api.HttpRule.repeatedFields_ = [11]; - -/** - * Oneof group definitions for this message. Each group defines the field - * numbers belonging to that group. When of these fields' value is set, all - * other fields in the group are cleared. During deserialization, if multiple - * fields are encountered for a group, only the last value seen will be kept. - * @private {!Array>} - * @const - */ -proto.google.api.HttpRule.oneofGroups_ = [[2,3,4,5,6,8]]; - -/** - * @enum {number} - */ -proto.google.api.HttpRule.PatternCase = { - PATTERN_NOT_SET: 0, - GET: 2, - PUT: 3, - POST: 4, - DELETE: 5, - PATCH: 6, - CUSTOM: 8 -}; - -/** - * @return {proto.google.api.HttpRule.PatternCase} - */ -proto.google.api.HttpRule.prototype.getPatternCase = function() { - return /** @type {proto.google.api.HttpRule.PatternCase} */(jspb.Message.computeOneofCase(this, proto.google.api.HttpRule.oneofGroups_[0])); -}; - - - -if (jspb.Message.GENERATE_TO_OBJECT) { -/** - * Creates an object representation of this proto. - * Field names that are reserved in JavaScript and will be renamed to pb_name. - * Optional fields that are not set will be set to undefined. - * To access a reserved field use, foo.pb_, eg, foo.pb_default. - * For the list of reserved names please see: - * net/proto2/compiler/js/internal/generator.cc#kKeyword. - * @param {boolean=} opt_includeInstance Deprecated. whether to include the - * JSPB instance for transitional soy proto support: - * http://goto/soy-param-migration - * @return {!Object} - */ -proto.google.api.HttpRule.prototype.toObject = function(opt_includeInstance) { - return proto.google.api.HttpRule.toObject(opt_includeInstance, this); -}; - - -/** - * Static version of the {@see toObject} method. - * @param {boolean|undefined} includeInstance Deprecated. Whether to include - * the JSPB instance for transitional soy proto support: - * http://goto/soy-param-migration - * @param {!proto.google.api.HttpRule} msg The msg instance to transform. - * @return {!Object} - * @suppress {unusedLocalVariables} f is only used for nested messages - */ -proto.google.api.HttpRule.toObject = function(includeInstance, msg) { - var f, obj = { - selector: jspb.Message.getFieldWithDefault(msg, 1, ""), - get: jspb.Message.getFieldWithDefault(msg, 2, ""), - put: jspb.Message.getFieldWithDefault(msg, 3, ""), - post: jspb.Message.getFieldWithDefault(msg, 4, ""), - pb_delete: jspb.Message.getFieldWithDefault(msg, 5, ""), - patch: jspb.Message.getFieldWithDefault(msg, 6, ""), - custom: (f = msg.getCustom()) && proto.google.api.CustomHttpPattern.toObject(includeInstance, f), - body: jspb.Message.getFieldWithDefault(msg, 7, ""), - responseBody: jspb.Message.getFieldWithDefault(msg, 12, ""), - additionalBindingsList: jspb.Message.toObjectList(msg.getAdditionalBindingsList(), - proto.google.api.HttpRule.toObject, includeInstance) - }; - - if (includeInstance) { - obj.$jspbMessageInstance = msg; - } - return obj; -}; -} - - -/** - * Deserializes binary data (in protobuf wire format). - * @param {jspb.ByteSource} bytes The bytes to deserialize. - * @return {!proto.google.api.HttpRule} - */ -proto.google.api.HttpRule.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.google.api.HttpRule; - return proto.google.api.HttpRule.deserializeBinaryFromReader(msg, reader); -}; - - -/** - * Deserializes binary data (in protobuf wire format) from the - * given reader into the given message object. - * @param {!proto.google.api.HttpRule} msg The message object to deserialize into. - * @param {!jspb.BinaryReader} reader The BinaryReader to use. - * @return {!proto.google.api.HttpRule} - */ -proto.google.api.HttpRule.deserializeBinaryFromReader = function(msg, reader) { - while (reader.nextField()) { - if (reader.isEndGroup()) { - break; - } - var field = reader.getFieldNumber(); - switch (field) { - case 1: - var value = /** @type {string} */ (reader.readString()); - msg.setSelector(value); - break; - case 2: - var value = /** @type {string} */ (reader.readString()); - msg.setGet(value); - break; - case 3: - var value = /** @type {string} */ (reader.readString()); - msg.setPut(value); - break; - case 4: - var value = /** @type {string} */ (reader.readString()); - msg.setPost(value); - break; - case 5: - var value = /** @type {string} */ (reader.readString()); - msg.setDelete(value); - break; - case 6: - var value = /** @type {string} */ (reader.readString()); - msg.setPatch(value); - break; - case 8: - var value = new proto.google.api.CustomHttpPattern; - reader.readMessage(value,proto.google.api.CustomHttpPattern.deserializeBinaryFromReader); - msg.setCustom(value); - break; - case 7: - var value = /** @type {string} */ (reader.readString()); - msg.setBody(value); - break; - case 12: - var value = /** @type {string} */ (reader.readString()); - msg.setResponseBody(value); - break; - case 11: - var value = new proto.google.api.HttpRule; - reader.readMessage(value,proto.google.api.HttpRule.deserializeBinaryFromReader); - msg.addAdditionalBindings(value); - break; - default: - reader.skipField(); - break; - } - } - return msg; -}; - - -/** - * Serializes the message to binary data (in protobuf wire format). - * @return {!Uint8Array} - */ -proto.google.api.HttpRule.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); - proto.google.api.HttpRule.serializeBinaryToWriter(this, writer); - return writer.getResultBuffer(); -}; - - -/** - * Serializes the given message to binary data (in protobuf wire - * format), writing to the given BinaryWriter. - * @param {!proto.google.api.HttpRule} message - * @param {!jspb.BinaryWriter} writer - * @suppress {unusedLocalVariables} f is only used for nested messages - */ -proto.google.api.HttpRule.serializeBinaryToWriter = function(message, writer) { - var f = undefined; - f = message.getSelector(); - if (f.length > 0) { - writer.writeString( - 1, - f - ); - } - f = /** @type {string} */ (jspb.Message.getField(message, 2)); - if (f != null) { - writer.writeString( - 2, - f - ); - } - f = /** @type {string} */ (jspb.Message.getField(message, 3)); - if (f != null) { - writer.writeString( - 3, - f - ); - } - f = /** @type {string} */ (jspb.Message.getField(message, 4)); - if (f != null) { - writer.writeString( - 4, - f - ); - } - f = /** @type {string} */ (jspb.Message.getField(message, 5)); - if (f != null) { - writer.writeString( - 5, - f - ); - } - f = /** @type {string} */ (jspb.Message.getField(message, 6)); - if (f != null) { - writer.writeString( - 6, - f - ); - } - f = message.getCustom(); - if (f != null) { - writer.writeMessage( - 8, - f, - proto.google.api.CustomHttpPattern.serializeBinaryToWriter - ); - } - f = message.getBody(); - if (f.length > 0) { - writer.writeString( - 7, - f - ); - } - f = message.getResponseBody(); - if (f.length > 0) { - writer.writeString( - 12, - f - ); - } - f = message.getAdditionalBindingsList(); - if (f.length > 0) { - writer.writeRepeatedMessage( - 11, - f, - proto.google.api.HttpRule.serializeBinaryToWriter - ); - } -}; - - -/** - * optional string selector = 1; - * @return {string} - */ -proto.google.api.HttpRule.prototype.getSelector = function() { - return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); -}; - - -/** - * @param {string} value - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.setSelector = function(value) { - return jspb.Message.setProto3StringField(this, 1, value); -}; - - -/** - * optional string get = 2; - * @return {string} - */ -proto.google.api.HttpRule.prototype.getGet = function() { - return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); -}; - - -/** - * @param {string} value - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.setGet = function(value) { - return jspb.Message.setOneofField(this, 2, proto.google.api.HttpRule.oneofGroups_[0], value); -}; - - -/** - * Clears the field making it undefined. - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.clearGet = function() { - return jspb.Message.setOneofField(this, 2, proto.google.api.HttpRule.oneofGroups_[0], undefined); -}; - - -/** - * Returns whether this field is set. - * @return {boolean} - */ -proto.google.api.HttpRule.prototype.hasGet = function() { - return jspb.Message.getField(this, 2) != null; -}; - - -/** - * optional string put = 3; - * @return {string} - */ -proto.google.api.HttpRule.prototype.getPut = function() { - return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); -}; - - -/** - * @param {string} value - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.setPut = function(value) { - return jspb.Message.setOneofField(this, 3, proto.google.api.HttpRule.oneofGroups_[0], value); -}; - - -/** - * Clears the field making it undefined. - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.clearPut = function() { - return jspb.Message.setOneofField(this, 3, proto.google.api.HttpRule.oneofGroups_[0], undefined); -}; - - -/** - * Returns whether this field is set. - * @return {boolean} - */ -proto.google.api.HttpRule.prototype.hasPut = function() { - return jspb.Message.getField(this, 3) != null; -}; - - -/** - * optional string post = 4; - * @return {string} - */ -proto.google.api.HttpRule.prototype.getPost = function() { - return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 4, "")); -}; - - -/** - * @param {string} value - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.setPost = function(value) { - return jspb.Message.setOneofField(this, 4, proto.google.api.HttpRule.oneofGroups_[0], value); -}; - - -/** - * Clears the field making it undefined. - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.clearPost = function() { - return jspb.Message.setOneofField(this, 4, proto.google.api.HttpRule.oneofGroups_[0], undefined); -}; - - -/** - * Returns whether this field is set. - * @return {boolean} - */ -proto.google.api.HttpRule.prototype.hasPost = function() { - return jspb.Message.getField(this, 4) != null; -}; - - -/** - * optional string delete = 5; - * @return {string} - */ -proto.google.api.HttpRule.prototype.getDelete = function() { - return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 5, "")); -}; - - -/** - * @param {string} value - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.setDelete = function(value) { - return jspb.Message.setOneofField(this, 5, proto.google.api.HttpRule.oneofGroups_[0], value); -}; - - -/** - * Clears the field making it undefined. - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.clearDelete = function() { - return jspb.Message.setOneofField(this, 5, proto.google.api.HttpRule.oneofGroups_[0], undefined); -}; - - -/** - * Returns whether this field is set. - * @return {boolean} - */ -proto.google.api.HttpRule.prototype.hasDelete = function() { - return jspb.Message.getField(this, 5) != null; -}; - - -/** - * optional string patch = 6; - * @return {string} - */ -proto.google.api.HttpRule.prototype.getPatch = function() { - return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 6, "")); -}; - - -/** - * @param {string} value - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.setPatch = function(value) { - return jspb.Message.setOneofField(this, 6, proto.google.api.HttpRule.oneofGroups_[0], value); -}; - - -/** - * Clears the field making it undefined. - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.clearPatch = function() { - return jspb.Message.setOneofField(this, 6, proto.google.api.HttpRule.oneofGroups_[0], undefined); -}; - - -/** - * Returns whether this field is set. - * @return {boolean} - */ -proto.google.api.HttpRule.prototype.hasPatch = function() { - return jspb.Message.getField(this, 6) != null; -}; - - -/** - * optional CustomHttpPattern custom = 8; - * @return {?proto.google.api.CustomHttpPattern} - */ -proto.google.api.HttpRule.prototype.getCustom = function() { - return /** @type{?proto.google.api.CustomHttpPattern} */ ( - jspb.Message.getWrapperField(this, proto.google.api.CustomHttpPattern, 8)); -}; - - -/** - * @param {?proto.google.api.CustomHttpPattern|undefined} value - * @return {!proto.google.api.HttpRule} returns this -*/ -proto.google.api.HttpRule.prototype.setCustom = function(value) { - return jspb.Message.setOneofWrapperField(this, 8, proto.google.api.HttpRule.oneofGroups_[0], value); -}; - - -/** - * Clears the message field making it undefined. - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.clearCustom = function() { - return this.setCustom(undefined); -}; - - -/** - * Returns whether this field is set. - * @return {boolean} - */ -proto.google.api.HttpRule.prototype.hasCustom = function() { - return jspb.Message.getField(this, 8) != null; -}; - - -/** - * optional string body = 7; - * @return {string} - */ -proto.google.api.HttpRule.prototype.getBody = function() { - return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 7, "")); -}; - - -/** - * @param {string} value - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.setBody = function(value) { - return jspb.Message.setProto3StringField(this, 7, value); -}; - - -/** - * optional string response_body = 12; - * @return {string} - */ -proto.google.api.HttpRule.prototype.getResponseBody = function() { - return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 12, "")); -}; - - -/** - * @param {string} value - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.setResponseBody = function(value) { - return jspb.Message.setProto3StringField(this, 12, value); -}; - - -/** - * repeated HttpRule additional_bindings = 11; - * @return {!Array} - */ -proto.google.api.HttpRule.prototype.getAdditionalBindingsList = function() { - return /** @type{!Array} */ ( - jspb.Message.getRepeatedWrapperField(this, proto.google.api.HttpRule, 11)); -}; - - -/** - * @param {!Array} value - * @return {!proto.google.api.HttpRule} returns this -*/ -proto.google.api.HttpRule.prototype.setAdditionalBindingsList = function(value) { - return jspb.Message.setRepeatedWrapperField(this, 11, value); -}; - - -/** - * @param {!proto.google.api.HttpRule=} opt_value - * @param {number=} opt_index - * @return {!proto.google.api.HttpRule} - */ -proto.google.api.HttpRule.prototype.addAdditionalBindings = function(opt_value, opt_index) { - return jspb.Message.addToRepeatedWrapperField(this, 11, opt_value, proto.google.api.HttpRule, opt_index); -}; - - -/** - * Clears the list making it empty but non-null. - * @return {!proto.google.api.HttpRule} returns this - */ -proto.google.api.HttpRule.prototype.clearAdditionalBindingsList = function() { - return this.setAdditionalBindingsList([]); -}; - - - - - -if (jspb.Message.GENERATE_TO_OBJECT) { -/** - * Creates an object representation of this proto. - * Field names that are reserved in JavaScript and will be renamed to pb_name. - * Optional fields that are not set will be set to undefined. - * To access a reserved field use, foo.pb_, eg, foo.pb_default. - * For the list of reserved names please see: - * net/proto2/compiler/js/internal/generator.cc#kKeyword. - * @param {boolean=} opt_includeInstance Deprecated. whether to include the - * JSPB instance for transitional soy proto support: - * http://goto/soy-param-migration - * @return {!Object} - */ -proto.google.api.CustomHttpPattern.prototype.toObject = function(opt_includeInstance) { - return proto.google.api.CustomHttpPattern.toObject(opt_includeInstance, this); -}; - - -/** - * Static version of the {@see toObject} method. - * @param {boolean|undefined} includeInstance Deprecated. Whether to include - * the JSPB instance for transitional soy proto support: - * http://goto/soy-param-migration - * @param {!proto.google.api.CustomHttpPattern} msg The msg instance to transform. - * @return {!Object} - * @suppress {unusedLocalVariables} f is only used for nested messages - */ -proto.google.api.CustomHttpPattern.toObject = function(includeInstance, msg) { - var f, obj = { - kind: jspb.Message.getFieldWithDefault(msg, 1, ""), - path: jspb.Message.getFieldWithDefault(msg, 2, "") - }; - - if (includeInstance) { - obj.$jspbMessageInstance = msg; - } - return obj; -}; -} - - -/** - * Deserializes binary data (in protobuf wire format). - * @param {jspb.ByteSource} bytes The bytes to deserialize. - * @return {!proto.google.api.CustomHttpPattern} - */ -proto.google.api.CustomHttpPattern.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.google.api.CustomHttpPattern; - return proto.google.api.CustomHttpPattern.deserializeBinaryFromReader(msg, reader); -}; - - -/** - * Deserializes binary data (in protobuf wire format) from the - * given reader into the given message object. - * @param {!proto.google.api.CustomHttpPattern} msg The message object to deserialize into. - * @param {!jspb.BinaryReader} reader The BinaryReader to use. - * @return {!proto.google.api.CustomHttpPattern} - */ -proto.google.api.CustomHttpPattern.deserializeBinaryFromReader = function(msg, reader) { - while (reader.nextField()) { - if (reader.isEndGroup()) { - break; - } - var field = reader.getFieldNumber(); - switch (field) { - case 1: - var value = /** @type {string} */ (reader.readString()); - msg.setKind(value); - break; - case 2: - var value = /** @type {string} */ (reader.readString()); - msg.setPath(value); - break; - default: - reader.skipField(); - break; - } - } - return msg; -}; - - -/** - * Serializes the message to binary data (in protobuf wire format). - * @return {!Uint8Array} - */ -proto.google.api.CustomHttpPattern.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); - proto.google.api.CustomHttpPattern.serializeBinaryToWriter(this, writer); - return writer.getResultBuffer(); -}; - - -/** - * Serializes the given message to binary data (in protobuf wire - * format), writing to the given BinaryWriter. - * @param {!proto.google.api.CustomHttpPattern} message - * @param {!jspb.BinaryWriter} writer - * @suppress {unusedLocalVariables} f is only used for nested messages - */ -proto.google.api.CustomHttpPattern.serializeBinaryToWriter = function(message, writer) { - var f = undefined; - f = message.getKind(); - if (f.length > 0) { - writer.writeString( - 1, - f - ); - } - f = message.getPath(); - if (f.length > 0) { - writer.writeString( - 2, - f - ); - } -}; - - -/** - * optional string kind = 1; - * @return {string} - */ -proto.google.api.CustomHttpPattern.prototype.getKind = function() { - return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); -}; - - -/** - * @param {string} value - * @return {!proto.google.api.CustomHttpPattern} returns this - */ -proto.google.api.CustomHttpPattern.prototype.setKind = function(value) { - return jspb.Message.setProto3StringField(this, 1, value); -}; - - -/** - * optional string path = 2; - * @return {string} - */ -proto.google.api.CustomHttpPattern.prototype.getPath = function() { - return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); -}; - - -/** - * @param {string} value - * @return {!proto.google.api.CustomHttpPattern} returns this - */ -proto.google.api.CustomHttpPattern.prototype.setPath = function(value) { - return jspb.Message.setProto3StringField(this, 2, value); -}; - - -goog.object.extend(exports, proto.google.api); diff --git a/yarn.lock b/yarn.lock index 568252973..99dff097e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1796,13 +1796,6 @@ __metadata: languageName: node linkType: hard -"@types/google-protobuf@npm:^3.15.12": - version: 3.15.12 - resolution: "@types/google-protobuf@npm:3.15.12" - checksum: c64efd268170eac0865a42c9616b05100e5ac07e7fa1ed87c827c9d2a58eb02cb2d01cb3248c7ddd563468ecb079295b81ab966e399ba08858f525896631e961 - languageName: node - linkType: hard - "@types/graceful-fs@npm:^4.1.3": version: 4.1.5 resolution: "@types/graceful-fs@npm:4.1.5" @@ -3829,13 +3822,6 @@ __metadata: languageName: node linkType: hard -"google-protobuf@npm:^3.21.2": - version: 3.21.2 - resolution: "google-protobuf@npm:3.21.2" - checksum: 3caa2e1e2654714cc1a201ac5e5faabcaa48f5fba3d8ff9b64ca66fe19e4e0506b94053f32eddc77bf3a7a47ac1660315c6744185c1e2bb27654fd76fe91b988 - languageName: node - linkType: hard - "graceful-fs@npm:4.2.10": version: 4.2.10 resolution: "graceful-fs@npm:4.2.10" @@ -7879,14 +7865,12 @@ __metadata: "@semantic-release/npm": ^10.0.4 "@semantic-release/release-notes-generator": ^11.0.4 "@tsconfig/strictest": ^2.0.1 - "@types/google-protobuf": ^3.15.12 "@types/jest": ^29.5.3 "@types/node": ^16.18.38 "@types/object-hash": ^3.0.2 case-anything: ^2.1.13 chokidar: ^3.5.3 dataloader: ^2.2.2 - google-protobuf: ^3.21.2 jest: ^29.6.1 jest-ts-webcompat-resolver: ^1.0.0 mongodb: ^5.7.0 From b1f61da02ba1b6e7973e9e99afbf0688c5f53176 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Wed, 24 Jul 2024 13:18:02 +0900 Subject: [PATCH 10/20] Make generic-definitions support http --- README.markdown | 4 - .../google-api-http-test.ts} | 8 +- .../google/api/annotations.proto | 0 .../google/api/annotations.ts | 0 .../google/api/http.proto | 0 .../google/api/http.ts | 0 .../google/protobuf/descriptor.proto | 0 .../google/protobuf/descriptor.ts | 0 integration/google-api-http/parameters.txt | 1 + .../{http => google-api-http}/simple.proto | 0 integration/google-api-http/simple.ts | 58 +++++++++++++++ integration/http/parameters.txt | 1 - integration/http/simple.ts | 56 -------------- src/generate-generic-service-definition.ts | 15 +++- src/generate-http.ts | 73 ------------------- src/main.ts | 5 -- src/options.ts | 13 ---- src/utils.ts | 16 ++++ tests/options-test.ts | 1 - 19 files changed, 93 insertions(+), 158 deletions(-) rename integration/{http/http-test.ts => google-api-http/google-api-http-test.ts} (81%) rename integration/{http => google-api-http}/google/api/annotations.proto (100%) rename integration/{http => google-api-http}/google/api/annotations.ts (100%) rename integration/{http => google-api-http}/google/api/http.proto (100%) rename integration/{http => google-api-http}/google/api/http.ts (100%) rename integration/{http => google-api-http}/google/protobuf/descriptor.proto (100%) rename integration/{http => google-api-http}/google/protobuf/descriptor.ts (100%) create mode 100644 integration/google-api-http/parameters.txt rename integration/{http => google-api-http}/simple.proto (100%) create mode 100644 integration/google-api-http/simple.ts delete mode 100644 integration/http/parameters.txt delete mode 100644 integration/http/simple.ts delete mode 100644 src/generate-http.ts diff --git a/README.markdown b/README.markdown index 870db912f..8b09fb275 100644 --- a/README.markdown +++ b/README.markdown @@ -426,10 +426,6 @@ Generated code will be placed in the Gradle build directory. Note that `addGrpcMetadata`, `addNestjsRestParameter` and `returnObservable` will still be false. -- With `--ts_proto_opt=http=true`, the defaults will change to generate http friendly types & service metadata that can be used to create your own http client. See the [http readme](HTTP.markdown) for more information and implementation examples. - - Specifically `outputEncodeMethods`, `outputJsonMethods`, and `outputClientImpl` will all be false, `lowerCaseServiceMethods` will be true and `outputServices` will be ignored. - - With `--ts_proto_opt=useDate=false`, fields of type `google.protobuf.Timestamp` will not be mapped to type `Date` in the generated types. See [Timestamp](#timestamp) for more details. - With `--ts_proto_opt=useMongoObjectId=true`, fields of a type called ObjectId where the message is constructed to have on field called value that is a string will be mapped to type `mongodb.ObjectId` in the generated types. This will require your project to install the mongodb npm package. See [ObjectId](#objectid) for more details. diff --git a/integration/http/http-test.ts b/integration/google-api-http/google-api-http-test.ts similarity index 81% rename from integration/http/http-test.ts rename to integration/google-api-http/google-api-http-test.ts index e57ea1dc4..2e28dbe12 100644 --- a/integration/http/http-test.ts +++ b/integration/google-api-http/google-api-http-test.ts @@ -1,11 +1,11 @@ /** * @jest-environment node */ -import { Messaging, GetMessageRequest, GetMessageResponse } from "./simple"; +import { MessagingDefinition, GetMessageRequest, GetMessageResponse } from "./simple"; -describe("http-test", () => { +describe("google-api-http-test", () => { it("compiles", () => { - expect(Messaging).toStrictEqual({ + expect(MessagingDefinition.methods).toStrictEqual({ getMessage: { path: "/v1/messages/{message_id}", method: "get", @@ -36,7 +36,7 @@ describe("http-test", () => { }); // Test that the request and response types are correctly typed - const copy = { ...Messaging.getMessage }; + const copy = { ...MessagingDefinition.methods.getMessage }; const request: GetMessageRequest = { messageId: "1", }; diff --git a/integration/http/google/api/annotations.proto b/integration/google-api-http/google/api/annotations.proto similarity index 100% rename from integration/http/google/api/annotations.proto rename to integration/google-api-http/google/api/annotations.proto diff --git a/integration/http/google/api/annotations.ts b/integration/google-api-http/google/api/annotations.ts similarity index 100% rename from integration/http/google/api/annotations.ts rename to integration/google-api-http/google/api/annotations.ts diff --git a/integration/http/google/api/http.proto b/integration/google-api-http/google/api/http.proto similarity index 100% rename from integration/http/google/api/http.proto rename to integration/google-api-http/google/api/http.proto diff --git a/integration/http/google/api/http.ts b/integration/google-api-http/google/api/http.ts similarity index 100% rename from integration/http/google/api/http.ts rename to integration/google-api-http/google/api/http.ts diff --git a/integration/http/google/protobuf/descriptor.proto b/integration/google-api-http/google/protobuf/descriptor.proto similarity index 100% rename from integration/http/google/protobuf/descriptor.proto rename to integration/google-api-http/google/protobuf/descriptor.proto diff --git a/integration/http/google/protobuf/descriptor.ts b/integration/google-api-http/google/protobuf/descriptor.ts similarity index 100% rename from integration/http/google/protobuf/descriptor.ts rename to integration/google-api-http/google/protobuf/descriptor.ts diff --git a/integration/google-api-http/parameters.txt b/integration/google-api-http/parameters.txt new file mode 100644 index 000000000..23c575952 --- /dev/null +++ b/integration/google-api-http/parameters.txt @@ -0,0 +1 @@ +outputClientImpl=false,outputEncodeMethods=false,outputJsonMethods=false,outputServices=generic-definitions \ No newline at end of file diff --git a/integration/http/simple.proto b/integration/google-api-http/simple.proto similarity index 100% rename from integration/http/simple.proto rename to integration/google-api-http/simple.proto diff --git a/integration/google-api-http/simple.ts b/integration/google-api-http/simple.ts new file mode 100644 index 000000000..50a5fabb5 --- /dev/null +++ b/integration/google-api-http/simple.ts @@ -0,0 +1,58 @@ +// Code generated by protoc-gen-ts_proto. DO NOT EDIT. +// source: simple.proto + +/* eslint-disable */ + +export const protobufPackage = ""; + +export interface GetMessageRequest { + messageId: string; +} + +export interface GetMessageResponse { + message: string; +} + +export interface CreateMessageRequest { + messageId: string; + /** mapped to the body */ + message: string; +} + +export interface CreateMessageResponse { +} + +export type MessagingDefinition = typeof MessagingDefinition; +export const MessagingDefinition = { + name: "Messaging", + fullName: "Messaging", + methods: { + getMessage: { + path: "/v1/messages/{message_id}", + method: "get", + requestType: undefined as unknown as GetMessageRequest, + responseType: undefined as unknown as GetMessageResponse, + }, + createMessage: { + path: "/v1/messages/{message_id}", + method: "post", + body: "message", + requestType: undefined as unknown as CreateMessageRequest, + responseType: undefined as unknown as CreateMessageResponse, + }, + updateMessage: { + path: "/v1/messages/{message_id}", + method: "patch", + body: "*", + requestType: undefined as unknown as CreateMessageRequest, + responseType: undefined as unknown as CreateMessageResponse, + }, + deleteMessage: { + path: "/v1/messages/{message_id}", + method: "delete", + body: "*", + requestType: undefined as unknown as GetMessageRequest, + responseType: undefined as unknown as CreateMessageResponse, + }, + }, +} as const; diff --git a/integration/http/parameters.txt b/integration/http/parameters.txt deleted file mode 100644 index ed86a6878..000000000 --- a/integration/http/parameters.txt +++ /dev/null @@ -1 +0,0 @@ -http=true \ No newline at end of file diff --git a/integration/http/simple.ts b/integration/http/simple.ts deleted file mode 100644 index ee05e844f..000000000 --- a/integration/http/simple.ts +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by protoc-gen-ts_proto. DO NOT EDIT. -// source: simple.proto - -/* eslint-disable */ - -export const protobufPackage = ""; - -export interface GetMessageRequest { - messageId: string; -} - -export interface GetMessageResponse { - message: string; -} - -export interface CreateMessageRequest { - messageId: string; - /** mapped to the body */ - message: string; -} - -export interface CreateMessageResponse { -} - -export const Messaging = { - getMessage: { - path: "/v1/messages/{message_id}", - method: "get", - requestType: undefined as unknown as GetMessageRequest, - responseType: undefined as unknown as GetMessageResponse, - }, - - createMessage: { - path: "/v1/messages/{message_id}", - method: "post", - body: "message", - requestType: undefined as unknown as CreateMessageRequest, - responseType: undefined as unknown as CreateMessageResponse, - }, - - updateMessage: { - path: "/v1/messages/{message_id}", - method: "patch", - body: "*", - requestType: undefined as unknown as CreateMessageRequest, - responseType: undefined as unknown as CreateMessageResponse, - }, - - deleteMessage: { - path: "/v1/messages/{message_id}", - method: "delete", - body: "*", - requestType: undefined as unknown as GetMessageRequest, - responseType: undefined as unknown as CreateMessageResponse, - }, -}; diff --git a/src/generate-generic-service-definition.ts b/src/generate-generic-service-definition.ts index c316bcdb6..bdc45ed81 100644 --- a/src/generate-generic-service-definition.ts +++ b/src/generate-generic-service-definition.ts @@ -10,7 +10,7 @@ import { uncapitalize } from "./case"; import { Context } from "./context"; import SourceInfo, { Fields } from "./sourceInfo"; import { messageToTypeName } from "./types"; -import { maybeAddComment, maybePrefixPackage } from "./utils"; +import { maybeAddComment, maybePrefixPackage, findHttpRule } from "./utils"; /** * Generates a framework-agnostic service descriptor. @@ -64,6 +64,19 @@ function generateMethodDefinition(ctx: Context, methodDesc: MethodDescriptorProt const inputType = messageToTypeName(ctx, methodDesc.inputType, { keepValueType: true }); const outputType = messageToTypeName(ctx, methodDesc.outputType, { keepValueType: true }); + const httpRule = findHttpRule(methodDesc.options?.httpRule); + + if (httpRule) { + return code` + { + path: "${httpRule.path}", + method: "${httpRule.method}",${httpRule.body ? `\nbody: "${httpRule.body}",` : ""} + requestType: undefined as unknown as ${inputType}, + responseType: undefined as unknown as ${outputType}, + } + `; + } + return code` { name: '${methodDesc.name}', diff --git a/src/generate-http.ts b/src/generate-http.ts deleted file mode 100644 index 32c3ddd63..000000000 --- a/src/generate-http.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { FileDescriptorProto, ServiceDescriptorProto, MethodOptions } from "ts-proto-descriptors"; -import { Code, code, joinCode } from "ts-poet"; -import { requestType, responseType } from "./types"; -import SourceInfo from "./sourceInfo"; -import { assertInstanceOf, FormattedMethodDescriptor } from "./utils"; -import { Context } from "./context"; - -function findHttpRule(httpRule: MethodOptions["httpRule"]) { - if (!httpRule) { - return; - } - - for (const method of ["get", "post", "put", "delete", "patch"] as const) { - if (httpRule[method]) { - return { - method: method, - path: httpRule[method], - body: httpRule.body, - }; - } - } -} - -export function generateHttpService( - ctx: Context, - _fileDesc: FileDescriptorProto, - _sourceInfo: SourceInfo, - serviceDesc: ServiceDescriptorProto, -): Code { - const chunks: Code[] = []; - - const httpRules: Record | undefined> = {}; - let hasHttpRule = false; - - serviceDesc.method.forEach((methodDesc) => { - const httpRule = findHttpRule(methodDesc.options?.httpRule); - - if (httpRule) { - hasHttpRule = true; - assertInstanceOf(methodDesc, FormattedMethodDescriptor); - httpRules[methodDesc.formattedName] = httpRule; - } - }); - - if (hasHttpRule) { - chunks.push(code` - export const ${serviceDesc.name} = { - `); - - serviceDesc.method.forEach((methodDesc) => { - assertInstanceOf(methodDesc, FormattedMethodDescriptor); - const httpRule = httpRules[methodDesc.formattedName]; - - if (!httpRule) { - return; - } - - chunks.push(code` - ${methodDesc.formattedName}: { - path: "${httpRule.path}", - method: "${httpRule.method}",${httpRule.body ? `\nbody: "${httpRule.body}",` : ""} - requestType: undefined as unknown as ${requestType(ctx, methodDesc)}, - responseType: undefined as unknown as ${responseType(ctx, methodDesc)}, - }, - `); - }); - - chunks.push(code`}`); - return joinCode(chunks, { on: "\n\n" }); - } - - return code``; -} diff --git a/src/main.ts b/src/main.ts index 8387173c0..a2de98b32 100644 --- a/src/main.ts +++ b/src/main.ts @@ -108,7 +108,6 @@ import { withOrMaybeCheckIsNull, } from "./utils"; import { visit, visitServices } from "./visit"; -import { generateHttpService } from "./generate-http"; export function generateFile(ctx: Context, fileDesc: FileDescriptorProto): [string, Code] { const { options, utils } = ctx; @@ -333,10 +332,6 @@ export function generateFile(ctx: Context, fileDesc: FileDescriptorProto): [stri chunks.push(code`export const ${serviceConstName} = "${serviceDesc.name}";`); } - if (options.http) { - chunks.push(generateHttpService(ctx, fileDesc, sInfo, serviceDesc)); - } - const uniqueServices = [...new Set(options.outputServices)].sort(); uniqueServices.forEach((outputService) => { if (outputService === ServiceOption.GRPC) { diff --git a/src/options.ts b/src/options.ts index 12575bbf5..c98ffc1bd 100644 --- a/src/options.ts +++ b/src/options.ts @@ -71,7 +71,6 @@ export type Options = { returnObservable: boolean; lowerCaseServiceMethods: boolean; nestJs: boolean; - http: boolean; env: EnvOption; unrecognizedEnum: boolean; unrecognizedEnumName: string; @@ -142,7 +141,6 @@ export function defaultOptions(): Options { metadataType: undefined, addNestjsRestParameter: false, nestJs: false, - http: false, env: EnvOption.BOTH, unrecognizedEnum: true, unrecognizedEnumName: "UNRECOGNIZED", @@ -190,23 +188,12 @@ const nestJsOptions: Partial = { useDate: DateOption.TIMESTAMP, }; -const httpOptions: Partial = { - lowerCaseServiceMethods: true, - outputEncodeMethods: false, - outputJsonMethods: false, - outputPartialMethods: false, - outputClientImpl: false, - outputServices: false as any, -}; - export function optionsFromParameter(parameter: string | undefined): Options { const options = defaultOptions(); if (parameter) { const parsed = parseParameter(parameter); if (parsed.nestJs) { Object.assign(options, nestJsOptions); - } else if (parsed.http) { - Object.assign(options, httpOptions); } Object.assign(options, parsed); } diff --git a/src/utils.ts b/src/utils.ts index cfc2afcdc..9fcfdc7a5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -340,3 +340,19 @@ export async function getVersions(request: CodeGeneratorRequest) { tsProtoVersion, }; } + +export function findHttpRule(httpRule: MethodOptions["httpRule"]) { + if (!httpRule) { + return; + } + + for (const method of ["get", "post", "put", "delete", "patch"] as const) { + if (httpRule[method]) { + return { + method: method, + path: httpRule[method], + body: httpRule.body, + }; + } + } +} diff --git a/tests/options-test.ts b/tests/options-test.ts index 7e55b6f29..e30b4a373 100644 --- a/tests/options-test.ts +++ b/tests/options-test.ts @@ -23,7 +23,6 @@ describe("options", () => { "fileSuffix": "", "forceLong": "number", "globalThisPolyfill": false, - "http": false, "importSuffix": "", "initializeFieldsAsUndefined": false, "lowerCaseServiceMethods": true, From 039d3643b1cb96f46d9fc5ddd4136ef907289366 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Wed, 24 Jul 2024 13:18:35 +0900 Subject: [PATCH 11/20] Remove HTTP.markdown --- HTTP.markdown | 112 -------------------------------------------------- 1 file changed, 112 deletions(-) delete mode 100644 HTTP.markdown diff --git a/HTTP.markdown b/HTTP.markdown deleted file mode 100644 index a94205d0a..000000000 --- a/HTTP.markdown +++ /dev/null @@ -1,112 +0,0 @@ -# Http - -If we have to following `.proto` file: - -```protobuf -syntax = "proto3"; - -import "google/api/annotations.proto"; - -service Messaging { - rpc GetMessage(GetMessageRequest) returns (GetMessageResponse) { - option (google.api.http) = { - get:"/v1/messages/{message_id}" - }; - } - rpc CreateMessage(CreateMessageRequest) returns (CreateMessageResponse) { - option (google.api.http) = { - post:"/v1/messages/{message_id}" - body: "message" - }; - } - rpc UpdateMessage(CreateMessageRequest) returns (CreateMessageResponse) { - option (google.api.http) = { - patch:"/v1/messages/{message_id}" - body: "*" - }; - } -} - -message GetMessageRequest { - string message_id = 1; -} -message GetMessageResponse { - string message = 1; -} - -message CreateMessageRequest { - string message_id = 1; - string message = 2; // mapped to the body -} - -message CreateMessageResponse {} -``` - -The output will be - -```typescript -// ... -export interface GetMessageRequest { - messageId: string; -} - -export interface GetMessageResponse { - message: string; -} - -export interface CreateMessageRequest { - messageId: string; - /** mapped to the body */ - message: string; -} - -export interface CreateMessageResponse {} - -export const Messaging = { - getMessage: { - path: "/v1/messages/{message_id}", - method: "get", - requestType: undefined as GetMessageRequest, - responseType: undefined as GetMessageResponse, - }, - - createMessage: { - path: "/v1/messages/{message_id}", - method: "post", - body: "message", - requestType: undefined as CreateMessageRequest, - responseType: undefined as CreateMessageResponse, - }, - - updateMessage: { - path: "/v1/messages/{message_id}", - method: "patch", - body: "*", - requestType: undefined as CreateMessageRequest, - responseType: undefined as CreateMessageResponse, - }, -}; -``` - -## Client implementation example - -```typescript -// This is just an example, do not use it directly. -function createApi(config: T) { - return function api(payload: T["requestType"]): Promise { - const path = config.path.replace("{message_id}", payload.messageId); - const method = config.method; - const body = method === "get" ? undefined : JSON.stringify({ message: payload.message }); - - return fetch(path, { method, body }); - }; -} - -const getMessage = createApi(Messaging.getMessage); - -getMessage({ - messageId: "123", -}).then((res) => { - // ... -}); -``` From 2715391f78e7e356903026b04b444851b856adc0 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Wed, 24 Jul 2024 15:58:29 +0900 Subject: [PATCH 12/20] Add generic-google-api-http-definitions --- GOOGLE-API-HTTP.markdown | 66 +++++++++++++++++++ README.markdown | 4 ++ .../google-api-http/google-api-http-test.ts | 14 ++-- integration/google-api-http/parameters.txt | 2 +- integration/google-api-http/simple.ts | 61 ++++++++--------- ...eric-google-api-http-service-definition.ts | 50 ++++++++++++++ src/main.ts | 3 + src/options.ts | 1 + 8 files changed, 160 insertions(+), 41 deletions(-) create mode 100644 GOOGLE-API-HTTP.markdown create mode 100644 src/generate-generic-google-api-http-service-definition.ts diff --git a/GOOGLE-API-HTTP.markdown b/GOOGLE-API-HTTP.markdown new file mode 100644 index 000000000..4f2710346 --- /dev/null +++ b/GOOGLE-API-HTTP.markdown @@ -0,0 +1,66 @@ +# Generate generic definitions from [google.api.http](https://cloud.google.com/endpoints/docs/grpc/transcoding) + +To generate `.ts` files for your `.proto` files that contain `google.api.http`, you can use the `--ts_proto_opt=onlyTypes=true,outputServices=generic-google-api-http-definitions` option. + +Please refer to [integration/google-api-http](./integration/google-api-http) for an input/output example. + +## Client implementation example + +```typescript +// This is just an example, please test it to see if it works for you. +function createApi< + S extends Record, +>( + fetcher: (input: { path: string; method: string; body?: string }) => Promise, + serviceDef: S, +): { [K in keyof S]: (payload: S[K]["requestType"]) => Promise } { + // @ts-expect-error + return Object.fromEntries( + Object.entries(serviceDef).map(([name, endpointDef]) => { + return [ + name, + async (payload: typeof endpointDef.requestType): Promise => { + const bodyKey = endpointDef.body; + const payloadClone = bodyKey === "*" ? JSON.parse(JSON.stringify(payload)) : null; + const path = endpointDef.path.replace(/\{([^\}]+)\}/g, (_, key) => { + delete payloadClone[key]; + return payload[key]; + }); + let body: string | undefined = undefined; + if (bodyKey === "*") { + body = JSON.stringify(payloadClone); + } else if (bodyKey) { + body = JSON.stringify({ [bodyKey]: payload[bodyKey] }); + } + + return fetcher({ path, method: endpointDef.method, body }); + }, + ]; + }), + ); +} + +const fetcher = (input: { path: string; method: string; body?: string }) => { + const url = "http://localhost:8080" + input.path; + const init: RequestInit = { + method: input.method, + headers: { + "Content-Type": "application/json", + }, + }; + if (input.body) { + init.body = input.body; + } + return fetch(url, init).then((res) => res.json()); +}; + +const api = createApi(fetcher, Messaging); + +api + .GetMessage({ + messageId: "123", + }) + .then((res) => { + console.log(res); + }); +``` diff --git a/README.markdown b/README.markdown index 8b09fb275..e3a64e344 100644 --- a/README.markdown +++ b/README.markdown @@ -442,6 +442,10 @@ Generated code will be placed in the Gradle build directory. - With `--ts_proto_opt=outputServices=generic-definitions`, ts-proto will output generic (framework-agnostic) service definitions. These definitions contain descriptors for each method with links to request and response types, which allows to generate server and client stubs at runtime, and also generate strong types for them at compile time. An example of a library that uses this approach is [nice-grpc](https://github.com/deeplay-io/nice-grpc). +- With `--ts_proto_opt=outputServices=generic-google-api-http-definitions`, ts-proto will output generic (framework-agnostic) service definitions from [google.api.http](https://cloud.google.com/endpoints/docs/grpc/transcoding). These definitions contain descriptors for each method with links to request and response types, which allows to implement a http client based on it. For more information see the [google.api.http readme](GOOGLE-API-HTTP.markdown). + + (Requires `onlyTypes=true`.) + - With `--ts_proto_opt=outputServices=nice-grpc`, ts-proto will output server and client stubs for [nice-grpc](https://github.com/deeplay-io/nice-grpc). This should be used together with generic definitions, i.e. you should specify two options: `outputServices=nice-grpc,outputServices=generic-definitions`. - With `--ts_proto_opt=metadataType=Foo@./some-file`, ts-proto add a generic (framework-agnostic) metadata field to the generic service definition. diff --git a/integration/google-api-http/google-api-http-test.ts b/integration/google-api-http/google-api-http-test.ts index 2e28dbe12..dc0adb76c 100644 --- a/integration/google-api-http/google-api-http-test.ts +++ b/integration/google-api-http/google-api-http-test.ts @@ -1,32 +1,32 @@ /** * @jest-environment node */ -import { MessagingDefinition, GetMessageRequest, GetMessageResponse } from "./simple"; +import { Messaging, GetMessageRequest, GetMessageResponse } from "./simple"; describe("google-api-http-test", () => { it("compiles", () => { - expect(MessagingDefinition.methods).toStrictEqual({ - getMessage: { + expect(Messaging).toStrictEqual({ + GetMessage: { path: "/v1/messages/{message_id}", method: "get", requestType: undefined, responseType: undefined, }, - createMessage: { + CreateMessage: { path: "/v1/messages/{message_id}", method: "post", body: "message", requestType: undefined, responseType: undefined, }, - updateMessage: { + UpdateMessage: { path: "/v1/messages/{message_id}", method: "patch", body: "*", requestType: undefined, responseType: undefined, }, - deleteMessage: { + DeleteMessage: { path: "/v1/messages/{message_id}", method: "delete", body: "*", @@ -36,7 +36,7 @@ describe("google-api-http-test", () => { }); // Test that the request and response types are correctly typed - const copy = { ...MessagingDefinition.methods.getMessage }; + const copy = { ...Messaging.GetMessage }; const request: GetMessageRequest = { messageId: "1", }; diff --git a/integration/google-api-http/parameters.txt b/integration/google-api-http/parameters.txt index 23c575952..876b6fbe3 100644 --- a/integration/google-api-http/parameters.txt +++ b/integration/google-api-http/parameters.txt @@ -1 +1 @@ -outputClientImpl=false,outputEncodeMethods=false,outputJsonMethods=false,outputServices=generic-definitions \ No newline at end of file +onlyTypes=true,outputServices=generic-google-api-http-definitions \ No newline at end of file diff --git a/integration/google-api-http/simple.ts b/integration/google-api-http/simple.ts index 50a5fabb5..ee8485977 100644 --- a/integration/google-api-http/simple.ts +++ b/integration/google-api-http/simple.ts @@ -22,37 +22,32 @@ export interface CreateMessageRequest { export interface CreateMessageResponse { } -export type MessagingDefinition = typeof MessagingDefinition; -export const MessagingDefinition = { - name: "Messaging", - fullName: "Messaging", - methods: { - getMessage: { - path: "/v1/messages/{message_id}", - method: "get", - requestType: undefined as unknown as GetMessageRequest, - responseType: undefined as unknown as GetMessageResponse, - }, - createMessage: { - path: "/v1/messages/{message_id}", - method: "post", - body: "message", - requestType: undefined as unknown as CreateMessageRequest, - responseType: undefined as unknown as CreateMessageResponse, - }, - updateMessage: { - path: "/v1/messages/{message_id}", - method: "patch", - body: "*", - requestType: undefined as unknown as CreateMessageRequest, - responseType: undefined as unknown as CreateMessageResponse, - }, - deleteMessage: { - path: "/v1/messages/{message_id}", - method: "delete", - body: "*", - requestType: undefined as unknown as GetMessageRequest, - responseType: undefined as unknown as CreateMessageResponse, - }, +export const Messaging = { + GetMessage: { + path: "/v1/messages/{message_id}", + method: "get", + requestType: undefined as unknown as GetMessageRequest, + responseType: undefined as unknown as GetMessageResponse, }, -} as const; + CreateMessage: { + path: "/v1/messages/{message_id}", + method: "post", + body: "message", + requestType: undefined as unknown as CreateMessageRequest, + responseType: undefined as unknown as CreateMessageResponse, + }, + UpdateMessage: { + path: "/v1/messages/{message_id}", + method: "patch", + body: "*", + requestType: undefined as unknown as CreateMessageRequest, + responseType: undefined as unknown as CreateMessageResponse, + }, + DeleteMessage: { + path: "/v1/messages/{message_id}", + method: "delete", + body: "*", + requestType: undefined as unknown as GetMessageRequest, + responseType: undefined as unknown as CreateMessageResponse, + }, +}; diff --git a/src/generate-generic-google-api-http-service-definition.ts b/src/generate-generic-google-api-http-service-definition.ts new file mode 100644 index 000000000..093482471 --- /dev/null +++ b/src/generate-generic-google-api-http-service-definition.ts @@ -0,0 +1,50 @@ +import { ServiceDescriptorProto, MethodOptions } from "ts-proto-descriptors"; +import { Code, code, joinCode } from "ts-poet"; +import { requestType, responseType } from "./types"; +import { assertInstanceOf, FormattedMethodDescriptor, findHttpRule } from "./utils"; +import { Context } from "./context"; + +export function generateGenericGoogleApiHttpServiceDefinition(ctx: Context, serviceDesc: ServiceDescriptorProto): Code { + const chunks: Code[] = []; + + const httpRules: Record | undefined> = {}; + let hasHttpRule = false; + + serviceDesc.method.forEach((methodDesc) => { + const httpRule = findHttpRule(methodDesc.options?.httpRule); + + if (httpRule) { + hasHttpRule = true; + assertInstanceOf(methodDesc, FormattedMethodDescriptor); + httpRules[methodDesc.formattedName] = httpRule; + } + }); + + if (hasHttpRule) { + chunks.push(code` + export const ${serviceDesc.name} = { + `); + + serviceDesc.method.forEach((methodDesc) => { + assertInstanceOf(methodDesc, FormattedMethodDescriptor); + const httpRule = httpRules[methodDesc.formattedName]; + + if (!httpRule) { + return; + } + + chunks.push(code`\ + ${methodDesc.formattedName}: { + path: "${httpRule.path}", + method: "${httpRule.method}",${httpRule.body ? `\nbody: "${httpRule.body}",` : ""} + requestType: undefined as unknown as ${requestType(ctx, methodDesc)}, + responseType: undefined as unknown as ${responseType(ctx, methodDesc)}, + },`); + }); + + chunks.push(code`}`); + return joinCode(chunks, { on: "\n" }); + } + + return code``; +} diff --git a/src/main.ts b/src/main.ts index a2de98b32..5a5f5c293 100644 --- a/src/main.ts +++ b/src/main.ts @@ -108,6 +108,7 @@ import { withOrMaybeCheckIsNull, } from "./utils"; import { visit, visitServices } from "./visit"; +import { generateGenericGoogleApiHttpServiceDefinition } from "./generate-generic-google-api-http-service-definition"; export function generateFile(ctx: Context, fileDesc: FileDescriptorProto): [string, Code] { const { options, utils } = ctx; @@ -340,6 +341,8 @@ export function generateFile(ctx: Context, fileDesc: FileDescriptorProto): [stri chunks.push(generateNiceGrpcService(ctx, fileDesc, sInfo, serviceDesc)); } else if (outputService === ServiceOption.GENERIC) { chunks.push(generateGenericServiceDefinition(ctx, fileDesc, sInfo, serviceDesc)); + } else if (outputService === ServiceOption.GENERIC_GOOGLE_API_HTTP) { + chunks.push(generateGenericGoogleApiHttpServiceDefinition(ctx, serviceDesc)); } else if (outputService === ServiceOption.DEFAULT) { // This service could be Twirp or grpc-web or JSON (maybe). So far all of their // interfaces are fairly similar so we share the same service interface. diff --git a/src/options.ts b/src/options.ts index c98ffc1bd..ca55da949 100644 --- a/src/options.ts +++ b/src/options.ts @@ -35,6 +35,7 @@ export enum ServiceOption { GRPC = "grpc-js", NICE_GRPC = "nice-grpc", GENERIC = "generic-definitions", + GENERIC_GOOGLE_API_HTTP = "generic-google-api-http-definitions", DEFAULT = "default", NONE = "none", } From 867034c010398e88602fec1ebd7d325f0f025de0 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Wed, 24 Jul 2024 16:20:38 +0900 Subject: [PATCH 13/20] Revert src/generate-generic-service-definition.ts --- src/generate-generic-service-definition.ts | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/src/generate-generic-service-definition.ts b/src/generate-generic-service-definition.ts index bdc45ed81..c316bcdb6 100644 --- a/src/generate-generic-service-definition.ts +++ b/src/generate-generic-service-definition.ts @@ -10,7 +10,7 @@ import { uncapitalize } from "./case"; import { Context } from "./context"; import SourceInfo, { Fields } from "./sourceInfo"; import { messageToTypeName } from "./types"; -import { maybeAddComment, maybePrefixPackage, findHttpRule } from "./utils"; +import { maybeAddComment, maybePrefixPackage } from "./utils"; /** * Generates a framework-agnostic service descriptor. @@ -64,19 +64,6 @@ function generateMethodDefinition(ctx: Context, methodDesc: MethodDescriptorProt const inputType = messageToTypeName(ctx, methodDesc.inputType, { keepValueType: true }); const outputType = messageToTypeName(ctx, methodDesc.outputType, { keepValueType: true }); - const httpRule = findHttpRule(methodDesc.options?.httpRule); - - if (httpRule) { - return code` - { - path: "${httpRule.path}", - method: "${httpRule.method}",${httpRule.body ? `\nbody: "${httpRule.body}",` : ""} - requestType: undefined as unknown as ${inputType}, - responseType: undefined as unknown as ${outputType}, - } - `; - } - return code` { name: '${methodDesc.name}', From fb3027977c099f2e0bbb6c41c19870421c394fe0 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Thu, 25 Jul 2024 10:40:09 +0900 Subject: [PATCH 14/20] Update implementation example --- GOOGLE-API-HTTP.markdown | 43 +++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/GOOGLE-API-HTTP.markdown b/GOOGLE-API-HTTP.markdown index 4f2710346..3ee018612 100644 --- a/GOOGLE-API-HTTP.markdown +++ b/GOOGLE-API-HTTP.markdown @@ -7,7 +7,7 @@ Please refer to [integration/google-api-http](./integration/google-api-http) for ## Client implementation example ```typescript -// This is just an example, please test it to see if it works for you. +// This is just a basic implementation, please test it to see if it works for you. function createApi< S extends Record, >( @@ -21,16 +21,45 @@ function createApi< name, async (payload: typeof endpointDef.requestType): Promise => { const bodyKey = endpointDef.body; - const payloadClone = bodyKey === "*" ? JSON.parse(JSON.stringify(payload)) : null; - const path = endpointDef.path.replace(/\{([^\}]+)\}/g, (_, key) => { - delete payloadClone[key]; - return payload[key]; - }); + const hasFieldsInPath = endpointDef.path.includes("{"); + const payloadClone = + hasFieldsInPath || (bodyKey && bodyKey !== "*") ? JSON.parse(JSON.stringify(payload)) : undefined; + + // Spec: https://cloud.google.com/service-infrastructure/docs/service-management/reference/rpc/google.api#path-template-syntax + // This code only handles simple cases. + let path = hasFieldsInPath + ? endpointDef.path.replace(/\{([^\}]+)\}/g, (_, fieldRef) => { + let deleteKey: string; + let result: string; + + if (fieldRef.includes("=")) { + // Handle path template like "/v1/{name=messages/*}" + const [key, value] = fieldRef.split("="); + deleteKey = key; + result = value.replace("*", payload[key]); + } else { + // Handle path template like "/v1/messages/{message_id}" + deleteKey = fieldRef; + result = payload[fieldRef]; + } + + delete payloadClone[deleteKey]; + return result; + }) + : endpointDef.path; + let body: string | undefined = undefined; + if (bodyKey === "*") { - body = JSON.stringify(payloadClone); + body = JSON.stringify(payloadClone ?? payload); } else if (bodyKey) { body = JSON.stringify({ [bodyKey]: payload[bodyKey] }); + delete payloadClone[bodyKey]; + } + + const qs = new URLSearchParams(payloadClone ?? payload).toString(); + if (qs) { + path += "?" + qs; } return fetcher({ path, method: endpointDef.method, body }); From 09765ca0b6132dfe366d9e9d0c5e6569f335535e Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Thu, 25 Jul 2024 10:42:55 +0900 Subject: [PATCH 15/20] Update implementation example --- GOOGLE-API-HTTP.markdown | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/GOOGLE-API-HTTP.markdown b/GOOGLE-API-HTTP.markdown index 3ee018612..ae28c8254 100644 --- a/GOOGLE-API-HTTP.markdown +++ b/GOOGLE-API-HTTP.markdown @@ -29,22 +29,16 @@ function createApi< // This code only handles simple cases. let path = hasFieldsInPath ? endpointDef.path.replace(/\{([^\}]+)\}/g, (_, fieldRef) => { - let deleteKey: string; - let result: string; - if (fieldRef.includes("=")) { // Handle path template like "/v1/{name=messages/*}" const [key, value] = fieldRef.split("="); - deleteKey = key; - result = value.replace("*", payload[key]); + delete payloadClone[key]; + return value.replace("*", payload[key]); } else { // Handle path template like "/v1/messages/{message_id}" - deleteKey = fieldRef; - result = payload[fieldRef]; + delete payloadClone[fieldRef]; + return payload[fieldRef]; } - - delete payloadClone[deleteKey]; - return result; }) : endpointDef.path; From fc884a3378c31580c8bcb0b1365e51375e15c784 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Thu, 25 Jul 2024 10:47:31 +0900 Subject: [PATCH 16/20] Fix implementation example --- GOOGLE-API-HTTP.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/GOOGLE-API-HTTP.markdown b/GOOGLE-API-HTTP.markdown index ae28c8254..fd4ef09f1 100644 --- a/GOOGLE-API-HTTP.markdown +++ b/GOOGLE-API-HTTP.markdown @@ -42,11 +42,14 @@ function createApi< }) : endpointDef.path; + if (bodyKey === "*") { + const body = JSON.stringify(payloadClone ?? payload); + return fetcher({ path, method: endpointDef.method, body }); + } + let body: string | undefined = undefined; - if (bodyKey === "*") { - body = JSON.stringify(payloadClone ?? payload); - } else if (bodyKey) { + if (bodyKey) { body = JSON.stringify({ [bodyKey]: payload[bodyKey] }); delete payloadClone[bodyKey]; } From cada9a2249048b68e9b8b19fdc6e5c667fa3bcb5 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Fri, 26 Jul 2024 09:46:14 +0900 Subject: [PATCH 17/20] Simplify client implementation example --- GOOGLE-API-HTTP.markdown | 59 ++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/GOOGLE-API-HTTP.markdown b/GOOGLE-API-HTTP.markdown index fd4ef09f1..f4dbfa13a 100644 --- a/GOOGLE-API-HTTP.markdown +++ b/GOOGLE-API-HTTP.markdown @@ -20,65 +20,64 @@ function createApi< return [ name, async (payload: typeof endpointDef.requestType): Promise => { + payload = { ...payload }; + const { method } = endpointDef; const bodyKey = endpointDef.body; - const hasFieldsInPath = endpointDef.path.includes("{"); - const payloadClone = - hasFieldsInPath || (bodyKey && bodyKey !== "*") ? JSON.parse(JSON.stringify(payload)) : undefined; - - // Spec: https://cloud.google.com/service-infrastructure/docs/service-management/reference/rpc/google.api#path-template-syntax - // This code only handles simple cases. - let path = hasFieldsInPath - ? endpointDef.path.replace(/\{([^\}]+)\}/g, (_, fieldRef) => { - if (fieldRef.includes("=")) { - // Handle path template like "/v1/{name=messages/*}" - const [key, value] = fieldRef.split("="); - delete payloadClone[key]; - return value.replace("*", payload[key]); - } else { - // Handle path template like "/v1/messages/{message_id}" - delete payloadClone[fieldRef]; - return payload[fieldRef]; - } - }) - : endpointDef.path; + + // Path template syntax: https://cloud.google.com/service-infrastructure/docs/service-management/reference/rpc/google.api#path-template-syntax + // This code only handles the simplest case. Please extend it if you need more complex path templates. + if (/(=|\*|\.|:)/.test(path)) { + throw new Error(`Unsupported path template syntax: ${path}.`); + } + + let path = endpointDef.path.replace(/\{([^\}]+)\}/g, (_, fieldPath) => { + // Handle path template like "/v1/messages/{message_id}" + delete payload[fieldPath]; + return payload[fieldPath]; + }); if (bodyKey === "*") { - const body = JSON.stringify(payloadClone ?? payload); - return fetcher({ path, method: endpointDef.method, body }); + const body = JSON.stringify(payload); + return fetcher({ path, method, body }); } let body: string | undefined = undefined; if (bodyKey) { body = JSON.stringify({ [bodyKey]: payload[bodyKey] }); - delete payloadClone[bodyKey]; + delete payload[bodyKey]; } - const qs = new URLSearchParams(payloadClone ?? payload).toString(); + const qs = new URLSearchParams(payload).toString(); if (qs) { path += "?" + qs; } - return fetcher({ path, method: endpointDef.method, body }); + return fetcher({ path, method, body }); }, ]; }), ); } -const fetcher = (input: { path: string; method: string; body?: string }) => { +async function fetcher(input: { path: string; method: string; body?: string }) { const url = "http://localhost:8080" + input.path; const init: RequestInit = { method: input.method, headers: { "Content-Type": "application/json", }, + body: input.body, }; - if (input.body) { - init.body = input.body; + + const res = await fetch(url, init); + + if (res.ok) { + return await res.json(); } - return fetch(url, init).then((res) => res.json()); -}; + + throw new Error(`Failed to fetch ${url}: ${res.status} ${res.statusText}`); +} const api = createApi(fetcher, Messaging); From 58dd95852c4dbabd81c161df3f460a51a703eb59 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Fri, 26 Jul 2024 09:49:06 +0900 Subject: [PATCH 18/20] Fix client implementation --- GOOGLE-API-HTTP.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GOOGLE-API-HTTP.markdown b/GOOGLE-API-HTTP.markdown index f4dbfa13a..37923fd02 100644 --- a/GOOGLE-API-HTTP.markdown +++ b/GOOGLE-API-HTTP.markdown @@ -33,7 +33,7 @@ function createApi< let path = endpointDef.path.replace(/\{([^\}]+)\}/g, (_, fieldPath) => { // Handle path template like "/v1/messages/{message_id}" delete payload[fieldPath]; - return payload[fieldPath]; + return encodeURIComponent(payload[fieldPath]); }); if (bodyKey === "*") { From 94bbb546405f62ed56fb68af5bfbb1ce59bfc3e8 Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Fri, 26 Jul 2024 10:41:15 +0900 Subject: [PATCH 19/20] Use google-gax --- GOOGLE-API-HTTP.markdown | 35 +++++++---------------------------- 1 file changed, 7 insertions(+), 28 deletions(-) diff --git a/GOOGLE-API-HTTP.markdown b/GOOGLE-API-HTTP.markdown index 37923fd02..492f2da1b 100644 --- a/GOOGLE-API-HTTP.markdown +++ b/GOOGLE-API-HTTP.markdown @@ -7,7 +7,9 @@ Please refer to [integration/google-api-http](./integration/google-api-http) for ## Client implementation example ```typescript -// This is just a basic implementation, please test it to see if it works for you. +import { PathTemplate } from "google-gax"; +import { excludeKeys } from "filter-obj"; + function createApi< S extends Record, >( @@ -20,35 +22,12 @@ function createApi< return [ name, async (payload: typeof endpointDef.requestType): Promise => { - payload = { ...payload }; const { method } = endpointDef; - const bodyKey = endpointDef.body; - - // Path template syntax: https://cloud.google.com/service-infrastructure/docs/service-management/reference/rpc/google.api#path-template-syntax - // This code only handles the simplest case. Please extend it if you need more complex path templates. - if (/(=|\*|\.|:)/.test(path)) { - throw new Error(`Unsupported path template syntax: ${path}.`); - } - - let path = endpointDef.path.replace(/\{([^\}]+)\}/g, (_, fieldPath) => { - // Handle path template like "/v1/messages/{message_id}" - delete payload[fieldPath]; - return encodeURIComponent(payload[fieldPath]); - }); - - if (bodyKey === "*") { - const body = JSON.stringify(payload); - return fetcher({ path, method, body }); - } - - let body: string | undefined = undefined; - - if (bodyKey) { - body = JSON.stringify({ [bodyKey]: payload[bodyKey] }); - delete payload[bodyKey]; - } + const pathTemplate = new PathTemplate(endpointDef.path); + const path = pathTemplate.render(payload); + const remainPayload = excludeKeys(payload, Object.keys(pathTemplate.match(path))); - const qs = new URLSearchParams(payload).toString(); + const qs = new URLSearchParams(remainPayload).toString(); if (qs) { path += "?" + qs; } From bca889e1f8dc90f32395c35d87d28c90f1a6ec3b Mon Sep 17 00:00:00 2001 From: Jas Chen Date: Fri, 26 Jul 2024 10:47:26 +0900 Subject: [PATCH 20/20] Fix body --- GOOGLE-API-HTTP.markdown | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/GOOGLE-API-HTTP.markdown b/GOOGLE-API-HTTP.markdown index 492f2da1b..baab73a69 100644 --- a/GOOGLE-API-HTTP.markdown +++ b/GOOGLE-API-HTTP.markdown @@ -22,11 +22,23 @@ function createApi< return [ name, async (payload: typeof endpointDef.requestType): Promise => { - const { method } = endpointDef; + const { method, body: bodyKey } = endpointDef; const pathTemplate = new PathTemplate(endpointDef.path); const path = pathTemplate.render(payload); const remainPayload = excludeKeys(payload, Object.keys(pathTemplate.match(path))); + if (bodyKey === "*") { + const body = JSON.stringify(remainPayload); + return fetcher({ path, method, body }); + } + + let body: string | undefined = undefined; + + if (bodyKey) { + body = JSON.stringify({ [bodyKey]: payload[bodyKey] }); + delete remainPayload[bodyKey]; + } + const qs = new URLSearchParams(remainPayload).toString(); if (qs) { path += "?" + qs;