@trevrpc/protoc-gen-trevrpc-js 0.0.0-stage → 1.11.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 trev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # @trevrpc/protoc-gen-trevrpc-js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A `protoc` plugin that generates a codec for each message, for the TrevRPC browser client, [`@trevrpc/trevrpc-js`](https://www.npmjs.com/package/@trevrpc/trevrpc-js). It runs after [`protoc-gen-es`](https://github.com/bufbuild/protobuf-es) and writes `<file>_trevrpc.js` next to its `<file>_pb.js`. A codec encodes and decodes the same protobuf-es messages as `toBinary` and `fromBinary`, to the same bytes, with code written for its message type instead of protobuf-es's generic per-field dispatch.
4
+
5
+ > **Compatibility:** every TrevRPC package shares one version, and packages of the same version are compatible
6
+ > with each other: generated codecs need the `@trevrpc/trevrpc-js` of the plugin's version or later. Compatibility
7
+ > across different versions isn't guaranteed yet; that's a milestone for 2.0.
8
+
9
+ ```sh
10
+ npm install @trevrpc/trevrpc-js @bufbuild/protobuf
11
+ npm install --save-dev @bufbuild/protoc-gen-es @trevrpc/protoc-gen-trevrpc-js
12
+ ```
13
+
14
+ Add the plugin to `buf.gen.yaml` after `protoc-gen-es`, with the same `target` and `import_extension`:
15
+
16
+ ```yaml
17
+ version: v2
18
+ plugins:
19
+ - local: protoc-gen-es
20
+ out: src/gen
21
+ opt: target=ts
22
+ - local: protoc-gen-trevrpc-js
23
+ out: src/gen
24
+ opt: target=ts
25
+ ```
26
+
27
+ Pass a service's codecs to `createClient`:
28
+
29
+ ```ts
30
+ import { createClient } from "@trevrpc/trevrpc-js";
31
+
32
+ import { Greeter } from "./gen/greeter_pb.js";
33
+ import { GreeterCodecs } from "./gen/greeter_trevrpc.js";
34
+
35
+ const greeter = createClient(Greeter, channel, { codecs: GreeterCodecs });
36
+ ```
37
+
38
+ - Each message gets a codec, such as `GreetRequestCodec`, and each service the codecs of its request and response types, such as `GreeterCodecs`. Combine the codecs of several services in one array when a client needs them.
39
+ - Messages are the usual protobuf-es messages, with the same property order and `$unknown` for unknown fields, so `create`, `equals`, `toJson` and the generated types work on them as before.
40
+ - A codec fails where protobuf-es fails, with protobuf-es's error: invalid values such as an `int32` of 1.5, invalid UTF-8 in a string, truncated input, and messages nested more than 100 deep.
41
+ - Decoding differs on two kinds of malformed input: a known field sent with another wire type is kept in `$unknown`, as the Go and Rust runtimes keep it, where `fromBinary` reads it as its declared type anyway; and a nested message whose last field runs past its length makes the codec fail and fall back to `fromBinary`, which accepts it, so such input is decoded twice.
42
+ - Methods whose types have no codec use protobuf-es, as do clients without the `codecs` option. A codec applies only to the schema it was generated with, the one its `_trevrpc.js` imports, so regenerate both files together.
43
+ - `GreetRequestCodec.encode(message)` and `GreetRequestCodec.decode(bytes)` run a codec directly, like `toBinary` and `fromBinary`.
44
+
45
+ The generated code covers proto3 messages. Messages of proto2 and editions files, and messages with a field that protobuf-es represents specially (a wrapper type such as `google.protobuf.StringValue`, which it unboxes, or `google.protobuf.Struct`, which is a JSON object), get a codec that runs protobuf-es, as do fields of message types that weren't generated in the same run, such as the other well-known types. Their encoding is unchanged; only their speed is protobuf-es's.
46
+
47
+ The plugin takes protobuf-es's plugin options: `target` (`js`, `ts`, `dts`, or a combination like `js+dts`), `import_extension` and `js_import_style`.
48
+
49
+ ## Development
50
+
51
+ The plugin runs from this directory with the dependencies of trevrpc-js, whose tests generate codecs with it and check them against protobuf-es (`test/codec.test.js`):
52
+
53
+ ```sh
54
+ npm ci --prefix ..
55
+ npm test --prefix ..
56
+ npm run check # format check, lint
57
+ ```
58
+
59
+ `nix build .#trevrpc-js.protocGen` checks the published files and runs the installed plugin; `nix build .#trevrpc-js` builds it too and puts it next to `trevrpc-interop-browser`.
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { runNodeJs } from "@bufbuild/protoplugin";
3
+
4
+ import { protocGenTrevrpcJs } from "../src/plugin.js";
5
+
6
+ runNodeJs(protocGenTrevrpcJs);
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@trevrpc/protoc-gen-trevrpc-js",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.11.1",
4
+ "description": "Generates message codecs for TrevRPC browser clients, next to protoc-gen-es's code",
5
+ "homepage": "https://trev.zip/llc/TrevRPC",
6
+ "bugs": {
7
+ "url": "https://trev.zip/llc/TrevRPC/issues"
8
+ },
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://trev.zip/llc/TrevRPC.git",
13
+ "directory": "trevrpc-js/protoc-gen-trevrpc-js"
14
+ },
15
+ "bin": {
16
+ "protoc-gen-trevrpc-js": "bin/protoc-gen-trevrpc-js"
17
+ },
18
+ "files": [
19
+ "bin/**",
20
+ "src/**",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "type": "module",
25
+ "exports": {
26
+ ".": "./src/plugin.js"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "scripts": {
32
+ "format": "oxfmt --write",
33
+ "format:check": "oxfmt --check",
34
+ "lint": "oxlint --deny-warnings bin src",
35
+ "check": "npm run format:check && npm run lint"
36
+ },
37
+ "dependencies": {
38
+ "@bufbuild/protobuf": "^2.17.0",
39
+ "@bufbuild/protoplugin": "^2.17.0"
40
+ },
41
+ "peerDependencies": {
42
+ "@trevrpc/trevrpc-js": "^1.11.1"
43
+ },
44
+ "peerDependenciesMeta": {
45
+ "@trevrpc/trevrpc-js": {
46
+ "optional": true
47
+ }
48
+ },
49
+ "engines": {
50
+ "node": ">=24"
51
+ },
52
+ "packageManager": "npm@12.2.2"
53
+ }
package/src/plugin.js ADDED
@@ -0,0 +1,703 @@
1
+ // protoc-gen-trevrpc-js: generates a codec for each message, `<file>_trevrpc.js`, next to the
2
+ // `<file>_pb.js` that protoc-gen-es generates. A codec encodes and decodes the same protobuf-es
3
+ // messages as toBinary() and fromBinary(), to the same bytes, with code written for its type; see
4
+ // src/codec.js of @trevrpc/trevrpc-js, which runs it.
5
+ //
6
+ // Each file gets:
7
+ //
8
+ // export const GreetRequestCodec = defineCodec(GreetRequestSchema, read, write); (per message)
9
+ // export const GreeterCodecs = [GreetRequestCodec, GreetResponseCodec]; (per service)
10
+ //
11
+ // The generated code covers proto3 messages. Messages of other editions, and those with fields
12
+ // that protobuf-es represents specially (wrapper types, which it unboxes, and Struct, which is a
13
+ // JSON object), get a codec that runs protobuf-es, as do fields of message types that weren't
14
+ // generated in the same run, such as the well-known types.
15
+ import { ScalarType } from "@bufbuild/protobuf";
16
+ import { isWrapperDesc } from "@bufbuild/protobuf/wkt";
17
+ import { createEcmaScriptPlugin } from "@bufbuild/protoplugin";
18
+
19
+ import packageJson from "../package.json" with { type: "json" };
20
+
21
+ /** Where generated code imports the codec runtime from. */
22
+ const Runtime = "@trevrpc/trevrpc-js/codec";
23
+ const EditionProto3 = 999;
24
+ /** FeatureSet.FieldPresence.IMPLICIT, the presence of proto3 fields without `optional`. */
25
+ const Implicit = 2;
26
+
27
+ const Varint = 0;
28
+ const Fixed64 = 1;
29
+ const LengthDelimited = 2;
30
+ const Fixed32 = 5;
31
+
32
+ /**
33
+ * How each scalar type is read and written: the Reader and Writer method, the wire type, the
34
+ * packed method (when it has a dedicated one), and the test that a value of an implicit-presence
35
+ * field is set, which matches the one protobuf-es makes.
36
+ */
37
+ const Scalars = new Map([
38
+ [ScalarType.DOUBLE, scalar("double", Fixed64, "packedDouble", float)],
39
+ [ScalarType.FLOAT, scalar("float", Fixed32, "packedFloat", float)],
40
+ [ScalarType.INT64, scalar("int64", Varint, undefined, loose)],
41
+ [ScalarType.UINT64, scalar("uint64", Varint, undefined, loose)],
42
+ [ScalarType.INT32, scalar("int32", Varint, "packedInt32", loose)],
43
+ [ScalarType.FIXED64, scalar("fixed64", Fixed64, undefined, loose)],
44
+ [ScalarType.FIXED32, scalar("fixed32", Fixed32, "packedFixed32", loose)],
45
+ [ScalarType.BOOL, scalar("bool", Varint, "packedBool", (v) => `${v} !== false`)],
46
+ [ScalarType.STRING, scalar("string", LengthDelimited, undefined, (v) => `${v} !== ""`)],
47
+ [
48
+ ScalarType.BYTES,
49
+ scalar(
50
+ "bytes",
51
+ LengthDelimited,
52
+ undefined,
53
+ (v) => `(!(${v} instanceof Uint8Array) || ${v}.byteLength > 0)`,
54
+ ),
55
+ ],
56
+ [ScalarType.UINT32, scalar("uint32", Varint, "packedUint32", loose)],
57
+ [ScalarType.SFIXED32, scalar("sfixed32", Fixed32, "packedSfixed32", loose)],
58
+ [ScalarType.SFIXED64, scalar("sfixed64", Fixed64, undefined, loose)],
59
+ [ScalarType.SINT32, scalar("sint32", Varint, "packedSint32", loose)],
60
+ [ScalarType.SINT64, scalar("sint64", Varint, undefined, loose)],
61
+ ]);
62
+
63
+ function scalar(method, wire, packed, isSet) {
64
+ const long = method.endsWith("64");
65
+ return { method, wire, packed, isSet, long };
66
+ }
67
+
68
+ /** Numbers, bigints and numeric strings: loose inequality matches 0, 0n and "0", as protobuf-es. */
69
+ function loose(v) {
70
+ return `${v} != 0`;
71
+ }
72
+
73
+ /** Floats: Object.is tells -0, which is written, from 0, which is not. */
74
+ function float(v) {
75
+ return `!Object.is(${v}, 0)`;
76
+ }
77
+
78
+ export const protocGenTrevrpcJs = createEcmaScriptPlugin({
79
+ name: "protoc-gen-trevrpc-js",
80
+ version: `v${packageJson.version}`,
81
+ generateTs: (schema) => generate(schema, "ts"),
82
+ generateJs: (schema) => generate(schema, "js"),
83
+ generateDts: (schema) => generate(schema, "dts"),
84
+ });
85
+
86
+ function generate(schema, target) {
87
+ const generated = new Set(schema.files);
88
+ for (const file of schema.files) {
89
+ const messages = fileMessages(file);
90
+ if (messages.length === 0 && file.services.length === 0) {
91
+ continue;
92
+ }
93
+ const extension = target === "dts" ? "d.ts" : target;
94
+ const f = schema.generateFile(`${file.name}_trevrpc.${extension}`);
95
+ f.preamble(file);
96
+ new FileGenerator(f, file, target, generated).generate(messages);
97
+ }
98
+ }
99
+
100
+ /** The messages of a file, nested ones included, in declaration order. */
101
+ function fileMessages(file) {
102
+ const messages = [];
103
+ const add = (message) => {
104
+ messages.push(message);
105
+ message.nestedMessages.forEach(add);
106
+ };
107
+ file.messages.forEach(add);
108
+ return messages;
109
+ }
110
+
111
+ /**
112
+ * Whether generated code reads and writes `message`. Only proto3 messages qualify: other editions
113
+ * have closed enums, groups, required fields and defaults on the prototype chain. Wrapper fields,
114
+ * which protobuf-es unboxes, and Struct fields, which it represents as JSON objects, are left to
115
+ * protobuf-es too.
116
+ */
117
+ function isNative(message) {
118
+ if (message.file.edition !== EditionProto3) {
119
+ return false;
120
+ }
121
+ return message.fields.every((field) => {
122
+ const type = field.message;
123
+ if (type === undefined) {
124
+ return true;
125
+ }
126
+ if (field.fieldKind === "message" && field.oneof === undefined && isWrapperDesc(type)) {
127
+ return false;
128
+ }
129
+ return (
130
+ type.typeName !== "google.protobuf.Struct" || message.typeName === "google.protobuf.Value"
131
+ );
132
+ });
133
+ }
134
+
135
+ function tagValue(fieldNo, wireType) {
136
+ return ((fieldNo << 3) | wireType) >>> 0;
137
+ }
138
+
139
+ /** The statement that writes a tag. */
140
+ function writeTag(fieldNo, wireType) {
141
+ const tag = tagValue(fieldNo, wireType);
142
+ return tag < 0x80 ? `w.byte(${tag});` : `w.varint(${tag});`;
143
+ }
144
+
145
+ class FileGenerator {
146
+ constructor(f, file, target, generated) {
147
+ this.f = f;
148
+ this.file = file;
149
+ this.target = target;
150
+ this.generated = generated;
151
+ this.ts = target === "ts";
152
+ // The runtime's exports, each imported on first use: this.rt.Reader and the like.
153
+ this.rt = new Proxy(
154
+ {},
155
+ {
156
+ get: (cache, name) => (cache[name] ??= f.import(name, Runtime)),
157
+ },
158
+ );
159
+ }
160
+
161
+ /** A TypeScript annotation, printed only for the ts target. */
162
+ type(...annotation) {
163
+ return this.ts ? annotation : "";
164
+ }
165
+
166
+ generate(messages) {
167
+ for (const message of messages) {
168
+ if (this.target === "dts") {
169
+ this.declareCodec(message);
170
+ } else if (isNative(message)) {
171
+ this.generateConstructor(message);
172
+ this.generateReader(message);
173
+ this.generateWriter(message);
174
+ this.generateCodec(message);
175
+ } else {
176
+ this.generateFallback(message);
177
+ this.generateCodec(message);
178
+ }
179
+ }
180
+ for (const service of this.file.services) {
181
+ this.generateServiceCodecs(service);
182
+ }
183
+ }
184
+
185
+ /** The base name of a message's generated symbols: protoc-gen-es's name for its type. */
186
+ name(message) {
187
+ return this.f.importShape(message).name;
188
+ }
189
+
190
+ codecName(message) {
191
+ return `${this.name(message)}Codec`;
192
+ }
193
+
194
+ /**
195
+ * How generated code reads (`read`) or writes (`write`) a message of `type`: its generated
196
+ * function in this file, the codec of another generated file, or protobuf-es. Returns the
197
+ * printables of a call, given the printables of the arguments.
198
+ */
199
+ call(kind, type, args) {
200
+ if (type.file === this.file) {
201
+ return [`$${kind}${this.name(type)}(`, ...args, ")"];
202
+ }
203
+ if (this.generated.has(type.file)) {
204
+ const codec = this.f.import(this.codecName(type), `./${type.file.name}_trevrpc.js`);
205
+ return [codec, `.${kind}(`, ...args, ")"];
206
+ }
207
+ const fallback = kind === "read" ? this.rt.readMessage : this.rt.writeMessage;
208
+ return [fallback, "(", this.f.importSchema(type), ", ", ...args, ")"];
209
+ }
210
+
211
+ /** The zero value of a scalar field, as protobuf-es creates it. */
212
+ scalarZero(type, longAsString) {
213
+ switch (type) {
214
+ case ScalarType.STRING:
215
+ return ['""'];
216
+ case ScalarType.BOOL:
217
+ return ["false"];
218
+ case ScalarType.BYTES:
219
+ return [this.rt.EmptyBytes];
220
+ default:
221
+ if (Scalars.get(type).long) {
222
+ return longAsString ? ['"0"'] : [this.rt.Int64Zero];
223
+ }
224
+ return ["0"];
225
+ }
226
+ }
227
+
228
+ /** The expression that reads a scalar value. */
229
+ readScalar(type, longAsString) {
230
+ const { method, long } = Scalars.get(type);
231
+ return long && longAsString ? `String(r.${method}())` : `r.${method}()`;
232
+ }
233
+
234
+ // ------------------------------------------------------------------------------------- decode
235
+
236
+ /**
237
+ * A constructor that lays out properties exactly as create() does: members in declaration
238
+ * order, zero values for implicit scalars, lists and maps, and no property for message fields
239
+ * and scalars with explicit presence until they are set. Every decoded message of a type then
240
+ * shares one object shape.
241
+ *
242
+ * A constructor, not an object literal, and `new Array()`, not []: V8 pretenures literals whose
243
+ * objects tend to survive (decoded messages do), allocating them straight into the old
244
+ * generation while the strings and arrays they point to stay young, and every scavenge then has
245
+ * to process those old-to-young pointers. On a 2.6 MB message that spent ~40% of decode time in
246
+ * GC.
247
+ */
248
+ generateConstructor(message) {
249
+ const { f } = this;
250
+ const assignments = [[`this.$typeName = ${JSON.stringify(message.typeName)};`]];
251
+ for (const member of message.members) {
252
+ const name = member.localName;
253
+ if (member.kind === "oneof") {
254
+ assignments.push([`this.${name} = { case: undefined };`]);
255
+ continue;
256
+ }
257
+ switch (member.fieldKind) {
258
+ case "list":
259
+ assignments.push([`this.${name} = new Array();`]);
260
+ break;
261
+ case "map":
262
+ assignments.push([`this.${name} = {};`]);
263
+ break;
264
+ case "enum":
265
+ if (member.presence === Implicit) {
266
+ assignments.push([`this.${name} = ${member.enum.values[0].number};`]);
267
+ }
268
+ break;
269
+ case "scalar":
270
+ if (member.presence === Implicit) {
271
+ assignments.push([
272
+ `this.${name} = `,
273
+ ...this.scalarZero(member.scalar, member.longAsString),
274
+ ";",
275
+ ]);
276
+ }
277
+ break;
278
+ // Singular message fields are absent from a new message.
279
+ }
280
+ }
281
+ const ctor = `$${this.name(message)}`;
282
+ f.print("function ", ctor, "(", this.type("this: any"), ") {");
283
+ for (const assignment of assignments) {
284
+ f.print(" ", ...assignment);
285
+ }
286
+ f.print("}");
287
+ f.print(ctor, ".prototype = Object.prototype; // plain objects, as create() makes");
288
+ f.print();
289
+ }
290
+
291
+ /** Opens the function that reads a message: `$read<name>(r, end, depth, into)`. */
292
+ printReadHead(name) {
293
+ const { rt } = this;
294
+ this.f.print(
295
+ "function $read",
296
+ name,
297
+ "(r",
298
+ this.type(": ", rt.Reader),
299
+ ", end",
300
+ this.type(": number"),
301
+ ", depth",
302
+ this.type(": number"),
303
+ ", into",
304
+ this.type("?: any"),
305
+ ")",
306
+ this.type(": any"),
307
+ " {",
308
+ );
309
+ }
310
+
311
+ /** Opens the function that writes a message: `$write<name>(w, m)`. */
312
+ printWriteHead(name) {
313
+ const { rt } = this;
314
+ this.f.print(
315
+ "function $write",
316
+ name,
317
+ "(w",
318
+ this.type(": ", rt.Writer),
319
+ ", m",
320
+ this.type(": any"),
321
+ ")",
322
+ this.type(": void"),
323
+ " {",
324
+ );
325
+ }
326
+
327
+ generateReader(message) {
328
+ const { f, rt } = this;
329
+ const name = this.name(message);
330
+ this.printReadHead(name);
331
+ f.print(
332
+ " if (depth >= ",
333
+ rt.RecursionLimit,
334
+ ") ",
335
+ rt.depthError,
336
+ "(",
337
+ JSON.stringify(message.typeName),
338
+ ");",
339
+ );
340
+ f.print(
341
+ " const m",
342
+ this.type(": any"),
343
+ " = into ?? new ",
344
+ this.ts ? `($${name} as any)` : `$${name}`,
345
+ "();",
346
+ );
347
+ f.print(" while (r.pos < end) {");
348
+ f.print(" const tag = r.tag();");
349
+ f.print(" switch (tag) {");
350
+ for (const field of message.fields) {
351
+ for (const line of this.decodeCases(field)) {
352
+ f.print(" ", ...line);
353
+ }
354
+ }
355
+ f.print(" default:");
356
+ f.print(" r.unknown(m, tag, depth);");
357
+ f.print(" }");
358
+ f.print(" }");
359
+ f.print(" r.checkEnd(end);");
360
+ f.print(" return m;");
361
+ f.print("}");
362
+ f.print();
363
+ }
364
+
365
+ /** The `case` clauses that read one field, as lines of printables. */
366
+ decodeCases(field) {
367
+ const no = field.number;
368
+ const target = `m.${field.localName}`;
369
+ const assign = (value) =>
370
+ field.oneof
371
+ ? [`m.${field.oneof.localName} = { case: "${field.localName}", value: `, ...value, " };"]
372
+ : [`${target} = `, ...value, ";"];
373
+
374
+ switch (field.fieldKind) {
375
+ case "enum":
376
+ return [[`case ${tagValue(no, Varint)}: `, ...assign(["r.int32()"]), " break;"]];
377
+ case "scalar": {
378
+ const { wire } = Scalars.get(field.scalar);
379
+ const value = this.readScalar(field.scalar, field.longAsString);
380
+ return [[`case ${tagValue(no, wire)}: `, ...assign([value]), " break;"]];
381
+ }
382
+ case "message": {
383
+ // Another occurrence of a singular message field merges into it.
384
+ const into = field.oneof
385
+ ? `m.${field.oneof.localName}.case === "${field.localName}" ? m.${field.oneof.localName}.value : undefined`
386
+ : target;
387
+ const read = this.call("read", field.message, [`r, r.lenEnd(), depth + 1, ${into}`]);
388
+ return [[`case ${tagValue(no, LengthDelimited)}: `, ...assign(read), " break;"]];
389
+ }
390
+ case "list":
391
+ return this.decodeListCases(field, target);
392
+ case "map":
393
+ return this.decodeMapCase(field, target);
394
+ }
395
+ }
396
+
397
+ decodeListCases(field, target) {
398
+ const no = field.number;
399
+ if (field.listKind === "message") {
400
+ const read = this.call("read", field.message, ["r, r.lenEnd(), depth + 1, undefined"]);
401
+ return [[`case ${tagValue(no, LengthDelimited)}: ${target}.push(`, ...read, "); break;"]];
402
+ }
403
+ const type = field.listKind === "enum" ? ScalarType.INT32 : field.scalar;
404
+ const longAsString = field.listKind === "scalar" && field.longAsString;
405
+ const { wire, packed, long } = Scalars.get(type);
406
+ const one = [
407
+ `case ${tagValue(no, wire)}: ${target}.push(${this.readScalar(type, longAsString)}); break;`,
408
+ ];
409
+ if (wire === LengthDelimited) {
410
+ return [one];
411
+ }
412
+ // Parsers accept both encodings of a repeated scalar, packed or not.
413
+ const packedRead = long
414
+ ? `r.packedLong(${target}, r.${Scalars.get(type).method}, ${longAsString});`
415
+ : `r.${packed}(${target});`;
416
+ return [one, [`case ${tagValue(no, LengthDelimited)}: ${packedRead} break;`]];
417
+ }
418
+
419
+ decodeMapCase(field, target) {
420
+ const { rt } = this;
421
+ const no = field.number;
422
+ const key = Scalars.get(field.mapKey);
423
+ // Map keys and values are read as protobuf-es reads them: 64-bit integers never as strings.
424
+ let readValue;
425
+ let zeroValue;
426
+ let valueTag;
427
+ switch (field.mapKind) {
428
+ case "message":
429
+ // Another value in one entry merges into the first, as for any message field.
430
+ readValue = this.call("read", field.message, ["r, r.lenEnd(), depth + 1, v"]);
431
+ zeroValue = [rt.emptyMessage, "(", this.f.importSchema(field.message), ")"];
432
+ valueTag = tagValue(2, LengthDelimited);
433
+ break;
434
+ case "enum":
435
+ readValue = ["r.int32()"];
436
+ zeroValue = [`${field.enum.values[0].number}`];
437
+ valueTag = tagValue(2, Varint);
438
+ break;
439
+ case "scalar":
440
+ readValue = [this.readScalar(field.scalar, false)];
441
+ // Bytes values get an instance each, as in protobuf-es.
442
+ zeroValue =
443
+ field.scalar === ScalarType.BYTES
444
+ ? ["new Uint8Array(0)"]
445
+ : this.scalarZero(field.scalar, false);
446
+ valueTag = tagValue(2, Scalars.get(field.scalar).wire);
447
+ break;
448
+ }
449
+ const set =
450
+ field.mapKey === ScalarType.STRING
451
+ ? [rt.setMapEntry, `(${target}, k, v);`]
452
+ : [`${target}[k`, this.type(" as any"), "] = v;"];
453
+ return [
454
+ [`case ${tagValue(no, LengthDelimited)}: {`],
455
+ [" const e = r.lenEnd();"],
456
+ [" let k", this.type(": any"), " = ", ...this.scalarZero(field.mapKey, false), ";"],
457
+ [" let v", this.type(": any"), " = undefined;"],
458
+ [" while (r.pos < e) {"],
459
+ [" const t = r.tag();"],
460
+ [` if (t === ${tagValue(1, key.wire)}) k = ${this.readScalar(field.mapKey, false)};`],
461
+ [` else if (t === ${valueTag}) v = `, ...readValue, ";"],
462
+ [" else r.skipTag(t, depth);"],
463
+ [" }"],
464
+ [" r.checkEnd(e);"],
465
+ [" if (v === undefined) v = ", ...zeroValue, ";"],
466
+ [" ", ...set],
467
+ [" break;"],
468
+ ["}"],
469
+ ];
470
+ }
471
+
472
+ // ------------------------------------------------------------------------------------- encode
473
+
474
+ generateWriter(message) {
475
+ const { f, rt } = this;
476
+ const name = this.name(message);
477
+ this.printWriteHead(name);
478
+ // As protobuf-es, which rejects a message of another type unless the type has no fields.
479
+ if (message.fields.length > 0) {
480
+ const typeName = JSON.stringify(message.typeName);
481
+ f.print(` if (m.$typeName !== ${typeName}) `, rt.foreignError, `(${typeName}, m);`);
482
+ }
483
+ // In field number order, as protobuf-es writes them.
484
+ const fields = message.fields.toSorted((a, b) => a.number - b.number);
485
+ for (const field of fields) {
486
+ for (const line of this.encodeField(field)) {
487
+ f.print(" ", ...line);
488
+ }
489
+ }
490
+ f.print(" if (m.$unknown !== undefined) w.unknown(m.$unknown);");
491
+ f.print("}");
492
+ f.print();
493
+ }
494
+
495
+ /** The statements that write one field, as lines of printables. */
496
+ encodeField(field) {
497
+ const no = field.number;
498
+ // A oneof member is written when its case is selected, and its value is `.value`.
499
+ const value = field.oneof ? `m.${field.oneof.localName}.value` : `m.${field.localName}`;
500
+ const guard = (condition) =>
501
+ field.oneof
502
+ ? `if (m.${field.oneof.localName}.case === "${field.localName}")`
503
+ : `if (${condition})`;
504
+
505
+ switch (field.fieldKind) {
506
+ case "enum": {
507
+ const condition =
508
+ field.presence === Implicit
509
+ ? `${value} !== ${field.enum.values[0].number}`
510
+ : `${value} !== undefined`;
511
+ return [[`${guard(condition)} { ${writeTag(no, Varint)} w.int32(${value}); }`]];
512
+ }
513
+ case "scalar": {
514
+ const { method, wire, isSet } = Scalars.get(field.scalar);
515
+ const condition = field.presence === Implicit ? isSet(value) : `${value} !== undefined`;
516
+ return [[`${guard(condition)} { ${writeTag(no, wire)} w.${method}(${value}); }`]];
517
+ }
518
+ case "message": {
519
+ const write = this.call("write", field.message, [`w, ${value}`]);
520
+ return [
521
+ [
522
+ `${guard(`${value} !== undefined`)} { ${writeTag(no, LengthDelimited)} const s = w.fork(); `,
523
+ ...write,
524
+ "; w.join(s); }",
525
+ ],
526
+ ];
527
+ }
528
+ case "list":
529
+ return this.encodeList(field, `m.${field.localName}`);
530
+ case "map":
531
+ return this.encodeMap(field, `m.${field.localName}`);
532
+ }
533
+ }
534
+
535
+ encodeList(field, list) {
536
+ const no = field.number;
537
+ if (field.listKind === "message") {
538
+ const write = this.call("write", field.message, ["w, a[i]"]);
539
+ return [
540
+ [
541
+ `for (let i = 0, a = ${list}; i < a.length; i++) { ${writeTag(no, LengthDelimited)} const s = w.fork(); `,
542
+ ...write,
543
+ "; w.join(s); }",
544
+ ],
545
+ ];
546
+ }
547
+ const type = field.listKind === "enum" ? ScalarType.INT32 : field.scalar;
548
+ const { method, wire, packed, long } = Scalars.get(type);
549
+ if (!field.packed) {
550
+ return [
551
+ [
552
+ `for (let i = 0, a = ${list}; i < a.length; i++) { ${writeTag(no, wire)} w.${method}(a[i]); }`,
553
+ ],
554
+ ];
555
+ }
556
+ const write = long ? `w.packedLong(${list}, w.${method});` : `w.${packed}(${list});`;
557
+ return [[`if (${list}.length > 0) { ${writeTag(no, LengthDelimited)} ${write} }`]];
558
+ }
559
+
560
+ encodeMap(field, record) {
561
+ const { rt } = this;
562
+ const no = field.number;
563
+ const key = Scalars.get(field.mapKey);
564
+ // Keys are strings in the record; converted back as protobuf-es converts them.
565
+ let keyValue;
566
+ switch (field.mapKey) {
567
+ case ScalarType.STRING:
568
+ keyValue = ["k"];
569
+ break;
570
+ case ScalarType.BOOL:
571
+ keyValue = [rt.boolKey, "(k)"];
572
+ break;
573
+ case ScalarType.UINT64:
574
+ case ScalarType.FIXED64:
575
+ keyValue = [rt.uint64Key, "(k)"];
576
+ break;
577
+ case ScalarType.INT64:
578
+ case ScalarType.SFIXED64:
579
+ case ScalarType.SINT64:
580
+ keyValue = [rt.int64Key, "(k)"];
581
+ break;
582
+ default:
583
+ keyValue = [rt.intKey, "(k)"];
584
+ }
585
+ let writeValue;
586
+ if (field.mapKind === "message") {
587
+ writeValue = [
588
+ `${writeTag(2, LengthDelimited)} const s2 = w.fork(); `,
589
+ ...this.call("write", field.message, ["w, o[k]"]),
590
+ "; w.join(s2);",
591
+ ];
592
+ } else {
593
+ const type = field.mapKind === "enum" ? ScalarType.INT32 : field.scalar;
594
+ const { method, wire } = Scalars.get(type);
595
+ writeValue = [`${writeTag(2, wire)} w.${method}(o[k]);`];
596
+ }
597
+ return [
598
+ ["{"],
599
+ [` const o`, this.type(": any"), ` = ${record}, ks = Object.keys(o);`],
600
+ [" for (let i = 0; i < ks.length; i++) {"],
601
+ [" const k = ks[i];"],
602
+ [
603
+ ` ${writeTag(no, LengthDelimited)} const s = w.fork(); ${writeTag(1, key.wire)} w.${key.method}(`,
604
+ ...keyValue,
605
+ "); ",
606
+ ...writeValue,
607
+ " w.join(s);",
608
+ ],
609
+ [" }"],
610
+ ["}"],
611
+ ];
612
+ }
613
+
614
+ // -------------------------------------------------------------------------------------- codecs
615
+
616
+ /** Reads and writes a message the generator leaves to protobuf-es. */
617
+ generateFallback(message) {
618
+ const { f, rt } = this;
619
+ const name = this.name(message);
620
+ const schema = f.importSchema(message);
621
+ this.printReadHead(name);
622
+ f.print(" return ", rt.readMessage, "(", schema, ", r, end, depth, into);");
623
+ f.print("}");
624
+ f.print();
625
+ this.printWriteHead(name);
626
+ f.print(" ", rt.writeMessage, "(", schema, ", w, m);");
627
+ f.print("}");
628
+ f.print();
629
+ }
630
+
631
+ generateCodec(message) {
632
+ const { f } = this;
633
+ const name = this.name(message);
634
+ f.print(f.jsDoc(`The codec of ${message.typeName}.`));
635
+ f.print(
636
+ f.export("const", this.codecName(message)),
637
+ " = /* @__PURE__ */ ",
638
+ this.rt.defineCodec,
639
+ "(",
640
+ f.importSchema(message),
641
+ `, $read${name}, $write${name});`,
642
+ );
643
+ f.print();
644
+ }
645
+
646
+ declareCodec(message) {
647
+ const { f } = this;
648
+ f.print(f.jsDoc(`The codec of ${message.typeName}.`));
649
+ f.print(
650
+ f.export("declare const", this.codecName(message)),
651
+ ": ",
652
+ f.import("MessageCodec", Runtime, true),
653
+ "<typeof ",
654
+ f.importSchema(message, true),
655
+ ">;",
656
+ );
657
+ f.print();
658
+ }
659
+
660
+ /**
661
+ * The codecs of the request and response types of a service, which createClient() takes as its
662
+ * `codecs` option. Types without a generated codec, such as the well-known types, are left out,
663
+ * and protobuf-es encodes and decodes them.
664
+ */
665
+ generateServiceCodecs(service) {
666
+ const { f } = this;
667
+ const types = [];
668
+ for (const method of service.methods) {
669
+ for (const type of [method.input, method.output]) {
670
+ if (this.generated.has(type.file) && !types.includes(type)) {
671
+ types.push(type);
672
+ }
673
+ }
674
+ }
675
+ const name = `${f.importSchema(service).name}Codecs`;
676
+ f.print(f.jsDoc(`The codecs of the requests and responses of ${service.typeName}.`));
677
+ const codecType = f.import("MessageCodec", Runtime, true);
678
+ if (this.target === "dts") {
679
+ f.print(f.export("declare const", name), ": readonly ", codecType, "[];");
680
+ f.print();
681
+ return;
682
+ }
683
+ const codecs = [];
684
+ for (const type of types) {
685
+ if (codecs.length > 0) {
686
+ codecs.push(", ");
687
+ }
688
+ codecs.push(
689
+ type.file === this.file
690
+ ? this.codecName(type)
691
+ : f.import(this.codecName(type), `./${type.file.name}_trevrpc.js`),
692
+ );
693
+ }
694
+ f.print(
695
+ f.export("const", name),
696
+ this.type(": readonly ", codecType, "[]"),
697
+ " = [",
698
+ ...codecs,
699
+ "];",
700
+ );
701
+ f.print();
702
+ }
703
+ }