build-used-car-request-slim.mjs
7.85 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
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import {
copyFileSync,
existsSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const packageSpec = 'glsk-toolkit@1.0.5';
const expectedIntegrity =
'sha512-BUWYTM5NWzN0n2jho6b5nbTwfCiQHBz+Ce5DN6MmJi8pQxI+AXFqgD5DDY1BfRdXjAVsHXdyBauw1VJjFX3Tqw==';
const lockPath = path.join(projectRoot, 'scripts/used-car-request-slim.package-lock.json');
const outputPath = path.join(projectRoot, 'packageUsedCar/newRequestIndex.js');
const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const refreshLock = process.argv.includes('--refresh-lock');
function run(command, args, cwd) {
const result = spawnSync(command, args, {
cwd,
encoding: 'utf8',
shell: process.platform === 'win32' && command === npmCommand,
stdio: ['ignore', 'pipe', 'pipe'],
});
if (result.status !== 0) {
throw new Error(
`${command} ${args.join(' ')} failed\n${result.stdout || ''}\n${result.stderr || ''}`,
);
}
return result.stdout;
}
function readNormalized(filePath) {
return readFileSync(filePath, 'utf8').replace(/\r\n/g, '\n');
}
function replaceOnce(filePath, before, after) {
const source = readNormalized(filePath);
const first = source.indexOf(before);
assert.notEqual(first, -1, `missing source anchor in ${filePath}: ${before}`);
assert.equal(
source.indexOf(before, first + before.length),
-1,
`duplicate source anchor in ${filePath}: ${before}`,
);
writeFileSync(filePath, source.replace(before, after), 'utf8');
}
function removeSectionOnce(filePath, start, end) {
const source = readNormalized(filePath);
const startIndex = source.indexOf(start);
assert.notEqual(startIndex, -1, `missing section start in ${filePath}: ${start}`);
assert.equal(
source.indexOf(start, startIndex + start.length),
-1,
`duplicate section start in ${filePath}: ${start}`,
);
const endIndex = source.indexOf(end, startIndex + start.length);
assert.notEqual(endIndex, -1, `missing section end in ${filePath}: ${end}`);
writeFileSync(filePath, source.slice(0, startIndex) + source.slice(endIndex), 'utf8');
}
function collectFiles(directory) {
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const entryPath = path.join(directory, entry.name);
return entry.isDirectory() ? collectFiles(entryPath) : [entryPath];
});
}
const buildRoot = mkdtempSync(path.join(tmpdir(), 'glsk-toolkit-slim-'));
try {
const packOutput = run(
npmCommand,
['pack', packageSpec, '--json', '--pack-destination', buildRoot],
projectRoot,
);
const [packed] = JSON.parse(packOutput);
assert.equal(packed.integrity, expectedIntegrity, 'npm metadata integrity mismatch');
const tarballPath = path.join(buildRoot, packed.filename);
const actualIntegrity = `sha512-${createHash('sha512')
.update(readFileSync(tarballPath))
.digest('base64')}`;
assert.equal(actualIntegrity, expectedIntegrity, 'tarball integrity mismatch');
run('tar', ['-xf', tarballPath, '-C', buildRoot], projectRoot);
const sourceRoot = path.join(buildRoot, 'package');
const packageJsonPath = path.join(sourceRoot, 'package.json');
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
assert.equal(packageJson.dependencies['@sentry/browser'], '^7.101.1');
delete packageJson.dependencies['@sentry/browser'];
writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`, 'utf8');
const indexPath = path.join(sourceRoot, 'src/index.ts');
replaceOnce(indexPath, "import * as Sentry from './monitoring/sentry';\n", '');
replaceOnce(
indexPath,
'export { Request, Defaults, Sentry, simpleGet, generateUUID };',
'export { Request, Defaults, simpleGet, generateUUID };',
);
replaceOnce(
indexPath,
"export type { SentryOptions, ErrorReportOptions } from './monitoring/sentry';",
'',
);
const requestPath = path.join(sourceRoot, 'src/core/request.ts');
replaceOnce(requestPath, 'import { initSentry } from "../monitoring/sentry";\n', '');
replaceOnce(
requestPath,
' // 根据配置决定是否初始化 Sentry\n if (this.defaults.sentry.enable && this.defaults.sentry.dsn) {\n initSentry(this.defaults.sentry.dsn, this.defaults.sentry.options || {});\n }\n',
'',
);
const defaultsPath = path.join(sourceRoot, 'src/core/defaults.ts');
replaceOnce(
defaultsPath,
' // Sentry 配置\n sentry: {\n enable: boolean;\n dsn?: string;\n options?: Record<string, any>;\n };\n',
'',
);
replaceOnce(
defaultsPath,
' // 检查必填参数\n if (config.sentry?.enable && !config.sentry?.dsn) {\n throw new Error("sentry.dsn is required when sentry is enabled");\n }\n',
'',
);
replaceOnce(
defaultsPath,
' this.sentry = {\n enable: config.sentry?.enable ?? false,\n dsn: config.sentry?.dsn,\n options: config.sentry?.options || {},\n };\n',
'',
);
const libsIndexPath = path.join(sourceRoot, 'src/libs/index.ts');
replaceOnce(libsIndexPath, "import * as Sentry from './sentry-miniapp'\n", '');
replaceOnce(libsIndexPath, 'export { Sentry, stringify }', 'export { stringify }');
const errorPath = path.join(sourceRoot, 'src/utils/error.ts');
replaceOnce(errorPath, "import { reportNetworkError } from '../monitoring/sentry';\n\n", '');
replaceOnce(
errorPath,
' // 如果配置中包含 sentry.dsn,则上报错误到 Sentry\n if (config && config.sentry?.dsn) {\n this.reportToSentry();\n }\n',
'',
);
removeSectionOnce(
errorPath,
' /**\n * 将错误上报到 Sentry\n',
' /**\n * 创建网络错误\n',
);
const typesPath = path.join(sourceRoot, 'src/types/index.d.ts');
removeSectionOnce(
typesPath,
'export interface SentryConfig {\n',
'export interface ResponseConfig {\n',
);
replaceOnce(
typesPath,
' sentry?: SentryConfig; // Sentry配置,包含错误上报开关、DSN和选项\n',
'',
);
for (const relativePath of [
'src/monitoring/sentry.ts',
'src/libs/sentry-miniapp.js',
'src/libs/sentry-miniapp.d.ts',
]) {
const sentrySourcePath = path.join(sourceRoot, relativePath);
assert.ok(existsSync(sentrySourcePath), `missing Sentry source: ${relativePath}`);
rmSync(sentrySourcePath);
}
const sentryResidues = [packageJsonPath, ...collectFiles(path.join(sourceRoot, 'src'))]
.filter((filePath) => /sentry/i.test(readFileSync(filePath, 'utf8')))
.map((filePath) => path.relative(sourceRoot, filePath));
assert.deepEqual(sentryResidues, [], `Sentry source residues: ${sentryResidues.join(', ')}`);
if (refreshLock) {
run(
npmCommand,
['install', '--package-lock-only', '--ignore-scripts', '--no-audit', '--no-fund'],
sourceRoot,
);
copyFileSync(path.join(sourceRoot, 'package-lock.json'), lockPath);
}
assert.ok(existsSync(lockPath), 'dedicated build lock is missing; run with --refresh-lock once');
copyFileSync(lockPath, path.join(sourceRoot, 'package-lock.json'));
run(npmCommand, ['ci', '--ignore-scripts', '--no-audit', '--no-fund'], sourceRoot);
run(npmCommand, ['run', 'build'], sourceRoot);
const generatedPath = path.join(sourceRoot, 'dist/index.js');
const generated = readFileSync(generatedPath, 'utf8');
assert.doesNotMatch(generated, /sentry/i, 'generated bundle still contains Sentry');
copyFileSync(generatedPath, outputPath);
console.log(
`[build-used-car-request-slim] wrote ${Buffer.byteLength(generated)} bytes to ${path.relative(
projectRoot,
outputPath,
)}`,
);
} finally {
rmSync(buildRoot, { recursive: true, force: true });
}