@bufbuild/protoplugin 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.
Files changed (79) hide show
  1. package/dist/cjs/create-es-plugin.d.ts +8 -12
  2. package/dist/cjs/create-es-plugin.js +15 -13
  3. package/dist/cjs/ecmascript/file-preamble.js +8 -7
  4. package/dist/cjs/ecmascript/generated-file.d.ts +19 -20
  5. package/dist/cjs/ecmascript/generated-file.js +95 -108
  6. package/dist/cjs/ecmascript/import-path.d.ts +0 -6
  7. package/dist/cjs/ecmascript/import-path.js +1 -22
  8. package/dist/cjs/ecmascript/import-symbol.d.ts +1 -3
  9. package/dist/cjs/ecmascript/import-symbol.js +3 -5
  10. package/dist/cjs/ecmascript/index.d.ts +3 -16
  11. package/dist/cjs/ecmascript/index.js +3 -29
  12. package/dist/cjs/ecmascript/jsdoc.d.ts +2 -13
  13. package/dist/cjs/ecmascript/jsdoc.js +23 -31
  14. package/dist/cjs/ecmascript/names.d.ts +4 -0
  15. package/dist/cjs/ecmascript/names.js +119 -0
  16. package/dist/cjs/ecmascript/parameter.d.ts +3 -3
  17. package/dist/cjs/ecmascript/parameter.js +2 -2
  18. package/dist/cjs/ecmascript/printable.d.ts +36 -0
  19. package/dist/cjs/ecmascript/runtime-imports.d.ts +12 -23
  20. package/dist/cjs/ecmascript/runtime-imports.js +28 -29
  21. package/dist/cjs/ecmascript/safe-identifier.d.ts +6 -0
  22. package/dist/cjs/ecmascript/safe-identifier.js +90 -0
  23. package/dist/cjs/ecmascript/schema.d.ts +10 -9
  24. package/dist/cjs/ecmascript/schema.js +64 -20
  25. package/dist/cjs/ecmascript/transpile.js +1 -1
  26. package/dist/cjs/index.d.ts +2 -6
  27. package/dist/cjs/index.js +6 -1
  28. package/dist/cjs/plugin.d.ts +1 -1
  29. package/dist/cjs/run-node.js +4 -3
  30. package/dist/cjs/source-code-info.d.ts +18 -0
  31. package/dist/cjs/source-code-info.js +259 -0
  32. package/dist/esm/create-es-plugin.d.ts +8 -12
  33. package/dist/esm/create-es-plugin.js +15 -13
  34. package/dist/esm/ecmascript/file-preamble.js +5 -4
  35. package/dist/esm/ecmascript/generated-file.d.ts +19 -20
  36. package/dist/esm/ecmascript/generated-file.js +97 -110
  37. package/dist/esm/ecmascript/import-path.d.ts +0 -6
  38. package/dist/esm/ecmascript/import-path.js +0 -20
  39. package/dist/esm/ecmascript/import-symbol.d.ts +1 -3
  40. package/dist/esm/ecmascript/import-symbol.js +3 -5
  41. package/dist/esm/ecmascript/index.d.ts +3 -16
  42. package/dist/esm/ecmascript/index.js +1 -18
  43. package/dist/esm/ecmascript/jsdoc.d.ts +2 -13
  44. package/dist/esm/ecmascript/jsdoc.js +20 -29
  45. package/dist/esm/ecmascript/names.d.ts +4 -0
  46. package/dist/esm/ecmascript/names.js +113 -0
  47. package/dist/esm/ecmascript/parameter.d.ts +3 -3
  48. package/dist/esm/ecmascript/parameter.js +2 -2
  49. package/dist/esm/ecmascript/printable.d.ts +36 -0
  50. package/dist/esm/ecmascript/{opaque-printables.js → printable.js} +1 -1
  51. package/dist/esm/ecmascript/runtime-imports.d.ts +12 -23
  52. package/dist/esm/ecmascript/runtime-imports.js +28 -29
  53. package/dist/esm/ecmascript/safe-identifier.d.ts +6 -0
  54. package/dist/esm/ecmascript/safe-identifier.js +86 -0
  55. package/dist/esm/ecmascript/schema.d.ts +10 -9
  56. package/dist/esm/ecmascript/schema.js +66 -22
  57. package/dist/esm/ecmascript/transpile.js +1 -1
  58. package/dist/esm/index.d.ts +2 -6
  59. package/dist/esm/index.js +1 -0
  60. package/dist/esm/plugin.d.ts +1 -1
  61. package/dist/esm/run-node.js +4 -3
  62. package/dist/esm/source-code-info.d.ts +18 -0
  63. package/dist/esm/source-code-info.js +252 -0
  64. package/package.json +4 -4
  65. package/dist/cjs/ecmascript/legacy-custom-options.d.ts +0 -40
  66. package/dist/cjs/ecmascript/legacy-custom-options.js +0 -121
  67. package/dist/cjs/ecmascript/legacy-gencommon.d.ts +0 -26
  68. package/dist/cjs/ecmascript/legacy-gencommon.js +0 -237
  69. package/dist/cjs/ecmascript/opaque-printables.d.ts +0 -26
  70. package/dist/cjs/ecmascript/reify-wkt.d.ts +0 -100
  71. package/dist/cjs/ecmascript/reify-wkt.js +0 -170
  72. package/dist/esm/ecmascript/legacy-custom-options.d.ts +0 -40
  73. package/dist/esm/ecmascript/legacy-custom-options.js +0 -115
  74. package/dist/esm/ecmascript/legacy-gencommon.d.ts +0 -26
  75. package/dist/esm/ecmascript/legacy-gencommon.js +0 -230
  76. package/dist/esm/ecmascript/opaque-printables.d.ts +0 -26
  77. package/dist/esm/ecmascript/reify-wkt.d.ts +0 -100
  78. package/dist/esm/ecmascript/reify-wkt.js +0 -166
  79. /package/dist/cjs/ecmascript/{opaque-printables.js → printable.js} +0 -0
@@ -0,0 +1,113 @@
1
+ // Copyright 2021-2024 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
+ import { wktPublicImportPaths } from "@bufbuild/protobuf/codegenv1";
15
+ import { nestedTypes } from "@bufbuild/protobuf/reflect";
16
+ import { safeIdentifier } from "./safe-identifier.js";
17
+ export function generateFilePath(file, bootstrapWkt, filesToGenerate) {
18
+ // Well-known types are published with the runtime package. We usually want
19
+ // the generated code to import them from the runtime package, with the
20
+ // following exceptions:
21
+ // 1. We are bootstrapping the runtime package via the plugin option
22
+ // "bootstrap_wkt". In that case, we cannot refer to the runtime package
23
+ // itself.
24
+ // 2. We were explicitly asked to generate the well-known type.
25
+ const wktFrom = wktPublicImportPaths[file.proto.name];
26
+ if (wktFrom !== undefined &&
27
+ !bootstrapWkt &&
28
+ !filesToGenerate.find((f) => f.name === file.name)) {
29
+ return wktFrom;
30
+ }
31
+ return "./" + file.name + "_pb.js";
32
+ }
33
+ export function localDescName(desc) {
34
+ const file = desc.kind == "file" ? desc : desc.file;
35
+ const { descNames } = allNames(file);
36
+ const name = descNames.get(desc);
37
+ if (name === undefined) {
38
+ throw new Error(`unable to determine unique identifier for ${desc.toString()}`);
39
+ }
40
+ return name;
41
+ }
42
+ export function localShapeName(desc) {
43
+ const { shapeNames } = allNames(desc.file);
44
+ const name = shapeNames.get(desc);
45
+ if (name === undefined) {
46
+ throw new Error(`unable to determine unique identifier for ${desc.toString()}`);
47
+ }
48
+ return name;
49
+ }
50
+ function idealDescName(desc, i) {
51
+ const escape = i === 0 ? "" : i === 1 ? "$" : `$${i - 1}`;
52
+ switch (desc.kind) {
53
+ case "file":
54
+ return (safeIdentifier("fileDesc_" + desc.name.replace(/[^a-zA-Z0-9_]+/g, "_")) + escape);
55
+ case "enum":
56
+ return baseName(desc) + "Desc" + escape;
57
+ case "message":
58
+ return baseName(desc) + "Desc" + escape;
59
+ case "extension":
60
+ return baseName(desc) + escape;
61
+ case "service":
62
+ return baseName(desc) + escape;
63
+ }
64
+ }
65
+ function idealShapeName(desc, i) {
66
+ const escape = i === 0 ? "" : i === 1 ? "$" : `$${i - 1}`;
67
+ return baseName(desc) + escape;
68
+ }
69
+ function baseName(desc) {
70
+ const pkg = desc.file.proto.package;
71
+ const offset = pkg.length > 0 ? pkg.length + 1 : 0;
72
+ const name = desc.typeName.substring(offset).replace(/\./g, "_");
73
+ return safeIdentifier(name);
74
+ }
75
+ function allNames(file) {
76
+ const taken = new Set();
77
+ const shapeNames = new Map();
78
+ const descNames = new Map();
79
+ for (const desc of [file, ...nestedTypes(file)]) {
80
+ switch (desc.kind) {
81
+ case "enum":
82
+ case "message": {
83
+ let descName;
84
+ let shapeName;
85
+ for (let i = 0;; i++) {
86
+ descName = idealDescName(desc, i);
87
+ shapeName = idealShapeName(desc, i);
88
+ if (!taken.has(descName) && !taken.has(shapeName)) {
89
+ break;
90
+ }
91
+ }
92
+ taken.add(descName);
93
+ taken.add(shapeName);
94
+ descNames.set(desc, descName);
95
+ shapeNames.set(desc, shapeName);
96
+ break;
97
+ }
98
+ default: {
99
+ let descName;
100
+ for (let i = 0;; i++) {
101
+ descName = idealDescName(desc, i);
102
+ if (!taken.has(descName)) {
103
+ break;
104
+ }
105
+ }
106
+ taken.add(descName);
107
+ descNames.set(desc, descName);
108
+ break;
109
+ }
110
+ }
111
+ }
112
+ return { shapeNames, descNames };
113
+ }
@@ -1,5 +1,5 @@
1
- import { Target } from "./target.js";
2
- import { RewriteImports } from "./import-path.js";
1
+ import type { Target } from "./target.js";
2
+ import type { RewriteImports } from "./import-path.js";
3
3
  export interface ParsedParameter {
4
4
  targets: Target[];
5
5
  tsNocheck: boolean;
@@ -10,4 +10,4 @@ export interface ParsedParameter {
10
10
  jsImportStyle: "module" | "legacy_commonjs";
11
11
  sanitizedParameter: string;
12
12
  }
13
- export declare function parseParameter(parameter: string | undefined, parseExtraOption: ((key: string, value: string) => void) | undefined): ParsedParameter;
13
+ export declare function parseParameter(parameter: string, parseExtraOption: ((key: string, value: string) => void) | undefined): ParsedParameter;
@@ -14,7 +14,7 @@
14
14
  import { PluginOptionError } from "../error.js";
15
15
  export function parseParameter(parameter, parseExtraOption) {
16
16
  let targets = ["js", "dts"];
17
- let tsNocheck = true;
17
+ let tsNocheck = false;
18
18
  let bootstrapWkt = false;
19
19
  let keepEmptyFiles = false;
20
20
  const rewriteImports = [];
@@ -143,7 +143,7 @@ export function parseParameter(parameter, parseExtraOption) {
143
143
  };
144
144
  }
145
145
  function splitParameter(parameter) {
146
- if (parameter == undefined) {
146
+ if (parameter.length == 0) {
147
147
  return [];
148
148
  }
149
149
  return parameter.split(",").map((raw) => {
@@ -0,0 +1,36 @@
1
+ import type { DescEnum, DescExtension, DescFile, DescMessage, DescService } from "@bufbuild/protobuf";
2
+ import { ScalarType, LongType } from "@bufbuild/protobuf/reflect";
3
+ import type { ImportSymbol } from "./import-symbol.js";
4
+ /**
5
+ * All types that can be passed to GeneratedFile.print()
6
+ */
7
+ export type Printable = string | number | boolean | bigint | Uint8Array | ImportSymbol | ExportStatement | JSDocBlock | LiteralString | LiteralProtoInt64 | DescImport | ShapeImport | Printable[];
8
+ export type ExportStatement = {
9
+ kind: "es_export_stmt";
10
+ name: string;
11
+ declaration?: string;
12
+ };
13
+ export type LiteralProtoInt64 = {
14
+ readonly kind: "es_proto_int64";
15
+ type: ScalarType.INT64 | ScalarType.SINT64 | ScalarType.SFIXED64 | ScalarType.UINT64 | ScalarType.FIXED64;
16
+ longType: LongType;
17
+ value: bigint | string;
18
+ };
19
+ export type LiteralString = {
20
+ readonly kind: "es_string";
21
+ value: string;
22
+ };
23
+ export type DescImport = {
24
+ readonly kind: "es_desc_ref";
25
+ desc: DescMessage | DescEnum | DescExtension | DescService | DescFile;
26
+ typeOnly?: boolean;
27
+ };
28
+ export type ShapeImport = {
29
+ readonly kind: "es_shape_ref";
30
+ desc: DescMessage | DescEnum;
31
+ };
32
+ export type JSDocBlock = {
33
+ readonly kind: "es_jsdoc";
34
+ text: string;
35
+ indentation?: string;
36
+ };
@@ -11,4 +11,4 @@
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
- export {};
14
+ import { ScalarType, LongType } from "@bufbuild/protobuf/reflect";
@@ -1,25 +1,14 @@
1
1
  import type { ImportSymbol } from "./import-symbol.js";
2
- export interface RuntimeImports {
3
- proto2: ImportSymbol;
4
- proto3: ImportSymbol;
5
- Message: ImportSymbol;
6
- PartialMessage: ImportSymbol;
7
- PlainMessage: ImportSymbol;
8
- FieldList: ImportSymbol;
9
- MessageType: ImportSymbol;
10
- Extension: ImportSymbol;
11
- BinaryReadOptions: ImportSymbol;
12
- BinaryWriteOptions: ImportSymbol;
13
- JsonReadOptions: ImportSymbol;
14
- JsonWriteOptions: ImportSymbol;
15
- JsonValue: ImportSymbol;
16
- JsonObject: ImportSymbol;
17
- protoDouble: ImportSymbol;
18
- protoInt64: ImportSymbol;
19
- ScalarType: ImportSymbol;
20
- LongType: ImportSymbol;
21
- MethodKind: ImportSymbol;
22
- MethodIdempotency: ImportSymbol;
23
- IMessageTypeRegistry: ImportSymbol;
24
- }
2
+ import { symbols } from "@bufbuild/protobuf/codegenv1";
3
+ export type RuntimeImports = mapRecord<typeof symbols>;
25
4
  export declare function createRuntimeImports(bootstrapWkt: boolean): RuntimeImports;
5
+ type mapRecord<T extends Record<string, unknown>> = {
6
+ [P in keyof T]: T[P] extends symbolInfo ? ImportSymbol : T[P] extends Record<string, unknown> ? mapRecord<T[P]> : never;
7
+ };
8
+ declare function mapRecord<T extends Record<string, unknown>>(record: T, bootstrapWkt: boolean): mapRecord<T>;
9
+ type symbolInfo = {
10
+ readonly typeOnly: boolean;
11
+ readonly from: string;
12
+ readonly bootstrapWktFrom: string;
13
+ };
14
+ export {};
@@ -12,35 +12,34 @@
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
14
  import { createImportSymbol } from "./import-symbol.js";
15
- import { codegenInfo } from "@bufbuild/protobuf";
15
+ import { symbols } from "@bufbuild/protobuf/codegenv1";
16
16
  export function createRuntimeImports(bootstrapWkt) {
17
- // prettier-ignore
18
- return {
19
- proto2: infoToSymbol("proto2", bootstrapWkt),
20
- proto3: infoToSymbol("proto3", bootstrapWkt),
21
- Message: infoToSymbol("Message", bootstrapWkt),
22
- PartialMessage: infoToSymbol("PartialMessage", bootstrapWkt),
23
- PlainMessage: infoToSymbol("PlainMessage", bootstrapWkt),
24
- FieldList: infoToSymbol("FieldList", bootstrapWkt),
25
- MessageType: infoToSymbol("MessageType", bootstrapWkt),
26
- Extension: infoToSymbol("Extension", bootstrapWkt),
27
- BinaryReadOptions: infoToSymbol("BinaryReadOptions", bootstrapWkt),
28
- BinaryWriteOptions: infoToSymbol("BinaryWriteOptions", bootstrapWkt),
29
- JsonReadOptions: infoToSymbol("JsonReadOptions", bootstrapWkt),
30
- JsonWriteOptions: infoToSymbol("JsonWriteOptions", bootstrapWkt),
31
- JsonValue: infoToSymbol("JsonValue", bootstrapWkt),
32
- JsonObject: infoToSymbol("JsonObject", bootstrapWkt),
33
- protoDouble: infoToSymbol("protoDouble", bootstrapWkt),
34
- protoInt64: infoToSymbol("protoInt64", bootstrapWkt),
35
- ScalarType: infoToSymbol("ScalarType", bootstrapWkt),
36
- LongType: infoToSymbol("LongType", bootstrapWkt),
37
- MethodKind: infoToSymbol("MethodKind", bootstrapWkt),
38
- MethodIdempotency: infoToSymbol("MethodIdempotency", bootstrapWkt),
39
- IMessageTypeRegistry: infoToSymbol("IMessageTypeRegistry", bootstrapWkt),
40
- };
17
+ return mapRecord(symbols, bootstrapWkt);
41
18
  }
42
- function infoToSymbol(name, bootstrapWkt) {
43
- const info = codegenInfo.symbols[name];
44
- const symbol = createImportSymbol(name, bootstrapWkt ? info.privateImportPath : info.publicImportPath);
45
- return info.typeOnly ? symbol.toTypeOnly() : symbol;
19
+ function mapRecord(record, bootstrapWkt) {
20
+ const result = Object.create(null);
21
+ for (const [key, value] of Object.entries(record)) {
22
+ if (isSymbolInfo(value)) {
23
+ result[key] = createImportSymbol(key, bootstrapWkt ? value.bootstrapWktFrom : value.from, value.typeOnly);
24
+ }
25
+ else {
26
+ result[key] = mapRecord(record[key], bootstrapWkt);
27
+ }
28
+ }
29
+ return result;
30
+ }
31
+ function isSymbolInfo(arg) {
32
+ if (typeof arg != "object" || arg === null) {
33
+ return false;
34
+ }
35
+ const wantNames = [
36
+ "typeOnly",
37
+ "from",
38
+ "bootstrapWktFrom",
39
+ ];
40
+ const gotNames = Object.getOwnPropertyNames(arg);
41
+ if (gotNames.length !== wantNames.length) {
42
+ return false;
43
+ }
44
+ return wantNames.every((w) => gotNames.includes(w));
46
45
  }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Escapes names that are reserved identifiers in ECMAScript, TypeScript.
3
+ *
4
+ * Also see safeObjectProperty() from @bufbuild/protoplugin/reflect.
5
+ */
6
+ export declare function safeIdentifier(name: string): string;
@@ -0,0 +1,86 @@
1
+ // Copyright 2021-2024 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
+ * Names that cannot be used for identifiers, such as class names,
16
+ * but _can_ be used for object properties.
17
+ */
18
+ const reservedIdentifiers = new Set([
19
+ // ECMAScript 2015 keywords
20
+ "break",
21
+ "case",
22
+ "catch",
23
+ "class",
24
+ "const",
25
+ "continue",
26
+ "debugger",
27
+ "default",
28
+ "delete",
29
+ "do",
30
+ "else",
31
+ "export",
32
+ "extends",
33
+ "false",
34
+ "finally",
35
+ "for",
36
+ "function",
37
+ "if",
38
+ "import",
39
+ "in",
40
+ "instanceof",
41
+ "new",
42
+ "null",
43
+ "return",
44
+ "super",
45
+ "switch",
46
+ "this",
47
+ "throw",
48
+ "true",
49
+ "try",
50
+ "typeof",
51
+ "var",
52
+ "void",
53
+ "while",
54
+ "with",
55
+ "yield",
56
+ // ECMAScript 2015 future reserved keywords
57
+ "enum",
58
+ "implements",
59
+ "interface",
60
+ "let",
61
+ "package",
62
+ "private",
63
+ "protected",
64
+ "public",
65
+ "static",
66
+ // Class name cannot be 'Object' when targeting ES5 with module CommonJS
67
+ "Object",
68
+ // TypeScript keywords that cannot be used for types (as opposed to variables)
69
+ "bigint",
70
+ "number",
71
+ "boolean",
72
+ "string",
73
+ "object",
74
+ // Identifiers reserved for the runtime, so we can generate legible code
75
+ "globalThis",
76
+ "Uint8Array",
77
+ "Partial",
78
+ ]);
79
+ /**
80
+ * Escapes names that are reserved identifiers in ECMAScript, TypeScript.
81
+ *
82
+ * Also see safeObjectProperty() from @bufbuild/protoplugin/reflect.
83
+ */
84
+ export function safeIdentifier(name) {
85
+ return reservedIdentifiers.has(name) ? name + "$" : name;
86
+ }
@@ -1,9 +1,9 @@
1
- import type { CodeGeneratorRequest, DescFile } from "@bufbuild/protobuf";
2
- import { FeatureSetDefaults } from "@bufbuild/protobuf";
1
+ import type { DescEnum, DescExtension, DescFile, DescMessage, DescService } from "@bufbuild/protobuf";
2
+ import type { CodeGeneratorRequest } from "@bufbuild/protobuf/wkt";
3
+ import { Edition } from "@bufbuild/protobuf/wkt";
3
4
  import type { FileInfo, GeneratedFile } from "./generated-file.js";
4
- import { RuntimeImports } from "./runtime-imports.js";
5
5
  import type { Target } from "./target.js";
6
- import { ParsedParameter } from "./parameter.js";
6
+ import type { ParsedParameter } from "./parameter.js";
7
7
  /**
8
8
  * Schema describes the files and types that the plugin is requested to
9
9
  * generate.
@@ -21,14 +21,15 @@ export interface Schema {
21
21
  * The plugin option `target`. A code generator should support all targets.
22
22
  */
23
23
  readonly targets: readonly Target[];
24
- /**
25
- * Provides some symbols from the runtime library @bufbuild/protobuf.
26
- */
27
- readonly runtime: RuntimeImports;
28
24
  /**
29
25
  * Generate a new file with the given name.
30
26
  */
31
27
  generateFile(name: string): GeneratedFile;
28
+ /**
29
+ * List all types in a file (including messages, enumerations, and extensions
30
+ * nested in messages).
31
+ */
32
+ typesInFile(file: DescFile): Iterable<DescMessage | DescEnum | DescExtension | DescService>;
32
33
  /**
33
34
  * The original google.protobuf.compiler.CodeGeneratorRequest.
34
35
  */
@@ -38,5 +39,5 @@ interface SchemaController extends Schema {
38
39
  getFileInfo: () => FileInfo[];
39
40
  prepareGenerate(target: Target): void;
40
41
  }
41
- export declare function createSchema(request: CodeGeneratorRequest, parameter: ParsedParameter, pluginName: string, pluginVersion: string, featureSetDefaults: FeatureSetDefaults | undefined): SchemaController;
42
+ export declare function createSchema(request: CodeGeneratorRequest, parameter: ParsedParameter, pluginName: string, pluginVersion: string, minimumEdition: Edition, maximumEdition: Edition): SchemaController;
42
43
  export {};
@@ -11,38 +11,36 @@
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 { codegenInfo, createDescriptorSet, } from "@bufbuild/protobuf";
14
+ import { create } from "@bufbuild/protobuf";
15
+ import { Edition, FileDescriptorSetDesc } from "@bufbuild/protobuf/wkt";
16
+ import { createFileRegistry, nestedTypes } from "@bufbuild/protobuf/reflect";
15
17
  import { createGeneratedFile } from "./generated-file.js";
16
- import { createRuntimeImports } from "./runtime-imports.js";
17
18
  import { createImportSymbol } from "./import-symbol.js";
18
- import { deriveImportPath, makeImportPath, rewriteImportPath, } from "./import-path.js";
19
+ import { deriveImportPath, rewriteImportPath } from "./import-path.js";
19
20
  import { makeFilePreamble } from "./file-preamble.js";
20
- export function createSchema(request, parameter, pluginName, pluginVersion, featureSetDefaults) {
21
- const descriptorSet = createDescriptorSet(request.protoFile, {
22
- featureSetDefaults,
23
- });
24
- const filesToGenerate = findFilesToGenerate(descriptorSet, request);
25
- const runtime = createRuntimeImports(parameter.bootstrapWkt);
26
- const createTypeImport = (desc) => {
27
- const name = codegenInfo.localName(desc);
28
- const from = makeImportPath(desc.file, parameter.bootstrapWkt, filesToGenerate);
29
- return createImportSymbol(name, from);
30
- };
31
- const createPreamble = (descFile) => makeFilePreamble(descFile, pluginName, pluginVersion, parameter.sanitizedParameter, parameter.tsNocheck);
21
+ import { localDescName, localShapeName, generateFilePath } from "./names.js";
22
+ import { createRuntimeImports } from "./runtime-imports.js";
23
+ export function createSchema(request, parameter, pluginName, pluginVersion, minimumEdition, maximumEdition) {
24
+ const { allFiles, filesToGenerate } = getFilesToGenerate(request, minimumEdition, maximumEdition);
32
25
  let target;
33
26
  const generatedFiles = [];
27
+ const runtime = createRuntimeImports(parameter.bootstrapWkt);
28
+ const resolveDescImport = (desc, typeOnly) => createImportSymbol(localDescName(desc), generateFilePath(desc.kind == "file" ? desc : desc.file, parameter.bootstrapWkt, filesToGenerate), typeOnly);
29
+ const resolveShapeImport = (desc) => createImportSymbol(localShapeName(desc), generateFilePath(desc.file, parameter.bootstrapWkt, filesToGenerate), true);
30
+ const createPreamble = (descFile) => makeFilePreamble(descFile, pluginName, pluginVersion, parameter.sanitizedParameter, parameter.tsNocheck);
31
+ const rewriteImport = (importPath) => rewriteImportPath(importPath, parameter.rewriteImports, parameter.importExtension);
34
32
  return {
35
33
  targets: parameter.targets,
36
- runtime,
37
34
  proto: request,
38
35
  files: filesToGenerate,
39
- allFiles: descriptorSet.files,
36
+ allFiles: allFiles,
37
+ typesInFile: nestedTypes,
40
38
  generateFile(name) {
41
39
  if (target === undefined) {
42
40
  throw new Error("prepareGenerate() must be called before generateFile()");
43
41
  }
44
42
  const genFile = createGeneratedFile(name, deriveImportPath(name), target === "js" ? parameter.jsImportStyle : "module", // ts and dts always use import/export, only js may use commonjs
45
- (importPath) => rewriteImportPath(importPath, parameter.rewriteImports, parameter.importExtension), createTypeImport, runtime, createPreamble);
43
+ rewriteImport, resolveDescImport, resolveShapeImport, createPreamble, runtime);
46
44
  generatedFiles.push(genFile);
47
45
  return genFile;
48
46
  },
@@ -56,10 +54,56 @@ export function createSchema(request, parameter, pluginName, pluginVersion, feat
56
54
  },
57
55
  };
58
56
  }
59
- function findFilesToGenerate(descriptorSet, request) {
60
- const missing = request.fileToGenerate.filter((fileToGenerate) => descriptorSet.files.every((file) => fileToGenerate !== file.name + ".proto"));
57
+ function getFilesToGenerate(request, minimumEdition, maximumEdition) {
58
+ if (minimumEdition > maximumEdition) {
59
+ throw new Error(`configured minimumEdition ${editionToString(minimumEdition)} > maximumEdition ${editionToString(maximumEdition)} - please contact plugin author`);
60
+ }
61
+ const missing = request.fileToGenerate.filter((fileToGenerate) => !request.protoFile.find((f) => f.name === fileToGenerate));
61
62
  if (missing.length) {
62
- throw `files_to_generate missing in the request: ${missing.join(", ")}`;
63
+ throw new Error(`files_to_generate missing in the request: ${missing.join(", ")}`);
64
+ }
65
+ for (const file of request.protoFile) {
66
+ if (request.fileToGenerate.includes(file.name)) {
67
+ let edition;
68
+ switch (file.syntax) {
69
+ case "":
70
+ case "proto2":
71
+ edition = Edition.EDITION_PROTO2;
72
+ break;
73
+ case "proto3":
74
+ edition = Edition.EDITION_PROTO3;
75
+ break;
76
+ case "editions":
77
+ edition = file.edition;
78
+ break;
79
+ default:
80
+ edition = Edition.EDITION_UNKNOWN;
81
+ break;
82
+ }
83
+ if (edition < minimumEdition) {
84
+ throw new Error(`${file.name}: unsupported edition ${editionToString(edition)} - the earliest supported edition is ${editionToString(minimumEdition)}`);
85
+ }
86
+ if (edition > maximumEdition) {
87
+ throw new Error(`${file.name}: unsupported edition ${editionToString(edition)} - the latest supported edition is ${editionToString(maximumEdition)}`);
88
+ }
89
+ }
90
+ }
91
+ const registry = createFileRegistry(create(FileDescriptorSetDesc, {
92
+ file: request.protoFile,
93
+ }));
94
+ const allFiles = [];
95
+ const filesToGenerate = [];
96
+ for (const file of registry.files) {
97
+ allFiles.push(file);
98
+ if (request.fileToGenerate.includes(file.proto.name)) {
99
+ filesToGenerate.push(file);
100
+ }
101
+ }
102
+ return { allFiles, filesToGenerate };
103
+ }
104
+ function editionToString(edition) {
105
+ if (edition in Edition) {
106
+ return Edition[edition].replace(/^EDITION_/, "");
63
107
  }
64
- return descriptorSet.files.filter((file) => request.fileToGenerate.includes(file.name + ".proto"));
108
+ return `unknown (${edition})`;
65
109
  }
@@ -112,7 +112,7 @@ export function transpile(files, transpileJs, transpileDts, jsImportStyle) {
112
112
  throw err;
113
113
  }
114
114
  if (result.emitSkipped) {
115
- throw Error("An problem occurred during transpilation and files were not generated. Contact the plugin author for support.");
115
+ throw Error("A problem occurred during transpilation and files were not generated. Contact the plugin author for support.");
116
116
  }
117
117
  return results;
118
118
  }
@@ -1,8 +1,4 @@
1
- import { Schema as SchemaInternal } from "./ecmascript/schema.js";
2
- export { Plugin } from "./plugin.js";
1
+ export type { Plugin } from "./plugin.js";
3
2
  export { runNodeJs } from "./run-node.js";
4
3
  export { createEcmaScriptPlugin } from "./create-es-plugin.js";
5
- /**
6
- * @deprecated Please use Schema from @bufbuild/protoplugin/ecmascript instead
7
- */
8
- export type Schema = SchemaInternal;
4
+ export { getComments, getDeclarationString, getPackageComments, getSyntaxComments, } from "./source-code-info.js";
package/dist/esm/index.js CHANGED
@@ -13,3 +13,4 @@
13
13
  // limitations under the License.
14
14
  export { runNodeJs } from "./run-node.js";
15
15
  export { createEcmaScriptPlugin } from "./create-es-plugin.js";
16
+ export { getComments, getDeclarationString, getPackageComments, getSyntaxComments, } from "./source-code-info.js";
@@ -1,4 +1,4 @@
1
- import type { CodeGeneratorRequest, CodeGeneratorResponse } from "@bufbuild/protobuf";
1
+ import type { CodeGeneratorRequest, CodeGeneratorResponse } from "@bufbuild/protobuf/wkt";
2
2
  /**
3
3
  * Represents any code generator plugin.
4
4
  */
@@ -11,8 +11,9 @@
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 { CodeGeneratorRequest } from "@bufbuild/protobuf";
15
14
  import { isPluginOptionError, reasonToString } from "./error.js";
15
+ import { fromBinary, toBinary } from "@bufbuild/protobuf";
16
+ import { CodeGeneratorRequestDesc, CodeGeneratorResponseDesc, } from "@bufbuild/protobuf/wkt";
16
17
  /**
17
18
  * Run a plugin with Node.js.
18
19
  *
@@ -37,9 +38,9 @@ export function runNodeJs(plugin) {
37
38
  }
38
39
  readBytes(process.stdin)
39
40
  .then((data) => {
40
- const req = CodeGeneratorRequest.fromBinary(data);
41
+ const req = fromBinary(CodeGeneratorRequestDesc, data);
41
42
  const res = plugin.run(req);
42
- return writeBytes(process.stdout, res.toBinary());
43
+ return writeBytes(process.stdout, toBinary(CodeGeneratorResponseDesc, res));
43
44
  })
44
45
  .then(() => process.exit(0))
45
46
  .catch((reason) => {
@@ -0,0 +1,18 @@
1
+ import type { DescField, DescEnumValue, DescExtension, DescComments, AnyDesc, DescFile } from "@bufbuild/protobuf";
2
+ /**
3
+ * Get comments on the package element in the protobuf source.
4
+ */
5
+ export declare function getPackageComments(desc: DescFile): DescComments;
6
+ /**
7
+ * Get comments on the syntax element in the protobuf source.
8
+ */
9
+ export declare function getSyntaxComments(desc: DescFile): DescComments;
10
+ /**
11
+ * Get comments on the element in the protobuf source.
12
+ */
13
+ export declare function getComments(desc: Exclude<AnyDesc, DescFile>): DescComments;
14
+ /**
15
+ * Return a string that matches the definition of a field in the protobuf
16
+ * source. Does not take custom options into account.
17
+ */
18
+ export declare function getDeclarationString(desc: DescField | DescExtension | DescEnumValue): string;