@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,28 @@
1
+ import protobufjs, { type AnyNestedObject } from 'protobufjs';
2
+ import { type Logger } from '@graphql-hive/logger';
3
+ import type { YamlConfig } from '@graphql-mesh/types';
4
+ import { type ChannelCredentials } from '@grpc/grpc-js';
5
+ import { DisposableStack } from '@whatwg-node/disposablestack';
6
+ import type { MaybePromise } from '@whatwg-node/promise-helpers';
7
+ export declare class GrpcLoaderHelper extends DisposableStack {
8
+ private subgraphName;
9
+ private baseDir;
10
+ private log;
11
+ private config;
12
+ private schemaComposer;
13
+ constructor(subgraphName: string, baseDir: string, log: Logger, config: YamlConfig.GrpcHandler);
14
+ buildSchema(): Promise<import("graphql").GraphQLSchema>;
15
+ private processReflection;
16
+ private processDescriptorFile;
17
+ private processProtoFile;
18
+ private getDescriptorSets;
19
+ getCredentials(): MaybePromise<ChannelCredentials>;
20
+ visit({ nested, name, currentPath, rootJsonName, rootJson, rootLogger: log, }: {
21
+ nested: AnyNestedObject;
22
+ name: string;
23
+ currentPath: string[];
24
+ rootJsonName: string;
25
+ rootJson: protobufjs.INamespace;
26
+ rootLogger: Logger;
27
+ }): void;
28
+ }
@@ -0,0 +1,28 @@
1
+ import protobufjs, { type AnyNestedObject } from 'protobufjs';
2
+ import { type Logger } from '@graphql-hive/logger';
3
+ import type { YamlConfig } from '@graphql-mesh/types';
4
+ import { type ChannelCredentials } from '@grpc/grpc-js';
5
+ import { DisposableStack } from '@whatwg-node/disposablestack';
6
+ import type { MaybePromise } from '@whatwg-node/promise-helpers';
7
+ export declare class GrpcLoaderHelper extends DisposableStack {
8
+ private subgraphName;
9
+ private baseDir;
10
+ private log;
11
+ private config;
12
+ private schemaComposer;
13
+ constructor(subgraphName: string, baseDir: string, log: Logger, config: YamlConfig.GrpcHandler);
14
+ buildSchema(): Promise<import("graphql").GraphQLSchema>;
15
+ private processReflection;
16
+ private processDescriptorFile;
17
+ private processProtoFile;
18
+ private getDescriptorSets;
19
+ getCredentials(): MaybePromise<ChannelCredentials>;
20
+ visit({ nested, name, currentPath, rootJsonName, rootJson, rootLogger: log, }: {
21
+ nested: AnyNestedObject;
22
+ name: string;
23
+ currentPath: string[];
24
+ rootJsonName: string;
25
+ rootJson: protobufjs.INamespace;
26
+ rootLogger: Logger;
27
+ }): void;
28
+ }
@@ -0,0 +1,22 @@
1
+ import { type Logger } from '@graphql-hive/logger';
2
+ import type { YamlConfig } from '@graphql-mesh/types';
3
+ interface LoaderContext {
4
+ cwd: string;
5
+ log: Logger;
6
+ }
7
+ export type ProtobufSourceType = 'grpc' | 'connect' | 'twirp';
8
+ export type ProtobufLoaderOptions = YamlConfig.GrpcHandler & {
9
+ /**
10
+ * RPC stack for emit/dial conventions. Same `.proto` parse for all.
11
+ * Day one: `grpc`. Connect/Twirp loader emit can follow; hand SDL works now via HTTPS location.
12
+ */
13
+ type?: ProtobufSourceType;
14
+ };
15
+ /**
16
+ * Load a protobuf-RPC subgraph from `.proto` / reflection.
17
+ */
18
+ export declare function loadProtobufSubgraph(name: string, options: ProtobufLoaderOptions): (ctx: LoaderContext) => {
19
+ name: string;
20
+ schema$: Promise<import("graphql").GraphQLSchema>;
21
+ };
22
+ export {};
@@ -0,0 +1,22 @@
1
+ import { type Logger } from '@graphql-hive/logger';
2
+ import type { YamlConfig } from '@graphql-mesh/types';
3
+ interface LoaderContext {
4
+ cwd: string;
5
+ log: Logger;
6
+ }
7
+ export type ProtobufSourceType = 'grpc' | 'connect' | 'twirp';
8
+ export type ProtobufLoaderOptions = YamlConfig.GrpcHandler & {
9
+ /**
10
+ * RPC stack for emit/dial conventions. Same `.proto` parse for all.
11
+ * Day one: `grpc`. Connect/Twirp loader emit can follow; hand SDL works now via HTTPS location.
12
+ */
13
+ type?: ProtobufSourceType;
14
+ };
15
+ /**
16
+ * Load a protobuf-RPC subgraph from `.proto` / reflection.
17
+ */
18
+ export declare function loadProtobufSubgraph(name: string, options: ProtobufLoaderOptions): (ctx: LoaderContext) => {
19
+ name: string;
20
+ schema$: Promise<import("graphql").GraphQLSchema>;
21
+ };
22
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare function isGrpcScalar(type: string): boolean;
2
+ export declare function getGraphQLScalarForGrpc(scalarType: string): string;
@@ -0,0 +1,2 @@
1
+ export declare function isGrpcScalar(type: string): boolean;
2
+ export declare function getGraphQLScalarForGrpc(scalarType: string): string;
@@ -0,0 +1,5 @@
1
+ import type { SchemaComposer } from 'graphql-compose';
2
+ import type { INamespace, Root } from 'protobufjs';
3
+ export declare function addIncludePathResolver(root: Root, includePaths: string[]): void;
4
+ export declare function getTypeName(schemaComposer: SchemaComposer, pathWithName: string[] | undefined, isInput: boolean): string;
5
+ export declare function walkToFindTypePath(rootJson: INamespace, pathWithName: string[], baseTypePath: string[]): string[];
@@ -0,0 +1,5 @@
1
+ import type { SchemaComposer } from 'graphql-compose';
2
+ import type { INamespace, Root } from 'protobufjs';
3
+ export declare function addIncludePathResolver(root: Root, includePaths: string[]): void;
4
+ export declare function getTypeName(schemaComposer: SchemaComposer, pathWithName: string[] | undefined, isInput: boolean): string;
5
+ export declare function walkToFindTypePath(rootJson: INamespace, pathWithName: string[], baseTypePath: string[]): string[];
@@ -0,0 +1,53 @@
1
+ # Hand-authored ConnectRPC-style subgraph (no Connect loader).
2
+ # Same @protobuf__rpc surface as gRPC loader emit; HTTPS location → HTTP + default application/proto.
3
+
4
+ extend schema
5
+ @link(url: "https://the-guild.dev/graphql/mesh/protobuf/v1.0", import: ["@protobuf__rpc"])
6
+
7
+ schema @transport(subgraph: "movies", kind: "protobuf", location: "https://movies.example.com") {
8
+ query: Query
9
+ }
10
+
11
+ type Query {
12
+ moviesByYear(year: Int!): MoviesResult!
13
+ @protobuf__rpc(
14
+ service: "Example"
15
+ method: "GetMovies"
16
+ args: """
17
+ # Encode GraphQL field arguments into the protobuf request message.
18
+ # Each line is fieldId(protoType): graphqlPath (relative to this field args).
19
+ 1(message): input.movie {
20
+ 2(int64): year
21
+ }
22
+ """
23
+ selection: """
24
+ # Decode the protobuf response message into GraphQL fields.
25
+ # Each line is fieldId(protoType): graphqlFieldName.
26
+ 1(repeated message): result {
27
+ 1(string): name
28
+ 2(int64): year
29
+ 3(float): rating
30
+ 4(repeated string): cast
31
+ 6(enum{UNSPECIFIED=0,ACTION=1,DRAMA=2}): genre
32
+ }
33
+ """
34
+ )
35
+ }
36
+
37
+ type MoviesResult {
38
+ result: [Movie!]!
39
+ }
40
+
41
+ type Movie {
42
+ name: String!
43
+ year: Int!
44
+ rating: Float
45
+ cast: [String!]
46
+ genre: Genre
47
+ }
48
+
49
+ enum Genre {
50
+ UNSPECIFIED
51
+ ACTION
52
+ DRAMA
53
+ }
@@ -0,0 +1,59 @@
1
+ # Hand-authored Twirp-style subgraph (no Twirp loader).
2
+ # location includes /twirp base; Content-Type via @transport(headers:) (Twirp uses application/protobuf).
3
+
4
+ extend schema
5
+ @link(url: "https://the-guild.dev/graphql/mesh/protobuf/v1.0", import: ["@protobuf__rpc"])
6
+
7
+ schema
8
+ @transport(
9
+ subgraph: "movies"
10
+ kind: "protobuf"
11
+ location: "https://movies.example.com/twirp"
12
+ headers: [["Content-Type", "application/protobuf"]]
13
+ ) {
14
+ query: Query
15
+ }
16
+
17
+ type Query {
18
+ moviesByYear(year: Int!): MoviesResult!
19
+ @protobuf__rpc(
20
+ service: "Example"
21
+ method: "GetMovies"
22
+ args: """
23
+ # Encode GraphQL field arguments into the protobuf request message.
24
+ # Each line is fieldId(protoType): graphqlPath (relative to this field args).
25
+ 1(message): input.movie {
26
+ 2(int64): year
27
+ }
28
+ """
29
+ selection: """
30
+ # Decode the protobuf response message into GraphQL fields.
31
+ # Each line is fieldId(protoType): graphqlFieldName.
32
+ 1(repeated message): result {
33
+ 1(string): name
34
+ 2(int64): year
35
+ 3(float): rating
36
+ 4(repeated string): cast
37
+ 6(enum{UNSPECIFIED=0,ACTION=1,DRAMA=2}): genre
38
+ }
39
+ """
40
+ )
41
+ }
42
+
43
+ type MoviesResult {
44
+ result: [Movie!]!
45
+ }
46
+
47
+ type Movie {
48
+ name: String!
49
+ year: Int!
50
+ rating: Float
51
+ cast: [String!]
52
+ genre: Genre
53
+ }
54
+
55
+ enum Genre {
56
+ UNSPECIFIED
57
+ ACTION
58
+ DRAMA
59
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@omnigraph/protobuf",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.2",
4
+ "type": "module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "ardatan/graphql-mesh",
8
+ "directory": "packages/loaders/protobuf"
9
+ },
10
+ "license": "MIT",
11
+ "engines": {
12
+ "node": ">=22.18.0"
13
+ },
14
+ "main": "dist/cjs/index.js",
15
+ "module": "dist/esm/index.js",
16
+ "exports": {
17
+ ".": {
18
+ "require": {
19
+ "types": "./dist/typings/index.d.cts",
20
+ "default": "./dist/cjs/index.js"
21
+ },
22
+ "import": {
23
+ "types": "./dist/typings/index.d.ts",
24
+ "default": "./dist/esm/index.js"
25
+ },
26
+ "default": {
27
+ "types": "./dist/typings/index.d.ts",
28
+ "default": "./dist/esm/index.js"
29
+ }
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "typings": "dist/typings/index.d.ts",
34
+ "peerDependencies": {
35
+ "graphql": "^16.0.0 || ^17.0.0"
36
+ },
37
+ "dependencies": {
38
+ "@ardatan/grpc-reflection-js": "^0.0.2",
39
+ "@graphql-hive/logger": "^1.1.1",
40
+ "@graphql-mesh/cross-helpers": "^0.4.18",
41
+ "@graphql-mesh/string-interpolation": "^0.5.18",
42
+ "@graphql-mesh/transport-common": "^1.1.2",
43
+ "@graphql-mesh/utils": "^0.107.3",
44
+ "@graphql-tools/load-files": "^8.0.9",
45
+ "@graphql-tools/utils": "^13.2.2",
46
+ "@grpc/grpc-js": "^1.14.5",
47
+ "@whatwg-node/disposablestack": "^0.1.0",
48
+ "graphql-compose": "^9.3.0",
49
+ "graphql-scalars": "^2.0.1",
50
+ "lodash.has": "^4.5.2",
51
+ "micromatch": "^4.0.8",
52
+ "protobufjs": "^8.8.1"
53
+ },
54
+ "devDependencies": {
55
+ "graphql": "16.14.0"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public",
59
+ "directory": "dist"
60
+ },
61
+ "sideEffects": false,
62
+ "typescript": {
63
+ "definition": "dist/typings/index.d.ts"
64
+ }
65
+ }
@@ -0,0 +1,31 @@
1
+ import { DirectiveLocation, GraphQLBoolean, GraphQLDirective, GraphQLString } from 'graphql';
2
+
3
+ export const protobufRpcDirective = new GraphQLDirective({
4
+ name: 'protobuf__rpc',
5
+ locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.OBJECT],
6
+ args: {
7
+ subgraph: {
8
+ type: GraphQLString,
9
+ },
10
+ service: {
11
+ type: GraphQLString,
12
+ },
13
+ method: {
14
+ type: GraphQLString,
15
+ },
16
+ args: {
17
+ type: GraphQLString,
18
+ },
19
+ selection: {
20
+ type: GraphQLString,
21
+ },
22
+ stream: {
23
+ type: GraphQLBoolean,
24
+ },
25
+ entity: {
26
+ type: GraphQLBoolean,
27
+ },
28
+ },
29
+ });
30
+
31
+ export { TransportDirective as transportDirective } from '@graphql-mesh/utils';
@@ -0,0 +1,166 @@
1
+ import type { INamespace } from 'protobufjs';
2
+ import { walkToFindTypePath } from './utils.js';
3
+
4
+ /**
5
+ * Emit typed protobuf mapping strings from protobufjs JSON namespace (loader-time only).
6
+ * Output is indented and may include `#` comments for humans/AI; the transport parser skips them.
7
+ */
8
+
9
+ export function emitEnumValues(
10
+ rootJson: INamespace,
11
+ pathWithName: string[],
12
+ typeName: string,
13
+ ): string {
14
+ const typePath = walkToFindTypePath(rootJson, pathWithName, typeName.split('.'));
15
+ let cur: any = rootJson;
16
+ for (const p of typePath) {
17
+ cur = cur?.nested?.[p];
18
+ }
19
+ if (!cur?.values) {
20
+ return 'enum{}';
21
+ }
22
+ const parts = Object.entries(cur.values as Record<string, number>).map(
23
+ ([name, num]) => `${name}=${num}`,
24
+ );
25
+ return `enum{${parts.join(',')}}`;
26
+ }
27
+
28
+ export function protoTypeToken(
29
+ rootJson: INamespace,
30
+ pathWithName: string[],
31
+ field: { type?: string; rule?: string; keyType?: string },
32
+ ): string {
33
+ const base = field.type || 'string';
34
+ let token: string;
35
+ if (field.keyType) {
36
+ token = `map<${scalarOrEnum(rootJson, pathWithName, field.keyType)},${scalarOrEnum(rootJson, pathWithName, base)}>`;
37
+ } else if (isScalar(base)) {
38
+ token = base === 'bytes' ? 'bytes' : normalizeScalar(base);
39
+ } else {
40
+ const typePath = walkToFindTypePath(rootJson, pathWithName, base.split('.'));
41
+ let cur: any = rootJson;
42
+ for (const p of typePath) {
43
+ cur = cur?.nested?.[p];
44
+ }
45
+ if (cur?.values) {
46
+ token = emitEnumValues(rootJson, pathWithName, base);
47
+ } else {
48
+ token = 'message';
49
+ }
50
+ }
51
+ if (field.rule === 'repeated') {
52
+ return `repeated ${token}`;
53
+ }
54
+ return token;
55
+ }
56
+
57
+ function isScalar(t: string): boolean {
58
+ return [
59
+ 'double',
60
+ 'float',
61
+ 'int32',
62
+ 'int64',
63
+ 'uint32',
64
+ 'uint64',
65
+ 'sint32',
66
+ 'sint64',
67
+ 'fixed32',
68
+ 'fixed64',
69
+ 'sfixed32',
70
+ 'sfixed64',
71
+ 'bool',
72
+ 'string',
73
+ 'bytes',
74
+ ].includes(t);
75
+ }
76
+
77
+ function normalizeScalar(t: string): string {
78
+ return t;
79
+ }
80
+
81
+ function scalarOrEnum(rootJson: INamespace, pathWithName: string[], t: string): string {
82
+ if (isScalar(t)) return normalizeScalar(t);
83
+ const typePath = walkToFindTypePath(rootJson, pathWithName, t.split('.'));
84
+ let cur: any = rootJson;
85
+ for (const p of typePath) {
86
+ cur = cur?.nested?.[p];
87
+ }
88
+ if (cur?.values) return emitEnumValues(rootJson, pathWithName, t);
89
+ return 'string';
90
+ }
91
+
92
+ export function emitFieldsMapping(
93
+ rootJson: INamespace,
94
+ pathWithName: string[],
95
+ typeName: string,
96
+ bindMode: 'relative' | 'prefix',
97
+ bindPrefix = '',
98
+ indent = ' ',
99
+ ): string {
100
+ const typePath = walkToFindTypePath(rootJson, pathWithName, typeName.split('.'));
101
+ let cur: any = rootJson;
102
+ for (const p of typePath) {
103
+ cur = cur?.nested?.[p];
104
+ }
105
+ const fields = cur?.fields as
106
+ Record<string, { type?: string; id?: number; rule?: string; keyType?: string }> | undefined;
107
+ if (!fields) return '';
108
+ const lines: string[] = [];
109
+ for (const [fieldName, field] of Object.entries(fields)) {
110
+ const id = field.id ?? 0;
111
+ const token = protoTypeToken(rootJson, pathWithName, field);
112
+ const bind = bindMode === 'prefix' && bindPrefix ? `${bindPrefix}.${fieldName}` : fieldName;
113
+ if (token === 'message' || token === 'repeated message') {
114
+ const nestedType = field.type!;
115
+ const nested = emitFieldsMapping(
116
+ rootJson,
117
+ pathWithName,
118
+ nestedType,
119
+ 'relative',
120
+ '',
121
+ indent + ' ',
122
+ );
123
+ lines.push(`${indent}${id}(${token}): ${bind} {`);
124
+ if (nested) {
125
+ lines.push(nested);
126
+ }
127
+ lines.push(`${indent}}`);
128
+ } else {
129
+ lines.push(`${indent}${id}(${token}): ${bind}`);
130
+ }
131
+ }
132
+ return lines.join('\n');
133
+ }
134
+
135
+ /** Request: GraphQL args use `input` wrapping the request message fields. */
136
+ export function emitRequestBody(
137
+ rootJson: INamespace,
138
+ pathWithName: string[],
139
+ requestType: string,
140
+ ): string {
141
+ const inner = emitFieldsMapping(rootJson, pathWithName, requestType, 'prefix', 'input', ' ');
142
+ const header = [
143
+ '# Encode GraphQL field arguments into the protobuf request message.',
144
+ '# Each line is fieldId(protoType): graphqlPath (relative to this field args).',
145
+ ].join('\n');
146
+ if (!inner.trim()) {
147
+ return `${header}\n`;
148
+ }
149
+ return `${header}\n${inner}\n`;
150
+ }
151
+
152
+ export function emitResponseSelection(
153
+ rootJson: INamespace,
154
+ pathWithName: string[],
155
+ responseType: string,
156
+ ): string {
157
+ const inner = emitFieldsMapping(rootJson, pathWithName, responseType, 'relative', '', ' ');
158
+ const header = [
159
+ '# Decode the protobuf response message into GraphQL fields.',
160
+ '# Each line is fieldId(protoType): graphqlFieldName.',
161
+ ].join('\n');
162
+ if (!inner.trim()) {
163
+ return `${header}\n`;
164
+ }
165
+ return `${header}\n${inner}\n`;
166
+ }