ropImport.js
11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
const fs = require("fs");
const path = require("path");
const {
loadSwagger,
buildContract,
formatContractMarkdown,
buildParamsTemplate,
buildResponseTemplate,
methodSuffixToPascal,
toMethodFileName,
findMethod,
DEFAULT_SWAGGER_SNAPSHOT,
} = require("./swaggerInspect");
const SMARTCARLIFE_PREFIX = "dj.api.smartcarlife.";
const API_DIR = path.join(__dirname, "../../api");
const ADAPTERS_ROOT = path.join(API_DIR, "adapters");
const GATEWAY_PREFIXES = new Set(["pc", "pad", "app", "h5", "wx", "mini"]);
const METHOD_PATTERN = /dj\.api\.[a-zA-Z0-9_.]+/g;
function extractMethodFromText(text = "") {
const matches = text.match(METHOD_PATTERN);
if (!matches || !matches.length) {
return null;
}
return matches.sort((a, b) => b.length - a.length)[0];
}
function assertSmartcarlifeMethod(method) {
if (!method || !method.startsWith(SMARTCARLIFE_PREFIX)) {
throw new Error(`仅支持 ${SMARTCARLIFE_PREFIX}* 接口,收到: ${method || "(empty)"}`);
}
}
function inferFeatureName(method) {
assertSmartcarlifeMethod(method);
const rest = method.slice(SMARTCARLIFE_PREFIX.length);
const segments = rest.split(".").filter(Boolean);
if (!segments.length) {
throw new Error(`无法从 method 推断 feature: ${method}`);
}
let start = 0;
if (GATEWAY_PREFIXES.has(segments[0]) && segments.length > 2) {
start = 1;
}
if (segments.length - start < 2) {
return segments[start] || segments[0];
}
return segments[segments.length - 2];
}
function listApiFiles() {
if (!fs.existsSync(API_DIR)) {
return [];
}
return fs.readdirSync(API_DIR)
.filter((name) => name.endsWith(".js") && !name.endsWith(".mock.js") && name !== "request.js")
.map((name) => path.join(API_DIR, name));
}
function detectApiFile(method, apiOverride) {
if (apiOverride) {
const filePath = apiOverride.endsWith(".js")
? path.resolve(API_DIR, apiOverride)
: path.resolve(API_DIR, `${apiOverride}.js`);
if (!fs.existsSync(filePath)) {
throw new Error(`API 文件不存在: ${filePath}`);
}
return filePath;
}
const needle = `method = "${method}"`;
const needle2 = `method = \`${method}\``;
const hit = listApiFiles().find((filePath) => {
const content = fs.readFileSync(filePath, "utf8");
return content.includes(needle) || content.includes(needle2) || content.includes(`"${method}"`);
});
return hit || path.join(API_DIR, `${inferFeatureName(method)}.js`);
}
function findExistingApiBinding(apiFilePath, method) {
const content = fs.readFileSync(apiFilePath, "utf8");
if (!content.includes(method)) {
return null;
}
const fnStartRegex = /export\s+function\s+(\w+)\s*\([^)]*\)\s*\{/g;
let match = fnStartRegex.exec(content);
while (match) {
const start = match.index;
const functionName = match[1];
const nextExport = content.indexOf("export function", start + 1);
const blockEnd = nextExport === -1 ? content.length : nextExport;
const block = content.slice(start, blockEnd).trim();
if (block.includes(`"${method}"`) || block.includes(`\`${method}\``)) {
return { functionName, block };
}
match = fnStartRegex.exec(content);
}
return null;
}
function buildActionResponseTemplate(contract) {
const pascal = methodSuffixToPascal(contract.method);
const { buildJsdocTypedefs } = require("./swaggerInspect");
const typedefs = buildJsdocTypedefs(contract);
return `${typedefs}
/**
* ${contract.method} 响应 → 页面数据
* @param {*} [res]
* @returns {*}
* @see __contracts__/${toMethodFileName(contract.method)}.contract.md
*/
export function map${pascal}Response(res = {}) {
return res;
}
export default map${pascal}Response;
`;
}
function getAdapterTemplates(contract) {
const isPage = !!contract.response.pagination;
return {
params: buildParamsTemplate(contract),
response: isPage ? buildResponseTemplate(contract) : buildActionResponseTemplate(contract),
pascal: methodSuffixToPascal(contract.method),
isPage,
};
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
function writeFileSafe(filePath, content, { dryRun, force }) {
if (dryRun) {
return { path: filePath, status: "dry-run" };
}
if (fs.existsSync(filePath) && !force) {
return { path: filePath, status: "skipped" };
}
ensureDir(path.dirname(filePath));
fs.writeFileSync(filePath, content, "utf8");
return { path: filePath, status: "wrote" };
}
function buildImportPlan(options = {}) {
const method = options.method || extractMethodFromText(options.text || "");
if (!method) {
throw new Error("未找到 ROP method,请传入 --method 或包含 dj.api.* 的文本");
}
assertSmartcarlifeMethod(method);
const feature = options.feature || inferFeatureName(method);
const adapterDir = path.join(ADAPTERS_ROOT, feature);
const apiFilePath = detectApiFile(method, options.api);
const apiFileName = path.basename(apiFilePath);
const binding = fs.existsSync(apiFilePath)
? findExistingApiBinding(apiFilePath, method)
: null;
let contract;
try {
const swagger = options.swaggerDoc || null;
if (!swagger) {
throw new Error("swagger required");
}
contract = buildContract(swagger, method);
} catch (error) {
const wrapped = new Error(`Swagger 中未找到 method: ${method}。请先执行 npm run rop:swagger:fetch`);
wrapped.cause = error;
throw wrapped;
}
const templates = getAdapterTemplates(contract);
const methodFile = toMethodFileName(method);
const files = {
contractJson: path.join(adapterDir, "__contracts__", `${methodFile}.contract.json`),
contractMd: path.join(adapterDir, "__contracts__", `${methodFile}.contract.md`),
params: path.join(adapterDir, `build${templates.pascal}Params.js`),
response: path.join(adapterDir, `map${templates.pascal}Response.js`),
api: apiFilePath,
};
return {
method,
feature,
contract,
templates,
files,
apiFileName,
binding,
adapterDir,
};
}
function buildMigratedFunctionBody({
method,
binding,
templates,
mockLoader,
mockFn,
}) {
const buildFn = `build${templates.pascal}Params`;
const mapFn = templates.isPage ? `map${templates.pascal}PageResponse` : `map${templates.pascal}Response`;
const lines = [];
lines.push(`export function ${binding.functionName}(data) {`);
if (mockLoader && mockFn) {
lines.push(`\tif (${mockLoader}) {`);
lines.push(`\t\treturn loadAbnormalFlowMock().then((m) => m.${mockFn}(data));`);
lines.push("\t}");
}
lines.push("\tconst payload = {");
lines.push(`\t\t...${buildFn}(data),`);
lines.push(`\t\tmethod: "${method}",`);
lines.push("\t};");
lines.push(`\treturn request(payload, RequestMethods.POST).then(${mapFn});`);
lines.push("}");
return `${lines.join("\n")}\n`;
}
function upsertImportLine(content, importLine) {
if (content.includes(importLine)) {
return content;
}
const requestImport = content.match(/^import .+ from ["'].\/request["']/m);
if (requestImport) {
return content.replace(requestImport[0], `${requestImport[0]}\n${importLine}`);
}
return `${importLine}\n${content}`;
}
function migrateApiFile(apiFilePath, plan, { dryRun }) {
if (!plan.binding) {
return { path: apiFilePath, status: "skipped", reason: "no-existing-function" };
}
const content = fs.readFileSync(apiFilePath, "utf8");
const buildFn = `build${plan.templates.pascal}Params`;
const mapFn = plan.templates.isPage
? `map${plan.templates.pascal}PageResponse`
: `map${plan.templates.pascal}Response`;
const importLine = `import { ${buildFn} } from "./adapters/${plan.feature}/build${plan.templates.pascal}Params";`;
const mapImportLine = `import { ${mapFn} } from "./adapters/${plan.feature}/map${plan.templates.pascal}Response";`;
let mockFlag = null;
let mockFn = null;
if (content.includes("USE_ABNORMAL_FLOW_MOCK")) {
mockFlag = "USE_ABNORMAL_FLOW_MOCK";
if (plan.binding.functionName === "getPcAbnormalFlowDeclarationDetail") {
mockFn = "mockPcAbnormalFlowDeclarationDetail";
}
if (plan.binding.functionName === "approvePcAbnormalFlowDeclaration") {
mockFn = "mockApprovePcAbnormalFlowDeclaration";
}
}
const newBlock = buildMigratedFunctionBody({
method: plan.method,
binding: plan.binding,
templates: plan.templates,
mockLoader: mockFlag,
mockFn,
});
let next = content.replace(plan.binding.block, newBlock.trim());
next = upsertImportLine(next, importLine);
next = upsertImportLine(next, mapImportLine);
if (dryRun) {
return { path: apiFilePath, status: "dry-run", preview: newBlock };
}
fs.writeFileSync(apiFilePath, next, "utf8");
return { path: apiFilePath, status: "migrated" };
}
function migrateMockFile(plan, { dryRun }) {
const mockPath = path.join(API_DIR, "abnormalFlow.mock.js");
if (!fs.existsSync(mockPath)) {
return { path: mockPath, status: "skipped", reason: "mock-not-found" };
}
if (!plan.method.includes("abnormalFlowDeclaration")) {
return { path: mockPath, status: "skipped", reason: "not-abnormal-flow" };
}
const mapFn = plan.templates.isPage
? `map${plan.templates.pascal}PageResponse`
: `map${plan.templates.pascal}Response`;
const importLine = `import { ${mapFn} } from "./adapters/${plan.feature}/map${plan.templates.pascal}Response";`;
let content = fs.readFileSync(mockPath, "utf8");
content = upsertImportLine(content, importLine);
if (plan.binding?.functionName === "getPcAbnormalFlowDeclarationDetail") {
content = content.replace(
/return delay\(\{[\s\S]*?approvalLogs: item\.approvalLogs \|\| \[\],[\s\S]*?\}\);/,
`return delay(${mapFn}({\n\t\ttradeInfo: buildTradeFields(item),\n\t\tdeclarationInfo: {\n\t\t\tabnormalType: item.abnormalType,\n\t\t\tremark: item.remark,\n\t\t\tcreatedBy: item.createdBy,\n\t\t\tcreatedDate: item.createdDate,\n\t\t\tvoucherImageUrls: item.voucherImageUrls,\n\t\t},\n\t\tapprovalLogs: item.approvalLogs || [],\n\t}));`,
);
}
if (plan.binding?.functionName === "approvePcAbnormalFlowDeclaration") {
content = content.replace(
/return delay\(true\);/,
`return delay(${mapFn}(true));`,
);
}
if (dryRun) {
return { path: mockPath, status: "dry-run" };
}
fs.writeFileSync(mockPath, content, "utf8");
return { path: mockPath, status: "migrated" };
}
async function runImport(options = {}) {
const swaggerSource = options.swagger || DEFAULT_SWAGGER_SNAPSHOT;
const swaggerDoc = await loadSwagger(swaggerSource);
const plan = buildImportPlan({ ...options, swaggerDoc });
const writeOpts = { dryRun: !!options.dryRun, force: !!options.force };
const fileResults = [];
fileResults.push(writeFileSafe(
plan.files.contractJson,
`${JSON.stringify(plan.contract, null, 2)}\n`,
writeOpts,
));
fileResults.push(writeFileSafe(
plan.files.contractMd,
`${formatContractMarkdown(plan.contract)}\n`,
writeOpts,
));
fileResults.push(writeFileSafe(plan.files.params, plan.templates.params, writeOpts));
fileResults.push(writeFileSafe(plan.files.response, plan.templates.response, writeOpts));
const apiResult = migrateApiFile(plan.files.api, plan, writeOpts);
fileResults.push(apiResult);
const mockResult = migrateMockFile(plan, writeOpts);
fileResults.push(mockResult);
const report = {
method: plan.method,
summary: plan.contract.summary,
feature: plan.feature,
apiFile: plan.apiFileName,
existingFunction: plan.binding?.functionName || null,
requestParams: plan.contract.request.parameters
.filter((p) => p.name !== "sessionId")
.map((p) => ({ name: p.name, required: p.required, type: p.type })),
responseRoot: plan.contract.response.rootType,
pagination: !!plan.contract.response.pagination,
files: fileResults,
nextSteps: [
"npm run rop:contract:check",
plan.binding ? "页面 export 函数名未变,通常无需改 Vue" : "在 src/api 中补充 export 函数",
],
};
if (!options.dryRun) {
const reportPath = path.join(process.cwd(), "rop-import.report.json");
fs.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
report.reportPath = reportPath;
}
return report;
}
module.exports = {
extractMethodFromText,
inferFeatureName,
detectApiFile,
findExistingApiBinding,
buildImportPlan,
buildActionResponseTemplate,
getAdapterTemplates,
migrateApiFile,
migrateMockFile,
runImport,
SMARTCARLIFE_PREFIX,
API_DIR,
ADAPTERS_ROOT,
};