ts-proto-client 1.0.2 → 1.0.4

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 (3) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +5 -228
  3. package/package.json +1 -3
package/README.md CHANGED
@@ -214,4 +214,4 @@ protoc --version
214
214
 
215
215
  ## License
216
216
 
217
- MIT
217
+ MIT
package/dist/index.js CHANGED
@@ -1,230 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import{Command as q}from"commander";import b from"fs";import R from"path";import y from"fs";import j from"path";import{Root as P,Service as x}from"protobufjs";import u from"path";import w from"fs";var g=["get","post","put","delete","patch"];function C(t){let o=[t,u.join(t,"/third_party/googleapis")],e=new P;return e.resolvePath=(n,p)=>{for(let s of o){let i=u.join(s,p);if(w.existsSync(i))return i}return p},e}function h(t,o=[]){if(!t.nested)return o;for(let e of Object.values(t.nested))e instanceof x&&o.push(e),h(e,o);return o}function A(t){let o=t.parsedOptions?.find(n=>n["(google.api.http)"])?.["(google.api.http)"];if(!o)return null;let e=g.find(n=>o[n]);return e?{method:e,url:o[e],summary:t.options?.["(grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation).summary"]}:null}function v(t,o){let e=u.resolve(process.cwd(),t),n=C(e);n.loadSync(u.join(e,o));let p=h(n),s={};for(let i of p){let a=[];for(let r of Object.values(i.methods)){let m=A(r);m&&a.push({name:r.name,requestType:r.requestType,responseType:r.responseType,...m})}s[i.name]=a}return s}function O(t,o){let e=[];for(let[n,p]of Object.entries(t)){let s=new Set,i=[];for(let r of p){s.add(r.requestType),s.add(r.responseType);let m=r.method==="get"?"params: data":"data",d=[];r.summary&&d.push(`// ${r.summary}`),d.push(`export function ${r.name}(data: ${r.requestType}) {`,` return service<${r.responseType}>({`,` url: "${r.url.replace("/api","")}",`,` method: "${r.method}",`,` ${m}`," })","}"),i.push(d.join(`
3
+ `))}let a=[...s].sort();e.push({[n]:['import { service } from "../..";',"","import type {",` ${a.join(`,
4
+ `)}`,`} from "${o}";`,"",i.join(`
2
5
 
3
- // src/index.ts
4
- import { Command } from "commander";
5
-
6
- // src/commands/generate.ts
7
- import fs4 from "fs";
8
- import path4 from "path";
9
-
10
- // src/generators/api.ts
11
- import fs2 from "fs";
12
- import path2 from "path";
13
-
14
- // src/utils/index.ts
15
- import { Root, Service } from "protobufjs";
16
- import path from "path";
17
- import fs from "fs";
18
-
19
- // src/constants.ts
20
- var HTTP_METHODS = [
21
- "get",
22
- "post",
23
- "put",
24
- "delete",
25
- "patch"
26
- ];
27
-
28
- // src/utils/index.ts
29
- function createRoot(rootPath) {
30
- const INCLUDE_PATHS = [
31
- rootPath,
32
- path.join(rootPath, "/third_party/googleapis")
33
- ];
34
- const root = new Root();
35
- root.resolvePath = (_, target) => {
36
- for (const includePath of INCLUDE_PATHS) {
37
- const filePath = path.join(
38
- includePath,
39
- target
40
- );
41
- if (fs.existsSync(filePath)) {
42
- return filePath;
43
- }
44
- }
45
- return target;
46
- };
47
- return root;
48
- }
49
- function findServices(namespace, result = []) {
50
- if (!namespace.nested) return result;
51
- for (const item of Object.values(namespace.nested)) {
52
- if (item instanceof Service) {
53
- result.push(item);
54
- }
55
- findServices(item, result);
56
- }
57
- return result;
58
- }
59
- function getHttpInfo(method) {
60
- const http = method.parsedOptions?.find(
61
- (item) => item["(google.api.http)"]
62
- )?.["(google.api.http)"];
63
- if (!http) return null;
64
- const methodName = HTTP_METHODS.find(
65
- (key) => http[key]
66
- );
67
- if (!methodName) return null;
68
- return {
69
- method: methodName,
70
- url: http[methodName],
71
- summary: method.options?.["(grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation).summary"]
72
- };
73
- }
74
- function parseProto(protosPath, protoFilePath) {
75
- const rootPath = path.resolve(process.cwd(), protosPath);
76
- const root = createRoot(rootPath);
77
- root.loadSync(path.join(rootPath, protoFilePath));
78
- const services = findServices(root);
79
- const apis = {};
80
- for (const service of services) {
81
- const api = [];
82
- for (const method of Object.values(service.methods)) {
83
- const httpInfo = getHttpInfo(method);
84
- if (!httpInfo) continue;
85
- api.push({
86
- name: method.name,
87
- requestType: method.requestType,
88
- responseType: method.responseType,
89
- ...httpInfo
90
- });
91
- }
92
- apis[service.name] = api;
93
- }
94
- return apis;
95
- }
96
- function generateApiCode(apis, importTypePath) {
97
- const modules = [];
98
- for (const [key, api] of Object.entries(apis)) {
99
- const types = /* @__PURE__ */ new Set();
100
- const functions = [];
101
- for (const data of api) {
102
- types.add(data.requestType);
103
- types.add(data.responseType);
104
- const requestField = data.method === "get" ? "params: data" : "data";
105
- const lines = [];
106
- if (data.summary) lines.push(`// ${data.summary}`);
107
- lines.push(
108
- `export function ${data.name}(data: ${data.requestType}) {`,
109
- ` return service<${data.responseType}>({`,
110
- ` url: "${data.url.replace("/api", "")}",`,
111
- ` method: "${data.method}",`,
112
- ` ${requestField}`,
113
- ` })`,
114
- `}`
115
- );
116
- functions.push(
117
- lines.join("\n")
118
- );
119
- }
120
- const imports = [...types].sort();
121
- modules.push({
122
- [key]: [
123
- `import { service } from "@/plugins";`,
124
- "",
125
- "import type {",
126
- ` ${imports.join(",\n ")}`,
127
- `} from "${importTypePath}";`,
128
- "",
129
- functions.join("\n\n")
130
- ].join("\n")
131
- });
132
- }
133
- return modules;
134
- }
135
- function getOutputPath(baseDir, protoFile) {
136
- const normalized = protoFile.replace(/\\/g, "/").replace(/^\.?\//, "").replace(/\.proto$/, "");
137
- return path.join(baseDir, normalized);
138
- }
139
-
140
- // src/generators/api.ts
141
- function generateApi(options) {
142
- const outputPath = path2.resolve(process.cwd(), options.apiOutput);
143
- if (!fs2.existsSync(outputPath)) {
144
- fs2.mkdirSync(outputPath, { recursive: true });
145
- }
146
- const apis = parseProto(options.root, options.file);
147
- const result = getOutputPath(options.typeOutput, options.file);
148
- const relativePath = path2.relative(options.apiOutput, result).replace(/\\/g, "/");
149
- const codes = generateApiCode(apis, relativePath);
150
- for (const code of codes) {
151
- for (const [name, content] of Object.entries(code)) {
152
- fs2.writeFileSync(`${outputPath}/${name}.ts`, content, "utf8");
153
- }
154
- }
155
- console.log("\u2705 Generate Success");
156
- }
157
-
158
- // src/generators/type.ts
159
- import { execSync } from "child_process";
160
- import { createRequire } from "module";
161
- import fs3 from "fs";
162
- import path3 from "path";
163
- function generateTypes(options) {
164
- const require2 = createRequire(import.meta.url);
165
- const tsProtoPkg = require2.resolve("ts-proto/package.json");
166
- const tsProtoRoot = path3.dirname(tsProtoPkg);
167
- const pluginName = process.platform === "win32" ? "protoc-gen-ts_proto.cmd" : "protoc-gen-ts_proto";
168
- const pluginPath = path3.resolve(tsProtoRoot, `./node_modules/.bin/${pluginName}`);
169
- const outputPath = path3.resolve(process.cwd(), options.typeOutput);
170
- if (!fs3.existsSync(outputPath)) {
171
- fs3.mkdirSync(outputPath, { recursive: true });
172
- }
173
- const rootPath = path3.resolve(process.cwd(), options.root);
174
- const configs = [
175
- "protoc",
176
- `--plugin=protoc-gen-ts_proto=${pluginPath}`,
177
- `--ts_proto_out=${outputPath}`,
178
- "--ts_proto_opt=onlyTypes=true",
179
- // 仅生成 TypeScript
180
- "--ts_proto_opt=useOptionals=messages",
181
- // message 字段生成可选属性
182
- "--ts_proto_opt=esModuleInterop=true",
183
- // 使用 ES Module 风格导入
184
- `--proto_path=${rootPath}`,
185
- `--proto_path=${path3.join(rootPath, "/third_party/googleapis")}`,
186
- // protos 中的 google 依赖
187
- path3.join(rootPath, options.file)
188
- ];
189
- execSync(configs.join(" "), { stdio: "inherit" });
190
- fs3.rmSync(
191
- path3.join(outputPath, "google"),
192
- { recursive: true, force: true }
193
- );
194
- fs3.rmSync(
195
- path3.join(outputPath, "common.ts"),
196
- { force: true }
197
- );
198
- }
199
-
200
- // src/commands/generate.ts
201
- async function generate(options) {
202
- if (!fs4.existsSync(path4.resolve(process.cwd(), options.root))) {
203
- console.log(`proto \u9879\u76EE\u4E0D\u5B58\u5728(${options.root})`);
204
- return;
205
- }
206
- generateTypes(options);
207
- generateApi(options);
208
- }
209
-
210
- // src/index.ts
211
- var program = new Command();
212
- program.name("proto-gen").description("proto code generator").version("1.0.0");
213
- program.command("generate").option("--file, --file <path>").option("--root, --root <path>").option("--type-output, --typeOutput <path>").option("--api-output, --apiOutput <path>").action((options) => {
214
- if (options.file === void 0) {
215
- console.log("proto file \u4E0D\u80FD\u4E3A\u7A7A, \u8BF7\u8F93\u5165 --file ./account.proto");
216
- return;
217
- }
218
- if (options.root === void 0) {
219
- console.log("proto \u6587\u4EF6\u7684\u6839\u8DEF\u5F84\u4E0D\u80FD\u4E3A\u7A7A, \u8BF7\u8F93\u5165 --root ../protos");
220
- return;
221
- }
222
- if (options.typeOutput === void 0) {
223
- options.typeOutput = "src/protos/type";
224
- }
225
- if (options.apiOutput === void 0) {
226
- options.apiOutput = "src/protos/api";
227
- }
228
- generate(options);
229
- });
230
- program.parse();
6
+ `)].join(`
7
+ `)})}return e}function T(t,o){let e=o.replace(/\\/g,"/").replace(/^\.?\//,"").replace(/\.proto$/,"");return u.join(t,e)}function _(t){let o=j.resolve(process.cwd(),t.apiOutput);y.existsSync(o)||y.mkdirSync(o,{recursive:!0});let e=v(t.root,t.file),n=T(t.typeOutput,t.file),p=j.relative(t.apiOutput,n).replace(/\\/g,"/"),s=O(e,p);for(let i of s)for(let[a,r]of Object.entries(i))y.writeFileSync(`${o}/${a}.ts`,r,"utf8");console.log("\u2705 Generate Success")}import{execSync as H}from"child_process";import f from"fs";import c from"path";function $(t){let o=c.resolve(process.cwd(),t.typeOutput);f.existsSync(o)||f.mkdirSync(o,{recursive:!0});let e=c.resolve(process.cwd(),t.root),n=["protoc",`--ts_proto_out=${o}`,"--ts_proto_opt=onlyTypes=true","--ts_proto_opt=useOptionals=messages","--ts_proto_opt=esModuleInterop=true",`--proto_path=${e}`,`--proto_path=${c.join(e,"/third_party/googleapis")}`,c.join(e,t.file)],p={...process.env,PATH:`${c.join(process.cwd(),"node_modules",".bin")};${process.env.PATH}`};console.log(`${c.join(process.cwd(),"node_modules",".bin")};${process.env.PATH}`),H(n.join(" "),{stdio:"inherit",env:p}),f.rmSync(c.join(o,"google"),{recursive:!0,force:!0}),f.rmSync(c.join(o,"common.ts"),{force:!0})}async function S(t){if(!b.existsSync(R.resolve(process.cwd(),t.root))){console.log(`proto \u9879\u76EE\u4E0D\u5B58\u5728(${t.root})`);return}$(t),_(t)}var l=new q;l.name("proto-gen").description("proto code generator").version("1.0.0");l.command("generate").option("--file, --file <path>").option("--root, --root <path>").option("--type-output, --typeOutput <path>").option("--api-output, --apiOutput <path>").action(t=>{if(t.file===void 0){console.log("proto file \u4E0D\u80FD\u4E3A\u7A7A, \u8BF7\u8F93\u5165 --file ./account.proto");return}if(t.root===void 0){console.log("proto \u6587\u4EF6\u7684\u6839\u8DEF\u5F84\u4E0D\u80FD\u4E3A\u7A7A, \u8BF7\u8F93\u5165 --root ../protos");return}t.typeOutput===void 0&&(t.typeOutput="src/protos/type"),t.apiOutput===void 0&&(t.apiOutput="src/protos/api"),S(t)});l.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ts-proto-client",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -20,13 +20,11 @@
20
20
  "packageManager": "pnpm@10.14.0",
21
21
  "dependencies": {
22
22
  "commander": "^15.0.0",
23
- "prompts": "^2.4.2",
24
23
  "protobufjs": "^8.6.3",
25
24
  "ts-proto": "^2.11.8"
26
25
  },
27
26
  "devDependencies": {
28
27
  "@types/node": "^25.9.3",
29
- "@types/prompts": "^2.4.9",
30
28
  "tsup": "^8.5.1",
31
29
  "tsx": "^4.22.4",
32
30
  "typescript": "^6.0.3"