@omnigraph/protobuf 0.0.0-stage → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,556 @@
1
+ import { specifiedDirectives } from 'graphql';
2
+ import {
3
+ SchemaComposer,
4
+ type EnumTypeComposerValueConfigDefinition,
5
+ type ObjectTypeComposer,
6
+ type ObjectTypeComposerFieldConfigAsObjectDefinition,
7
+ } from 'graphql-compose';
8
+ import {
9
+ GraphQLBigInt,
10
+ GraphQLByte,
11
+ GraphQLJSON,
12
+ GraphQLUnsignedInt,
13
+ GraphQLVoid,
14
+ } from 'graphql-scalars';
15
+ import micromatch from 'micromatch';
16
+ import protobufjs, { type AnyNestedObject, type IParseOptions, type Message } from 'protobufjs';
17
+ import descriptor, { type IFileDescriptorSet } from 'protobufjs/ext/descriptor.js';
18
+ import { Client } from '@ardatan/grpc-reflection-js';
19
+ import { type Logger } from '@graphql-hive/logger';
20
+ import { fs, path } from '@graphql-mesh/cross-helpers';
21
+ import { stringInterpolator } from '@graphql-mesh/string-interpolation';
22
+ import type { YamlConfig } from '@graphql-mesh/types';
23
+ import { matchFiles } from '@graphql-tools/load-files';
24
+ import { GraphQLStreamDirective, type Constructor } from '@graphql-tools/utils';
25
+ import {
26
+ credentials,
27
+ Client as GrpcClient,
28
+ Metadata,
29
+ type ChannelCredentials,
30
+ } from '@grpc/grpc-js';
31
+ import { DisposableStack } from '@whatwg-node/disposablestack';
32
+ import type { MaybePromise } from '@whatwg-node/promise-helpers';
33
+ import { protobufRpcDirective, transportDirective } from './directives.js';
34
+ import { emitRequestBody, emitResponseSelection } from './emitMapping.js';
35
+ import { addIncludePathResolver, getTypeName, walkToFindTypePath } from './utils.js';
36
+
37
+ const { Root } = protobufjs;
38
+
39
+ interface LoadOptions extends IParseOptions {
40
+ includeDirs?: string[];
41
+ }
42
+
43
+ type DecodedDescriptorSet = Message<IFileDescriptorSet> & IFileDescriptorSet;
44
+
45
+ const QUERY_METHOD_PREFIXES = ['get', 'list', 'search'];
46
+
47
+ export class GrpcLoaderHelper extends DisposableStack {
48
+ private schemaComposer = new SchemaComposer();
49
+ constructor(
50
+ private subgraphName: string,
51
+ private baseDir: string,
52
+ private log: Logger,
53
+ private config: YamlConfig.GrpcHandler,
54
+ ) {
55
+ super();
56
+ }
57
+
58
+ async buildSchema() {
59
+ this.schemaComposer.add(GraphQLBigInt);
60
+ this.schemaComposer.add(GraphQLByte);
61
+ this.schemaComposer.add(GraphQLUnsignedInt);
62
+ this.schemaComposer.add(GraphQLVoid);
63
+ this.schemaComposer.add(GraphQLJSON);
64
+ this.schemaComposer.createScalarTC({
65
+ name: 'File',
66
+ });
67
+
68
+ this.config.requestTimeout = this.config.requestTimeout || 200000;
69
+
70
+ this.log.debug(`Getting channel credentials`);
71
+ const creds = await this.getCredentials();
72
+ if ('_unref' in creds && typeof creds._unref === 'function') {
73
+ this.defer(() => (creds as { _unref: () => void })._unref());
74
+ }
75
+
76
+ this.log.debug(`Getting stored root and decoded descriptor set objects`);
77
+ const descriptorSets = await this.getDescriptorSets(creds);
78
+
79
+ for (const { name: rootJsonName, rootJson } of descriptorSets) {
80
+ const rootLogger = this.log.child({ root: rootJsonName });
81
+
82
+ this.log.debug(`Building the schema structure based on the root object`);
83
+ this.visit({
84
+ nested: rootJson,
85
+ name: '',
86
+ currentPath: [],
87
+ rootJsonName,
88
+ rootJson,
89
+ rootLogger,
90
+ });
91
+ }
92
+
93
+ // graphql-compose doesn't add @defer and @stream to the schema
94
+ specifiedDirectives.forEach(directive => this.schemaComposer.addDirective(directive));
95
+
96
+ if (!this.schemaComposer.hasDirective('stream')) {
97
+ this.schemaComposer.addDirective(GraphQLStreamDirective);
98
+ }
99
+
100
+ this.log.debug(`Building the final GraphQL Schema`);
101
+ this.schemaComposer.addDirective(transportDirective);
102
+ const schema = this.schemaComposer.buildSchema();
103
+ const schemaExtensions: Record<string, any> = (schema.extensions = schema.extensions || {});
104
+ const directiveExtensions = (schemaExtensions.directives = schemaExtensions.directives || {});
105
+ directiveExtensions.transport = {
106
+ subgraph: this.subgraphName,
107
+ kind: 'protobuf',
108
+ location: this.config.endpoint,
109
+ options: {
110
+ requestTimeout: this.config.requestTimeout,
111
+ credentialsSsl: this.config.credentialsSsl,
112
+ useHTTPS: this.config.useHTTPS,
113
+ metaData: this.config.metaData ? Object.entries(this.config.metaData) : undefined,
114
+ // Serialize as entries so keys like `grpc.max_receive_message_length` are GraphQL-safe
115
+ channelOptions: this.config.channelOptions
116
+ ? Object.entries(this.config.channelOptions)
117
+ : undefined,
118
+ },
119
+ };
120
+ return schema;
121
+ }
122
+
123
+ private processReflection(creds: ChannelCredentials): Promise<Promise<protobufjs.Root>[]> {
124
+ this.log.debug(`Using the reflection`);
125
+ const reflectionEndpoint = stringInterpolator.parse(this.config.endpoint, {
126
+ env: globalThis.process?.env,
127
+ });
128
+ this.log.debug(`Creating gRPC Reflection Client`);
129
+ const reflectionClient = new Client(reflectionEndpoint, creds, this.config.channelOptions);
130
+ // Attach reflectionMetadata to server-reflection calls (routing / auth metadata)
131
+ if (this.config.reflectionMetadata) {
132
+ const meta = new Metadata();
133
+ const resolverData = { env: globalThis.process?.env };
134
+ for (const [key, value] of Object.entries(this.config.reflectionMetadata)) {
135
+ const interpolated =
136
+ typeof value === 'string' ? stringInterpolator.parse(value, resolverData) : value;
137
+ meta.set(key, String(interpolated));
138
+ }
139
+ const grpcClient = reflectionClient.grpcClient as {
140
+ serverReflectionInfo: (...args: any[]) => any;
141
+ };
142
+ const originalServerReflectionInfo = grpcClient.serverReflectionInfo.bind(grpcClient);
143
+ grpcClient.serverReflectionInfo = (...args: any[]) => {
144
+ args[0] = meta;
145
+ return originalServerReflectionInfo(...args);
146
+ };
147
+ }
148
+ // Avoid Close RPC name collisions if present on generated clients
149
+ this.defer(() => GrpcClient.prototype.close.call(reflectionClient.grpcClient));
150
+ return reflectionClient.listServices().then(services =>
151
+ (services.filter(service => service && !service?.startsWith('grpc.')) as string[]).map(
152
+ service => {
153
+ this.log.debug(`Resolving root of Service: ${service} from the reflection response`);
154
+ return reflectionClient.fileContainingSymbol(service);
155
+ },
156
+ ),
157
+ );
158
+ }
159
+
160
+ private async processDescriptorFile() {
161
+ let fileName: string;
162
+ let options: LoadOptions;
163
+ if (typeof this.config.source === 'object') {
164
+ fileName = this.config.source.file;
165
+ options = {
166
+ ...this.config.source.load,
167
+ includeDirs: this.config.source.load.includeDirs?.map(includeDir =>
168
+ path.isAbsolute(includeDir) ? includeDir : path.join(this.baseDir, includeDir),
169
+ ),
170
+ };
171
+ } else {
172
+ fileName = this.config.source;
173
+ }
174
+ fileName = stringInterpolator.parse(fileName, { env: globalThis.process?.env });
175
+ const absoluteFilePath = path.isAbsolute(fileName)
176
+ ? fileName
177
+ : path.join(this.baseDir, fileName);
178
+ this.log.debug(`Using the descriptor set from ${absoluteFilePath} `);
179
+ const descriptorSetBuffer = await fs.promises.readFile(absoluteFilePath);
180
+ this.log.debug(`Reading ${absoluteFilePath} `);
181
+ let decodedDescriptorSet: DecodedDescriptorSet;
182
+ if (absoluteFilePath.endsWith('json')) {
183
+ this.log.debug(`Parsing ${absoluteFilePath} as json`);
184
+ const descriptorSetJSON = JSON.parse(descriptorSetBuffer.toString());
185
+ decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(
186
+ descriptorSetJSON,
187
+ ) as unknown as DecodedDescriptorSet;
188
+ } else {
189
+ decodedDescriptorSet = descriptor.FileDescriptorSet.decode(
190
+ descriptorSetBuffer,
191
+ ) as unknown as DecodedDescriptorSet;
192
+ }
193
+ this.log.debug(`Creating root from descriptor set`);
194
+ const rootFromDescriptor = (Root as any).fromDescriptor(decodedDescriptorSet);
195
+ if (options.includeDirs) {
196
+ if (!Array.isArray(options.includeDirs)) {
197
+ throw new Error('The includeDirs option must be an array');
198
+ }
199
+ addIncludePathResolver(rootFromDescriptor, options.includeDirs);
200
+ }
201
+ return rootFromDescriptor;
202
+ }
203
+
204
+ private async processProtoFile() {
205
+ this.log.debug(`Using proto file(s)`);
206
+ let protoRoot = new Root();
207
+ let fileGlob: string;
208
+ let options: LoadOptions = {
209
+ keepCase: true,
210
+ alternateCommentMode: true,
211
+ };
212
+ if (typeof this.config.source === 'object') {
213
+ fileGlob = this.config.source.file;
214
+ options = {
215
+ ...options,
216
+ ...this.config.source.load,
217
+ includeDirs: this.config.source.load?.includeDirs?.map(includeDir =>
218
+ path.isAbsolute(includeDir) ? includeDir : path.join(this.baseDir, includeDir),
219
+ ),
220
+ };
221
+ if (options.includeDirs) {
222
+ if (!Array.isArray(options.includeDirs)) {
223
+ throw new Error('The includeDirs option must be an array');
224
+ }
225
+ addIncludePathResolver(protoRoot, options.includeDirs);
226
+ }
227
+ } else {
228
+ fileGlob = this.config.source;
229
+ }
230
+
231
+ fileGlob = stringInterpolator.parse(fileGlob, { env: globalThis.process?.env });
232
+
233
+ const fileNames = await matchFiles(fileGlob, {
234
+ cwd: this.baseDir,
235
+ absolute: false,
236
+ });
237
+ this.log.debug(`Loading proto files(${fileGlob}); \n ${fileNames.join('\n')} `);
238
+ protoRoot = await protoRoot.load(
239
+ fileNames.map(filePath =>
240
+ path.isAbsolute(filePath) ? filePath : path.join(this.baseDir, filePath),
241
+ ),
242
+ options,
243
+ );
244
+ this.log.debug(`Adding proto content to the root`);
245
+ return protoRoot;
246
+ }
247
+
248
+ private async getDescriptorSets(creds: ChannelCredentials) {
249
+ const rootPromises: Promise<protobufjs.Root>[] = [];
250
+ this.log.debug(`Building Roots`);
251
+ const filePath = this.config.source
252
+ ? typeof this.config.source === 'string'
253
+ ? this.config.source
254
+ : this.config.source.file
255
+ : undefined;
256
+ // Missing or empty source means gRPC reflection (also accepts source: { file: '' } workaround)
257
+ if (filePath?.endsWith('json')) {
258
+ rootPromises.push(this.processDescriptorFile());
259
+ } else if (filePath?.endsWith('proto')) {
260
+ rootPromises.push(this.processProtoFile());
261
+ } else {
262
+ const reflectionPromises = await this.processReflection(creds);
263
+ rootPromises.push(...reflectionPromises);
264
+ }
265
+
266
+ return Promise.all(
267
+ rootPromises.map(async (root$, i) => {
268
+ const root = await root$;
269
+ const rootName = root.name || `Root${i}`;
270
+ const rootLogger = this.log.child({ root: rootName });
271
+ rootLogger.debug(`Resolving entire the root tree`);
272
+ root.resolveAll();
273
+ rootLogger.debug(`Creating artifacts from descriptor set and root`);
274
+ return {
275
+ name: rootName,
276
+ rootJson: root.toJSON({
277
+ keepComments: true,
278
+ }),
279
+ };
280
+ }),
281
+ );
282
+ }
283
+
284
+ getCredentials(): MaybePromise<ChannelCredentials> {
285
+ this.log.debug(`Getting channel credentials`);
286
+ if (this.config.credentialsSsl) {
287
+ this.log.debug(
288
+ () =>
289
+ `Using SSL Connection with credentials at ${this.config.credentialsSsl.privateKey} & ${this.config.credentialsSsl.certChain}`,
290
+ );
291
+ const absolutePrivateKeyPath = path.isAbsolute(this.config.credentialsSsl.privateKey)
292
+ ? this.config.credentialsSsl.privateKey
293
+ : path.join(this.baseDir, this.config.credentialsSsl.privateKey);
294
+ const absoluteCertChainPath = path.isAbsolute(this.config.credentialsSsl.certChain)
295
+ ? this.config.credentialsSsl.certChain
296
+ : path.join(this.baseDir, this.config.credentialsSsl.certChain);
297
+
298
+ const sslFiles = [
299
+ fs.promises.readFile(absolutePrivateKeyPath),
300
+ fs.promises.readFile(absoluteCertChainPath),
301
+ ];
302
+ if (this.config.credentialsSsl.rootCA !== 'rootCA') {
303
+ const absoluteRootCAPath = path.isAbsolute(this.config.credentialsSsl.rootCA)
304
+ ? this.config.credentialsSsl.rootCA
305
+ : path.join(this.baseDir, this.config.credentialsSsl.rootCA);
306
+ sslFiles.unshift(fs.promises.readFile(absoluteRootCAPath));
307
+ }
308
+ return Promise.all(sslFiles).then(([rootCA, privateKey, certChain]) =>
309
+ credentials.createSsl(rootCA, privateKey, certChain),
310
+ );
311
+ } else if (this.config.useHTTPS) {
312
+ this.log.debug(`Using SSL Connection`);
313
+ return credentials.createSsl();
314
+ }
315
+ this.log.debug(`Using insecure connection`);
316
+ return credentials.createInsecure();
317
+ }
318
+
319
+ visit({
320
+ nested,
321
+ name,
322
+ currentPath,
323
+ rootJsonName,
324
+ rootJson,
325
+ rootLogger: log,
326
+ }: {
327
+ nested: AnyNestedObject;
328
+ name: string;
329
+ currentPath: string[];
330
+ rootJsonName: string;
331
+ rootJson: protobufjs.INamespace;
332
+ rootLogger: Logger;
333
+ }) {
334
+ const pathWithName = [...currentPath, ...name.split('.')].filter(Boolean);
335
+ if ('nested' in nested) {
336
+ for (const key in nested.nested) {
337
+ log.debug(`Visiting ${currentPath}.nested[${key}]`);
338
+ const currentNested = nested.nested[key];
339
+ this.visit({
340
+ nested: currentNested,
341
+ name: key,
342
+ currentPath: pathWithName,
343
+ rootJsonName,
344
+ rootJson,
345
+ rootLogger: log,
346
+ });
347
+ }
348
+ }
349
+ const typeName = pathWithName.join('__');
350
+ if ('values' in nested) {
351
+ const enumValues: Record<string, EnumTypeComposerValueConfigDefinition> = {};
352
+ const commentMap = (nested as any).comments;
353
+ for (const [key] of Object.entries(nested.values)) {
354
+ log.debug(`Visiting ${currentPath}.nested.values[${key}]`);
355
+ enumValues[key] = {
356
+ description: commentMap?.[key],
357
+ };
358
+ }
359
+ this.schemaComposer.createEnumTC({
360
+ name: typeName,
361
+ values: enumValues,
362
+ description: (nested as any).comment,
363
+ });
364
+ } else if ('fields' in nested) {
365
+ const inputTypeName = typeName + '_Input';
366
+ const outputTypeName = typeName;
367
+ const description = (nested as any).comment;
368
+ const fieldEntries = Object.entries(nested.fields) as [
369
+ string,
370
+ protobufjs.IField & { comment: string; keyType?: string },
371
+ ][];
372
+ if (fieldEntries.length) {
373
+ const inputTC = this.schemaComposer.createInputTC({
374
+ name: inputTypeName,
375
+ description,
376
+ fields: {},
377
+ });
378
+ const outputTC = this.schemaComposer.createObjectTC({
379
+ name: outputTypeName,
380
+ description,
381
+ fields: {},
382
+ });
383
+ for (const [fieldName, { type, rule, comment, keyType }] of fieldEntries) {
384
+ log.debug(`Visiting ${currentPath}.nested.fields[${fieldName}]`);
385
+ const baseFieldTypePath = type.split('.');
386
+ inputTC.addFields({
387
+ [fieldName]: {
388
+ type: () => {
389
+ let fieldInputTypeName: string;
390
+ if (keyType) {
391
+ fieldInputTypeName = 'JSON';
392
+ } else {
393
+ const fieldTypePath = walkToFindTypePath(
394
+ rootJson,
395
+ pathWithName,
396
+ baseFieldTypePath,
397
+ );
398
+ fieldInputTypeName = getTypeName(this.schemaComposer, fieldTypePath, true);
399
+ }
400
+ return rule === 'repeated' ? `[${fieldInputTypeName}]` : fieldInputTypeName;
401
+ },
402
+ description: comment,
403
+ },
404
+ });
405
+ outputTC.addFields({
406
+ [fieldName]: {
407
+ type: () => {
408
+ let fieldTypeName: string;
409
+ if (keyType) {
410
+ fieldTypeName = 'JSON';
411
+ } else {
412
+ const fieldTypePath = walkToFindTypePath(
413
+ rootJson,
414
+ pathWithName,
415
+ baseFieldTypePath,
416
+ );
417
+ fieldTypeName = getTypeName(this.schemaComposer, fieldTypePath, false);
418
+ }
419
+ return rule === 'repeated' ? `[${fieldTypeName}]` : fieldTypeName;
420
+ },
421
+ description: comment,
422
+ },
423
+ });
424
+ }
425
+ } else {
426
+ this.schemaComposer.createScalarTC({
427
+ ...GraphQLJSON.toConfig(),
428
+ name: inputTypeName,
429
+ description,
430
+ });
431
+ this.schemaComposer.createScalarTC({
432
+ ...GraphQLJSON.toConfig(),
433
+ name: outputTypeName,
434
+ description,
435
+ });
436
+ }
437
+ } else if ('methods' in nested) {
438
+ const objPath = pathWithName.join('.');
439
+ for (const methodName in nested.methods) {
440
+ const method = nested.methods[methodName];
441
+ const rootFieldName = [...pathWithName, methodName].join('_');
442
+ const fieldConfigTypeFactory = () => {
443
+ const baseResponseTypePath = method.responseType?.split('.');
444
+ if (baseResponseTypePath) {
445
+ const responseTypePath = walkToFindTypePath(
446
+ rootJson,
447
+ pathWithName,
448
+ baseResponseTypePath,
449
+ );
450
+ return getTypeName(this.schemaComposer, responseTypePath, false);
451
+ }
452
+ return 'Void';
453
+ };
454
+ const fieldConfig: ObjectTypeComposerFieldConfigAsObjectDefinition<any, any> = {
455
+ type: () => {
456
+ const typeName = fieldConfigTypeFactory();
457
+ if (method.responseStream) {
458
+ return `[${typeName}]`;
459
+ }
460
+ return typeName;
461
+ },
462
+ description: method.comment,
463
+ };
464
+ const fieldConfigArgs = {
465
+ input: () => {
466
+ if (method.requestStream) {
467
+ return 'File';
468
+ }
469
+ const baseRequestTypePath = method.requestType?.split('.');
470
+ if (baseRequestTypePath) {
471
+ const requestTypePath = walkToFindTypePath(
472
+ rootJson,
473
+ pathWithName,
474
+ baseRequestTypePath,
475
+ );
476
+ const requestTypeName = getTypeName(this.schemaComposer, requestTypePath, true);
477
+ return requestTypeName;
478
+ }
479
+ return undefined;
480
+ },
481
+ };
482
+ fieldConfig.args = fieldConfigArgs;
483
+ const methodNameLowerCased = methodName.toLowerCase();
484
+ const prefixQueryMethod = this.config.prefixQueryMethod || QUERY_METHOD_PREFIXES;
485
+ let rootTypeComposer: ObjectTypeComposer;
486
+ if (this.config.selectQueryOrMutationField) {
487
+ const selection = this.config.selectQueryOrMutationField.find(
488
+ selection => micromatch([rootFieldName], selection.fieldName).length > 0,
489
+ );
490
+ const rootTypeName = selection?.type?.toLowerCase();
491
+ if (rootTypeName) {
492
+ if (rootTypeName === 'query') {
493
+ rootTypeComposer = this.schemaComposer.Query;
494
+ } else if (rootTypeName === 'mutation') {
495
+ rootTypeComposer = this.schemaComposer.Mutation;
496
+ } else if (rootTypeName === 'subscription') {
497
+ rootTypeComposer = this.schemaComposer.Subscription;
498
+ } else {
499
+ throw new Error(
500
+ `Unknown type provided ${selection.type} for ${rootFieldName}; available options are Query, Mutation and Subscription`,
501
+ );
502
+ }
503
+ }
504
+ }
505
+ if (rootTypeComposer == null) {
506
+ rootTypeComposer = prefixQueryMethod.some(prefix =>
507
+ methodNameLowerCased.startsWith(prefix),
508
+ )
509
+ ? this.schemaComposer.Query
510
+ : this.schemaComposer.Mutation;
511
+ }
512
+ const serviceName = pathWithName.join('.') || objPath;
513
+ const argsMapping = method.requestType
514
+ ? emitRequestBody(rootJson, pathWithName, method.requestType)
515
+ : '';
516
+ const selection = method.responseType
517
+ ? emitResponseSelection(rootJson, pathWithName, method.responseType)
518
+ : '';
519
+ const rpcDirective = {
520
+ name: 'protobuf__rpc',
521
+ args: {
522
+ subgraph: this.subgraphName,
523
+ service: serviceName,
524
+ method: methodName,
525
+ args: argsMapping,
526
+ selection,
527
+ stream: !!method.responseStream,
528
+ },
529
+ };
530
+ this.schemaComposer.addDirective(protobufRpcDirective);
531
+ rootTypeComposer.addFields({
532
+ [rootFieldName]: {
533
+ ...fieldConfig,
534
+ directives: [rpcDirective],
535
+ },
536
+ });
537
+ if (method.responseStream) {
538
+ this.schemaComposer.Subscription.addFields({
539
+ [rootFieldName]: {
540
+ args: fieldConfigArgs,
541
+ description: method.comment,
542
+ type: fieldConfigTypeFactory,
543
+ directives: [
544
+ {
545
+ ...rpcDirective,
546
+ args: { ...rpcDirective.args, stream: true },
547
+ },
548
+ ],
549
+ },
550
+ });
551
+ }
552
+ }
553
+ // connectivity state removed from protobuf author surface
554
+ }
555
+ }
556
+ }
package/src/index.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { type Logger } from '@graphql-hive/logger';
2
+ import type { YamlConfig } from '@graphql-mesh/types';
3
+ import { GrpcLoaderHelper } from './grpcLoaderHelper.js';
4
+
5
+ interface LoaderContext {
6
+ cwd: string;
7
+ log: Logger;
8
+ }
9
+
10
+ export type ProtobufSourceType = 'grpc' | 'connect' | 'twirp';
11
+
12
+ export type ProtobufLoaderOptions = YamlConfig.GrpcHandler & {
13
+ /**
14
+ * RPC stack for emit/dial conventions. Same `.proto` parse for all.
15
+ * Day one: `grpc`. Connect/Twirp loader emit can follow; hand SDL works now via HTTPS location.
16
+ */
17
+ type?: ProtobufSourceType;
18
+ };
19
+
20
+ /**
21
+ * Load a protobuf-RPC subgraph from `.proto` / reflection.
22
+ */
23
+ export function loadProtobufSubgraph(name: string, options: ProtobufLoaderOptions) {
24
+ return (ctx: LoaderContext) => {
25
+ const helper = new GrpcLoaderHelper(name, ctx.cwd, ctx.log, {
26
+ ...options,
27
+ // type reserved for future connect/twirp emit path conventions
28
+ });
29
+ const schema$ = helper.buildSchema().finally(() => helper.dispose());
30
+ return {
31
+ name,
32
+ schema$,
33
+ };
34
+ };
35
+ }
package/src/scalars.ts ADDED
@@ -0,0 +1,31 @@
1
+ type ScalarMap = Map<string, string>;
2
+
3
+ const SCALARS: ScalarMap = new Map([
4
+ ['bool', 'Boolean'],
5
+ ['bytes', 'Byte'],
6
+ ['double', 'Float'],
7
+ ['fixed32', 'Int'],
8
+ ['fixed64', 'BigInt'],
9
+ ['float', 'Float'],
10
+ ['int32', 'Int'],
11
+ ['int64', 'BigInt'],
12
+ ['sfixed32', 'Int'],
13
+ ['sfixed64', 'BigInt'],
14
+ ['sint32', 'Int'],
15
+ ['sint64', 'BigInt'],
16
+ ['string', 'String'],
17
+ ['uint32', 'UnsignedInt'],
18
+ ['uint64', 'BigInt'], // A new scalar might be needed
19
+ ]);
20
+
21
+ export function isGrpcScalar(type: string): boolean {
22
+ return SCALARS.has(type);
23
+ }
24
+
25
+ export function getGraphQLScalarForGrpc(scalarType: string): string {
26
+ const gqlScalar = SCALARS.get(scalarType);
27
+ if (!gqlScalar) {
28
+ throw new Error(`Could not find GraphQL Scalar for type ${scalarType}`);
29
+ }
30
+ return SCALARS.get(scalarType);
31
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,61 @@
1
+ import type { SchemaComposer } from 'graphql-compose';
2
+ import lodashHas from 'lodash.has';
3
+ import type { INamespace, Root } from 'protobufjs';
4
+ import { fs, path as pathModule } from '@graphql-mesh/cross-helpers';
5
+ import { getGraphQLScalarForGrpc, isGrpcScalar } from './scalars.js';
6
+
7
+ export function addIncludePathResolver(root: Root, includePaths: string[]): void {
8
+ const originalResolvePath = root.resolvePath;
9
+ root.resolvePath = (origin: string, target: string) => {
10
+ if (pathModule.isAbsolute(target)) {
11
+ return target;
12
+ }
13
+ for (const directory of includePaths) {
14
+ const fullPath: string = pathModule.join(directory, target);
15
+ if (fs.existsSync(fullPath)) {
16
+ return fullPath;
17
+ }
18
+ }
19
+ const path = originalResolvePath(origin, target);
20
+ if (path === null) {
21
+ console.warn(`${target} not found in any of the include paths ${includePaths}`);
22
+ }
23
+ return path;
24
+ };
25
+ }
26
+
27
+ export function getTypeName(
28
+ schemaComposer: SchemaComposer,
29
+ pathWithName: string[] | undefined,
30
+ isInput: boolean,
31
+ ) {
32
+ if (pathWithName?.length) {
33
+ const baseTypeName = pathWithName.filter(Boolean).join('__');
34
+ if (isGrpcScalar(baseTypeName)) {
35
+ return getGraphQLScalarForGrpc(baseTypeName);
36
+ }
37
+ if (schemaComposer.isEnumType(baseTypeName)) {
38
+ return baseTypeName;
39
+ }
40
+ return isInput ? baseTypeName + '_Input' : baseTypeName;
41
+ }
42
+ return 'Void';
43
+ }
44
+
45
+ export function walkToFindTypePath(
46
+ rootJson: INamespace,
47
+ pathWithName: string[],
48
+ baseTypePath: string[],
49
+ ) {
50
+ // Reflection / Fully-qualified names often look like `.echo.GreetingRequest`
51
+ // (`split('.')` → `['', 'echo', …]`). Empty segments break `nested['']` walks.
52
+ const normalizedBase = baseTypePath.filter(Boolean);
53
+ const currentWalkingPath = pathWithName.filter(Boolean);
54
+ while (!lodashHas(rootJson.nested, currentWalkingPath.concat(normalizedBase).join('.nested.'))) {
55
+ if (!currentWalkingPath.length) {
56
+ break;
57
+ }
58
+ currentWalkingPath.pop();
59
+ }
60
+ return currentWalkingPath.concat(normalizedBase);
61
+ }