From 99857c80058ad3f7d2573c8535020bd50924f648 Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Wed, 18 Sep 2019 11:44:13 -0700 Subject: [PATCH 01/11] init lro setup --- package.json | 6 +- templates/typescript_gapic/package.json.njk | 2 +- .../src/$version/$service_client.ts.njk | 136 +++++++++++++----- .../src/$version/$service_proto_list.json.njk | 3 + typescript/test/baseline.ts | 6 +- 5 files changed, 111 insertions(+), 42 deletions(-) create mode 100644 templates/typescript_gapic/src/$version/$service_proto_list.json.njk diff --git a/package.json b/package.json index 5226913a3..5f289db51 100644 --- a/package.json +++ b/package.json @@ -38,14 +38,14 @@ "@types/get-stdin": "^5.0.1", "@types/google-protobuf": "^3.2.7", "@types/mocha": "^5.2.5", - "@types/node": "^11.12.0", + "@types/node": "^11.13.20", "@types/nunjucks": "^3.1.0", "@types/rimraf": "^2.0.2", "assert-rejects": "^1.0.0", - "c8": "^5.0.1", + "c8": "^5.0.4", "codecov": "^3.0.4", "espower-typescript": "^9.0.0", - "google-gax": "^1.3.0", + "google-gax": "^1.5.2", "gts": "^0.9.0", "intelli-espower-loader": "^1.0.1", "mocha": "^5.2.0", diff --git a/templates/typescript_gapic/package.json.njk b/templates/typescript_gapic/package.json.njk index bc92170c5..7780ad42d 100644 --- a/templates/typescript_gapic/package.json.njk +++ b/templates/typescript_gapic/package.json.njk @@ -24,7 +24,7 @@ "lint": "gts check", "clean": "gts clean", "compile": "tsc -p .", - "compile-protos": "pbjs -p protos -t static-module -o pbjs-genfiles/protos.js {{ api.filesToGenerate.join(' ') }} && pbts pbjs-genfiles/protos.js -o pbjs-genfiles/protos.d.ts", + "compile-protos": "compileProtos src", "fix": "gts fix", "prepare": "npm run compile-protos && npm run compile", "pretest": "npm run compile-protos && npm run compile" diff --git a/templates/typescript_gapic/src/$version/$service_client.ts.njk b/templates/typescript_gapic/src/$version/$service_client.ts.njk index 3cacf1a72..8a60b0d2f 100644 --- a/templates/typescript_gapic/src/$version/$service_client.ts.njk +++ b/templates/typescript_gapic/src/$version/$service_client.ts.njk @@ -1,7 +1,6 @@ {% import "./license.njk" as license %}{{license.license()}} import * as gax from 'google-gax'; import * as path from 'path'; -import * as protobuf from 'protobufjs'; import * as packageJson from '../../package.json'; import * as protos from '../../pbjs-genfiles/protos'; @@ -14,7 +13,9 @@ export interface ClientOptions extends gax.GrpcClientOptions, gax.ClientStubOptions { libName?: string; libVersion?: string; - clientConfig?: gax.ClientConfig; + clientConfig: gax.ClientConfig; + fallback?: boolean; + apiEndpoint?: string; } interface Descriptors { @@ -49,42 +50,56 @@ export class {{ service.name }}Client { constructor(opts: ClientOptions) { // Ensure that options include the service address and port. + opts = opts || {}; + const isBrowser = (typeof window !== 'undefined'); + if (isBrowser){ + opts.fallback = true; + } + // If we are in browser, we are already using fallback because of the + // "browser" field in package.json. + // But if we were explicitly requested to use fallback, let's do it now. + const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + const servicePath = + opts.servicePath || + opts.apiEndpoint || + (this.constructor as typeof {{service.name}}Client).servicePath; + opts = Object.assign( { clientConfig: {}, port: (this.constructor as typeof {{ service.name }}Client).port, - servicePath: (this.constructor as typeof {{ service.name }}Client).servicePath, + servicePath: servicePath, }, opts); // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof {{ service.name }}Client).scopes; - const gaxGrpc = new gax.GrpcClient(opts); + const gaxGrpc = new gaxModule.GrpcClient(opts); // Save the auth object to the client, for use by other methods. - this.auth = gaxGrpc.auth; + this.auth = (gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ `gl-node/${process.version}`, `grpc/${gaxGrpc.grpcVersion}`, - `gax/${gax.version}`, + `gax/${gaxModule.version}`, `gapic/${version}`, + `gl-web/${gaxModule.version}` ]; if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); } + // Load the applicable protos. + // For Node.js, pass the path to JSON proto file. + // For browsers, pass the JSON content. - const gaxProtos = Object.assign( - {}, -{%- set protosJoiner = joiner() %} -{%- for filename in api.filesToGenerate %} - {{- protosJoiner() }} - gaxGrpc.loadProto( - path.join(__dirname, '..', '..', 'protos'), - '{{ filename }}') -{%- endfor -%} + const typescriptProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); + const gaxProtos = gaxGrpc.loadProto( + opts.fallback ? + require("../../protos/protos.json") : + typescriptProtoPath ); {%- if (service.paging.length > 0) %} @@ -96,7 +111,7 @@ export class {{ service.name }}Client { {%- for method in service.paging %} {{- pagingJoiner() }} {{ method.name.toCamelCase() }}: - new gax.PageDescriptor('pageToken', 'nextPageToken', '{{ method.pagingFieldName }}') + new gaxModule.PageDescriptor('pageToken', 'nextPageToken', '{{ method.pagingFieldName }}') {%- endfor %} }; {%- endif %} @@ -109,41 +124,41 @@ export class {{ service.name }}Client { {%- set streamingJoiner = joiner() %} {%- for method in service.streaming %} {{- streamingJoiner() }} - {{ method.name.toCamelCase() }}: new gax.StreamDescriptor(gax.StreamType.{{ method.streaming }}) + {{ method.name.toCamelCase() }}: new gaxModule.StreamDescriptor(gax.StreamType.{{ method.streaming }}) {%- endfor %} }; {%- endif %} -{%- if (service.longrunning.length > 0) %} +{%- if (service.longRunning.length > 0) %} // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. - let protoFilesRoot = new gax.GoogleProtoFilesRoot(); -{%- for filename in api.filesToGenerate %} - protoFilesRoot = protobuf.loadSync( - path.join(__dirname, '..', '..', 'protos', '{{ filename }}'), - protoFilesRoot); -{%- endfor %} + const protoFilesRoot = opts.fallback? + gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + gaxModule.protobuf.loadSync(typescriptProtoPath); - const operationsClient = new gax.lro({ - auth: gaxGrpc.auth, + const operationsClient = gaxModule.lro({ + auth: this.auth, + // @ts-ignore grpc: gaxGrpc.grpc, }).operationsClient(opts); -{%- for method in service.longrunning %} +{%- for method in service.longRunning %} const {{ method.name.toCamelCase() }}Response = protoFilesRoot.lookup( - '{{ method.longrunning.responseType }}'); + '{{ method.longRunning.responseType }}'); const {{ method.name.toCamelCase() }}Metadata = protoFilesRoot.lookup( - '{{ method.longrunning.metadataType }}'); + '{{ method.longRunning.metadataType }}'); {%- endfor %} this._descriptors.longrunning = { -{%- set longrunningJoiner = joiner() %} -{%- for method in service.longrunning %} - {{- longrunningJoiner() }} - {{ method.name.toCamelCase() }}: new gax.LongrunningDescriptor( +{%- set longRunningJoiner = joiner() %} +{%- for method in service.longRunning %} + {{- longRunningJoiner() }} + {{ method.name.toCamelCase() }}: new gaxModule.LongrunningDescriptor( operationsClient, + // @ts-ignore {{ method.name.toCamelCase() }}Response.decode.bind({{ method.name.toCamelCase() }}Response), + // @ts-ignore {{ method.name.toCamelCase() }}Metadata.decode.bind({{ method.name.toCamelCase() }}Metadata)) {%- endfor %} }; @@ -161,9 +176,13 @@ export class {{ service.name }}Client { // Put together the "service stub" for // google.showcase.v1alpha2.Echo. - const {{ service.name.toCamelCase() }}Stub = + const echoStub = gaxGrpc.createStub( // @ts-ignore We cannot check types that are loaded in runtime. - gaxGrpc.createStub(gaxProtos.{{ api.naming.protoPackage }}.{{ service.name }}, opts); + opts.fallback ? + // @ts-ignore + gaxProtos.lookupService('{{api.naming.protoPackage}}.{{ service.name }}') : + protos.{{api.naming.protoPackage}}.{{ service.name }}, + opts); const {{ service.name.toCamelCase() }}StubMethods = [ @@ -175,7 +194,9 @@ export class {{ service.name }}Client { ]; for (const methodName of {{ service.name.toCamelCase() }}StubMethods) { + // @ts-ignore const innerCallPromise = {{ service.name.toCamelCase() }}Stub.then( + // @ts-ignore stub => (...args: Array<{}>) => { return stub[methodName].apply(stub, args); }, @@ -198,6 +219,13 @@ export class {{ service.name }}Client { static get servicePath() { return '{{ service.hostname }}'; } + /** + * The DNS address for this API service - same as servicePath(), + * exists for compatibility reasons. + */ + static get apiEndpoint() { + return 'localhost'; + } /** * The port for this API service. @@ -328,4 +356,42 @@ export class {{ service.name }}Client { } {%- endif %} {% endfor %} +{% for method in service.longRunning %} + {{ method.name.toCamelCase() }}( + request: protos{{ method.inputInterface }}, + options?: gax.CallOptions): + Promise<[ + protos{{ method.outputInterface }}, + protos{{ method.inputInterface }}|undefined, {}|undefined + ]>; + {{ method.name.toCamelCase() }}( + request: protos{{ method.inputInterface }}, + options: gax.CallOptions, + callback: Callback< + protos{{ method.outputInterface }}, + protos{{ method.inputInterface }}|undefined, + {}|undefined>): void; + {{ method.name.toCamelCase() }}( + request: protos{{ method.inputInterface }}, + optionsOrCallback?: gax.CallOptions|Callback< + protos{{ method.outputInterface }}, + protos{{ method.inputInterface }}|undefined, {}|undefined>, + callback?: Callback< + protos{{ method.outputInterface }}, + protos{{ method.inputInterface }}|undefined, + {}|undefined>): + Promise<[ + protos{{ method.outputInterface }}, + protos{{ method.inputInterface }}|undefined, {}|undefined + ]>|void { + request = request || {}; + let options = optionsOrCallback; + if (typeof options === 'function' && callback === undefined) { + callback = options; + options = {}; + } + options = options || {}; + return this._innerApiCalls.{{ method.name.toCamelCase() }}(request, options, callback); + } +{% endfor %} } diff --git a/templates/typescript_gapic/src/$version/$service_proto_list.json.njk b/templates/typescript_gapic/src/$version/$service_proto_list.json.njk new file mode 100644 index 000000000..bdc3c05e7 --- /dev/null +++ b/templates/typescript_gapic/src/$version/$service_proto_list.json.njk @@ -0,0 +1,3 @@ +[ + {{ api.filesToGenerate.join(',') }} +] \ No newline at end of file diff --git a/typescript/test/baseline.ts b/typescript/test/baseline.ts index 51f8c47e2..c40a2883d 100644 --- a/typescript/test/baseline.ts +++ b/typescript/test/baseline.ts @@ -60,9 +60,9 @@ describe('CodeGeneratorTest', () => { `protoc --typescript_gapic_out=${OUTPUT_DIR} ` + `-I${GOOGLE_GAX_PROTOS_DIR} ` + `-I${PROTOS_DIR} ` + ECHO_PROTO_FILE); - assert.strictEqual( - fs.readFileSync(GENERATED_CLIENT_FILE).toString(), - fs.readFileSync(CLIENT_LIBRARY_BASELINE).toString()); + // assert.strictEqual( + // fs.readFileSync(GENERATED_CLIENT_FILE).toString(), + // fs.readFileSync(CLIENT_LIBRARY_BASELINE).toString()); }); }); }); From 5b98dae964500b5cc0c481b8affb949895f9808b Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Thu, 19 Sep 2019 17:53:38 -0700 Subject: [PATCH 02/11] upgrade google-gax --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 7f22d00d6..9f60b6b54 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,7 @@ "c8": "^5.0.4", "codecov": "^3.0.4", "espower-typescript": "^9.0.0", - "google-gax": "^1.5.2", + "google-gax": "^1.6.0", "gts": "^0.9.0", "intelli-espower-loader": "^1.0.1", "mocha": "^6.0.0", From c179f9768106011702d35e14091bbbc139f344bb Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Mon, 30 Sep 2019 16:00:57 -0700 Subject: [PATCH 03/11] add dom to tsconfig for browser check --- templates/typescript_gapic/tsconfig.json.njk | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/templates/typescript_gapic/tsconfig.json.njk b/templates/typescript_gapic/tsconfig.json.njk index a7647fcc4..2d9b83e3f 100644 --- a/templates/typescript_gapic/tsconfig.json.njk +++ b/templates/typescript_gapic/tsconfig.json.njk @@ -3,7 +3,8 @@ "compilerOptions": { "rootDir": ".", "outDir": "build", - "resolveJsonModule": true + "resolveJsonModule": true, + "lib": ["es2016", "dom"] }, "include": [ "src/*.ts", From 028eb20616af051adfa339a3d80fc92160ec445c Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Mon, 30 Sep 2019 16:09:50 -0700 Subject: [PATCH 04/11] copy protos to build/ --- .../src/$version/$service_client.ts.njk | 43 ++----------------- 1 file changed, 3 insertions(+), 40 deletions(-) diff --git a/templates/typescript_gapic/src/$version/$service_client.ts.njk b/templates/typescript_gapic/src/$version/$service_client.ts.njk index 8a60b0d2f..9972ce3cf 100644 --- a/templates/typescript_gapic/src/$version/$service_client.ts.njk +++ b/templates/typescript_gapic/src/$version/$service_client.ts.njk @@ -3,7 +3,7 @@ import * as gax from 'google-gax'; import * as path from 'path'; import * as packageJson from '../../package.json'; -import * as protos from '../../pbjs-genfiles/protos'; +import * as protos from '../../protos/protos'; import * as gapicConfig from './echo_client_config.json'; const version = packageJson.version; @@ -181,7 +181,8 @@ export class {{ service.name }}Client { opts.fallback ? // @ts-ignore gaxProtos.lookupService('{{api.naming.protoPackage}}.{{ service.name }}') : - protos.{{api.naming.protoPackage}}.{{ service.name }}, + // @ts-ignore + gaxProtos.{{api.naming.protoPackage}}.{{ service.name }}, opts); const {{ service.name.toCamelCase() }}StubMethods = @@ -356,42 +357,4 @@ export class {{ service.name }}Client { } {%- endif %} {% endfor %} -{% for method in service.longRunning %} - {{ method.name.toCamelCase() }}( - request: protos{{ method.inputInterface }}, - options?: gax.CallOptions): - Promise<[ - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined - ]>; - {{ method.name.toCamelCase() }}( - request: protos{{ method.inputInterface }}, - options: gax.CallOptions, - callback: Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, - {}|undefined>): void; - {{ method.name.toCamelCase() }}( - request: protos{{ method.inputInterface }}, - optionsOrCallback?: gax.CallOptions|Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined>, - callback?: Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, - {}|undefined>): - Promise<[ - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined - ]>|void { - request = request || {}; - let options = optionsOrCallback; - if (typeof options === 'function' && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.{{ method.name.toCamelCase() }}(request, options, callback); - } -{% endfor %} } From c44232363435c7c9c22c9912e2f493b808cf87c0 Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Mon, 30 Sep 2019 16:11:23 -0700 Subject: [PATCH 05/11] Revert "copy protos to build/" This reverts commit 028eb20616af051adfa339a3d80fc92160ec445c. --- .../src/$version/$service_client.ts.njk | 43 +++++++++++++++++-- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/templates/typescript_gapic/src/$version/$service_client.ts.njk b/templates/typescript_gapic/src/$version/$service_client.ts.njk index 9972ce3cf..8a60b0d2f 100644 --- a/templates/typescript_gapic/src/$version/$service_client.ts.njk +++ b/templates/typescript_gapic/src/$version/$service_client.ts.njk @@ -3,7 +3,7 @@ import * as gax from 'google-gax'; import * as path from 'path'; import * as packageJson from '../../package.json'; -import * as protos from '../../protos/protos'; +import * as protos from '../../pbjs-genfiles/protos'; import * as gapicConfig from './echo_client_config.json'; const version = packageJson.version; @@ -181,8 +181,7 @@ export class {{ service.name }}Client { opts.fallback ? // @ts-ignore gaxProtos.lookupService('{{api.naming.protoPackage}}.{{ service.name }}') : - // @ts-ignore - gaxProtos.{{api.naming.protoPackage}}.{{ service.name }}, + protos.{{api.naming.protoPackage}}.{{ service.name }}, opts); const {{ service.name.toCamelCase() }}StubMethods = @@ -357,4 +356,42 @@ export class {{ service.name }}Client { } {%- endif %} {% endfor %} +{% for method in service.longRunning %} + {{ method.name.toCamelCase() }}( + request: protos{{ method.inputInterface }}, + options?: gax.CallOptions): + Promise<[ + protos{{ method.outputInterface }}, + protos{{ method.inputInterface }}|undefined, {}|undefined + ]>; + {{ method.name.toCamelCase() }}( + request: protos{{ method.inputInterface }}, + options: gax.CallOptions, + callback: Callback< + protos{{ method.outputInterface }}, + protos{{ method.inputInterface }}|undefined, + {}|undefined>): void; + {{ method.name.toCamelCase() }}( + request: protos{{ method.inputInterface }}, + optionsOrCallback?: gax.CallOptions|Callback< + protos{{ method.outputInterface }}, + protos{{ method.inputInterface }}|undefined, {}|undefined>, + callback?: Callback< + protos{{ method.outputInterface }}, + protos{{ method.inputInterface }}|undefined, + {}|undefined>): + Promise<[ + protos{{ method.outputInterface }}, + protos{{ method.inputInterface }}|undefined, {}|undefined + ]>|void { + request = request || {}; + let options = optionsOrCallback; + if (typeof options === 'function' && callback === undefined) { + callback = options; + options = {}; + } + options = options || {}; + return this._innerApiCalls.{{ method.name.toCamelCase() }}(request, options, callback); + } +{% endfor %} } From 351d6ffc1b1b58837a7c6345e9dfe1c3bd0eebe6 Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Mon, 30 Sep 2019 16:12:32 -0700 Subject: [PATCH 06/11] copy protos/ to build/ --- templates/typescript_gapic/package.json.njk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/typescript_gapic/package.json.njk b/templates/typescript_gapic/package.json.njk index 870de17dd..c53d80649 100644 --- a/templates/typescript_gapic/package.json.njk +++ b/templates/typescript_gapic/package.json.njk @@ -23,7 +23,7 @@ "scripts": { "lint": "gts check", "clean": "gts clean", - "compile": "tsc -p .", + "compile": "tsc -p . && cp -r protos build/", "compile-protos": "compileProtos src", "fix": "gts fix", "prepare": "npm run compile-protos && npm run compile", From 73f3bd83950be6c237898e81d51483531435286c Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Mon, 30 Sep 2019 16:20:38 -0700 Subject: [PATCH 07/11] load protos from json file --- .../src/$version/$service_client.ts.njk | 89 ++++++------------- 1 file changed, 26 insertions(+), 63 deletions(-) diff --git a/templates/typescript_gapic/src/$version/$service_client.ts.njk b/templates/typescript_gapic/src/$version/$service_client.ts.njk index 8a60b0d2f..e43bc9101 100644 --- a/templates/typescript_gapic/src/$version/$service_client.ts.njk +++ b/templates/typescript_gapic/src/$version/$service_client.ts.njk @@ -3,7 +3,7 @@ import * as gax from 'google-gax'; import * as path from 'path'; import * as packageJson from '../../package.json'; -import * as protos from '../../pbjs-genfiles/protos'; +import * as protosType from '../../protos/protos'; import * as gapicConfig from './echo_client_config.json'; const version = packageJson.version; @@ -96,7 +96,7 @@ export class {{ service.name }}Client { // For browsers, pass the JSON content. const typescriptProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const gaxProtos = gaxGrpc.loadProto( + const protos = gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : typescriptProtoPath @@ -180,7 +180,8 @@ export class {{ service.name }}Client { // @ts-ignore We cannot check types that are loaded in runtime. opts.fallback ? // @ts-ignore - gaxProtos.lookupService('{{api.naming.protoPackage}}.{{ service.name }}') : + protos.lookupService('{{api.naming.protoPackage}}.{{ service.name }}') : + // @ts-ignore protos.{{api.naming.protoPackage}}.{{ service.name }}, opts); @@ -274,31 +275,31 @@ export class {{ service.name }}Client { {%- for method in service.simpleMethods %} {{ method.name.toCamelCase() }}( - request: protos{{ method.inputInterface }}, + request: protosType{{ method.inputInterface }}, options?: gax.CallOptions): Promise<[ - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined ]>; {{ method.name.toCamelCase() }}( - request: protos{{ method.inputInterface }}, + request: protosType{{ method.inputInterface }}, options: gax.CallOptions, callback: Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined>): void; {{ method.name.toCamelCase() }}( - request: protos{{ method.inputInterface }}, + request: protosType{{ method.inputInterface }}, optionsOrCallback?: gax.CallOptions|Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined>, + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined>, callback?: Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined>): Promise<[ - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined ]>|void { request = request || {}; let options = optionsOrCallback; @@ -320,7 +321,7 @@ export class {{ service.name }}Client { } {%- elif method.serverStreaming %} {{ method.name.toCamelCase() }}( - request?: protos{{ method.inputInterface }}, + request?: protosType{{ method.inputInterface }}, options?: gax.CallOptions): gax.ServerStreamingCall{ request = request || {}; @@ -331,21 +332,21 @@ export class {{ service.name }}Client { {{ method.name.toCamelCase() }}( options: gax.CallOptions, callback: Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined>): + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined>): gax.ClientStreamingCall; {{ method.name.toCamelCase() }}( callback: Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined>): + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined>): gax.ClientStreamingCall; {{ method.name.toCamelCase() }}( optionsOrCallback: gax.CallOptions|Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined>, + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined>, callback?: Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined>): + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined>): gax.ClientStreamingCall { if (optionsOrCallback instanceof Function && callback === undefined) { callback = optionsOrCallback; @@ -356,42 +357,4 @@ export class {{ service.name }}Client { } {%- endif %} {% endfor %} -{% for method in service.longRunning %} - {{ method.name.toCamelCase() }}( - request: protos{{ method.inputInterface }}, - options?: gax.CallOptions): - Promise<[ - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined - ]>; - {{ method.name.toCamelCase() }}( - request: protos{{ method.inputInterface }}, - options: gax.CallOptions, - callback: Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, - {}|undefined>): void; - {{ method.name.toCamelCase() }}( - request: protos{{ method.inputInterface }}, - optionsOrCallback?: gax.CallOptions|Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined>, - callback?: Callback< - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, - {}|undefined>): - Promise<[ - protos{{ method.outputInterface }}, - protos{{ method.inputInterface }}|undefined, {}|undefined - ]>|void { - request = request || {}; - let options = optionsOrCallback; - if (typeof options === 'function' && callback === undefined) { - callback = options; - options = {}; - } - options = options || {}; - return this._innerApiCalls.{{ method.name.toCamelCase() }}(request, options, callback); - } -{% endfor %} } From df2c8ef77aa503c93e33bdd49b2c2d58440a7f1d Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Mon, 30 Sep 2019 16:28:56 -0700 Subject: [PATCH 08/11] LRO methods & update baseline test --- .../src/$version/$service_client.ts.njk | 38 ++++ .../test/testdata/echo_client_baseline.ts.txt | 175 ++++++++++++++---- 2 files changed, 173 insertions(+), 40 deletions(-) diff --git a/templates/typescript_gapic/src/$version/$service_client.ts.njk b/templates/typescript_gapic/src/$version/$service_client.ts.njk index e43bc9101..cf321dcab 100644 --- a/templates/typescript_gapic/src/$version/$service_client.ts.njk +++ b/templates/typescript_gapic/src/$version/$service_client.ts.njk @@ -357,4 +357,42 @@ export class {{ service.name }}Client { } {%- endif %} {% endfor %} +{%- for method in service.longRunning %} + {{ method.name.toCamelCase() }}( + request: protosType{{ method.inputInterface }}, + options?: gax.CallOptions): + Promise<[ + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined + ]>; + {{ method.name.toCamelCase() }}( + request: protosType{{ method.inputInterface }}, + options: gax.CallOptions, + callback: Callback< + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, + {}|undefined>): void; + {{ method.name.toCamelCase() }}( + request: protosType{{ method.inputInterface }}, + optionsOrCallback?: gax.CallOptions|Callback< + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined>, + callback?: Callback< + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, + {}|undefined>): + Promise<[ + protosType{{ method.outputInterface }}, + protosType{{ method.inputInterface }}|undefined, {}|undefined + ]>|void { + request = request || {}; + let options = optionsOrCallback; + if (typeof options === 'function' && callback === undefined) { + callback = options; + options = {}; + } + options = options || {}; + return this._innerApiCalls.{{ method.name.toCamelCase() }}(request, options, callback); + } +{%- endfor %} } diff --git a/typescript/test/testdata/echo_client_baseline.ts.txt b/typescript/test/testdata/echo_client_baseline.ts.txt index efa02f718..b630a92d5 100644 --- a/typescript/test/testdata/echo_client_baseline.ts.txt +++ b/typescript/test/testdata/echo_client_baseline.ts.txt @@ -18,10 +18,9 @@ import * as gax from 'google-gax'; import * as path from 'path'; -import * as protobuf from 'protobufjs'; import * as packageJson from '../../package.json'; -import * as protos from '../../pbjs-genfiles/protos'; +import * as protosType from '../../protos/protos'; import * as gapicConfig from './echo_client_config.json'; const version = packageJson.version; @@ -31,7 +30,9 @@ export interface ClientOptions extends gax.GrpcClientOptions, gax.ClientStubOptions { libName?: string; libVersion?: string; - clientConfig?: gax.ClientConfig; + clientConfig: gax.ClientConfig; + fallback?: boolean; + apiEndpoint?: string; } interface Descriptors { @@ -66,53 +67,97 @@ export class EchoClient { constructor(opts: ClientOptions) { // Ensure that options include the service address and port. + opts = opts || {}; + const isBrowser = (typeof window !== 'undefined'); + if (isBrowser){ + opts.fallback = true; + } + // If we are in browser, we are already using fallback because of the + // "browser" field in package.json. + // But if we were explicitly requested to use fallback, let's do it now. + const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + const servicePath = + opts.servicePath || + opts.apiEndpoint || + (this.constructor as typeof EchoClient).servicePath; + opts = Object.assign( { clientConfig: {}, port: (this.constructor as typeof EchoClient).port, - servicePath: (this.constructor as typeof EchoClient).servicePath, + servicePath: servicePath, }, opts); // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof EchoClient).scopes; - const gaxGrpc = new gax.GrpcClient(opts); + const gaxGrpc = new gaxModule.GrpcClient(opts); // Save the auth object to the client, for use by other methods. - this.auth = gaxGrpc.auth; + this.auth = (gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ `gl-node/${process.version}`, `grpc/${gaxGrpc.grpcVersion}`, - `gax/${gax.version}`, + `gax/${gaxModule.version}`, `gapic/${version}`, + `gl-web/${gaxModule.version}` ]; if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); } + // Load the applicable protos. + // For Node.js, pass the path to JSON proto file. + // For browsers, pass the JSON content. - const gaxProtos = Object.assign( - {}, - gaxGrpc.loadProto( - path.join(__dirname, '..', '..', 'protos'), - 'google/showcase/v1beta1/echo.proto')); + const typescriptProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); + const protos = gaxGrpc.loadProto( + opts.fallback ? + require("../../protos/protos.json") : + typescriptProtoPath + ); // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this._descriptors.page = { pagedExpand: - new gax.PageDescriptor('pageToken', 'nextPageToken', 'responses') + new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'responses') }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this._descriptors.stream = { - expand: new gax.StreamDescriptor(gax.StreamType.SERVER_STREAMING), - collect: new gax.StreamDescriptor(gax.StreamType.CLIENT_STREAMING), - chat: new gax.StreamDescriptor(gax.StreamType.BIDI_STREAMING) + expand: new gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING), + collect: new gaxModule.StreamDescriptor(gax.StreamType.CLIENT_STREAMING), + chat: new gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING) + }; + // This API contains "long-running operations", which return a + // an Operation object that allows for tracking of the operation, + // rather than holding a request open. + const protoFilesRoot = opts.fallback? + gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + gaxModule.protobuf.loadSync(typescriptProtoPath); + + const operationsClient = gaxModule.lro({ + auth: this.auth, + // @ts-ignore + grpc: gaxGrpc.grpc, + }).operationsClient(opts); + const waitResponse = protoFilesRoot.lookup( + 'WaitResponse'); + const waitMetadata = protoFilesRoot.lookup( + 'WaitMetadata'); + + this._descriptors.longrunning = { + wait: new gaxModule.LongrunningDescriptor( + operationsClient, + // @ts-ignore + waitResponse.decode.bind(waitResponse), + // @ts-ignore + waitMetadata.decode.bind(waitMetadata)) }; // Put together the default options sent with requests. @@ -127,15 +172,22 @@ export class EchoClient { // Put together the "service stub" for // google.showcase.v1alpha2.Echo. - const echoStub = + const echoStub = gaxGrpc.createStub( // @ts-ignore We cannot check types that are loaded in runtime. - gaxGrpc.createStub(gaxProtos.google.showcase.v1beta1.Echo, opts); + opts.fallback ? + // @ts-ignore + protos.lookupService('google.showcase.v1beta1.Echo') : + // @ts-ignore + protos.google.showcase.v1beta1.Echo, + opts); const echoStubMethods = ['echo', 'expand', 'collect', 'chat', 'pagedExpand', 'wait']; for (const methodName of echoStubMethods) { + // @ts-ignore const innerCallPromise = echoStub.then( + // @ts-ignore stub => (...args: Array<{}>) => { return stub[methodName].apply(stub, args); }, @@ -158,6 +210,13 @@ export class EchoClient { static get servicePath() { return 'localhost'; } + /** + * The DNS address for this API service - same as servicePath(), + * exists for compatibility reasons. + */ + static get apiEndpoint() { + return 'localhost'; + } /** * The port for this API service. @@ -194,31 +253,31 @@ export class EchoClient { // -- Service calls -- // ------------------- echo( - request: protos.google.showcase.v1beta1.IEchoRequest, + request: protosType.google.showcase.v1beta1.IEchoRequest, options?: gax.CallOptions): Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined + protosType.google.showcase.v1beta1.IEchoResponse, + protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined ]>; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, + request: protosType.google.showcase.v1beta1.IEchoRequest, options: gax.CallOptions, callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, + protosType.google.showcase.v1beta1.IEchoResponse, + protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): void; echo( - request: protos.google.showcase.v1beta1.IEchoRequest, + request: protosType.google.showcase.v1beta1.IEchoRequest, optionsOrCallback?: gax.CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>, + protosType.google.showcase.v1beta1.IEchoResponse, + protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>, callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, + protosType.google.showcase.v1beta1.IEchoResponse, + protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): Promise<[ - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined + protosType.google.showcase.v1beta1.IEchoResponse, + protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined ]>|void { request = request || {}; let options = optionsOrCallback; @@ -231,7 +290,7 @@ export class EchoClient { } expand( - request?: protos.google.showcase.v1beta1.IExpandRequest, + request?: protosType.google.showcase.v1beta1.IExpandRequest, options?: gax.CallOptions): gax.ServerStreamingCall{ request = request || {}; @@ -242,21 +301,21 @@ export class EchoClient { collect( options: gax.CallOptions, callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): + protosType.google.showcase.v1beta1.IEchoResponse, + protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): gax.ClientStreamingCall; collect( callback: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): + protosType.google.showcase.v1beta1.IEchoResponse, + protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): gax.ClientStreamingCall; collect( optionsOrCallback: gax.CallOptions|Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>, + protosType.google.showcase.v1beta1.IEchoResponse, + protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>, callback?: Callback< - protos.google.showcase.v1beta1.IEchoResponse, - protos.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): + protosType.google.showcase.v1beta1.IEchoResponse, + protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): gax.ClientStreamingCall { if (optionsOrCallback instanceof Function && callback === undefined) { callback = optionsOrCallback; @@ -273,4 +332,40 @@ export class EchoClient { return this._innerApiCalls.chat(options); } + wait( + request: protosType.google.showcase.v1beta1.IWaitRequest, + options?: gax.CallOptions): + Promise<[ + protosType.google.longrunning.IOperation, + protosType.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined + ]>; + wait( + request: protosType.google.showcase.v1beta1.IWaitRequest, + options: gax.CallOptions, + callback: Callback< + protosType.google.longrunning.IOperation, + protosType.google.showcase.v1beta1.IWaitRequest|undefined, + {}|undefined>): void; + wait( + request: protosType.google.showcase.v1beta1.IWaitRequest, + optionsOrCallback?: gax.CallOptions|Callback< + protosType.google.longrunning.IOperation, + protosType.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined>, + callback?: Callback< + protosType.google.longrunning.IOperation, + protosType.google.showcase.v1beta1.IWaitRequest|undefined, + {}|undefined>): + Promise<[ + protosType.google.longrunning.IOperation, + protosType.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options = optionsOrCallback; + if (typeof options === 'function' && callback === undefined) { + callback = options; + options = {}; + } + options = options || {}; + return this._innerApiCalls.wait(request, options, callback); + } } From 07ae4432eb85e1a7eab12bc5d1b95d1628bf6177 Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Mon, 30 Sep 2019 16:35:24 -0700 Subject: [PATCH 09/11] gts fix --- typescript/src/cli.ts | 4 +- typescript/src/generator.ts | 35 ++++--- typescript/src/schema/api.ts | 58 ++++------ typescript/src/schema/naming.ts | 13 ++- typescript/src/schema/proto.ts | 180 +++++++++++++------------------- typescript/src/templater.ts | 43 +++----- typescript/src/util.ts | 4 +- typescript/test/baseline.ts | 86 ++++++--------- typescript/test/multi_proto.ts | 87 ++++++--------- typescript/test/naming.ts | 2 +- typescript/test/proto.ts | 10 +- typescript/test/util.ts | 118 ++++++--------------- 12 files changed, 242 insertions(+), 398 deletions(-) diff --git a/typescript/src/cli.ts b/typescript/src/cli.ts index 4225cbbdb..51481f102 100644 --- a/typescript/src/cli.ts +++ b/typescript/src/cli.ts @@ -15,11 +15,11 @@ // limitations under the License. import * as commandLineArgs from 'command-line-args'; -import { Generator } from './generator'; +import {Generator} from './generator'; async function main() { const optionDefinitions: commandLineArgs.OptionDefinition[] = [ - { name: 'descriptor', type: String }, + {name: 'descriptor', type: String}, ]; const options = commandLineArgs(optionDefinitions); diff --git a/typescript/src/generator.ts b/typescript/src/generator.ts index c1bb6bf10..3fb7e789a 100644 --- a/typescript/src/generator.ts +++ b/typescript/src/generator.ts @@ -17,9 +17,9 @@ import * as path from 'path'; import * as plugin from '../../pbjs-genfiles/plugin'; -import { API } from './schema/api'; -import { processTemplates } from './templater'; -import { commonPrefix } from './util'; +import {API} from './schema/api'; +import {processTemplates} from './templater'; +import {commonPrefix} from './util'; const templateDirectory = 'templates/typescript_gapic'; // If needed, we can make it possible to load templates from different locations @@ -30,15 +30,16 @@ export class Generator { response: plugin.google.protobuf.compiler.CodeGeneratorResponse; constructor() { - this.request = plugin.google.protobuf.compiler.CodeGeneratorRequest.create(); - this.response = plugin.google.protobuf.compiler.CodeGeneratorResponse.create(); + this.request = + plugin.google.protobuf.compiler.CodeGeneratorRequest.create(); + this.response = + plugin.google.protobuf.compiler.CodeGeneratorResponse.create(); } async initializeFromStdin() { const inputBuffer = await getStdin.buffer(); this.request = plugin.google.protobuf.compiler.CodeGeneratorRequest.decode( - inputBuffer - ); + inputBuffer); } addProtosToResponse() { @@ -48,7 +49,8 @@ export class Generator { protoFilenames.push(proto.name); } } - const protoList = plugin.google.protobuf.compiler.CodeGeneratorResponse.File.create(); + const protoList = + plugin.google.protobuf.compiler.CodeGeneratorResponse.File.create(); protoList.name = 'proto.list'; protoList.content = protoFilenames.join('\n') + '\n'; this.response.file.push(protoList); @@ -56,11 +58,9 @@ export class Generator { buildAPIObject(): API { const protoFilesToGenerate = this.request.protoFile.filter( - pf => pf.name && this.request.fileToGenerate.includes(pf.name) - ); - const packageNamesToGenerate = protoFilesToGenerate.map( - pf => pf.package || '' - ); + pf => pf.name && this.request.fileToGenerate.includes(pf.name)); + const packageNamesToGenerate = + protoFilesToGenerate.map(pf => pf.package || ''); const packageName = commonPrefix(packageNamesToGenerate).replace(/\.$/, ''); if (packageName === '') { throw new Error('Cannot get package name to generate.'); @@ -77,7 +77,8 @@ export class Generator { async generate() { const fileToGenerate = this.request.fileToGenerate; - this.response = plugin.google.protobuf.compiler.CodeGeneratorResponse.create(); + this.response = + plugin.google.protobuf.compiler.CodeGeneratorResponse.create(); this.addProtosToResponse(); const api = this.buildAPIObject(); @@ -86,9 +87,9 @@ export class Generator { // console.warn(JSON.stringify(api.services, null, ' ')); // console.warn(JSON.stringify(api, null, ' ')); - const outputBuffer = plugin.google.protobuf.compiler.CodeGeneratorResponse.encode( - this.response - ).finish(); + const outputBuffer = plugin.google.protobuf.compiler.CodeGeneratorResponse + .encode(this.response) + .finish(); process.stdout.write(outputBuffer); } } diff --git a/typescript/src/schema/api.ts b/typescript/src/schema/api.ts index 0c3e2066a..a94094108 100644 --- a/typescript/src/schema/api.ts +++ b/typescript/src/schema/api.ts @@ -1,7 +1,7 @@ import * as plugin from '../../../pbjs-genfiles/plugin'; -import { Naming } from './naming'; -import { Proto } from './proto'; +import {Naming} from './naming'; +import {Proto} from './proto'; export interface ProtosMap { [filename: string]: Proto; @@ -13,53 +13,37 @@ export class API { // TODO: subpackages constructor( - fileDescriptors: plugin.google.protobuf.IFileDescriptorProto[], - packageName: string - ) { - this.naming = new Naming( - fileDescriptors.filter( - fd => fd.package && fd.package.startsWith(packageName) - ) - ); - this.protos = fileDescriptors - .filter(fd => fd.name) - .reduce( - (map, fd) => { - map[fd.name!] = new Proto(fd, packageName); - return map; - }, - {} as ProtosMap - ); + fileDescriptors: plugin.google.protobuf.IFileDescriptorProto[], + packageName: string) { + this.naming = new Naming(fileDescriptors.filter( + fd => fd.package && fd.package.startsWith(packageName))); + this.protos = fileDescriptors.filter(fd => fd.name).reduce((map, fd) => { + map[fd.name!] = new Proto(fd, packageName); + return map; + }, {} as ProtosMap); } get services() { return Object.keys(this.protos) - .map(filename => this.protos[filename]) - .filter(proto => proto.fileToGenerate) - .reduce( - (retval, proto) => { + .map(filename => this.protos[filename]) + .filter(proto => proto.fileToGenerate) + .reduce((retval, proto) => { retval.push( - ...Object.keys(proto.services).map(name => proto.services[name]) - ); + ...Object.keys(proto.services).map(name => proto.services[name])); return retval; - }, - [] as plugin.google.protobuf.IServiceDescriptorProto[] - ); + }, [] as plugin.google.protobuf.IServiceDescriptorProto[]); } get filesToGenerate() { - return Object.keys(this.protos).filter( - proto => this.protos[proto].fileToGenerate - ); + return Object.keys(this.protos) + .filter(proto => this.protos[proto].fileToGenerate); } get protoFilesToGenerateJSON() { return JSON.stringify( - this.filesToGenerate.map(file => { - return `../../protos/${file}`; - }), - null, - ' ' - ); + this.filesToGenerate.map(file => { + return `../../protos/${file}`; + }), + null, ' '); } } diff --git a/typescript/src/schema/naming.ts b/typescript/src/schema/naming.ts index a31ca7427..6d758443c 100644 --- a/typescript/src/schema/naming.ts +++ b/typescript/src/schema/naming.ts @@ -1,5 +1,5 @@ import * as plugin from '../../../pbjs-genfiles/plugin'; -import { commonPrefix } from '../util'; +import {commonPrefix} from '../util'; export class Naming { name: string; @@ -20,16 +20,16 @@ export class Naming { // Define the regular expression to match a version component // (e.g. "v1", "v1beta4", etc.). - const pattern = /^((?:[a-z0-9_.]+?)\.)?([a-z0-9_]+)(?:\.(v[0-9]+(p[0-9]+)?((alpha|beta)[0-9]+)?[^.]*))?$/; + const pattern = + /^((?:[a-z0-9_.]+?)\.)?([a-z0-9_]+)(?:\.(v[0-9]+(p[0-9]+)?((alpha|beta)[0-9]+)?[^.]*))?$/; const match = rootPackage.match(pattern); if (!match) { throw new Error(`Cannot parse package name ${rootPackage}.`); } const [, namespaces, name, version] = match; if (!namespaces) { - throw new Error( - `Cannot parse package name ${rootPackage}: namespace is not defined.` - ); + throw new Error(`Cannot parse package name ${ + rootPackage}: namespace is not defined.`); } this.name = name.capitalize(); this.productName = this.name; @@ -39,8 +39,7 @@ export class Naming { if (!this.version && protoPackages.length > 1) { throw new Error( - 'All protos must have the same proto package up to and including the version.' - ); + 'All protos must have the same proto package up to and including the version.'); } } } diff --git a/typescript/src/schema/proto.ts b/typescript/src/schema/proto.ts index a32b8e2a2..f01995650 100644 --- a/typescript/src/schema/proto.ts +++ b/typescript/src/schema/proto.ts @@ -1,24 +1,20 @@ -import { ENGINE_METHOD_DIGESTS } from 'constants'; -import { NEG_ONE } from 'long'; +import {ENGINE_METHOD_DIGESTS} from 'constants'; +import {NEG_ONE} from 'long'; import * as plugin from '../../../pbjs-genfiles/plugin'; -interface MethodDescriptorProto - extends plugin.google.protobuf.IMethodDescriptorProto { - idempotence: 'idempotent' | 'non_idempotent'; +interface MethodDescriptorProto extends + plugin.google.protobuf.IMethodDescriptorProto { + idempotence: 'idempotent'|'non_idempotent'; longRunning?: plugin.google.longrunning.IOperationInfo; - streaming: - | 'CLIENT_STREAMING' - | 'SERVER_STREAMING' - | 'BIDI_STREAMING' - | undefined; - pagingFieldName: string | undefined; + streaming:|'CLIENT_STREAMING'|'SERVER_STREAMING'|'BIDI_STREAMING'|undefined; + pagingFieldName: string|undefined; inputInterface: string; outputInterface: string; } -interface ServiceDescriptorProto - extends plugin.google.protobuf.IServiceDescriptorProto { +interface ServiceDescriptorProto extends + plugin.google.protobuf.IServiceDescriptorProto { method: MethodDescriptorProto[]; simpleMethods: MethodDescriptorProto[]; longRunning: MethodDescriptorProto[]; @@ -47,12 +43,9 @@ export interface EnumsMap { // methods of the given service, to use in templates. function idempotence(method: MethodDescriptorProto) { - if ( - method.options && - method.options['.google.api.http'] && - (method.options['.google.api.http']['get'] || - method.options['.google.api.http']['put']) - ) { + if (method.options && method.options['.google.api.http'] && + (method.options['.google.api.http']['get'] || + method.options['.google.api.http']['put'])) { return 'idempotent'; } return 'non_idempotent'; @@ -82,20 +75,17 @@ function pagingFieldName(messages: MessagesMap, method: MethodDescriptorProto) { const inputType = messages[method.inputType!]; const outputType = messages[method.outputType!]; const hasPageToken = - inputType && inputType.field!.some(field => field.name === 'page_token'); + inputType && inputType.field!.some(field => field.name === 'page_token'); const hasPageSize = - inputType && inputType.field!.some(field => field.name === 'page_size'); - const hasNextPageToken = - outputType && - outputType.field!.some(field => field.name === 'next_page_token'); + inputType && inputType.field!.some(field => field.name === 'page_size'); + const hasNextPageToken = outputType && + outputType.field!.some(field => field.name === 'next_page_token'); if (!hasPageToken || !hasPageSize || !hasNextPageToken) { return undefined; } const repeatedFields = outputType.field!.filter( - field => - field.label === - plugin.google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED - ); + field => field.label === + plugin.google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED); if (repeatedFields.length !== 1) { return undefined; } @@ -108,72 +98,56 @@ function toInterface(type: string) { function augmentMethod(messages: MessagesMap, method: MethodDescriptorProto) { method = Object.assign( - { - idempotence: idempotence(method), - longRunning: longrunning(method), - streaming: streaming(method), - pagingFieldName: pagingFieldName(messages, method), - inputInterface: toInterface(method.inputType!), - outputInterface: toInterface(method.outputType!), - }, - method - ) as MethodDescriptorProto; + { + idempotence: idempotence(method), + longRunning: longrunning(method), + streaming: streaming(method), + pagingFieldName: pagingFieldName(messages, method), + inputInterface: toInterface(method.inputType!), + outputInterface: toInterface(method.outputType!), + }, + method) as MethodDescriptorProto; return method; } function augmentService( - messages: MessagesMap, - service: plugin.google.protobuf.IServiceDescriptorProto -) { + messages: MessagesMap, + service: plugin.google.protobuf.IServiceDescriptorProto) { const augmentedService = service as ServiceDescriptorProto; - augmentedService.method = augmentedService.method.map(method => - augmentMethod(messages, method) - ); + augmentedService.method = + augmentedService.method.map(method => augmentMethod(messages, method)); augmentedService.simpleMethods = augmentedService.method.filter( - method => - !method.longRunning && !method.streaming && !method.pagingFieldName - ); - augmentedService.longRunning = augmentedService.method.filter( - method => method.longRunning - ); - augmentedService.streaming = augmentedService.method.filter( - method => method.streaming - ); + method => + !method.longRunning && !method.streaming && !method.pagingFieldName); + augmentedService.longRunning = + augmentedService.method.filter(method => method.longRunning); + augmentedService.streaming = + augmentedService.method.filter(method => method.streaming); augmentedService.clientStreaming = augmentedService.method.filter( - method => method.streaming === 'CLIENT_STREAMING' - ); + method => method.streaming === 'CLIENT_STREAMING'); augmentedService.serverStreaming = augmentedService.method.filter( - method => method.streaming === 'SERVER_STREAMING' - ); + method => method.streaming === 'SERVER_STREAMING'); augmentedService.bidiStreaming = augmentedService.method.filter( - method => method.streaming === 'BIDI_STREAMING' - ); - augmentedService.paging = augmentedService.method.filter( - method => method.pagingFieldName - ); + method => method.streaming === 'BIDI_STREAMING'); + augmentedService.paging = + augmentedService.method.filter(method => method.pagingFieldName); augmentedService.hostname = ''; augmentedService.port = 0; - if ( - augmentedService.options && - augmentedService.options['.google.api.defaultHost'] - ) { + if (augmentedService.options && + augmentedService.options['.google.api.defaultHost']) { const match = augmentedService.options['.google.api.defaultHost'].match( - /^(.*):(\d+)$/ - ); + /^(.*):(\d+)$/); if (match) { augmentedService.hostname = match[1]; augmentedService.port = Number.parseInt(match[2], 10); } } augmentedService.oauthScopes = []; - if ( - augmentedService.options && - augmentedService.options['.google.api.oauthScopes'] - ) { - augmentedService.oauthScopes = augmentedService.options[ - '.google.api.oauthScopes' - ].split(','); + if (augmentedService.options && + augmentedService.options['.google.api.oauthScopes']) { + augmentedService.oauthScopes = + augmentedService.options['.google.api.oauthScopes'].split(','); } return augmentedService; } @@ -187,48 +161,34 @@ export class Proto { // TODO: need to store metadata? address? constructor( - fd: plugin.google.protobuf.IFileDescriptorProto, - packageName: string - ) { + fd: plugin.google.protobuf.IFileDescriptorProto, packageName: string) { fd.enumType = fd.enumType || []; fd.messageType = fd.messageType || []; fd.service = fd.service || []; this.filePB2 = fd; - this.messages = fd.messageType - .filter(message => message.name) - .reduce( - (map, message) => { - map['.' + fd.package! + '.' + message.name!] = message; - return map; - }, - {} as MessagesMap - ); - - this.enums = fd.enumType - .filter(enum_ => enum_.name) - .reduce( - (map, enum_) => { + this.messages = fd.messageType.filter(message => message.name) + .reduce((map, message) => { + map['.' + fd.package! + '.' + message.name!] = + message; + return map; + }, {} as MessagesMap); + + this.enums = + fd.enumType.filter(enum_ => enum_.name).reduce((map, enum_) => { map[enum_.name!] = enum_; return map; - }, - {} as EnumsMap - ); - - this.fileToGenerate = fd.package - ? fd.package.startsWith(packageName) - : false; - - this.services = fd.service - .filter(service => service.name) - .map(service => augmentService(this.messages, service)) - .reduce( - (map, service) => { - map[service.name!] = service; - return map; - }, - {} as ServicesMap - ); + }, {} as EnumsMap); + + this.fileToGenerate = + fd.package ? fd.package.startsWith(packageName) : false; + + this.services = fd.service.filter(service => service.name) + .map(service => augmentService(this.messages, service)) + .reduce((map, service) => { + map[service.name!] = service; + return map; + }, {} as ServicesMap); } } diff --git a/typescript/src/templater.ts b/typescript/src/templater.ts index e995a3459..1966d14ca 100644 --- a/typescript/src/templater.ts +++ b/typescript/src/templater.ts @@ -5,9 +5,9 @@ import * as util from 'util'; import * as plugin from '../../pbjs-genfiles/plugin'; -import { API } from './schema/api'; +import {API} from './schema/api'; -const commonParameters: { [name: string]: string } = { +const commonParameters: {[name: string]: string} = { copyrightYear: new Date().getFullYear().toString(), }; @@ -16,9 +16,7 @@ const readDir = util.promisify(fs.readdir); const lstat = util.promisify(fs.lstat); async function recursiveFileList( - basePath: string, - nameRegex: RegExp -): Promise { + basePath: string, nameRegex: RegExp): Promise { const dirQueue: string[] = [basePath]; const result: string[] = []; while (dirQueue.length > 0) { @@ -38,26 +36,21 @@ async function recursiveFileList( } function renderFile( - targetFilename: string, - templateFilename: string, - renderParameters: {} -) { + targetFilename: string, templateFilename: string, renderParameters: {}) { const processed = nunjucks.render(templateFilename, renderParameters); - const output = plugin.google.protobuf.compiler.CodeGeneratorResponse.File.create(); + const output = + plugin.google.protobuf.compiler.CodeGeneratorResponse.File.create(); output.name = targetFilename; output.content = processed; return output; } function processOneTemplate( - basePath: string, - templateFilename: string, - api: API -) { - const result: plugin.google.protobuf.compiler.CodeGeneratorResponse.File[] = []; - let outputFilename = templateFilename - .substr(basePath.length + 1) - .replace(/\.njk$/, ''); + basePath: string, templateFilename: string, api: API) { + const result: plugin.google.protobuf.compiler.CodeGeneratorResponse.File[] = + []; + let outputFilename = + templateFilename.substr(basePath.length + 1).replace(/\.njk$/, ''); // Filename can have one or more variables in it that should be substituted // with their actual values. Currently supported: $service, $version Note: @@ -67,18 +60,13 @@ function processOneTemplate( // {api, commonParameters} if (outputFilename.match(/\$service/)) { for (const service of api.services) { - result.push( - renderFile( + result.push(renderFile( outputFilename.replace(/\$service/, service.name!.toLowerCase()), - templateFilename, - { api, commonParameters, service } - ) - ); + templateFilename, {api, commonParameters, service})); } } else { result.push( - renderFile(outputFilename, templateFilename, { api, commonParameters }) - ); + renderFile(outputFilename, templateFilename, {api, commonParameters})); } return result; @@ -87,7 +75,8 @@ function processOneTemplate( export async function processTemplates(basePath: string, api: API) { basePath = basePath.replace(/\/*$/, ''); const templateFiles = await recursiveFileList(basePath, /^(?!_[^_]).*\.njk$/); - const result: plugin.google.protobuf.compiler.CodeGeneratorResponse.File[] = []; + const result: plugin.google.protobuf.compiler.CodeGeneratorResponse.File[] = + []; for (const templateFilename of templateFiles) { const generatedFiles = processOneTemplate(basePath, templateFilename, api); result.push(...generatedFiles); diff --git a/typescript/src/util.ts b/typescript/src/util.ts index b0191c89d..401c928f9 100644 --- a/typescript/src/util.ts +++ b/typescript/src/util.ts @@ -25,8 +25,8 @@ String.prototype.capitalize = function(this: string): string { String.prototype.words = function(this: string): string[] { // split on spaces, non-alphanumeric, or capital letters return this.split(/(?=[A-Z])|[\s\W_]+/) - .filter(w => w.length > 0) - .map(w => w.toLowerCase()); + .filter(w => w.length > 0) + .map(w => w.toLowerCase()); }; String.prototype.toCamelCase = function(this: string): string { diff --git a/typescript/test/baseline.ts b/typescript/test/baseline.ts index a4cacfcfd..34575241e 100644 --- a/typescript/test/baseline.ts +++ b/typescript/test/baseline.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import { execSync } from 'child_process'; +import {execSync} from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as rimraf from 'rimraf'; @@ -21,68 +21,48 @@ import * as rimraf from 'rimraf'; const cwd = process.cwd(); const OUTPUT_DIR = path.join(cwd, '.baseline-test-out'); -const GENERATED_CLIENT_FILE = path.join( - OUTPUT_DIR, - 'src', - 'v1beta1', - 'echo_client.ts' -); -const GOOGLE_GAX_PROTOS_DIR = path.join( - cwd, - 'node_modules', - 'google-gax', - 'protos' -); +const GENERATED_CLIENT_FILE = + path.join(OUTPUT_DIR, 'src', 'v1beta1', 'echo_client.ts'); +const GOOGLE_GAX_PROTOS_DIR = + path.join(cwd, 'node_modules', 'google-gax', 'protos'); const PROTOS_DIR = path.join(cwd, 'build', 'test', 'protos'); -const ECHO_PROTO_FILE = path.join( - PROTOS_DIR, - 'google', - 'showcase', - 'v1beta1', - 'echo.proto' -); +const ECHO_PROTO_FILE = + path.join(PROTOS_DIR, 'google', 'showcase', 'v1beta1', 'echo.proto'); const CLIENT_LIBRARY_BASELINE = path.join( - cwd, - 'typescript', - 'test', - 'testdata', - 'echo_client_baseline.ts.txt' -); + cwd, 'typescript', 'test', 'testdata', 'echo_client_baseline.ts.txt'); const SRCDIR = path.join(cwd, 'build', 'src'); const CLI = path.join(SRCDIR, 'cli.js'); const PLUGIN = path.join(SRCDIR, 'protoc-gen-typescript_gapic'); describe('CodeGeneratorTest', () => { describe('Generate client library', () => { - it('Generated client library should have same output with baseline.', function() { - this.timeout(10000); - if (fs.existsSync(OUTPUT_DIR)) { - rimraf.sync(OUTPUT_DIR); - } - fs.mkdirSync(OUTPUT_DIR); + it('Generated client library should have same output with baseline.', + function() { + this.timeout(10000); + if (fs.existsSync(OUTPUT_DIR)) { + rimraf.sync(OUTPUT_DIR); + } + fs.mkdirSync(OUTPUT_DIR); - if (fs.existsSync(PLUGIN)) { - rimraf.sync(PLUGIN); - } - fs.copyFileSync(CLI, PLUGIN); - process.env['PATH'] = SRCDIR + path.delimiter + process.env['PATH']; + if (fs.existsSync(PLUGIN)) { + rimraf.sync(PLUGIN); + } + fs.copyFileSync(CLI, PLUGIN); + process.env['PATH'] = SRCDIR + path.delimiter + process.env['PATH']; - try { - execSync(`chmod +x ${PLUGIN}`); - } catch (err) { - console.warn(`Failed to chmod +x ${PLUGIN}: ${err}. Ignoring...`); - } + try { + execSync(`chmod +x ${PLUGIN}`); + } catch (err) { + console.warn(`Failed to chmod +x ${PLUGIN}: ${err}. Ignoring...`); + } - execSync( - `protoc --typescript_gapic_out=${OUTPUT_DIR} ` + - `-I${GOOGLE_GAX_PROTOS_DIR} ` + - `-I${PROTOS_DIR} ` + - ECHO_PROTO_FILE - ); - assert.strictEqual( - fs.readFileSync(GENERATED_CLIENT_FILE).toString(), - fs.readFileSync(CLIENT_LIBRARY_BASELINE).toString() - ); - }); + execSync( + `protoc --typescript_gapic_out=${OUTPUT_DIR} ` + + `-I${GOOGLE_GAX_PROTOS_DIR} ` + + `-I${PROTOS_DIR} ` + ECHO_PROTO_FILE); + assert.strictEqual( + fs.readFileSync(GENERATED_CLIENT_FILE).toString(), + fs.readFileSync(CLIENT_LIBRARY_BASELINE).toString()); + }); }); }); diff --git a/typescript/test/multi_proto.ts b/typescript/test/multi_proto.ts index b37496bfe..54a8d688b 100644 --- a/typescript/test/multi_proto.ts +++ b/typescript/test/multi_proto.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import { execSync } from 'child_process'; +import {execSync} from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as rimraf from 'rimraf'; @@ -21,69 +21,50 @@ import * as rimraf from 'rimraf'; const cwd = process.cwd(); const OUTPUT_DIR = path.join(cwd, '.multi-proto-test-out'); -const GENERATED_PROTO_FILE = path.join( - OUTPUT_DIR, - 'src', - 'v1', - 'keymanagementservice_proto_list.json' -); -const GOOGLE_GAX_PROTOS_DIR = path.join( - cwd, - 'node_modules', - 'google-gax', - 'protos' -); +const GENERATED_PROTO_FILE = + path.join(OUTPUT_DIR, 'src', 'v1', 'keymanagementservice_proto_list.json'); +const GOOGLE_GAX_PROTOS_DIR = + path.join(cwd, 'node_modules', 'google-gax', 'protos'); const PROTOS_DIR = path.join(cwd, 'build', 'test', 'protos'); -const KMS_PROTO_FILE = path.join( - PROTOS_DIR, - 'google', - 'kms', - 'v1', - 'service.proto' -); +const KMS_PROTO_FILE = + path.join(PROTOS_DIR, 'google', 'kms', 'v1', 'service.proto'); const PROTOLIST_LIBRARY_BASELINE = path.join( - cwd, - 'typescript', - 'test', - 'testdata', - 'keymanagementservice_proto_list.json' -); + cwd, 'typescript', 'test', 'testdata', + 'keymanagementservice_proto_list.json'); const SRCDIR = path.join(cwd, 'build', 'src'); const CLI = path.join(SRCDIR, 'cli.js'); const PLUGIN = path.join(SRCDIR, 'protoc-gen-typescript_gapic'); describe('Proto List Generate Test', () => { describe('Generate Client library', () => { - it('Generated proto list should have same output with baseline.', function() { - this.timeout(10000); - if (fs.existsSync(OUTPUT_DIR)) { - rimraf.sync(OUTPUT_DIR); - } - fs.mkdirSync(OUTPUT_DIR); + it('Generated proto list should have same output with baseline.', + function() { + this.timeout(10000); + if (fs.existsSync(OUTPUT_DIR)) { + rimraf.sync(OUTPUT_DIR); + } + fs.mkdirSync(OUTPUT_DIR); - if (fs.existsSync(PLUGIN)) { - rimraf.sync(PLUGIN); - } - fs.copyFileSync(CLI, PLUGIN); - process.env['PATH'] = SRCDIR + path.delimiter + process.env['PATH']; + if (fs.existsSync(PLUGIN)) { + rimraf.sync(PLUGIN); + } + fs.copyFileSync(CLI, PLUGIN); + process.env['PATH'] = SRCDIR + path.delimiter + process.env['PATH']; - try { - execSync(`chmod +x ${PLUGIN}`); - } catch (err) { - console.warn(`Failed to chmod +x ${PLUGIN}: ${err}. Ignoring...`); - } + try { + execSync(`chmod +x ${PLUGIN}`); + } catch (err) { + console.warn(`Failed to chmod +x ${PLUGIN}: ${err}. Ignoring...`); + } - execSync( - `protoc --typescript_gapic_out=${OUTPUT_DIR} ` + - `-I${GOOGLE_GAX_PROTOS_DIR} ` + - `-I${PROTOS_DIR} ` + - KMS_PROTO_FILE - ); - assert.strictEqual( - fs.readFileSync(GENERATED_PROTO_FILE).toString(), - fs.readFileSync(PROTOLIST_LIBRARY_BASELINE).toString() - ); - }); + execSync( + `protoc --typescript_gapic_out=${OUTPUT_DIR} ` + + `-I${GOOGLE_GAX_PROTOS_DIR} ` + + `-I${PROTOS_DIR} ` + KMS_PROTO_FILE); + assert.strictEqual( + fs.readFileSync(GENERATED_PROTO_FILE).toString(), + fs.readFileSync(PROTOLIST_LIBRARY_BASELINE).toString()); + }); }); }); diff --git a/typescript/test/naming.ts b/typescript/test/naming.ts index a5c31117e..24d952ee5 100644 --- a/typescript/test/naming.ts +++ b/typescript/test/naming.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import * as plugin from '../../pbjs-genfiles/plugin'; -import { Naming } from '../src/schema/naming'; +import {Naming} from '../src/schema/naming'; describe('schema/naming.ts', () => { it('parses name correctly', () => { diff --git a/typescript/test/proto.ts b/typescript/test/proto.ts index 5da1b62b4..7e8e95251 100644 --- a/typescript/test/proto.ts +++ b/typescript/test/proto.ts @@ -15,8 +15,10 @@ import * as assert from 'assert'; import * as plugin from '../../pbjs-genfiles/plugin'; -import { Proto } from '../src/schema/proto'; +import {Proto} from '../src/schema/proto'; -describe('schema/proto.ts', () => { - // TODO: test service augmentation -}); +describe( + 'schema/proto.ts', + () => { + // TODO: test service augmentation + }); diff --git a/typescript/test/util.ts b/typescript/test/util.ts index 211afe3ee..10c77a5de 100644 --- a/typescript/test/util.ts +++ b/typescript/test/util.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import { commonPrefix } from '../src/util'; +import {commonPrefix} from '../src/util'; describe('util.ts', () => { describe('CommonPrefix', () => { @@ -86,132 +86,80 @@ describe('util.ts', () => { assert.deepStrictEqual(''.toCamelCase(), ''); assert.deepStrictEqual('test'.toCamelCase(), 'test'); assert.deepStrictEqual( - 'camelCaseString'.toCamelCase(), - 'camelCaseString' - ); + 'camelCaseString'.toCamelCase(), 'camelCaseString'); assert.deepStrictEqual( - 'PascalCaseString'.toCamelCase(), - 'pascalCaseString' - ); + 'PascalCaseString'.toCamelCase(), 'pascalCaseString'); assert.deepStrictEqual( - 'snake_case_string'.toCamelCase(), - 'snakeCaseString' - ); + 'snake_case_string'.toCamelCase(), 'snakeCaseString'); assert.deepStrictEqual( - 'kebab-case-string'.toCamelCase(), - 'kebabCaseString' - ); + 'kebab-case-string'.toCamelCase(), 'kebabCaseString'); assert.deepStrictEqual( - 'random/separators-string'.toCamelCase(), - 'randomSeparatorsString' - ); + 'random/separators-string'.toCamelCase(), 'randomSeparatorsString'); assert.deepStrictEqual( - 'mixedType-string.SomewhatWeird'.toCamelCase(), - 'mixedTypeStringSomewhatWeird' - ); + 'mixedType-string.SomewhatWeird'.toCamelCase(), + 'mixedTypeStringSomewhatWeird'); assert.deepStrictEqual( - 'productName.v1p1beta1'.toCamelCase(), - 'productNameV1p1beta1' - ); + 'productName.v1p1beta1'.toCamelCase(), 'productNameV1p1beta1'); }); it('should convert to PascalCase', () => { assert.deepStrictEqual(''.toPascalCase(), ''); assert.deepStrictEqual('test'.toPascalCase(), 'Test'); assert.deepStrictEqual( - 'camelCaseString'.toPascalCase(), - 'CamelCaseString' - ); + 'camelCaseString'.toPascalCase(), 'CamelCaseString'); assert.deepStrictEqual( - 'PascalCaseString'.toPascalCase(), - 'PascalCaseString' - ); + 'PascalCaseString'.toPascalCase(), 'PascalCaseString'); assert.deepStrictEqual( - 'snake_case_string'.toPascalCase(), - 'SnakeCaseString' - ); + 'snake_case_string'.toPascalCase(), 'SnakeCaseString'); assert.deepStrictEqual( - 'kebab-case-string'.toPascalCase(), - 'KebabCaseString' - ); + 'kebab-case-string'.toPascalCase(), 'KebabCaseString'); assert.deepStrictEqual( - 'random/separators-string'.toPascalCase(), - 'RandomSeparatorsString' - ); + 'random/separators-string'.toPascalCase(), 'RandomSeparatorsString'); assert.deepStrictEqual( - 'mixedType-string.SomewhatWeird'.toPascalCase(), - 'MixedTypeStringSomewhatWeird' - ); + 'mixedType-string.SomewhatWeird'.toPascalCase(), + 'MixedTypeStringSomewhatWeird'); assert.deepStrictEqual( - 'productName.v1p1beta1'.toPascalCase(), - 'ProductNameV1p1beta1' - ); + 'productName.v1p1beta1'.toPascalCase(), 'ProductNameV1p1beta1'); }); it('should convert to kebab-case', () => { assert.deepStrictEqual(''.toKebabCase(), ''); assert.deepStrictEqual('test'.toKebabCase(), 'test'); assert.deepStrictEqual( - 'camelCaseString'.toKebabCase(), - 'camel-case-string' - ); + 'camelCaseString'.toKebabCase(), 'camel-case-string'); assert.deepStrictEqual( - 'PascalCaseString'.toKebabCase(), - 'pascal-case-string' - ); + 'PascalCaseString'.toKebabCase(), 'pascal-case-string'); assert.deepStrictEqual( - 'snake_case_string'.toKebabCase(), - 'snake-case-string' - ); + 'snake_case_string'.toKebabCase(), 'snake-case-string'); assert.deepStrictEqual( - 'kebab-case-string'.toKebabCase(), - 'kebab-case-string' - ); + 'kebab-case-string'.toKebabCase(), 'kebab-case-string'); assert.deepStrictEqual( - 'random/separators-string'.toKebabCase(), - 'random-separators-string' - ); + 'random/separators-string'.toKebabCase(), 'random-separators-string'); assert.deepStrictEqual( - 'mixedType-string.SomewhatWeird'.toKebabCase(), - 'mixed-type-string-somewhat-weird' - ); + 'mixedType-string.SomewhatWeird'.toKebabCase(), + 'mixed-type-string-somewhat-weird'); assert.deepStrictEqual( - 'productName.v1p1beta1'.toKebabCase(), - 'product-name-v1p1beta1' - ); + 'productName.v1p1beta1'.toKebabCase(), 'product-name-v1p1beta1'); }); it('should convert to snake_case', () => { assert.deepStrictEqual(''.toSnakeCase(), ''); assert.deepStrictEqual('test'.toSnakeCase(), 'test'); assert.deepStrictEqual( - 'camelCaseString'.toSnakeCase(), - 'camel_case_string' - ); + 'camelCaseString'.toSnakeCase(), 'camel_case_string'); assert.deepStrictEqual( - 'PascalCaseString'.toSnakeCase(), - 'pascal_case_string' - ); + 'PascalCaseString'.toSnakeCase(), 'pascal_case_string'); assert.deepStrictEqual( - 'snake_case_string'.toSnakeCase(), - 'snake_case_string' - ); + 'snake_case_string'.toSnakeCase(), 'snake_case_string'); assert.deepStrictEqual( - 'kebab-case-string'.toSnakeCase(), - 'kebab_case_string' - ); + 'kebab-case-string'.toSnakeCase(), 'kebab_case_string'); assert.deepStrictEqual( - 'random/separators-string'.toSnakeCase(), - 'random_separators_string' - ); + 'random/separators-string'.toSnakeCase(), 'random_separators_string'); assert.deepStrictEqual( - 'mixedType-string.SomewhatWeird'.toSnakeCase(), - 'mixed_type_string_somewhat_weird' - ); + 'mixedType-string.SomewhatWeird'.toSnakeCase(), + 'mixed_type_string_somewhat_weird'); assert.deepStrictEqual( - 'productName.v1p1beta1'.toSnakeCase(), - 'product_name_v1p1beta1' - ); + 'productName.v1p1beta1'.toSnakeCase(), 'product_name_v1p1beta1'); }); }); }); From 728505c571f9cac3920e6ccd56624d617b8063de Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Tue, 1 Oct 2019 10:22:47 -0700 Subject: [PATCH 10/11] update gts version and fix back the format --- package.json | 2 +- typescript/src/cli.ts | 4 +- typescript/src/generator.ts | 35 +++---- typescript/src/schema/api.ts | 58 ++++++---- typescript/src/schema/naming.ts | 13 +-- typescript/src/schema/proto.ts | 180 +++++++++++++++++++------------- typescript/src/templater.ts | 43 +++++--- typescript/src/util.ts | 4 +- typescript/test/baseline.ts | 86 +++++++++------ typescript/test/multi_proto.ts | 87 +++++++++------ typescript/test/naming.ts | 2 +- typescript/test/proto.ts | 10 +- typescript/test/util.ts | 118 +++++++++++++++------ 13 files changed, 399 insertions(+), 243 deletions(-) diff --git a/package.json b/package.json index 9f60b6b54..288e4be6a 100644 --- a/package.json +++ b/package.json @@ -45,7 +45,7 @@ "codecov": "^3.0.4", "espower-typescript": "^9.0.0", "google-gax": "^1.6.0", - "gts": "^0.9.0", + "gts": "^1.0.0", "intelli-espower-loader": "^1.0.1", "mocha": "^6.0.0", "power-assert": "^1.6.0", diff --git a/typescript/src/cli.ts b/typescript/src/cli.ts index 51481f102..4225cbbdb 100644 --- a/typescript/src/cli.ts +++ b/typescript/src/cli.ts @@ -15,11 +15,11 @@ // limitations under the License. import * as commandLineArgs from 'command-line-args'; -import {Generator} from './generator'; +import { Generator } from './generator'; async function main() { const optionDefinitions: commandLineArgs.OptionDefinition[] = [ - {name: 'descriptor', type: String}, + { name: 'descriptor', type: String }, ]; const options = commandLineArgs(optionDefinitions); diff --git a/typescript/src/generator.ts b/typescript/src/generator.ts index 3fb7e789a..c1bb6bf10 100644 --- a/typescript/src/generator.ts +++ b/typescript/src/generator.ts @@ -17,9 +17,9 @@ import * as path from 'path'; import * as plugin from '../../pbjs-genfiles/plugin'; -import {API} from './schema/api'; -import {processTemplates} from './templater'; -import {commonPrefix} from './util'; +import { API } from './schema/api'; +import { processTemplates } from './templater'; +import { commonPrefix } from './util'; const templateDirectory = 'templates/typescript_gapic'; // If needed, we can make it possible to load templates from different locations @@ -30,16 +30,15 @@ export class Generator { response: plugin.google.protobuf.compiler.CodeGeneratorResponse; constructor() { - this.request = - plugin.google.protobuf.compiler.CodeGeneratorRequest.create(); - this.response = - plugin.google.protobuf.compiler.CodeGeneratorResponse.create(); + this.request = plugin.google.protobuf.compiler.CodeGeneratorRequest.create(); + this.response = plugin.google.protobuf.compiler.CodeGeneratorResponse.create(); } async initializeFromStdin() { const inputBuffer = await getStdin.buffer(); this.request = plugin.google.protobuf.compiler.CodeGeneratorRequest.decode( - inputBuffer); + inputBuffer + ); } addProtosToResponse() { @@ -49,8 +48,7 @@ export class Generator { protoFilenames.push(proto.name); } } - const protoList = - plugin.google.protobuf.compiler.CodeGeneratorResponse.File.create(); + const protoList = plugin.google.protobuf.compiler.CodeGeneratorResponse.File.create(); protoList.name = 'proto.list'; protoList.content = protoFilenames.join('\n') + '\n'; this.response.file.push(protoList); @@ -58,9 +56,11 @@ export class Generator { buildAPIObject(): API { const protoFilesToGenerate = this.request.protoFile.filter( - pf => pf.name && this.request.fileToGenerate.includes(pf.name)); - const packageNamesToGenerate = - protoFilesToGenerate.map(pf => pf.package || ''); + pf => pf.name && this.request.fileToGenerate.includes(pf.name) + ); + const packageNamesToGenerate = protoFilesToGenerate.map( + pf => pf.package || '' + ); const packageName = commonPrefix(packageNamesToGenerate).replace(/\.$/, ''); if (packageName === '') { throw new Error('Cannot get package name to generate.'); @@ -77,8 +77,7 @@ export class Generator { async generate() { const fileToGenerate = this.request.fileToGenerate; - this.response = - plugin.google.protobuf.compiler.CodeGeneratorResponse.create(); + this.response = plugin.google.protobuf.compiler.CodeGeneratorResponse.create(); this.addProtosToResponse(); const api = this.buildAPIObject(); @@ -87,9 +86,9 @@ export class Generator { // console.warn(JSON.stringify(api.services, null, ' ')); // console.warn(JSON.stringify(api, null, ' ')); - const outputBuffer = plugin.google.protobuf.compiler.CodeGeneratorResponse - .encode(this.response) - .finish(); + const outputBuffer = plugin.google.protobuf.compiler.CodeGeneratorResponse.encode( + this.response + ).finish(); process.stdout.write(outputBuffer); } } diff --git a/typescript/src/schema/api.ts b/typescript/src/schema/api.ts index a94094108..0c3e2066a 100644 --- a/typescript/src/schema/api.ts +++ b/typescript/src/schema/api.ts @@ -1,7 +1,7 @@ import * as plugin from '../../../pbjs-genfiles/plugin'; -import {Naming} from './naming'; -import {Proto} from './proto'; +import { Naming } from './naming'; +import { Proto } from './proto'; export interface ProtosMap { [filename: string]: Proto; @@ -13,37 +13,53 @@ export class API { // TODO: subpackages constructor( - fileDescriptors: plugin.google.protobuf.IFileDescriptorProto[], - packageName: string) { - this.naming = new Naming(fileDescriptors.filter( - fd => fd.package && fd.package.startsWith(packageName))); - this.protos = fileDescriptors.filter(fd => fd.name).reduce((map, fd) => { - map[fd.name!] = new Proto(fd, packageName); - return map; - }, {} as ProtosMap); + fileDescriptors: plugin.google.protobuf.IFileDescriptorProto[], + packageName: string + ) { + this.naming = new Naming( + fileDescriptors.filter( + fd => fd.package && fd.package.startsWith(packageName) + ) + ); + this.protos = fileDescriptors + .filter(fd => fd.name) + .reduce( + (map, fd) => { + map[fd.name!] = new Proto(fd, packageName); + return map; + }, + {} as ProtosMap + ); } get services() { return Object.keys(this.protos) - .map(filename => this.protos[filename]) - .filter(proto => proto.fileToGenerate) - .reduce((retval, proto) => { + .map(filename => this.protos[filename]) + .filter(proto => proto.fileToGenerate) + .reduce( + (retval, proto) => { retval.push( - ...Object.keys(proto.services).map(name => proto.services[name])); + ...Object.keys(proto.services).map(name => proto.services[name]) + ); return retval; - }, [] as plugin.google.protobuf.IServiceDescriptorProto[]); + }, + [] as plugin.google.protobuf.IServiceDescriptorProto[] + ); } get filesToGenerate() { - return Object.keys(this.protos) - .filter(proto => this.protos[proto].fileToGenerate); + return Object.keys(this.protos).filter( + proto => this.protos[proto].fileToGenerate + ); } get protoFilesToGenerateJSON() { return JSON.stringify( - this.filesToGenerate.map(file => { - return `../../protos/${file}`; - }), - null, ' '); + this.filesToGenerate.map(file => { + return `../../protos/${file}`; + }), + null, + ' ' + ); } } diff --git a/typescript/src/schema/naming.ts b/typescript/src/schema/naming.ts index 6d758443c..a31ca7427 100644 --- a/typescript/src/schema/naming.ts +++ b/typescript/src/schema/naming.ts @@ -1,5 +1,5 @@ import * as plugin from '../../../pbjs-genfiles/plugin'; -import {commonPrefix} from '../util'; +import { commonPrefix } from '../util'; export class Naming { name: string; @@ -20,16 +20,16 @@ export class Naming { // Define the regular expression to match a version component // (e.g. "v1", "v1beta4", etc.). - const pattern = - /^((?:[a-z0-9_.]+?)\.)?([a-z0-9_]+)(?:\.(v[0-9]+(p[0-9]+)?((alpha|beta)[0-9]+)?[^.]*))?$/; + const pattern = /^((?:[a-z0-9_.]+?)\.)?([a-z0-9_]+)(?:\.(v[0-9]+(p[0-9]+)?((alpha|beta)[0-9]+)?[^.]*))?$/; const match = rootPackage.match(pattern); if (!match) { throw new Error(`Cannot parse package name ${rootPackage}.`); } const [, namespaces, name, version] = match; if (!namespaces) { - throw new Error(`Cannot parse package name ${ - rootPackage}: namespace is not defined.`); + throw new Error( + `Cannot parse package name ${rootPackage}: namespace is not defined.` + ); } this.name = name.capitalize(); this.productName = this.name; @@ -39,7 +39,8 @@ export class Naming { if (!this.version && protoPackages.length > 1) { throw new Error( - 'All protos must have the same proto package up to and including the version.'); + 'All protos must have the same proto package up to and including the version.' + ); } } } diff --git a/typescript/src/schema/proto.ts b/typescript/src/schema/proto.ts index f01995650..a32b8e2a2 100644 --- a/typescript/src/schema/proto.ts +++ b/typescript/src/schema/proto.ts @@ -1,20 +1,24 @@ -import {ENGINE_METHOD_DIGESTS} from 'constants'; -import {NEG_ONE} from 'long'; +import { ENGINE_METHOD_DIGESTS } from 'constants'; +import { NEG_ONE } from 'long'; import * as plugin from '../../../pbjs-genfiles/plugin'; -interface MethodDescriptorProto extends - plugin.google.protobuf.IMethodDescriptorProto { - idempotence: 'idempotent'|'non_idempotent'; +interface MethodDescriptorProto + extends plugin.google.protobuf.IMethodDescriptorProto { + idempotence: 'idempotent' | 'non_idempotent'; longRunning?: plugin.google.longrunning.IOperationInfo; - streaming:|'CLIENT_STREAMING'|'SERVER_STREAMING'|'BIDI_STREAMING'|undefined; - pagingFieldName: string|undefined; + streaming: + | 'CLIENT_STREAMING' + | 'SERVER_STREAMING' + | 'BIDI_STREAMING' + | undefined; + pagingFieldName: string | undefined; inputInterface: string; outputInterface: string; } -interface ServiceDescriptorProto extends - plugin.google.protobuf.IServiceDescriptorProto { +interface ServiceDescriptorProto + extends plugin.google.protobuf.IServiceDescriptorProto { method: MethodDescriptorProto[]; simpleMethods: MethodDescriptorProto[]; longRunning: MethodDescriptorProto[]; @@ -43,9 +47,12 @@ export interface EnumsMap { // methods of the given service, to use in templates. function idempotence(method: MethodDescriptorProto) { - if (method.options && method.options['.google.api.http'] && - (method.options['.google.api.http']['get'] || - method.options['.google.api.http']['put'])) { + if ( + method.options && + method.options['.google.api.http'] && + (method.options['.google.api.http']['get'] || + method.options['.google.api.http']['put']) + ) { return 'idempotent'; } return 'non_idempotent'; @@ -75,17 +82,20 @@ function pagingFieldName(messages: MessagesMap, method: MethodDescriptorProto) { const inputType = messages[method.inputType!]; const outputType = messages[method.outputType!]; const hasPageToken = - inputType && inputType.field!.some(field => field.name === 'page_token'); + inputType && inputType.field!.some(field => field.name === 'page_token'); const hasPageSize = - inputType && inputType.field!.some(field => field.name === 'page_size'); - const hasNextPageToken = outputType && - outputType.field!.some(field => field.name === 'next_page_token'); + inputType && inputType.field!.some(field => field.name === 'page_size'); + const hasNextPageToken = + outputType && + outputType.field!.some(field => field.name === 'next_page_token'); if (!hasPageToken || !hasPageSize || !hasNextPageToken) { return undefined; } const repeatedFields = outputType.field!.filter( - field => field.label === - plugin.google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED); + field => + field.label === + plugin.google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED + ); if (repeatedFields.length !== 1) { return undefined; } @@ -98,56 +108,72 @@ function toInterface(type: string) { function augmentMethod(messages: MessagesMap, method: MethodDescriptorProto) { method = Object.assign( - { - idempotence: idempotence(method), - longRunning: longrunning(method), - streaming: streaming(method), - pagingFieldName: pagingFieldName(messages, method), - inputInterface: toInterface(method.inputType!), - outputInterface: toInterface(method.outputType!), - }, - method) as MethodDescriptorProto; + { + idempotence: idempotence(method), + longRunning: longrunning(method), + streaming: streaming(method), + pagingFieldName: pagingFieldName(messages, method), + inputInterface: toInterface(method.inputType!), + outputInterface: toInterface(method.outputType!), + }, + method + ) as MethodDescriptorProto; return method; } function augmentService( - messages: MessagesMap, - service: plugin.google.protobuf.IServiceDescriptorProto) { + messages: MessagesMap, + service: plugin.google.protobuf.IServiceDescriptorProto +) { const augmentedService = service as ServiceDescriptorProto; - augmentedService.method = - augmentedService.method.map(method => augmentMethod(messages, method)); + augmentedService.method = augmentedService.method.map(method => + augmentMethod(messages, method) + ); augmentedService.simpleMethods = augmentedService.method.filter( - method => - !method.longRunning && !method.streaming && !method.pagingFieldName); - augmentedService.longRunning = - augmentedService.method.filter(method => method.longRunning); - augmentedService.streaming = - augmentedService.method.filter(method => method.streaming); + method => + !method.longRunning && !method.streaming && !method.pagingFieldName + ); + augmentedService.longRunning = augmentedService.method.filter( + method => method.longRunning + ); + augmentedService.streaming = augmentedService.method.filter( + method => method.streaming + ); augmentedService.clientStreaming = augmentedService.method.filter( - method => method.streaming === 'CLIENT_STREAMING'); + method => method.streaming === 'CLIENT_STREAMING' + ); augmentedService.serverStreaming = augmentedService.method.filter( - method => method.streaming === 'SERVER_STREAMING'); + method => method.streaming === 'SERVER_STREAMING' + ); augmentedService.bidiStreaming = augmentedService.method.filter( - method => method.streaming === 'BIDI_STREAMING'); - augmentedService.paging = - augmentedService.method.filter(method => method.pagingFieldName); + method => method.streaming === 'BIDI_STREAMING' + ); + augmentedService.paging = augmentedService.method.filter( + method => method.pagingFieldName + ); augmentedService.hostname = ''; augmentedService.port = 0; - if (augmentedService.options && - augmentedService.options['.google.api.defaultHost']) { + if ( + augmentedService.options && + augmentedService.options['.google.api.defaultHost'] + ) { const match = augmentedService.options['.google.api.defaultHost'].match( - /^(.*):(\d+)$/); + /^(.*):(\d+)$/ + ); if (match) { augmentedService.hostname = match[1]; augmentedService.port = Number.parseInt(match[2], 10); } } augmentedService.oauthScopes = []; - if (augmentedService.options && - augmentedService.options['.google.api.oauthScopes']) { - augmentedService.oauthScopes = - augmentedService.options['.google.api.oauthScopes'].split(','); + if ( + augmentedService.options && + augmentedService.options['.google.api.oauthScopes'] + ) { + augmentedService.oauthScopes = augmentedService.options[ + '.google.api.oauthScopes' + ].split(','); } return augmentedService; } @@ -161,34 +187,48 @@ export class Proto { // TODO: need to store metadata? address? constructor( - fd: plugin.google.protobuf.IFileDescriptorProto, packageName: string) { + fd: plugin.google.protobuf.IFileDescriptorProto, + packageName: string + ) { fd.enumType = fd.enumType || []; fd.messageType = fd.messageType || []; fd.service = fd.service || []; this.filePB2 = fd; - this.messages = fd.messageType.filter(message => message.name) - .reduce((map, message) => { - map['.' + fd.package! + '.' + message.name!] = - message; - return map; - }, {} as MessagesMap); - - this.enums = - fd.enumType.filter(enum_ => enum_.name).reduce((map, enum_) => { + this.messages = fd.messageType + .filter(message => message.name) + .reduce( + (map, message) => { + map['.' + fd.package! + '.' + message.name!] = message; + return map; + }, + {} as MessagesMap + ); + + this.enums = fd.enumType + .filter(enum_ => enum_.name) + .reduce( + (map, enum_) => { map[enum_.name!] = enum_; return map; - }, {} as EnumsMap); - - this.fileToGenerate = - fd.package ? fd.package.startsWith(packageName) : false; - - this.services = fd.service.filter(service => service.name) - .map(service => augmentService(this.messages, service)) - .reduce((map, service) => { - map[service.name!] = service; - return map; - }, {} as ServicesMap); + }, + {} as EnumsMap + ); + + this.fileToGenerate = fd.package + ? fd.package.startsWith(packageName) + : false; + + this.services = fd.service + .filter(service => service.name) + .map(service => augmentService(this.messages, service)) + .reduce( + (map, service) => { + map[service.name!] = service; + return map; + }, + {} as ServicesMap + ); } } diff --git a/typescript/src/templater.ts b/typescript/src/templater.ts index 1966d14ca..e995a3459 100644 --- a/typescript/src/templater.ts +++ b/typescript/src/templater.ts @@ -5,9 +5,9 @@ import * as util from 'util'; import * as plugin from '../../pbjs-genfiles/plugin'; -import {API} from './schema/api'; +import { API } from './schema/api'; -const commonParameters: {[name: string]: string} = { +const commonParameters: { [name: string]: string } = { copyrightYear: new Date().getFullYear().toString(), }; @@ -16,7 +16,9 @@ const readDir = util.promisify(fs.readdir); const lstat = util.promisify(fs.lstat); async function recursiveFileList( - basePath: string, nameRegex: RegExp): Promise { + basePath: string, + nameRegex: RegExp +): Promise { const dirQueue: string[] = [basePath]; const result: string[] = []; while (dirQueue.length > 0) { @@ -36,21 +38,26 @@ async function recursiveFileList( } function renderFile( - targetFilename: string, templateFilename: string, renderParameters: {}) { + targetFilename: string, + templateFilename: string, + renderParameters: {} +) { const processed = nunjucks.render(templateFilename, renderParameters); - const output = - plugin.google.protobuf.compiler.CodeGeneratorResponse.File.create(); + const output = plugin.google.protobuf.compiler.CodeGeneratorResponse.File.create(); output.name = targetFilename; output.content = processed; return output; } function processOneTemplate( - basePath: string, templateFilename: string, api: API) { - const result: plugin.google.protobuf.compiler.CodeGeneratorResponse.File[] = - []; - let outputFilename = - templateFilename.substr(basePath.length + 1).replace(/\.njk$/, ''); + basePath: string, + templateFilename: string, + api: API +) { + const result: plugin.google.protobuf.compiler.CodeGeneratorResponse.File[] = []; + let outputFilename = templateFilename + .substr(basePath.length + 1) + .replace(/\.njk$/, ''); // Filename can have one or more variables in it that should be substituted // with their actual values. Currently supported: $service, $version Note: @@ -60,13 +67,18 @@ function processOneTemplate( // {api, commonParameters} if (outputFilename.match(/\$service/)) { for (const service of api.services) { - result.push(renderFile( + result.push( + renderFile( outputFilename.replace(/\$service/, service.name!.toLowerCase()), - templateFilename, {api, commonParameters, service})); + templateFilename, + { api, commonParameters, service } + ) + ); } } else { result.push( - renderFile(outputFilename, templateFilename, {api, commonParameters})); + renderFile(outputFilename, templateFilename, { api, commonParameters }) + ); } return result; @@ -75,8 +87,7 @@ function processOneTemplate( export async function processTemplates(basePath: string, api: API) { basePath = basePath.replace(/\/*$/, ''); const templateFiles = await recursiveFileList(basePath, /^(?!_[^_]).*\.njk$/); - const result: plugin.google.protobuf.compiler.CodeGeneratorResponse.File[] = - []; + const result: plugin.google.protobuf.compiler.CodeGeneratorResponse.File[] = []; for (const templateFilename of templateFiles) { const generatedFiles = processOneTemplate(basePath, templateFilename, api); result.push(...generatedFiles); diff --git a/typescript/src/util.ts b/typescript/src/util.ts index 401c928f9..b0191c89d 100644 --- a/typescript/src/util.ts +++ b/typescript/src/util.ts @@ -25,8 +25,8 @@ String.prototype.capitalize = function(this: string): string { String.prototype.words = function(this: string): string[] { // split on spaces, non-alphanumeric, or capital letters return this.split(/(?=[A-Z])|[\s\W_]+/) - .filter(w => w.length > 0) - .map(w => w.toLowerCase()); + .filter(w => w.length > 0) + .map(w => w.toLowerCase()); }; String.prototype.toCamelCase = function(this: string): string { diff --git a/typescript/test/baseline.ts b/typescript/test/baseline.ts index 34575241e..a4cacfcfd 100644 --- a/typescript/test/baseline.ts +++ b/typescript/test/baseline.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {execSync} from 'child_process'; +import { execSync } from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as rimraf from 'rimraf'; @@ -21,48 +21,68 @@ import * as rimraf from 'rimraf'; const cwd = process.cwd(); const OUTPUT_DIR = path.join(cwd, '.baseline-test-out'); -const GENERATED_CLIENT_FILE = - path.join(OUTPUT_DIR, 'src', 'v1beta1', 'echo_client.ts'); -const GOOGLE_GAX_PROTOS_DIR = - path.join(cwd, 'node_modules', 'google-gax', 'protos'); +const GENERATED_CLIENT_FILE = path.join( + OUTPUT_DIR, + 'src', + 'v1beta1', + 'echo_client.ts' +); +const GOOGLE_GAX_PROTOS_DIR = path.join( + cwd, + 'node_modules', + 'google-gax', + 'protos' +); const PROTOS_DIR = path.join(cwd, 'build', 'test', 'protos'); -const ECHO_PROTO_FILE = - path.join(PROTOS_DIR, 'google', 'showcase', 'v1beta1', 'echo.proto'); +const ECHO_PROTO_FILE = path.join( + PROTOS_DIR, + 'google', + 'showcase', + 'v1beta1', + 'echo.proto' +); const CLIENT_LIBRARY_BASELINE = path.join( - cwd, 'typescript', 'test', 'testdata', 'echo_client_baseline.ts.txt'); + cwd, + 'typescript', + 'test', + 'testdata', + 'echo_client_baseline.ts.txt' +); const SRCDIR = path.join(cwd, 'build', 'src'); const CLI = path.join(SRCDIR, 'cli.js'); const PLUGIN = path.join(SRCDIR, 'protoc-gen-typescript_gapic'); describe('CodeGeneratorTest', () => { describe('Generate client library', () => { - it('Generated client library should have same output with baseline.', - function() { - this.timeout(10000); - if (fs.existsSync(OUTPUT_DIR)) { - rimraf.sync(OUTPUT_DIR); - } - fs.mkdirSync(OUTPUT_DIR); + it('Generated client library should have same output with baseline.', function() { + this.timeout(10000); + if (fs.existsSync(OUTPUT_DIR)) { + rimraf.sync(OUTPUT_DIR); + } + fs.mkdirSync(OUTPUT_DIR); - if (fs.existsSync(PLUGIN)) { - rimraf.sync(PLUGIN); - } - fs.copyFileSync(CLI, PLUGIN); - process.env['PATH'] = SRCDIR + path.delimiter + process.env['PATH']; + if (fs.existsSync(PLUGIN)) { + rimraf.sync(PLUGIN); + } + fs.copyFileSync(CLI, PLUGIN); + process.env['PATH'] = SRCDIR + path.delimiter + process.env['PATH']; - try { - execSync(`chmod +x ${PLUGIN}`); - } catch (err) { - console.warn(`Failed to chmod +x ${PLUGIN}: ${err}. Ignoring...`); - } + try { + execSync(`chmod +x ${PLUGIN}`); + } catch (err) { + console.warn(`Failed to chmod +x ${PLUGIN}: ${err}. Ignoring...`); + } - execSync( - `protoc --typescript_gapic_out=${OUTPUT_DIR} ` + - `-I${GOOGLE_GAX_PROTOS_DIR} ` + - `-I${PROTOS_DIR} ` + ECHO_PROTO_FILE); - assert.strictEqual( - fs.readFileSync(GENERATED_CLIENT_FILE).toString(), - fs.readFileSync(CLIENT_LIBRARY_BASELINE).toString()); - }); + execSync( + `protoc --typescript_gapic_out=${OUTPUT_DIR} ` + + `-I${GOOGLE_GAX_PROTOS_DIR} ` + + `-I${PROTOS_DIR} ` + + ECHO_PROTO_FILE + ); + assert.strictEqual( + fs.readFileSync(GENERATED_CLIENT_FILE).toString(), + fs.readFileSync(CLIENT_LIBRARY_BASELINE).toString() + ); + }); }); }); diff --git a/typescript/test/multi_proto.ts b/typescript/test/multi_proto.ts index 54a8d688b..b37496bfe 100644 --- a/typescript/test/multi_proto.ts +++ b/typescript/test/multi_proto.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {execSync} from 'child_process'; +import { execSync } from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as rimraf from 'rimraf'; @@ -21,50 +21,69 @@ import * as rimraf from 'rimraf'; const cwd = process.cwd(); const OUTPUT_DIR = path.join(cwd, '.multi-proto-test-out'); -const GENERATED_PROTO_FILE = - path.join(OUTPUT_DIR, 'src', 'v1', 'keymanagementservice_proto_list.json'); -const GOOGLE_GAX_PROTOS_DIR = - path.join(cwd, 'node_modules', 'google-gax', 'protos'); +const GENERATED_PROTO_FILE = path.join( + OUTPUT_DIR, + 'src', + 'v1', + 'keymanagementservice_proto_list.json' +); +const GOOGLE_GAX_PROTOS_DIR = path.join( + cwd, + 'node_modules', + 'google-gax', + 'protos' +); const PROTOS_DIR = path.join(cwd, 'build', 'test', 'protos'); -const KMS_PROTO_FILE = - path.join(PROTOS_DIR, 'google', 'kms', 'v1', 'service.proto'); +const KMS_PROTO_FILE = path.join( + PROTOS_DIR, + 'google', + 'kms', + 'v1', + 'service.proto' +); const PROTOLIST_LIBRARY_BASELINE = path.join( - cwd, 'typescript', 'test', 'testdata', - 'keymanagementservice_proto_list.json'); + cwd, + 'typescript', + 'test', + 'testdata', + 'keymanagementservice_proto_list.json' +); const SRCDIR = path.join(cwd, 'build', 'src'); const CLI = path.join(SRCDIR, 'cli.js'); const PLUGIN = path.join(SRCDIR, 'protoc-gen-typescript_gapic'); describe('Proto List Generate Test', () => { describe('Generate Client library', () => { - it('Generated proto list should have same output with baseline.', - function() { - this.timeout(10000); - if (fs.existsSync(OUTPUT_DIR)) { - rimraf.sync(OUTPUT_DIR); - } - fs.mkdirSync(OUTPUT_DIR); + it('Generated proto list should have same output with baseline.', function() { + this.timeout(10000); + if (fs.existsSync(OUTPUT_DIR)) { + rimraf.sync(OUTPUT_DIR); + } + fs.mkdirSync(OUTPUT_DIR); - if (fs.existsSync(PLUGIN)) { - rimraf.sync(PLUGIN); - } - fs.copyFileSync(CLI, PLUGIN); - process.env['PATH'] = SRCDIR + path.delimiter + process.env['PATH']; + if (fs.existsSync(PLUGIN)) { + rimraf.sync(PLUGIN); + } + fs.copyFileSync(CLI, PLUGIN); + process.env['PATH'] = SRCDIR + path.delimiter + process.env['PATH']; - try { - execSync(`chmod +x ${PLUGIN}`); - } catch (err) { - console.warn(`Failed to chmod +x ${PLUGIN}: ${err}. Ignoring...`); - } + try { + execSync(`chmod +x ${PLUGIN}`); + } catch (err) { + console.warn(`Failed to chmod +x ${PLUGIN}: ${err}. Ignoring...`); + } - execSync( - `protoc --typescript_gapic_out=${OUTPUT_DIR} ` + - `-I${GOOGLE_GAX_PROTOS_DIR} ` + - `-I${PROTOS_DIR} ` + KMS_PROTO_FILE); - assert.strictEqual( - fs.readFileSync(GENERATED_PROTO_FILE).toString(), - fs.readFileSync(PROTOLIST_LIBRARY_BASELINE).toString()); - }); + execSync( + `protoc --typescript_gapic_out=${OUTPUT_DIR} ` + + `-I${GOOGLE_GAX_PROTOS_DIR} ` + + `-I${PROTOS_DIR} ` + + KMS_PROTO_FILE + ); + assert.strictEqual( + fs.readFileSync(GENERATED_PROTO_FILE).toString(), + fs.readFileSync(PROTOLIST_LIBRARY_BASELINE).toString() + ); + }); }); }); diff --git a/typescript/test/naming.ts b/typescript/test/naming.ts index 24d952ee5..a5c31117e 100644 --- a/typescript/test/naming.ts +++ b/typescript/test/naming.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import * as plugin from '../../pbjs-genfiles/plugin'; -import {Naming} from '../src/schema/naming'; +import { Naming } from '../src/schema/naming'; describe('schema/naming.ts', () => { it('parses name correctly', () => { diff --git a/typescript/test/proto.ts b/typescript/test/proto.ts index 7e8e95251..5da1b62b4 100644 --- a/typescript/test/proto.ts +++ b/typescript/test/proto.ts @@ -15,10 +15,8 @@ import * as assert from 'assert'; import * as plugin from '../../pbjs-genfiles/plugin'; -import {Proto} from '../src/schema/proto'; +import { Proto } from '../src/schema/proto'; -describe( - 'schema/proto.ts', - () => { - // TODO: test service augmentation - }); +describe('schema/proto.ts', () => { + // TODO: test service augmentation +}); diff --git a/typescript/test/util.ts b/typescript/test/util.ts index 10c77a5de..211afe3ee 100644 --- a/typescript/test/util.ts +++ b/typescript/test/util.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; -import {commonPrefix} from '../src/util'; +import { commonPrefix } from '../src/util'; describe('util.ts', () => { describe('CommonPrefix', () => { @@ -86,80 +86,132 @@ describe('util.ts', () => { assert.deepStrictEqual(''.toCamelCase(), ''); assert.deepStrictEqual('test'.toCamelCase(), 'test'); assert.deepStrictEqual( - 'camelCaseString'.toCamelCase(), 'camelCaseString'); + 'camelCaseString'.toCamelCase(), + 'camelCaseString' + ); assert.deepStrictEqual( - 'PascalCaseString'.toCamelCase(), 'pascalCaseString'); + 'PascalCaseString'.toCamelCase(), + 'pascalCaseString' + ); assert.deepStrictEqual( - 'snake_case_string'.toCamelCase(), 'snakeCaseString'); + 'snake_case_string'.toCamelCase(), + 'snakeCaseString' + ); assert.deepStrictEqual( - 'kebab-case-string'.toCamelCase(), 'kebabCaseString'); + 'kebab-case-string'.toCamelCase(), + 'kebabCaseString' + ); assert.deepStrictEqual( - 'random/separators-string'.toCamelCase(), 'randomSeparatorsString'); + 'random/separators-string'.toCamelCase(), + 'randomSeparatorsString' + ); assert.deepStrictEqual( - 'mixedType-string.SomewhatWeird'.toCamelCase(), - 'mixedTypeStringSomewhatWeird'); + 'mixedType-string.SomewhatWeird'.toCamelCase(), + 'mixedTypeStringSomewhatWeird' + ); assert.deepStrictEqual( - 'productName.v1p1beta1'.toCamelCase(), 'productNameV1p1beta1'); + 'productName.v1p1beta1'.toCamelCase(), + 'productNameV1p1beta1' + ); }); it('should convert to PascalCase', () => { assert.deepStrictEqual(''.toPascalCase(), ''); assert.deepStrictEqual('test'.toPascalCase(), 'Test'); assert.deepStrictEqual( - 'camelCaseString'.toPascalCase(), 'CamelCaseString'); + 'camelCaseString'.toPascalCase(), + 'CamelCaseString' + ); assert.deepStrictEqual( - 'PascalCaseString'.toPascalCase(), 'PascalCaseString'); + 'PascalCaseString'.toPascalCase(), + 'PascalCaseString' + ); assert.deepStrictEqual( - 'snake_case_string'.toPascalCase(), 'SnakeCaseString'); + 'snake_case_string'.toPascalCase(), + 'SnakeCaseString' + ); assert.deepStrictEqual( - 'kebab-case-string'.toPascalCase(), 'KebabCaseString'); + 'kebab-case-string'.toPascalCase(), + 'KebabCaseString' + ); assert.deepStrictEqual( - 'random/separators-string'.toPascalCase(), 'RandomSeparatorsString'); + 'random/separators-string'.toPascalCase(), + 'RandomSeparatorsString' + ); assert.deepStrictEqual( - 'mixedType-string.SomewhatWeird'.toPascalCase(), - 'MixedTypeStringSomewhatWeird'); + 'mixedType-string.SomewhatWeird'.toPascalCase(), + 'MixedTypeStringSomewhatWeird' + ); assert.deepStrictEqual( - 'productName.v1p1beta1'.toPascalCase(), 'ProductNameV1p1beta1'); + 'productName.v1p1beta1'.toPascalCase(), + 'ProductNameV1p1beta1' + ); }); it('should convert to kebab-case', () => { assert.deepStrictEqual(''.toKebabCase(), ''); assert.deepStrictEqual('test'.toKebabCase(), 'test'); assert.deepStrictEqual( - 'camelCaseString'.toKebabCase(), 'camel-case-string'); + 'camelCaseString'.toKebabCase(), + 'camel-case-string' + ); assert.deepStrictEqual( - 'PascalCaseString'.toKebabCase(), 'pascal-case-string'); + 'PascalCaseString'.toKebabCase(), + 'pascal-case-string' + ); assert.deepStrictEqual( - 'snake_case_string'.toKebabCase(), 'snake-case-string'); + 'snake_case_string'.toKebabCase(), + 'snake-case-string' + ); assert.deepStrictEqual( - 'kebab-case-string'.toKebabCase(), 'kebab-case-string'); + 'kebab-case-string'.toKebabCase(), + 'kebab-case-string' + ); assert.deepStrictEqual( - 'random/separators-string'.toKebabCase(), 'random-separators-string'); + 'random/separators-string'.toKebabCase(), + 'random-separators-string' + ); assert.deepStrictEqual( - 'mixedType-string.SomewhatWeird'.toKebabCase(), - 'mixed-type-string-somewhat-weird'); + 'mixedType-string.SomewhatWeird'.toKebabCase(), + 'mixed-type-string-somewhat-weird' + ); assert.deepStrictEqual( - 'productName.v1p1beta1'.toKebabCase(), 'product-name-v1p1beta1'); + 'productName.v1p1beta1'.toKebabCase(), + 'product-name-v1p1beta1' + ); }); it('should convert to snake_case', () => { assert.deepStrictEqual(''.toSnakeCase(), ''); assert.deepStrictEqual('test'.toSnakeCase(), 'test'); assert.deepStrictEqual( - 'camelCaseString'.toSnakeCase(), 'camel_case_string'); + 'camelCaseString'.toSnakeCase(), + 'camel_case_string' + ); assert.deepStrictEqual( - 'PascalCaseString'.toSnakeCase(), 'pascal_case_string'); + 'PascalCaseString'.toSnakeCase(), + 'pascal_case_string' + ); assert.deepStrictEqual( - 'snake_case_string'.toSnakeCase(), 'snake_case_string'); + 'snake_case_string'.toSnakeCase(), + 'snake_case_string' + ); assert.deepStrictEqual( - 'kebab-case-string'.toSnakeCase(), 'kebab_case_string'); + 'kebab-case-string'.toSnakeCase(), + 'kebab_case_string' + ); assert.deepStrictEqual( - 'random/separators-string'.toSnakeCase(), 'random_separators_string'); + 'random/separators-string'.toSnakeCase(), + 'random_separators_string' + ); assert.deepStrictEqual( - 'mixedType-string.SomewhatWeird'.toSnakeCase(), - 'mixed_type_string_somewhat_weird'); + 'mixedType-string.SomewhatWeird'.toSnakeCase(), + 'mixed_type_string_somewhat_weird' + ); assert.deepStrictEqual( - 'productName.v1p1beta1'.toSnakeCase(), 'product_name_v1p1beta1'); + 'productName.v1p1beta1'.toSnakeCase(), + 'product_name_v1p1beta1' + ); }); }); }); From 3b753a5ae05c3514f8642065fd61248ea660e934 Mon Sep 17 00:00:00 2001 From: xiaozhenliugg Date: Tue, 1 Oct 2019 10:32:25 -0700 Subject: [PATCH 11/11] change path name & update baseline --- .../src/$version/$service_client.ts.njk | 80 +++++++++---------- .../test/testdata/echo_client_baseline.ts.txt | 78 +++++++++--------- 2 files changed, 79 insertions(+), 79 deletions(-) diff --git a/templates/typescript_gapic/src/$version/$service_client.ts.njk b/templates/typescript_gapic/src/$version/$service_client.ts.njk index cf321dcab..8ff607ea6 100644 --- a/templates/typescript_gapic/src/$version/$service_client.ts.njk +++ b/templates/typescript_gapic/src/$version/$service_client.ts.njk @@ -3,7 +3,7 @@ import * as gax from 'google-gax'; import * as path from 'path'; import * as packageJson from '../../package.json'; -import * as protosType from '../../protos/protos'; +import * as protosTypes from '../../protos/protos'; import * as gapicConfig from './echo_client_config.json'; const version = packageJson.version; @@ -95,11 +95,11 @@ export class {{ service.name }}Client { // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. - const typescriptProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); + const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); const protos = gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : - typescriptProtoPath + nodejsProtoPath ); {%- if (service.paging.length > 0) %} @@ -135,7 +135,7 @@ export class {{ service.name }}Client { // rather than holding a request open. const protoFilesRoot = opts.fallback? gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : - gaxModule.protobuf.loadSync(typescriptProtoPath); + gaxModule.protobuf.loadSync(nodejsProtoPath); const operationsClient = gaxModule.lro({ auth: this.auth, @@ -176,7 +176,7 @@ export class {{ service.name }}Client { // Put together the "service stub" for // google.showcase.v1alpha2.Echo. - const echoStub = gaxGrpc.createStub( + const {{ service.name.toCamelCase() }}Stub = gaxGrpc.createStub( // @ts-ignore We cannot check types that are loaded in runtime. opts.fallback ? // @ts-ignore @@ -275,31 +275,31 @@ export class {{ service.name }}Client { {%- for method in service.simpleMethods %} {{ method.name.toCamelCase() }}( - request: protosType{{ method.inputInterface }}, + request: protosTypes{{ method.inputInterface }}, options?: gax.CallOptions): Promise<[ - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, {}|undefined + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined ]>; {{ method.name.toCamelCase() }}( - request: protosType{{ method.inputInterface }}, + request: protosTypes{{ method.inputInterface }}, options: gax.CallOptions, callback: Callback< - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined>): void; {{ method.name.toCamelCase() }}( - request: protosType{{ method.inputInterface }}, + request: protosTypes{{ method.inputInterface }}, optionsOrCallback?: gax.CallOptions|Callback< - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, {}|undefined>, + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined>, callback?: Callback< - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined>): Promise<[ - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, {}|undefined + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined ]>|void { request = request || {}; let options = optionsOrCallback; @@ -321,7 +321,7 @@ export class {{ service.name }}Client { } {%- elif method.serverStreaming %} {{ method.name.toCamelCase() }}( - request?: protosType{{ method.inputInterface }}, + request?: protosTypes{{ method.inputInterface }}, options?: gax.CallOptions): gax.ServerStreamingCall{ request = request || {}; @@ -332,21 +332,21 @@ export class {{ service.name }}Client { {{ method.name.toCamelCase() }}( options: gax.CallOptions, callback: Callback< - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, {}|undefined>): + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined>): gax.ClientStreamingCall; {{ method.name.toCamelCase() }}( callback: Callback< - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, {}|undefined>): + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined>): gax.ClientStreamingCall; {{ method.name.toCamelCase() }}( optionsOrCallback: gax.CallOptions|Callback< - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, {}|undefined>, + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined>, callback?: Callback< - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, {}|undefined>): + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined>): gax.ClientStreamingCall { if (optionsOrCallback instanceof Function && callback === undefined) { callback = optionsOrCallback; @@ -359,31 +359,31 @@ export class {{ service.name }}Client { {% endfor %} {%- for method in service.longRunning %} {{ method.name.toCamelCase() }}( - request: protosType{{ method.inputInterface }}, + request: protosTypes{{ method.inputInterface }}, options?: gax.CallOptions): Promise<[ - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, {}|undefined + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined ]>; {{ method.name.toCamelCase() }}( - request: protosType{{ method.inputInterface }}, + request: protosTypes{{ method.inputInterface }}, options: gax.CallOptions, callback: Callback< - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined>): void; {{ method.name.toCamelCase() }}( - request: protosType{{ method.inputInterface }}, + request: protosTypes{{ method.inputInterface }}, optionsOrCallback?: gax.CallOptions|Callback< - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, {}|undefined>, + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined>, callback?: Callback< - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined>): Promise<[ - protosType{{ method.outputInterface }}, - protosType{{ method.inputInterface }}|undefined, {}|undefined + protosTypes{{ method.outputInterface }}, + protosTypes{{ method.inputInterface }}|undefined, {}|undefined ]>|void { request = request || {}; let options = optionsOrCallback; diff --git a/typescript/test/testdata/echo_client_baseline.ts.txt b/typescript/test/testdata/echo_client_baseline.ts.txt index b630a92d5..f85a9b5f5 100644 --- a/typescript/test/testdata/echo_client_baseline.ts.txt +++ b/typescript/test/testdata/echo_client_baseline.ts.txt @@ -20,7 +20,7 @@ import * as gax from 'google-gax'; import * as path from 'path'; import * as packageJson from '../../package.json'; -import * as protosType from '../../protos/protos'; +import * as protosTypes from '../../protos/protos'; import * as gapicConfig from './echo_client_config.json'; const version = packageJson.version; @@ -112,11 +112,11 @@ export class EchoClient { // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. - const typescriptProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); + const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); const protos = gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : - typescriptProtoPath + nodejsProtoPath ); // Some of the methods on this service return "paged" results, @@ -139,7 +139,7 @@ export class EchoClient { // rather than holding a request open. const protoFilesRoot = opts.fallback? gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : - gaxModule.protobuf.loadSync(typescriptProtoPath); + gaxModule.protobuf.loadSync(nodejsProtoPath); const operationsClient = gaxModule.lro({ auth: this.auth, @@ -253,31 +253,31 @@ export class EchoClient { // -- Service calls -- // ------------------- echo( - request: protosType.google.showcase.v1beta1.IEchoRequest, + request: protosTypes.google.showcase.v1beta1.IEchoRequest, options?: gax.CallOptions): Promise<[ - protosType.google.showcase.v1beta1.IEchoResponse, - protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined + protosTypes.google.showcase.v1beta1.IEchoResponse, + protosTypes.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined ]>; echo( - request: protosType.google.showcase.v1beta1.IEchoRequest, + request: protosTypes.google.showcase.v1beta1.IEchoRequest, options: gax.CallOptions, callback: Callback< - protosType.google.showcase.v1beta1.IEchoResponse, - protosType.google.showcase.v1beta1.IEchoRequest|undefined, + protosTypes.google.showcase.v1beta1.IEchoResponse, + protosTypes.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): void; echo( - request: protosType.google.showcase.v1beta1.IEchoRequest, + request: protosTypes.google.showcase.v1beta1.IEchoRequest, optionsOrCallback?: gax.CallOptions|Callback< - protosType.google.showcase.v1beta1.IEchoResponse, - protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>, + protosTypes.google.showcase.v1beta1.IEchoResponse, + protosTypes.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>, callback?: Callback< - protosType.google.showcase.v1beta1.IEchoResponse, - protosType.google.showcase.v1beta1.IEchoRequest|undefined, + protosTypes.google.showcase.v1beta1.IEchoResponse, + protosTypes.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): Promise<[ - protosType.google.showcase.v1beta1.IEchoResponse, - protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined + protosTypes.google.showcase.v1beta1.IEchoResponse, + protosTypes.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined ]>|void { request = request || {}; let options = optionsOrCallback; @@ -290,7 +290,7 @@ export class EchoClient { } expand( - request?: protosType.google.showcase.v1beta1.IExpandRequest, + request?: protosTypes.google.showcase.v1beta1.IExpandRequest, options?: gax.CallOptions): gax.ServerStreamingCall{ request = request || {}; @@ -301,21 +301,21 @@ export class EchoClient { collect( options: gax.CallOptions, callback: Callback< - protosType.google.showcase.v1beta1.IEchoResponse, - protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): + protosTypes.google.showcase.v1beta1.IEchoResponse, + protosTypes.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): gax.ClientStreamingCall; collect( callback: Callback< - protosType.google.showcase.v1beta1.IEchoResponse, - protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): + protosTypes.google.showcase.v1beta1.IEchoResponse, + protosTypes.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): gax.ClientStreamingCall; collect( optionsOrCallback: gax.CallOptions|Callback< - protosType.google.showcase.v1beta1.IEchoResponse, - protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>, + protosTypes.google.showcase.v1beta1.IEchoResponse, + protosTypes.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>, callback?: Callback< - protosType.google.showcase.v1beta1.IEchoResponse, - protosType.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): + protosTypes.google.showcase.v1beta1.IEchoResponse, + protosTypes.google.showcase.v1beta1.IEchoRequest|undefined, {}|undefined>): gax.ClientStreamingCall { if (optionsOrCallback instanceof Function && callback === undefined) { callback = optionsOrCallback; @@ -333,31 +333,31 @@ export class EchoClient { } wait( - request: protosType.google.showcase.v1beta1.IWaitRequest, + request: protosTypes.google.showcase.v1beta1.IWaitRequest, options?: gax.CallOptions): Promise<[ - protosType.google.longrunning.IOperation, - protosType.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined + protosTypes.google.longrunning.IOperation, + protosTypes.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined ]>; wait( - request: protosType.google.showcase.v1beta1.IWaitRequest, + request: protosTypes.google.showcase.v1beta1.IWaitRequest, options: gax.CallOptions, callback: Callback< - protosType.google.longrunning.IOperation, - protosType.google.showcase.v1beta1.IWaitRequest|undefined, + protosTypes.google.longrunning.IOperation, + protosTypes.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined>): void; wait( - request: protosType.google.showcase.v1beta1.IWaitRequest, + request: protosTypes.google.showcase.v1beta1.IWaitRequest, optionsOrCallback?: gax.CallOptions|Callback< - protosType.google.longrunning.IOperation, - protosType.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined>, + protosTypes.google.longrunning.IOperation, + protosTypes.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined>, callback?: Callback< - protosType.google.longrunning.IOperation, - protosType.google.showcase.v1beta1.IWaitRequest|undefined, + protosTypes.google.longrunning.IOperation, + protosTypes.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined>): Promise<[ - protosType.google.longrunning.IOperation, - protosType.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined + protosTypes.google.longrunning.IOperation, + protosTypes.google.showcase.v1beta1.IWaitRequest|undefined, {}|undefined ]>|void { request = request || {}; let options = optionsOrCallback;