@bufbuild/protoc-gen-es 1.8.0 → 2.0.0-alpha.1

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.
package/src/util.ts CHANGED
@@ -12,18 +12,36 @@
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
14
 
15
+ import type { DescExtension, DescField } from "@bufbuild/protobuf";
15
16
  import {
16
- codegenInfo,
17
- DescEnumValue,
18
- DescExtension,
19
- DescField,
20
- FieldDescriptorProto_Label,
21
17
  LongType,
22
18
  ScalarType,
23
- ScalarValue,
24
- } from "@bufbuild/protobuf";
19
+ scalarTypeScriptType,
20
+ } from "@bufbuild/protobuf/reflect";
21
+ import { Edition, isWrapperDesc } from "@bufbuild/protobuf/wkt";
25
22
  import type { Printable } from "@bufbuild/protoplugin/ecmascript";
26
- import { localName } from "@bufbuild/protoplugin/ecmascript";
23
+
24
+ /**
25
+ * Tells whether a field uses the prototype chain for field presence.
26
+ * Behavior must match with the counterpart in @bufbuild/protobuf.
27
+ */
28
+ export function fieldUsesPrototype(field: DescField): field is DescField & {
29
+ fieldKind: "scalar" | "enum";
30
+ oneof: undefined;
31
+ repeated: false;
32
+ } {
33
+ if (field.parent.file.edition != Edition.EDITION_PROTO2) {
34
+ return false;
35
+ }
36
+ if (field.fieldKind != "scalar" && field.fieldKind != "enum") {
37
+ return false;
38
+ }
39
+ if (field.oneof) {
40
+ return false;
41
+ }
42
+ // proto2 singular scalar and enum fields use an initial value on the prototype chain
43
+ return true;
44
+ }
27
45
 
28
46
  export function getFieldTypeInfo(field: DescField | DescExtension): {
29
47
  typing: Printable;
@@ -36,20 +54,17 @@ export function getFieldTypeInfo(field: DescField | DescExtension): {
36
54
  switch (field.fieldKind) {
37
55
  case "scalar":
38
56
  typing.push(scalarTypeScriptType(field.scalar, field.longType));
39
- optional =
40
- field.optional ||
41
- field.proto.label === FieldDescriptorProto_Label.REQUIRED;
57
+ optional = field.optional;
42
58
  typingInferrableFromZeroValue = true;
43
59
  break;
44
60
  case "message": {
45
- const baseType = codegenInfo.getUnwrappedFieldType(field);
46
- if (baseType !== undefined) {
61
+ if (!field.oneof && isWrapperDesc(field.message)) {
62
+ const baseType = field.message.fields[0].scalar;
47
63
  typing.push(scalarTypeScriptType(baseType, LongType.BIGINT));
48
64
  } else {
49
65
  typing.push({
50
- kind: "es_ref_message",
51
- type: field.message,
52
- typeOnly: true,
66
+ kind: "es_shape_ref",
67
+ desc: field.message,
53
68
  });
54
69
  }
55
70
  optional = true;
@@ -58,15 +73,40 @@ export function getFieldTypeInfo(field: DescField | DescExtension): {
58
73
  }
59
74
  case "enum":
60
75
  typing.push({
61
- kind: "es_ref_enum",
62
- type: field.enum,
63
- typeOnly: true,
76
+ kind: "es_shape_ref",
77
+ desc: field.enum,
64
78
  });
65
- optional =
66
- field.optional ||
67
- field.proto.label === FieldDescriptorProto_Label.REQUIRED;
79
+ optional = field.optional;
68
80
  typingInferrableFromZeroValue = true;
69
81
  break;
82
+ case "list":
83
+ optional = false;
84
+ typingInferrableFromZeroValue = false;
85
+ switch (field.listKind) {
86
+ case "enum":
87
+ typing.push(
88
+ {
89
+ kind: "es_shape_ref",
90
+ desc: field.enum,
91
+ },
92
+ "[]",
93
+ );
94
+ break;
95
+ case "scalar":
96
+ typing.push(scalarTypeScriptType(field.scalar, field.longType), "[]");
97
+ break;
98
+ case "message": {
99
+ typing.push(
100
+ {
101
+ kind: "es_shape_ref",
102
+ desc: field.message,
103
+ },
104
+ "[]",
105
+ );
106
+ break;
107
+ }
108
+ }
109
+ break;
70
110
  case "map": {
71
111
  let keyType: string;
72
112
  switch (field.mapKey) {
@@ -82,25 +122,20 @@ export function getFieldTypeInfo(field: DescField | DescExtension): {
82
122
  break;
83
123
  }
84
124
  let valueType: Printable;
85
- switch (field.mapValue.kind) {
125
+ switch (field.mapKind) {
86
126
  case "scalar":
87
- valueType = scalarTypeScriptType(
88
- field.mapValue.scalar,
89
- LongType.BIGINT,
90
- );
127
+ valueType = scalarTypeScriptType(field.scalar, LongType.BIGINT);
91
128
  break;
92
129
  case "message":
93
130
  valueType = {
94
- kind: "es_ref_message",
95
- type: field.mapValue.message,
96
- typeOnly: true,
131
+ kind: "es_shape_ref",
132
+ desc: field.message,
97
133
  };
98
134
  break;
99
135
  case "enum":
100
136
  valueType = {
101
- kind: "es_ref_enum",
102
- type: field.mapValue.enum,
103
- typeOnly: true,
137
+ kind: "es_shape_ref",
138
+ desc: field.enum,
104
139
  };
105
140
  break;
106
141
  }
@@ -110,206 +145,32 @@ export function getFieldTypeInfo(field: DescField | DescExtension): {
110
145
  break;
111
146
  }
112
147
  }
113
- if (field.repeated) {
114
- typing.push("[]");
115
- optional = false;
116
- typingInferrableFromZeroValue = false;
117
- }
118
148
  return { typing, optional, typingInferrableFromZeroValue };
119
149
  }
120
150
 
121
- /**
122
- * Return a printable expression for the default value of a field.
123
- * Only applicable for singular scalar and enum fields.
124
- */
125
- export function getFieldDefaultValueExpression(
126
- field: DescField | DescExtension,
127
- enumAs:
128
- | "enum_value_as_is"
129
- | "enum_value_as_integer"
130
- | "enum_value_as_cast_integer" = "enum_value_as_is",
131
- ): Printable | undefined {
132
- if (field.repeated) {
133
- return undefined;
134
- }
135
- if (field.fieldKind !== "enum" && field.fieldKind !== "scalar") {
136
- return undefined;
137
- }
138
- const defaultValue = field.getDefaultValue();
139
- if (defaultValue === undefined) {
140
- return undefined;
141
- }
142
- switch (field.fieldKind) {
143
- case "enum": {
144
- const enumValue = field.enum.values.find(
145
- (value) => value.number === defaultValue,
146
- );
147
- if (enumValue === undefined) {
148
- throw new Error(
149
- `invalid enum default value: ${String(defaultValue)} for ${enumValue}`,
150
- );
151
- }
152
- return literalEnumValue(enumValue, enumAs);
153
- }
154
- case "scalar":
155
- return literalScalarValue(defaultValue, field);
156
- }
157
- }
158
-
159
- /**
160
- * Return a printable expression for the zero value of a field.
161
- *
162
- * Returns either:
163
- * - empty array literal for repeated fields
164
- * - empty object literal for maps
165
- * - undefined for message fields
166
- * - an enums first value
167
- * - scalar zero value
168
- */
169
- export function getFieldZeroValueExpression(
170
- field: DescField | DescExtension,
171
- enumAs:
172
- | "enum_value_as_is"
173
- | "enum_value_as_integer"
174
- | "enum_value_as_cast_integer" = "enum_value_as_is",
175
- ): Printable | undefined {
176
- if (field.repeated) {
177
- return "[]";
178
- }
179
- switch (field.fieldKind) {
180
- case "message":
181
- return undefined;
182
- case "map":
183
- return "{}";
184
- case "enum": {
185
- // In proto3, the first enum value must be zero.
186
- // In proto2, protobuf-go returns the first value as the default.
187
- if (field.enum.values.length < 1) {
188
- throw new Error("invalid enum: missing at least one value");
189
- }
190
- const zeroValue = field.enum.values[0];
191
- return literalEnumValue(zeroValue, enumAs);
192
- }
193
- case "scalar": {
194
- const defaultValue = codegenInfo.scalarZeroValue(
195
- field.scalar,
196
- field.longType,
197
- );
198
- return literalScalarValue(defaultValue, field);
199
- }
200
- }
201
- }
202
-
203
- function literalScalarValue(
204
- value: ScalarValue,
205
- field: (DescField | DescExtension) & { fieldKind: "scalar" },
151
+ export function functionCall(
152
+ fn: Printable,
153
+ args: Printable[],
154
+ typeParams?: Printable[],
206
155
  ): Printable {
207
- switch (field.scalar) {
208
- case ScalarType.DOUBLE:
209
- case ScalarType.FLOAT:
210
- case ScalarType.INT32:
211
- case ScalarType.FIXED32:
212
- case ScalarType.UINT32:
213
- case ScalarType.SFIXED32:
214
- case ScalarType.SINT32:
215
- if (typeof value != "number") {
216
- throw new Error(
217
- `Unexpected value for ${ScalarType[field.scalar]} ${field.toString()}: ${String(value)}`,
218
- );
219
- }
220
- return value;
221
- case ScalarType.BOOL:
222
- if (typeof value != "boolean") {
223
- throw new Error(
224
- `Unexpected value for ${ScalarType[field.scalar]} ${field.toString()}: ${String(value)}`,
225
- );
226
- }
227
- return value;
228
- case ScalarType.STRING:
229
- if (typeof value != "string") {
230
- throw new Error(
231
- `Unexpected value for ${ScalarType[field.scalar]} ${field.toString()}: ${String(value)}`,
232
- );
233
- }
234
- return { kind: "es_string", value };
235
- case ScalarType.BYTES:
236
- if (!(value instanceof Uint8Array)) {
237
- throw new Error(
238
- `Unexpected value for ${ScalarType[field.scalar]} ${field.toString()}: ${String(value)}`,
239
- );
240
- }
241
- return value;
242
- case ScalarType.INT64:
243
- case ScalarType.SINT64:
244
- case ScalarType.SFIXED64:
245
- case ScalarType.UINT64:
246
- case ScalarType.FIXED64:
247
- if (typeof value != "bigint" && typeof value != "string") {
248
- throw new Error(
249
- `Unexpected value for ${ScalarType[field.scalar]} ${field.toString()}: ${String(value)}`,
250
- );
251
- }
252
- return {
253
- kind: "es_proto_int64",
254
- type: field.scalar,
255
- longType: field.longType,
256
- value,
257
- };
156
+ let tp: Printable = [];
157
+ if (typeParams !== undefined && typeParams.length > 0) {
158
+ tp = ["<", commaSeparate(typeParams), ">"];
258
159
  }
160
+ return [fn, ...tp, "(", commaSeparate(args), ")"];
259
161
  }
260
162
 
261
- function literalEnumValue(
262
- value: DescEnumValue,
263
- enumAs:
264
- | "enum_value_as_is"
265
- | "enum_value_as_integer"
266
- | "enum_value_as_cast_integer",
267
- ): Printable {
268
- switch (enumAs) {
269
- case "enum_value_as_is":
270
- return [
271
- { kind: "es_ref_enum", type: value.parent, typeOnly: false },
272
- ".",
273
- localName(value),
274
- ];
275
- case "enum_value_as_integer":
276
- return [
277
- value.number,
278
- " /* ",
279
- value.parent.typeName,
280
- ".",
281
- value.name,
282
- " */",
283
- ];
284
- case "enum_value_as_cast_integer":
285
- return [
286
- value.number,
287
- " as ",
288
- { kind: "es_ref_enum", type: value.parent, typeOnly: true },
289
- ".",
290
- localName(value),
291
- ];
292
- }
163
+ export function arrayLiteral(elements: Printable[]): Printable {
164
+ return ["[", commaSeparate(elements), "]"];
293
165
  }
294
166
 
295
- function scalarTypeScriptType(type: ScalarType, longType: LongType): Printable {
296
- switch (type) {
297
- case ScalarType.STRING:
298
- return "string";
299
- case ScalarType.BOOL:
300
- return "boolean";
301
- case ScalarType.UINT64:
302
- case ScalarType.SFIXED64:
303
- case ScalarType.FIXED64:
304
- case ScalarType.SINT64:
305
- case ScalarType.INT64:
306
- if (longType === LongType.STRING) {
307
- return "string";
308
- }
309
- return "bigint";
310
- case ScalarType.BYTES:
311
- return "Uint8Array";
312
- default:
313
- return "number";
167
+ function commaSeparate(elements: Printable[]): Printable {
168
+ const r: Printable[] = [];
169
+ for (let i = 0; i < elements.length; i++) {
170
+ r.push(elements[i]);
171
+ if (i < elements.length - 1) {
172
+ r.push(", ");
173
+ }
314
174
  }
175
+ return r;
315
176
  }
package/tsconfig.json CHANGED
@@ -2,6 +2,11 @@
2
2
  "files": ["src/protoc-gen-es-plugin.ts"],
3
3
  "extends": "../../tsconfig.base.json",
4
4
  "compilerOptions": {
5
- "resolveJsonModule": true
5
+ // We import the plugin's version number from package.json
6
+ "resolveJsonModule": true,
7
+ // This package is CommonJS
8
+ "verbatimModuleSyntax": false,
9
+ "module": "CommonJS",
10
+ "moduleResolution": "Node10"
6
11
  }
7
12
  }
@@ -1,216 +0,0 @@
1
- "use strict";
2
- // Copyright 2021-2024 Buf Technologies, Inc.
3
- //
4
- // Licensed under the Apache License, Version 2.0 (the "License");
5
- // you may not use this file except in compliance with the License.
6
- // You may obtain a copy of the License at
7
- //
8
- // http://www.apache.org/licenses/LICENSE-2.0
9
- //
10
- // Unless required by applicable law or agreed to in writing, software
11
- // distributed under the License is distributed on an "AS IS" BASIS,
12
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- // See the License for the specific language governing permissions and
14
- // limitations under the License.
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.generateDts = void 0;
17
- const ecmascript_1 = require("@bufbuild/protoplugin/ecmascript");
18
- const editions_js_1 = require("./editions.js");
19
- const util_js_1 = require("./util.js");
20
- function generateDts(schema) {
21
- for (const file of schema.files) {
22
- const f = schema.generateFile(file.name + "_pb.d.ts");
23
- f.preamble(file);
24
- for (const enumeration of file.enums) {
25
- generateEnum(schema, f, enumeration);
26
- }
27
- for (const message of file.messages) {
28
- generateMessage(schema, f, message);
29
- }
30
- for (const extension of file.extensions) {
31
- generateExtension(schema, f, extension);
32
- }
33
- // We do not generate anything for services
34
- }
35
- }
36
- exports.generateDts = generateDts;
37
- // prettier-ignore
38
- function generateEnum(schema, f, enumeration) {
39
- f.print(f.jsDoc(enumeration));
40
- f.print("export declare enum ", enumeration, " {");
41
- for (const value of enumeration.values) {
42
- if (enumeration.values.indexOf(value) > 0) {
43
- f.print();
44
- }
45
- f.print(f.jsDoc(value, " "));
46
- f.print(" ", (0, ecmascript_1.localName)(value), " = ", value.number, ",");
47
- }
48
- f.print("}");
49
- f.print();
50
- }
51
- // prettier-ignore
52
- function generateMessage(schema, f, message) {
53
- const protoN = (0, editions_js_1.getNonEditionRuntime)(schema, message.file);
54
- const { PartialMessage, FieldList, Message, PlainMessage, BinaryReadOptions, JsonReadOptions, JsonValue } = schema.runtime;
55
- f.print(f.jsDoc(message));
56
- f.print("export declare class ", message, " extends ", Message, "<", message, "> {");
57
- for (const member of message.members) {
58
- switch (member.kind) {
59
- case "oneof":
60
- generateOneof(schema, f, member);
61
- break;
62
- default:
63
- generateField(schema, f, member);
64
- break;
65
- }
66
- f.print();
67
- }
68
- f.print(" constructor(data?: ", PartialMessage, "<", message, ">);");
69
- f.print();
70
- generateWktMethods(schema, f, message);
71
- f.print(" static readonly runtime: typeof ", protoN, ";");
72
- f.print(' static readonly typeName = ', f.string(message.typeName), ';');
73
- f.print(" static readonly fields: ", FieldList, ";");
74
- // In case we start supporting options, we have to surface them here
75
- //f.print(" static readonly options: { readonly [extensionName: string]: ", rt.JsonValue, " } = {};")
76
- f.print();
77
- generateWktStaticMethods(schema, f, message);
78
- f.print(" static fromBinary(bytes: Uint8Array, options?: Partial<", BinaryReadOptions, ">): ", message, ";");
79
- f.print();
80
- f.print(" static fromJson(jsonValue: ", JsonValue, ", options?: Partial<", JsonReadOptions, ">): ", message, ";");
81
- f.print();
82
- f.print(" static fromJsonString(jsonString: string, options?: Partial<", JsonReadOptions, ">): ", message, ";");
83
- f.print();
84
- f.print(" static equals(a: ", message, " | ", PlainMessage, "<", message, "> | undefined, b: ", message, " | ", PlainMessage, "<", message, "> | undefined): boolean;");
85
- f.print("}");
86
- f.print();
87
- for (const nestedEnum of message.nestedEnums) {
88
- generateEnum(schema, f, nestedEnum);
89
- }
90
- for (const nestedMessage of message.nestedMessages) {
91
- generateMessage(schema, f, nestedMessage);
92
- }
93
- for (const nestedExtension of message.nestedExtensions) {
94
- generateExtension(schema, f, nestedExtension);
95
- }
96
- }
97
- // prettier-ignore
98
- function generateOneof(schema, f, oneof) {
99
- f.print(f.jsDoc(oneof, " "));
100
- f.print(" ", (0, ecmascript_1.localName)(oneof), ": {");
101
- for (const field of oneof.fields) {
102
- if (oneof.fields.indexOf(field) > 0) {
103
- f.print(` } | {`);
104
- }
105
- f.print(f.jsDoc(field, " "));
106
- const { typing } = (0, util_js_1.getFieldTypeInfo)(field);
107
- f.print(` value: `, typing, `;`);
108
- f.print(` case: "`, (0, ecmascript_1.localName)(field), `";`);
109
- }
110
- f.print(` } | { case: undefined; value?: undefined };`);
111
- }
112
- // prettier-ignore
113
- function generateField(schema, f, field) {
114
- f.print(f.jsDoc(field, " "));
115
- const e = [];
116
- const { typing, optional } = (0, util_js_1.getFieldTypeInfo)(field);
117
- if (!optional) {
118
- e.push(" ", (0, ecmascript_1.localName)(field), ": ", typing, ";");
119
- }
120
- else {
121
- e.push(" ", (0, ecmascript_1.localName)(field), "?: ", typing, ";");
122
- }
123
- f.print(e);
124
- }
125
- // prettier-ignore
126
- function generateExtension(schema, f, ext) {
127
- const { typing } = (0, util_js_1.getFieldTypeInfo)(ext);
128
- f.print(f.jsDoc(ext));
129
- f.print(f.exportDecl("declare const", ext), ": ", schema.runtime.Extension, "<", ext.extendee, ", ", typing, ">;");
130
- f.print();
131
- }
132
- // prettier-ignore
133
- function generateWktMethods(schema, f, message) {
134
- const ref = (0, ecmascript_1.reifyWkt)(message);
135
- if (ref === undefined) {
136
- return;
137
- }
138
- const { Message, MessageType, IMessageTypeRegistry } = schema.runtime;
139
- switch (ref.typeName) {
140
- case "google.protobuf.Any":
141
- f.print(" packFrom(message: ", Message, "): void;");
142
- f.print();
143
- f.print(" unpackTo(target: ", Message, "): boolean;");
144
- f.print();
145
- f.print(" unpack(registry: ", IMessageTypeRegistry, "): Message | undefined;");
146
- f.print();
147
- f.print(" is(type: ", MessageType, " | string): boolean;");
148
- f.print();
149
- f.print(" private typeNameToUrl(name: string): string;");
150
- f.print();
151
- f.print(" private typeUrlToName(url: string): string;");
152
- f.print();
153
- break;
154
- case "google.protobuf.Timestamp":
155
- f.print(" toDate(): Date;");
156
- f.print();
157
- break;
158
- case "google.protobuf.Duration":
159
- case "google.protobuf.Struct":
160
- case "google.protobuf.Value":
161
- case "google.protobuf.ListValue":
162
- case "google.protobuf.FieldMask":
163
- case "google.protobuf.DoubleValue":
164
- case "google.protobuf.FloatValue":
165
- case "google.protobuf.Int64Value":
166
- case "google.protobuf.UInt64Value":
167
- case "google.protobuf.Int32Value":
168
- case "google.protobuf.UInt32Value":
169
- case "google.protobuf.BoolValue":
170
- case "google.protobuf.StringValue":
171
- case "google.protobuf.BytesValue":
172
- break;
173
- }
174
- }
175
- // prettier-ignore
176
- function generateWktStaticMethods(schema, f, message) {
177
- const ref = (0, ecmascript_1.reifyWkt)(message);
178
- if (ref === undefined) {
179
- return;
180
- }
181
- switch (ref.typeName) {
182
- case "google.protobuf.Any":
183
- f.print(" static pack(message: Message): ", message, ";");
184
- f.print();
185
- break;
186
- case "google.protobuf.Timestamp":
187
- f.print(" static now(): ", message, ";");
188
- f.print();
189
- f.print(" static fromDate(date: Date): ", message, ";");
190
- f.print();
191
- break;
192
- case "google.protobuf.DoubleValue":
193
- case "google.protobuf.FloatValue":
194
- case "google.protobuf.Int64Value":
195
- case "google.protobuf.UInt64Value":
196
- case "google.protobuf.Int32Value":
197
- case "google.protobuf.UInt32Value":
198
- case "google.protobuf.BoolValue":
199
- case "google.protobuf.StringValue":
200
- case "google.protobuf.BytesValue": {
201
- const { typing } = (0, util_js_1.getFieldTypeInfo)(ref.value);
202
- f.print(" static readonly fieldWrapper: {");
203
- f.print(" wrapField(value: ", typing, "): ", message, ",");
204
- f.print(" unwrapField(value: ", message, "): ", typing, ",");
205
- f.print(" };");
206
- f.print();
207
- break;
208
- }
209
- case "google.protobuf.Duration":
210
- case "google.protobuf.Struct":
211
- case "google.protobuf.Value":
212
- case "google.protobuf.ListValue":
213
- case "google.protobuf.FieldMask":
214
- break;
215
- }
216
- }
@@ -1,34 +0,0 @@
1
- "use strict";
2
- // Copyright 2021-2024 Buf Technologies, Inc.
3
- //
4
- // Licensed under the Apache License, Version 2.0 (the "License");
5
- // you may not use this file except in compliance with the License.
6
- // You may obtain a copy of the License at
7
- //
8
- // http://www.apache.org/licenses/LICENSE-2.0
9
- //
10
- // Unless required by applicable law or agreed to in writing, software
11
- // distributed under the License is distributed on an "AS IS" BASIS,
12
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- // See the License for the specific language governing permissions and
14
- // limitations under the License.
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- exports.getNonEditionRuntime = void 0;
17
- /**
18
- * Temporary function to retrieve the import symbol for the proto2 or proto3
19
- * runtime.
20
- *
21
- * For syntax "editions", this function raises and error.
22
- *
23
- * Once support for "editions" is implemented in the runtime, this function can
24
- * be removed.
25
- */
26
- function getNonEditionRuntime(schema, file) {
27
- var _a;
28
- if (file.syntax === "editions") {
29
- // TODO support editions
30
- throw new Error(`${(_a = file.proto.name) !== null && _a !== void 0 ? _a : ""}: syntax "editions" is not supported yet`);
31
- }
32
- return schema.runtime[file.syntax];
33
- }
34
- exports.getNonEditionRuntime = getNonEditionRuntime;