@bufbuild/protobuf 0.0.6 → 0.0.9

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.
Files changed (75) hide show
  1. package/README.md +34 -4
  2. package/dist/cjs/binary-encoding.js +2 -2
  3. package/dist/cjs/codegen-info.js +60 -0
  4. package/dist/cjs/create-descriptor-set.js +952 -0
  5. package/dist/cjs/create-registry-from-desc.js +376 -0
  6. package/dist/cjs/create-registry.js +75 -0
  7. package/dist/cjs/descriptor-set.js +0 -458
  8. package/dist/cjs/google/protobuf/any_pb.js +4 -2
  9. package/dist/cjs/google/protobuf/duration_pb.js +1 -1
  10. package/dist/cjs/google/protobuf/struct_pb.js +2 -2
  11. package/dist/cjs/google/protobuf/type_pb.js +1 -1
  12. package/dist/cjs/index.js +17 -7
  13. package/dist/cjs/{descriptor-registry.js → legacy-descriptor-registry.js} +35 -69
  14. package/dist/cjs/legacy-descriptor-set.js +453 -0
  15. package/dist/cjs/legacy-type-registry.js +104 -0
  16. package/dist/cjs/message.js +2 -1
  17. package/dist/cjs/private/binary-format-common.js +4 -3
  18. package/dist/cjs/private/binary-format-proto2.js +3 -6
  19. package/dist/cjs/private/binary-format-proto3.js +2 -5
  20. package/dist/cjs/private/enum.js +22 -31
  21. package/dist/cjs/private/field-wrapper.js +30 -1
  22. package/dist/cjs/private/field.js +1 -1
  23. package/dist/cjs/private/json-format-common.js +6 -5
  24. package/dist/cjs/private/message-type.js +2 -1
  25. package/dist/cjs/private/names.js +168 -29
  26. package/dist/cjs/proto-int64.js +1 -1
  27. package/dist/cjs/proto2.js +7 -9
  28. package/dist/cjs/proto3.js +10 -13
  29. package/dist/cjs/type-registry.js +0 -87
  30. package/dist/esm/binary-encoding.js +2 -2
  31. package/dist/esm/codegen-info.js +57 -0
  32. package/dist/esm/create-descriptor-set.js +947 -0
  33. package/dist/esm/create-registry-from-desc.js +371 -0
  34. package/dist/esm/create-registry.js +71 -0
  35. package/dist/esm/descriptor-set.js +1 -456
  36. package/dist/esm/google/protobuf/any_pb.js +4 -2
  37. package/dist/esm/google/protobuf/duration_pb.js +1 -1
  38. package/dist/esm/google/protobuf/struct_pb.js +2 -2
  39. package/dist/esm/google/protobuf/type_pb.js +1 -1
  40. package/dist/esm/index.js +9 -3
  41. package/dist/esm/{descriptor-registry.js → legacy-descriptor-registry.js} +33 -67
  42. package/dist/esm/legacy-descriptor-set.js +449 -0
  43. package/dist/esm/legacy-type-registry.js +100 -0
  44. package/dist/esm/message.js +2 -1
  45. package/dist/esm/private/binary-format-common.js +4 -3
  46. package/dist/esm/private/binary-format-proto2.js +3 -6
  47. package/dist/esm/private/binary-format-proto3.js +2 -5
  48. package/dist/esm/private/enum.js +22 -31
  49. package/dist/esm/private/field-wrapper.js +28 -0
  50. package/dist/esm/private/field.js +2 -2
  51. package/dist/esm/private/json-format-common.js +6 -5
  52. package/dist/esm/private/message-type.js +2 -1
  53. package/dist/esm/private/names.js +163 -24
  54. package/dist/esm/proto-int64.js +1 -1
  55. package/dist/esm/proto2.js +8 -10
  56. package/dist/esm/proto3.js +11 -14
  57. package/dist/esm/type-registry.js +1 -85
  58. package/dist/types/codegen-info.d.ts +19 -0
  59. package/dist/types/create-descriptor-set.d.ts +16 -0
  60. package/dist/types/create-registry-from-desc.d.ts +49 -0
  61. package/dist/types/create-registry.d.ts +8 -0
  62. package/dist/types/descriptor-set.d.ts +554 -108
  63. package/dist/types/enum.d.ts +9 -5
  64. package/dist/types/index.d.ts +9 -3
  65. package/dist/types/{descriptor-registry.d.ts → legacy-descriptor-registry.d.ts} +8 -6
  66. package/dist/types/legacy-descriptor-set.d.ts +152 -0
  67. package/dist/types/legacy-type-registry.d.ts +44 -0
  68. package/dist/types/private/enum.d.ts +4 -8
  69. package/dist/types/private/field-wrapper.d.ts +7 -0
  70. package/dist/types/private/message-type.d.ts +1 -4
  71. package/dist/types/private/names.d.ts +26 -8
  72. package/dist/types/private/proto-runtime.d.ts +2 -2
  73. package/dist/types/private/util.d.ts +1 -6
  74. package/dist/types/type-registry.d.ts +0 -38
  75. package/package.json +4 -3
@@ -0,0 +1,100 @@
1
+ // Copyright 2021-2022 Buf Technologies, Inc.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ /**
15
+ * @deprecated use createRegistry() instead
16
+ *
17
+ * TypeRegistry is a simple registry for all message, enum, or service types.
18
+ */
19
+ export class TypeRegistry {
20
+ constructor() {
21
+ this.messages = {};
22
+ this.enums = {};
23
+ this.services = {};
24
+ }
25
+ /**
26
+ * Find a message type by its protobuf type name.
27
+ */
28
+ findMessage(typeName) {
29
+ return this.messages[typeName];
30
+ }
31
+ /**
32
+ * Find an enum type by its protobuf type name.
33
+ */
34
+ findEnum(typeName) {
35
+ return this.enums[typeName];
36
+ }
37
+ /**
38
+ * Find a service type by its protobuf type name.
39
+ */
40
+ findService(typeName) {
41
+ return this.services[typeName];
42
+ }
43
+ /**
44
+ * Create a new TypeRegistry from the given types.
45
+ */
46
+ static from(...types) {
47
+ const registry = new TypeRegistry();
48
+ for (const type of types) {
49
+ registry.add(type);
50
+ }
51
+ return registry;
52
+ }
53
+ /**
54
+ * @deprecated use TypeRegistry.from()
55
+ */
56
+ static fromIterable(types) {
57
+ return TypeRegistry.from(...types);
58
+ }
59
+ /**
60
+ * @deprecated use TypeRegistry.from()
61
+ */
62
+ static fromTypes(...types) {
63
+ return TypeRegistry.from(...types);
64
+ }
65
+ /**
66
+ * Add a type to the registry. For messages, the types used in message
67
+ * fields are added recursively. For services, the message types used
68
+ * for requests and responses are added recursively.
69
+ */
70
+ add(type) {
71
+ if ("fields" in type) {
72
+ if (!this.findMessage(type.typeName)) {
73
+ this.messages[type.typeName] = type;
74
+ for (const field of type.fields.list()) {
75
+ if (field.kind == "message") {
76
+ this.add(field.T);
77
+ }
78
+ else if (field.kind == "map" && field.V.kind == "message") {
79
+ this.add(field.V.T);
80
+ }
81
+ else if (field.kind == "enum") {
82
+ this.add(field.T);
83
+ }
84
+ }
85
+ }
86
+ }
87
+ else if ("methods" in type) {
88
+ if (!this.findService(type.typeName)) {
89
+ this.services[type.typeName] = type;
90
+ for (const method of Object.values(type.methods)) {
91
+ this.add(method.I);
92
+ this.add(method.O);
93
+ }
94
+ }
95
+ }
96
+ else {
97
+ this.enums[type.typeName] = type;
98
+ }
99
+ }
100
+ }
@@ -81,8 +81,9 @@ export class Message {
81
81
  * Serialize the message to a JSON string.
82
82
  */
83
83
  toJsonString(options) {
84
+ var _a;
84
85
  const value = this.toJson(options);
85
- return JSON.stringify(value, null, options?.prettySpaces ?? 0);
86
+ return JSON.stringify(value, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);
86
87
  }
87
88
  /**
88
89
  * Retrieve the MessageType of this message - a singleton that represents
@@ -29,17 +29,18 @@ const writeDefaults = {
29
29
  writerFactory: () => new BinaryWriter(),
30
30
  };
31
31
  function makeReadOptions(options) {
32
- return options ? { ...readDefaults, ...options } : readDefaults;
32
+ return options ? Object.assign(Object.assign({}, readDefaults), options) : readDefaults;
33
33
  }
34
34
  function makeWriteOptions(options) {
35
- return options ? { ...writeDefaults, ...options } : writeDefaults;
35
+ return options ? Object.assign(Object.assign({}, writeDefaults), options) : writeDefaults;
36
36
  }
37
37
  export function makeBinaryFormatCommon() {
38
38
  return {
39
39
  makeReadOptions,
40
40
  makeWriteOptions,
41
41
  listUnknownFields(message) {
42
- return message[unknownFieldsSymbol] ?? [];
42
+ var _a;
43
+ return (_a = message[unknownFieldsSymbol]) !== null && _a !== void 0 ? _a : [];
43
44
  },
44
45
  discardUnknownFields(message) {
45
46
  delete message[unknownFieldsSymbol];
@@ -15,9 +15,7 @@ import { ScalarType } from "../field.js";
15
15
  import { makeBinaryFormatCommon, writeMapEntry, writeMessageField, writePacked, writeScalar, } from "./binary-format-common.js";
16
16
  /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unnecessary-condition, @typescript-eslint/strict-boolean-expressions, no-case-declarations, prefer-const */
17
17
  export function makeBinaryFormatProto2() {
18
- return {
19
- ...makeBinaryFormatCommon(),
20
- writeMessage(message, writer, options) {
18
+ return Object.assign(Object.assign({}, makeBinaryFormatCommon()), { writeMessage(message, writer, options) {
21
19
  const type = message.getType();
22
20
  let field;
23
21
  try {
@@ -81,7 +79,7 @@ export function makeBinaryFormatProto2() {
81
79
  }
82
80
  catch (e) {
83
81
  let m = field
84
- ? `cannot encode field ${type.typeName}.${field?.name} to binary`
82
+ ? `cannot encode field ${type.typeName}.${field === null || field === void 0 ? void 0 : field.name} to binary`
85
83
  : `cannot encode message ${type.typeName} to binary`;
86
84
  let r = e instanceof Error ? e.message : String(e);
87
85
  throw new Error(m + (r.length > 0 ? `: ${r}` : ""));
@@ -90,6 +88,5 @@ export function makeBinaryFormatProto2() {
90
88
  this.writeUnknownFields(message, writer);
91
89
  }
92
90
  return writer;
93
- },
94
- };
91
+ } });
95
92
  }
@@ -15,9 +15,7 @@ import { ScalarType } from "../field.js";
15
15
  import { makeBinaryFormatCommon, writeMapEntry, writeMessageField, writePacked, writeScalar, } from "./binary-format-common.js";
16
16
  /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unnecessary-condition, @typescript-eslint/strict-boolean-expressions, prefer-const, no-case-declarations */
17
17
  export function makeBinaryFormatProto3() {
18
- return {
19
- ...makeBinaryFormatCommon(),
20
- writeMessage(message, writer, options) {
18
+ return Object.assign(Object.assign({}, makeBinaryFormatCommon()), { writeMessage(message, writer, options) {
21
19
  const type = message.getType();
22
20
  for (const field of type.fields.byNumber()) {
23
21
  let value, // this will be our field value, whether it is member of a oneof or regular field
@@ -73,6 +71,5 @@ export function makeBinaryFormatProto3() {
73
71
  this.writeUnknownFields(message, writer);
74
72
  }
75
73
  return writer;
76
- },
77
- };
74
+ } });
78
75
  }
@@ -27,35 +27,30 @@ export function getEnumType(enumObject) {
27
27
  /**
28
28
  * Sets reflection information on a generated enum.
29
29
  */
30
- export function setEnumType(enumObject, typeName, values
31
- // We do not surface options at this time
32
- // opt?: {
33
- // options?: { readonly [extensionName: string]: JsonValue };
34
- // },
35
- ) {
30
+ export function setEnumType(enumObject, typeName, values, opt) {
36
31
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
37
- enumObject[enumTypeSymbol] = makeEnumType(typeName, values);
32
+ enumObject[enumTypeSymbol] = makeEnumType(typeName, values.map((v) => ({
33
+ no: v.no,
34
+ name: v.name,
35
+ localName: enumObject[v.no],
36
+ })), opt);
38
37
  }
39
- // We do not surface options at this time
40
- // export type PartialEnumValue = Omit<EnumValueInfo, 'options'> & Partial<Pick<EnumValueInfo, "options">>;
41
38
  /**
42
39
  * Create a new EnumType with the given values.
43
40
  */
44
- export function makeEnumType(typeName, values
45
- // We do not surface options at this time
46
- // opt?: {
47
- // options?: { readonly [extensionName: string]: JsonValue };
48
- // },
49
- ) {
41
+ export function makeEnumType(typeName, values,
42
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
43
+ _opt) {
50
44
  const names = Object.create(null);
51
45
  const numbers = Object.create(null);
52
46
  const normalValues = [];
53
47
  for (const value of values) {
54
48
  // We do not surface options at this time
55
49
  // const value: EnumValueInfo = {...v, options: v.options ?? emptyReadonlyObject};
56
- normalValues.push(value);
57
- names[value.name] = value;
58
- numbers[value.no] = value;
50
+ const n = normalizeEnumValue(value);
51
+ normalValues.push(n);
52
+ names[value.name] = n;
53
+ numbers[value.no] = n;
59
54
  }
60
55
  return {
61
56
  typeName,
@@ -72,25 +67,21 @@ export function makeEnumType(typeName, values
72
67
  }
73
68
  /**
74
69
  * Create a new enum object with the given values.
70
+ * Sets reflection information.
75
71
  */
76
72
  export function makeEnum(typeName, values, opt) {
77
73
  const enumObject = {};
78
74
  for (const value of values) {
79
- const name = makeEnumValueName(value, opt?.sharedPrefix);
80
- enumObject[name] = value.no;
81
- enumObject[value.no] = name;
75
+ const n = normalizeEnumValue(value);
76
+ enumObject[n.localName] = n.no;
77
+ enumObject[n.no] = n.localName;
82
78
  }
83
- setEnumType(enumObject, typeName, values);
79
+ setEnumType(enumObject, typeName, values, opt);
84
80
  return enumObject;
85
81
  }
86
- // Construct a local name for an enum value.
87
- // This logic matches the Go function with the same name in private/protoplugin/names.go
88
- function makeEnumValueName(value, sharedPrefix) {
89
- if (sharedPrefix === undefined) {
90
- return value.name;
82
+ function normalizeEnumValue(value) {
83
+ if ("localName" in value) {
84
+ return value;
91
85
  }
92
- if (!value.name.startsWith(sharedPrefix)) {
93
- return value.name;
94
- }
95
- return value.name.substring(sharedPrefix.length);
86
+ return Object.assign(Object.assign({}, value), { localName: value.name });
96
87
  }
@@ -11,6 +11,7 @@
11
11
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
+ import { ScalarType } from "../field.js";
14
15
  /**
15
16
  * Wrap field values whose message type has a wrapper.
16
17
  */
@@ -29,3 +30,30 @@ export function wrapField(type, value) {
29
30
  export function unwrapField(type, value) {
30
31
  return type.fieldWrapper ? type.fieldWrapper.unwrapField(value) : value;
31
32
  }
33
+ /**
34
+ * If the given field uses one of the well-known wrapper types, return
35
+ * the base type it wraps.
36
+ */
37
+ export function getUnwrappedFieldType(field) {
38
+ if (field.kind !== "message_field") {
39
+ return undefined;
40
+ }
41
+ if (field.repeated) {
42
+ return undefined;
43
+ }
44
+ if (field.oneof != undefined) {
45
+ return undefined;
46
+ }
47
+ return wktWrapperToScalarType[field.message.typeName];
48
+ }
49
+ const wktWrapperToScalarType = {
50
+ "google.protobuf.DoubleValue": ScalarType.DOUBLE,
51
+ "google.protobuf.FloatValue": ScalarType.FLOAT,
52
+ "google.protobuf.Int64Value": ScalarType.INT64,
53
+ "google.protobuf.UInt64Value": ScalarType.UINT64,
54
+ "google.protobuf.Int32Value": ScalarType.INT32,
55
+ "google.protobuf.UInt32Value": ScalarType.UINT32,
56
+ "google.protobuf.BoolValue": ScalarType.BOOL,
57
+ "google.protobuf.StringValue": ScalarType.STRING,
58
+ "google.protobuf.BytesValue": ScalarType.BYTES,
59
+ };
@@ -11,7 +11,7 @@
11
11
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
- import { makeOneofName } from "./names.js";
14
+ import { localOneofName } from "./names.js";
15
15
  import { assert } from "./assert.js";
16
16
  export class InternalOneofInfo {
17
17
  constructor(name) {
@@ -22,7 +22,7 @@ export class InternalOneofInfo {
22
22
  this.default = undefined;
23
23
  this.fields = [];
24
24
  this.name = name;
25
- this.localName = makeOneofName(name);
25
+ this.localName = localOneofName(name);
26
26
  }
27
27
  addField(field) {
28
28
  assert(field.oneof === this, `field ${field.name} not one of ${this.name}`);
@@ -29,10 +29,10 @@ const jsonWriteDefaults = {
29
29
  prettySpaces: 0,
30
30
  };
31
31
  function makeReadOptions(options) {
32
- return options ? { ...jsonReadDefaults, ...options } : jsonReadDefaults;
32
+ return options ? Object.assign(Object.assign({}, jsonReadDefaults), options) : jsonReadDefaults;
33
33
  }
34
34
  function makeWriteOptions(options) {
35
- return options ? { ...jsonWriteDefaults, ...options } : jsonWriteDefaults;
35
+ return options ? Object.assign(Object.assign({}, jsonWriteDefaults), options) : jsonWriteDefaults;
36
36
  }
37
37
  export function makeJsonFormatCommon(makeWriteField) {
38
38
  const writeField = makeWriteField(writeEnum, writeScalar);
@@ -43,7 +43,7 @@ export function makeJsonFormatCommon(makeWriteField) {
43
43
  if (json == null || Array.isArray(json) || typeof json != "object") {
44
44
  throw new Error(`cannot decode message ${type.typeName} from JSON: ${this.debug(json)}`);
45
45
  }
46
- message = message ?? new type();
46
+ message = message !== null && message !== void 0 ? message : new type();
47
47
  const oneofSeen = {};
48
48
  for (const [jsonKey, jsonValue] of Object.entries(json)) {
49
49
  const field = type.fields.findJsonName(jsonKey);
@@ -382,13 +382,14 @@ function readEnum(type, json, ignoreUnknownFields) {
382
382
  case "string":
383
383
  const value = type.findName(json);
384
384
  if (value || ignoreUnknownFields) {
385
- return value?.no;
385
+ return value === null || value === void 0 ? void 0 : value.no;
386
386
  }
387
387
  break;
388
388
  }
389
389
  throw new Error(`cannot decode enum ${type.typeName} from JSON: ${debugJsonValue(json)}`);
390
390
  }
391
391
  function writeEnum(type, value, emitIntrinsicDefault, enumAsInteger) {
392
+ var _a;
392
393
  if (value === undefined) {
393
394
  return value;
394
395
  }
@@ -403,7 +404,7 @@ function writeEnum(type, value, emitIntrinsicDefault, enumAsInteger) {
403
404
  return null;
404
405
  }
405
406
  const val = type.findNumber(value);
406
- return val?.name ?? value; // if we don't know the enum value, just return the number
407
+ return (_a = val === null || val === void 0 ? void 0 : val.name) !== null && _a !== void 0 ? _a : value; // if we don't know the enum value, just return the number
407
408
  }
408
409
  function writeScalar(type, value, emitIntrinsicDefault) {
409
410
  if (value === undefined) {
@@ -16,7 +16,8 @@ import { Message, } from "../message.js";
16
16
  * Create a new message type using the given runtime.
17
17
  */
18
18
  export function makeMessageType(runtime, typeName, fields, opt) {
19
- const localName = opt?.localName ?? typeName.substring(typeName.lastIndexOf(".") + 1);
19
+ var _a;
20
+ const localName = (_a = opt === null || opt === void 0 ? void 0 : opt.localName) !== null && _a !== void 0 ? _a : typeName.substring(typeName.lastIndexOf(".") + 1);
20
21
  const type = {
21
22
  [localName]: function (data) {
22
23
  runtime.util.initFields(this);
@@ -12,38 +12,113 @@
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
14
  /**
15
- * Returns the JSON name for a protobuf field, exactly like protoc does.
15
+ * Returns the name of a protobuf element in generated code.
16
+ *
17
+ * Field names - including oneofs - are converted to lowerCamelCase. For
18
+ * messages, enumerations and services, the package name is stripped from
19
+ * the type name. For nested messages and enumerations, the names are joined
20
+ * with an underscore. For methods, the first character is made lowercase.
16
21
  */
17
- export function makeJsonName(protoName) {
18
- return protoCamelCase(protoName);
22
+ export function localName(desc) {
23
+ switch (desc.kind) {
24
+ case "enum_field":
25
+ case "message_field":
26
+ case "map_field":
27
+ case "scalar_field":
28
+ return localFieldName(desc.name, desc.oneof !== undefined);
29
+ case "oneof":
30
+ return localOneofName(desc.name);
31
+ case "enum":
32
+ case "message":
33
+ case "service": {
34
+ const pkg = desc.file.proto.package;
35
+ const offset = pkg === undefined ? 0 : pkg.length + 1;
36
+ const name = desc.typeName.substring(offset).replace(/\./g, "_");
37
+ if (reservedIdent[name]) {
38
+ return name + "$";
39
+ }
40
+ return name;
41
+ }
42
+ case "enum_value": {
43
+ const sharedPrefix = desc.parent.sharedPrefix;
44
+ if (sharedPrefix === undefined) {
45
+ return desc.name;
46
+ }
47
+ const name = desc.name.substring(sharedPrefix.length);
48
+ if (reservedObjectProperties[name]) {
49
+ return name + "$";
50
+ }
51
+ return name;
52
+ }
53
+ case "rpc": {
54
+ let name = desc.name;
55
+ if (name.length == 0) {
56
+ return name;
57
+ }
58
+ name = name[0].toLowerCase() + name.substring(1);
59
+ if (reservedObjectProperties[name]) {
60
+ return name + "$";
61
+ }
62
+ return name;
63
+ }
64
+ }
19
65
  }
20
66
  /**
21
- * Returns the local name of a field, exactly like protoc-gen-es does.
67
+ * Returns the name of a field in generated code.
22
68
  */
23
- export function makeFieldName(protoName, inOneof) {
24
- const n = protoCamelCase(protoName);
69
+ export function localFieldName(protoName, inOneof) {
70
+ let name = protoCamelCase(protoName);
25
71
  if (inOneof) {
26
- return n;
72
+ // oneof member names are not properties, but values of the `case` property.
73
+ return name;
27
74
  }
28
- return rProp[n] ? n + escapeChar : n;
75
+ if (reservedObjectProperties[name] || reservedMessageProperties[name]) {
76
+ name = name + "$";
77
+ }
78
+ return name;
29
79
  }
30
80
  /**
31
- * Returns the local name of a oneof group, exactly like protoc-gen-es does.
81
+ * Returns the name of a oneof group in generated code.
32
82
  */
33
- export function makeOneofName(protoName) {
34
- return makeFieldName(protoName, false);
83
+ export function localOneofName(protoName) {
84
+ return localFieldName(protoName, false);
35
85
  }
36
86
  /**
37
- * Returns the local name of a rpc, exactly like protoc-gen-es does.
87
+ * Returns the JSON name for a protobuf field, exactly like protoc does.
38
88
  */
39
- export function makeMethodName(protoName) {
40
- if (protoName.length == 0) {
41
- return protoName;
89
+ export const fieldJsonName = protoCamelCase;
90
+ /**
91
+ * Finds a prefix shared by enum values, for example `MY_ENUM_` for
92
+ * `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`.
93
+ */
94
+ export function findEnumSharedPrefix(enumName, valueNames) {
95
+ const prefix = camelToSnakeCase(enumName) + "_";
96
+ for (const name of valueNames) {
97
+ if (!name.toLowerCase().startsWith(prefix)) {
98
+ return undefined;
99
+ }
100
+ const shortName = name.substring(prefix.length);
101
+ if (shortName.length == 0) {
102
+ return undefined;
103
+ }
104
+ if (/^\d/.test(shortName)) {
105
+ // identifiers must not start with numbers
106
+ return undefined;
107
+ }
42
108
  }
43
- return protoName[0].toLowerCase() + protoName.substring(1);
109
+ return prefix;
110
+ }
111
+ /**
112
+ * Converts lowerCamelCase or UpperCamelCase into lower_snake_case.
113
+ * This is used to find shared prefixes in an enum.
114
+ */
115
+ function camelToSnakeCase(camel) {
116
+ return (camel.substring(0, 1) + camel.substring(1).replace(/[A-Z]/g, (c) => "_" + c)).toLowerCase();
44
117
  }
45
- // Converts snake_case to protoCamelCase according to the convention
46
- // used by protoc to convert a field name to a JSON name.
118
+ /**
119
+ * Converts snake_case to protoCamelCase according to the convention
120
+ * used by protoc to convert a field name to a JSON name.
121
+ */
47
122
  function protoCamelCase(snakeCase) {
48
123
  let capNext = false;
49
124
  const b = [];
@@ -77,17 +152,81 @@ function protoCamelCase(snakeCase) {
77
152
  }
78
153
  return b.join("");
79
154
  }
80
- // escapeChar must be appended to a reserved name.
81
- // We choose '$' because it is invalid in proto identifiers.
82
- const escapeChar = "$";
83
- // Names that cannot be used for object properties.
84
- // See buf_es/protoc-gen-es/internal/protoplugin/names.go
85
- const rProp = {
155
+ // Names that cannot be used for identifiers, such as class names,
156
+ // but _can_ be used for object properties.
157
+ const reservedIdent = {
158
+ // ECMAScript 2015 keywords
159
+ break: true,
160
+ case: true,
161
+ catch: true,
162
+ class: true,
163
+ const: true,
164
+ continue: true,
165
+ debugger: true,
166
+ default: true,
167
+ delete: true,
168
+ do: true,
169
+ else: true,
170
+ export: true,
171
+ extends: true,
172
+ false: true,
173
+ finally: true,
174
+ for: true,
175
+ function: true,
176
+ if: true,
177
+ import: true,
178
+ in: true,
179
+ instanceof: true,
180
+ new: true,
181
+ null: true,
182
+ return: true,
183
+ super: true,
184
+ switch: true,
185
+ this: true,
186
+ throw: true,
187
+ true: true,
188
+ try: true,
189
+ typeof: true,
190
+ var: true,
191
+ void: true,
192
+ while: true,
193
+ with: true,
194
+ yield: true,
195
+ // ECMAScript 2015 future reserved keywords
196
+ enum: true,
197
+ implements: true,
198
+ interface: true,
199
+ let: true,
200
+ package: true,
201
+ private: true,
202
+ protected: true,
203
+ public: true,
204
+ static: true,
205
+ // Class name cannot be 'Object' when targeting ES5 with module CommonJS
206
+ Object: true,
207
+ // TypeScript keywords that cannot be used for types (as opposed to variables)
208
+ bigint: true,
209
+ number: true,
210
+ boolean: true,
211
+ string: true,
212
+ object: true,
213
+ // Identifiers reserved for the runtime, so we can generate legible code
214
+ globalThis: true,
215
+ Uint8Array: true,
216
+ Partial: true,
217
+ };
218
+ // Names that cannot be used for object properties because they are reserved
219
+ // by built-in JavaScript properties.
220
+ const reservedObjectProperties = {
86
221
  // names reserved by JavaScript
87
222
  constructor: true,
88
223
  toString: true,
89
224
  toJSON: true,
90
225
  valueOf: true,
226
+ };
227
+ // Names that cannot be used for object properties because they are reserved
228
+ // by the runtime.
229
+ const reservedMessageProperties = {
91
230
  // names reserved by the runtime
92
231
  getType: true,
93
232
  clone: true,
@@ -15,7 +15,7 @@ import { int64fromString, int64toString } from "./google/varint.js";
15
15
  function makeInt64Support() {
16
16
  const dv = new DataView(new ArrayBuffer(8));
17
17
  // note that Safari 14 implements BigInt, but not the DataView methods
18
- const ok = globalThis.BigInt !== undefined && // eslint-disable-line @typescript-eslint/no-unnecessary-condition -- conditional for BigInt is very much necessary
18
+ const ok = globalThis.BigInt !== undefined &&
19
19
  typeof dv.getBigInt64 === "function" &&
20
20
  typeof dv.getBigUint64 === "function" &&
21
21
  typeof dv.setBigInt64 === "function" &&
@@ -16,14 +16,12 @@ import { makeBinaryFormatProto2 } from "./private/binary-format-proto2.js";
16
16
  import { makeUtilCommon } from "./private/util-common.js";
17
17
  import { InternalFieldList } from "./private/field-list.js";
18
18
  import { InternalOneofInfo } from "./private/field.js";
19
- import { makeFieldName, makeJsonName } from "./private/names.js";
19
+ import { localFieldName, fieldJsonName } from "./private/names.js";
20
20
  import { makeJsonFormatProto2 } from "./private/json-format-proto2.js";
21
21
  /**
22
22
  * Provides functionality for messages defined with the proto2 syntax.
23
23
  */
24
- export const proto2 = makeProtoRuntime("proto2", makeJsonFormatProto2(), makeBinaryFormatProto2(), {
25
- ...makeUtilCommon(),
26
- newFieldList(fields) {
24
+ export const proto2 = makeProtoRuntime("proto2", makeJsonFormatProto2(), makeBinaryFormatProto2(), Object.assign(Object.assign({}, makeUtilCommon()), { newFieldList(fields) {
27
25
  return new InternalFieldList(fields, normalizeFieldInfosProto2);
28
26
  },
29
27
  initFields(target) {
@@ -52,21 +50,21 @@ export const proto2 = makeProtoRuntime("proto2", makeJsonFormatProto2(), makeBin
52
50
  break;
53
51
  }
54
52
  }
55
- },
56
- });
53
+ } }));
57
54
  /* eslint-disable @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-argument */
58
55
  function normalizeFieldInfosProto2(fieldInfos) {
56
+ var _a, _b, _c;
59
57
  const r = [];
60
58
  let o;
61
59
  for (const field of typeof fieldInfos == "function"
62
60
  ? fieldInfos()
63
61
  : fieldInfos) {
64
62
  const f = field;
65
- f.localName = makeFieldName(field.name, field.oneof !== undefined);
66
- f.jsonName = field.jsonName ?? makeJsonName(field.name);
67
- f.repeated = field.repeated ?? false;
63
+ f.localName = localFieldName(field.name, field.oneof !== undefined);
64
+ f.jsonName = (_a = field.jsonName) !== null && _a !== void 0 ? _a : fieldJsonName(field.name);
65
+ f.repeated = (_b = field.repeated) !== null && _b !== void 0 ? _b : false;
68
66
  // In contrast to proto3, repeated fields are unpacked except when explicitly specified.
69
- f.packed = field.packed ?? false;
67
+ f.packed = (_c = field.packed) !== null && _c !== void 0 ? _c : false;
70
68
  // We do not surface options at this time
71
69
  // f.options = field.options ?? emptyReadonlyObject;
72
70
  if (field.oneof !== undefined) {