@anizoptera/publish-clean 0.7.3 → 0.8.0
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/README.md +54 -66
- package/dist/cli.js +597 -370
- package/package.json +4 -2
package/dist/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
-
// @anizoptera/publish-clean 0.
|
|
3
|
+
// @anizoptera/publish-clean 0.8.0 | https://github.com/Anizoptera/publish-clean#readme
|
|
4
4
|
import { readFileSync } from "node:fs";
|
|
5
5
|
import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
6
6
|
import { tmpdir } from "node:os";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
9
10
|
import { parseArgs } from "node:util";
|
|
10
|
-
import { execFileSync } from "node:child_process";
|
|
11
11
|
import { gunzipSync, gzipSync } from "node:zlib";
|
|
12
12
|
|
|
13
13
|
//#region src/error.ts
|
|
@@ -36,18 +36,6 @@ function isObject(value) {
|
|
|
36
36
|
function stringifyJson(value) {
|
|
37
37
|
return `${JSON.stringify(value, null, 2)}\n`;
|
|
38
38
|
}
|
|
39
|
-
/**
|
|
40
|
-
* The form used only to compare two manifests for equality. Key order carries no meaning to a
|
|
41
|
-
* consumer, so comparing the written form would report a difference where none exists.
|
|
42
|
-
*/
|
|
43
|
-
function stableJson(value) {
|
|
44
|
-
return JSON.stringify(stableValue(value));
|
|
45
|
-
}
|
|
46
|
-
function stableValue(value) {
|
|
47
|
-
if (Array.isArray(value)) return value.map(stableValue);
|
|
48
|
-
if (!isObject(value)) return value;
|
|
49
|
-
return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, stableValue(child)]));
|
|
50
|
-
}
|
|
51
39
|
|
|
52
40
|
//#endregion
|
|
53
41
|
//#region src/artifact.ts
|
|
@@ -90,10 +78,10 @@ const SUSPICIOUS_PATTERNS = [
|
|
|
90
78
|
];
|
|
91
79
|
function validatePackedFiles(files, skipSuspicious) {
|
|
92
80
|
const critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
|
|
93
|
-
if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
|
|
81
|
+
if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.map((file) => JSON.stringify(file)).join("\n")}`);
|
|
94
82
|
if (skipSuspicious) return;
|
|
95
83
|
const suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
|
|
96
|
-
if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
|
|
84
|
+
if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.map((file) => JSON.stringify(file)).join("\n")}`);
|
|
97
85
|
}
|
|
98
86
|
/**
|
|
99
87
|
* Refuses a rewritten tarball whose file set is not the packed one, entry for entry.
|
|
@@ -125,13 +113,13 @@ function assertSameEntries(packed, published) {
|
|
|
125
113
|
*
|
|
126
114
|
* - `"every-string"` for `main`, `module`, `types`, `typings`, `bin` and `typesVersions`,
|
|
127
115
|
* where every string is a path into this package.
|
|
128
|
-
* - `"relative-only"` for `
|
|
116
|
+
* - `"relative-only"` for `sideEffects` and the object form of
|
|
129
117
|
* `browser`, where a string may just as well be an external package name, a condition
|
|
130
118
|
* target or a glob. Only a `./` or `../` prefix marks it as a path here. Collecting the
|
|
131
119
|
* rest would report a missing file for something that was never a file.
|
|
132
120
|
*
|
|
133
121
|
* Booleans are skipped rather than ignored by accident: `sideEffects: false` and
|
|
134
|
-
* `
|
|
122
|
+
* `browser` replacements legitimately hold them. Export/import targets use their own walker.
|
|
135
123
|
*/
|
|
136
124
|
function collectDeclaredPaths(value, out, mode) {
|
|
137
125
|
if (typeof value === "string") {
|
|
@@ -153,39 +141,139 @@ function normalizeDeclaredPath(declared) {
|
|
|
153
141
|
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
|
|
154
142
|
return normalized;
|
|
155
143
|
}
|
|
156
|
-
/**
|
|
157
|
-
|
|
158
|
-
*
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
144
|
+
/** Node replaces every target star with the same subpath, including slashes. */
|
|
145
|
+
function matchesTarget(file, pattern) {
|
|
146
|
+
const parts = pattern.split("*");
|
|
147
|
+
const count = parts.length - 1;
|
|
148
|
+
if (count === 0) return file === pattern;
|
|
149
|
+
const size = (file.length - parts.reduce((sum, part) => sum + part.length, 0)) / count;
|
|
150
|
+
if (!Number.isInteger(size) || size < 0) return false;
|
|
151
|
+
const start = parts[0]?.length ?? 0;
|
|
152
|
+
return parts.join(file.slice(start, start + size)) === file;
|
|
153
|
+
}
|
|
154
|
+
/** Arrays skip invalid targets, but package-configuration errors must escape the fallback. */
|
|
155
|
+
var InvalidPackageTarget = class extends PublishCleanError {};
|
|
156
|
+
/** Export targets are URLs, unlike legacy main/bin paths; normalization must not hide invalid segments. */
|
|
157
|
+
function targetPath(target) {
|
|
158
|
+
if (!target.startsWith("./") || /%2f|%5c/i.test(target)) throw new InvalidPackageTarget(`Manifest declares invalid package paths: ${JSON.stringify(target)}`);
|
|
159
|
+
try {
|
|
160
|
+
if (decodeURIComponent(target.split(/[?#]/, 1)[0] ?? "").slice(2).split(/[\\/]/).some((segment) => [
|
|
161
|
+
".",
|
|
162
|
+
"..",
|
|
163
|
+
"node_modules"
|
|
164
|
+
].includes(segment.toLowerCase()))) throw new Error("Invalid target segment");
|
|
165
|
+
return decodeURIComponent(new URL(target, "file:///package/").pathname).slice(9);
|
|
166
|
+
} catch (cause) {
|
|
167
|
+
throw new InvalidPackageTarget(`Manifest declares invalid package paths: ${JSON.stringify(target)}`, { cause });
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/** True selects a target, null blocks a condition, undefined leaves later conditions reachable. */
|
|
171
|
+
function collectTargets(value, imports, pattern, out) {
|
|
172
|
+
if (value === null) return null;
|
|
173
|
+
if (typeof value === "string") {
|
|
174
|
+
if (imports && !value.startsWith(".") && !value.startsWith("/")) return true;
|
|
175
|
+
out.push({
|
|
176
|
+
name: targetPath(value),
|
|
177
|
+
kind: "target",
|
|
178
|
+
pattern
|
|
179
|
+
});
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
if (Array.isArray(value)) {
|
|
183
|
+
if (value.length === 0) return null;
|
|
184
|
+
let invalid;
|
|
185
|
+
for (const item of value) try {
|
|
186
|
+
const result = collectTargets(item, imports, pattern, out);
|
|
187
|
+
if (result === true) return true;
|
|
188
|
+
if (result === null) invalid = null;
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (!(error instanceof InvalidPackageTarget)) throw error;
|
|
191
|
+
invalid = error;
|
|
192
|
+
}
|
|
193
|
+
if (invalid) throw invalid;
|
|
194
|
+
return invalid;
|
|
195
|
+
}
|
|
196
|
+
if (!isObject(value)) throw new InvalidPackageTarget("Invalid exports/imports target; expected a path, condition object, array or null.");
|
|
197
|
+
const conditions = Object.entries(value);
|
|
198
|
+
for (const [condition] of conditions) {
|
|
199
|
+
const number = Number(condition);
|
|
200
|
+
if (String(number) === condition && number >= 0 && number < 4294967295) throw new PublishCleanError(`Invalid export condition: ${JSON.stringify(condition)}.`);
|
|
201
|
+
}
|
|
202
|
+
for (const [condition, item] of conditions) {
|
|
203
|
+
const definite = collectTargets(item, imports, pattern, out);
|
|
204
|
+
if (condition === "default" && definite !== void 0) return definite;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function collectMap(value, imports, out) {
|
|
208
|
+
if (value === void 0 || value === null) return;
|
|
209
|
+
if (imports && !isObject(value)) throw new PublishCleanError("imports must be a subpath map.");
|
|
210
|
+
if (!(isObject(value) && (imports || Object.keys(value).some((key) => key.startsWith("."))))) {
|
|
211
|
+
collectTargets(value, imports, false, out);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
for (const [key, target] of Object.entries(value)) {
|
|
215
|
+
if (imports ? !key.startsWith("#") || key === "#" || key.startsWith("#/") : key !== "." && !key.startsWith("./")) throw new PublishCleanError(`Invalid exports/imports key: ${JSON.stringify(key)}.`);
|
|
216
|
+
collectTargets(target, imports, key.includes("*"), out);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/** A CommonJS main tries file extensions and index files, not a nested package's main. */
|
|
220
|
+
function mainExists(name, files) {
|
|
221
|
+
const file = (target) => [
|
|
222
|
+
"",
|
|
223
|
+
".js",
|
|
224
|
+
".json",
|
|
225
|
+
".node"
|
|
226
|
+
].some((ext) => files.has(target + ext));
|
|
227
|
+
if (file(name)) return true;
|
|
228
|
+
const prefix = name ? `${name}/` : "";
|
|
229
|
+
return [
|
|
230
|
+
".js",
|
|
231
|
+
".json",
|
|
232
|
+
".node"
|
|
233
|
+
].some((extension) => files.has(`${prefix}index${extension}`));
|
|
234
|
+
}
|
|
235
|
+
/** Validate declared files using each field's consumer semantics, without extracting the archive. */
|
|
163
236
|
function assertDeclaredFiles(pkg, published) {
|
|
164
237
|
const declared = [];
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
238
|
+
const collect = (value, kind, mode = "every-string", patterns = false) => {
|
|
239
|
+
const names = [];
|
|
240
|
+
collectDeclaredPaths(value, names, mode);
|
|
241
|
+
declared.push(...names.map((name) => ({
|
|
242
|
+
name,
|
|
243
|
+
kind,
|
|
244
|
+
pattern: patterns && name.includes("*")
|
|
245
|
+
})));
|
|
246
|
+
};
|
|
247
|
+
collect(pkg.main, "main");
|
|
248
|
+
for (const field of ["types", "typings"]) collect(pkg[field], "types");
|
|
249
|
+
collect(pkg.typesVersions, "types", "every-string", true);
|
|
250
|
+
for (const field of ["module", "bin"]) collect(pkg[field], "file");
|
|
251
|
+
collect(pkg.browser, "file", typeof pkg.browser === "string" ? "every-string" : "relative-only");
|
|
252
|
+
collect(pkg.sideEffects, "glob", "relative-only");
|
|
253
|
+
collectMap(pkg.exports, false, declared);
|
|
254
|
+
collectMap(pkg.imports, true, declared);
|
|
255
|
+
const files = new Set(published);
|
|
256
|
+
const missing = [];
|
|
257
|
+
for (const item of declared) {
|
|
258
|
+
if (item.kind === "glob" && /[*?[\]{}]/.test(item.name)) continue;
|
|
259
|
+
const name = item.kind === "main" && [
|
|
260
|
+
"",
|
|
261
|
+
".",
|
|
262
|
+
"./"
|
|
263
|
+
].includes(item.name) ? "" : normalizeDeclaredPath(item.name);
|
|
264
|
+
if (name === null) throw new PublishCleanError(`Manifest declares invalid package paths: ${JSON.stringify(item.name)}`);
|
|
265
|
+
let found = files.has(name);
|
|
266
|
+
if (!found && item.pattern) found = published.some((file) => matchesTarget(file, name));
|
|
267
|
+
else if (!found && item.kind === "main") found = mainExists(name.replace(/\/$/, ""), files);
|
|
268
|
+
else if (!found && item.kind === "types") found = [
|
|
269
|
+
".d.ts",
|
|
270
|
+
".d.mts",
|
|
271
|
+
".d.cts",
|
|
272
|
+
"/index.d.ts"
|
|
273
|
+
].some((suffix) => files.has(name + suffix));
|
|
274
|
+
if (!found) missing.push(item.name);
|
|
275
|
+
}
|
|
276
|
+
if (missing.length) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((name) => JSON.stringify(name)).join("\n")}`);
|
|
189
277
|
}
|
|
190
278
|
|
|
191
279
|
//#endregion
|
|
@@ -198,12 +286,7 @@ function assertDeclaredFiles(pkg, published) {
|
|
|
198
286
|
* arguments a caller wrote after `--` straight into `npm publish`, so that vector is
|
|
199
287
|
* attacker-shaped by design. Every spawn here passes an argument vector, never a command line.
|
|
200
288
|
*/
|
|
201
|
-
/**
|
|
202
|
-
* The probe below is bounded because a wedged shim would otherwise hang the publish with no
|
|
203
|
-
* end: `execFileSync` blocks this thread, so no timer here could ever interrupt it. The bound
|
|
204
|
-
* belongs on the spawn itself. It stays generous because the only job is to separate a tool
|
|
205
|
-
* that answers from one that never will.
|
|
206
|
-
*/
|
|
289
|
+
/** Bound a hung version-manager shim without blocking the event loop. */
|
|
207
290
|
const TOOL_PROBE_TIMEOUT_MS = 1e4;
|
|
208
291
|
/**
|
|
209
292
|
* Windows cannot launch `pnpm` or `npm` directly: both are `.cmd` shims there, and Node's own
|
|
@@ -219,8 +302,8 @@ const TOOL_PROBE_TIMEOUT_MS = 1e4;
|
|
|
219
302
|
*/
|
|
220
303
|
function spawnArgs(command, args, platform) {
|
|
221
304
|
if (platform !== "win32") return [command, [...args]];
|
|
222
|
-
const unsafe = [command, ...args].filter((argument) => /[&|<>^%()]/.test(argument));
|
|
223
|
-
if (unsafe.length > 0) throw new PublishCleanError(`On Windows these arguments cannot be passed safely, because cmd.exe would interpret them:\n${unsafe.join("\n")}\
|
|
305
|
+
const unsafe = [command, ...args].filter((argument) => /[&|<>^%()\r\n]/.test(argument));
|
|
306
|
+
if (unsafe.length > 0) throw new PublishCleanError(`On Windows these arguments cannot be passed safely, because cmd.exe would interpret them:\n${unsafe.map((argument) => JSON.stringify(argument)).join("\n")}\nUse arguments without & | < > ^ % ( ) or line breaks, or publish from Linux or macOS.`);
|
|
224
307
|
return ["cmd.exe", [
|
|
225
308
|
"/d",
|
|
226
309
|
"/c",
|
|
@@ -228,74 +311,110 @@ function spawnArgs(command, args, platform) {
|
|
|
228
311
|
...args
|
|
229
312
|
]];
|
|
230
313
|
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
}
|
|
242
|
-
/**
|
|
243
|
-
* Runs a command with its streams attached to this process instead of captured.
|
|
244
|
-
*
|
|
245
|
-
* Reserved for `npm publish`. Every other command here is run for its output or its
|
|
246
|
-
* effect, but the publish is the one irreversible step, and npm's output is the only
|
|
247
|
-
* receipt the operator gets: the version that went out, the tarball size, the integrity
|
|
248
|
-
* hash, and the registry's own wording when it refuses. `run` would swallow all of it on
|
|
249
|
-
* success and hold the failure text until the process exits, which in CI means a log
|
|
250
|
-
* that says nothing about the one action that cannot be undone.
|
|
251
|
-
*/
|
|
252
|
-
function runAttached(command, args, cwd) {
|
|
253
|
-
execFileSync(...spawnArgs(command, args, process.platform), {
|
|
254
|
-
cwd,
|
|
255
|
-
stdio: [
|
|
256
|
-
"ignore",
|
|
257
|
-
"inherit",
|
|
258
|
-
"inherit"
|
|
259
|
-
]
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
/** Child output survives only on the thrown error, and is lost unless read off it here. */
|
|
263
|
-
function outputFromError(error, key) {
|
|
264
|
-
if (!isObject(error)) return "";
|
|
265
|
-
const output = error[key];
|
|
266
|
-
if (typeof output === "string") return output.trim();
|
|
267
|
-
if (output instanceof Uint8Array) return Buffer.from(output).toString("utf8").trim();
|
|
268
|
-
return "";
|
|
269
|
-
}
|
|
270
|
-
/**
|
|
271
|
-
* A required tool can fail three ways, and each one asks something different of the
|
|
272
|
-
* reader, so the probe reports what it observed instead of assuming the common case.
|
|
273
|
-
* A version-manager shim (asdf, mise, volta, corepack) resolves in PATH and still refuses
|
|
274
|
-
* to run when no version is pinned; calling that absence sends the reader to verify the
|
|
275
|
-
* one thing already correct, and `which pnpm` then agrees with them and not with us. The
|
|
276
|
-
* shim's own message names the fix, so it is forwarded rather than replaced.
|
|
277
|
-
*/
|
|
278
|
-
function toolFailureReason(cause) {
|
|
279
|
-
if (isObject(cause)) {
|
|
280
|
-
if (cause.code === "ENOENT") return "is not available in PATH";
|
|
281
|
-
if (cause.code === "ETIMEDOUT") return `did not answer --version within ${TOOL_PROBE_TIMEOUT_MS}ms`;
|
|
282
|
-
}
|
|
283
|
-
const stderr = outputFromError(cause, "stderr");
|
|
284
|
-
return `failed to run${stderr ? `: ${stderr}` : ""}`;
|
|
285
|
-
}
|
|
286
|
-
function requireTool(name) {
|
|
287
|
-
try {
|
|
288
|
-
execFileSync(...spawnArgs(name, ["--version"], process.platform), {
|
|
289
|
-
stdio: [
|
|
290
|
-
"ignore",
|
|
314
|
+
/** Await child settlement before returning, so temporary files cannot be removed under a live packer. */
|
|
315
|
+
function run(command, args, cwd, options = {}) {
|
|
316
|
+
options.signal?.throwIfAborted();
|
|
317
|
+
const output = options.output ?? "capture";
|
|
318
|
+
const detached = process.platform !== "win32" && output !== "publish";
|
|
319
|
+
return new Promise((resolve, reject) => {
|
|
320
|
+
const child = spawn(...spawnArgs(command, args, process.platform), {
|
|
321
|
+
cwd,
|
|
322
|
+
detached,
|
|
323
|
+
stdio: output === "capture" ? [
|
|
291
324
|
"ignore",
|
|
325
|
+
"pipe",
|
|
292
326
|
"pipe"
|
|
293
|
-
]
|
|
294
|
-
|
|
327
|
+
] : output === "pack" ? [
|
|
328
|
+
"ignore",
|
|
329
|
+
process.stderr,
|
|
330
|
+
process.stderr
|
|
331
|
+
] : "inherit"
|
|
295
332
|
});
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
333
|
+
let stdout = "";
|
|
334
|
+
let stderr = "";
|
|
335
|
+
let failure;
|
|
336
|
+
let escalation;
|
|
337
|
+
let stopping = false;
|
|
338
|
+
let termination;
|
|
339
|
+
const killGroup = (signal) => {
|
|
340
|
+
try {
|
|
341
|
+
if (child.pid !== void 0) {
|
|
342
|
+
if (detached) process.kill(-child.pid, signal);
|
|
343
|
+
else child.kill(signal);
|
|
344
|
+
}
|
|
345
|
+
} catch (error) {
|
|
346
|
+
if (!isObject(error) || error.code !== "ESRCH") failure = error instanceof Error ? error : new Error(String(error));
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
const stop = () => {
|
|
350
|
+
if (stopping || child.pid === void 0) return;
|
|
351
|
+
stopping = true;
|
|
352
|
+
if (process.platform === "win32") termination = new Promise((done) => {
|
|
353
|
+
const killer = spawn("taskkill", [
|
|
354
|
+
"/pid",
|
|
355
|
+
String(child.pid),
|
|
356
|
+
"/t",
|
|
357
|
+
"/f"
|
|
358
|
+
], { stdio: "ignore" });
|
|
359
|
+
killer.on("error", (error) => {
|
|
360
|
+
failure = error;
|
|
361
|
+
child.kill();
|
|
362
|
+
});
|
|
363
|
+
killer.once("close", (status) => {
|
|
364
|
+
if (status !== 0 && !failure) failure = new PublishCleanError("Unable to terminate the child process tree.");
|
|
365
|
+
done();
|
|
366
|
+
});
|
|
367
|
+
});
|
|
368
|
+
else {
|
|
369
|
+
killGroup("SIGTERM");
|
|
370
|
+
escalation = setTimeout(() => killGroup("SIGKILL"), 1e3);
|
|
371
|
+
escalation.unref();
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
const timer = options.timeout === void 0 ? void 0 : setTimeout(() => {
|
|
375
|
+
failure = new PublishCleanError(`${command} did not finish within ${options.timeout}ms.`);
|
|
376
|
+
stop();
|
|
377
|
+
}, options.timeout);
|
|
378
|
+
const collect = (chunk, stream) => {
|
|
379
|
+
if (stream === "stdout") stdout += chunk.toString();
|
|
380
|
+
else stderr += chunk.toString();
|
|
381
|
+
if (stdout.length + stderr.length > 1048576) {
|
|
382
|
+
failure = new PublishCleanError(`${command} exceeded the output limit for a metadata query.`);
|
|
383
|
+
stdout = stdout.slice(-4096);
|
|
384
|
+
stderr = stderr.slice(-4096);
|
|
385
|
+
stop();
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
child.stdout?.on("data", (chunk) => collect(chunk, "stdout"));
|
|
389
|
+
child.stderr?.on("data", (chunk) => collect(chunk, "stderr"));
|
|
390
|
+
child.on("error", (error) => {
|
|
391
|
+
failure = error;
|
|
392
|
+
});
|
|
393
|
+
options.signal?.addEventListener("abort", stop, { once: true });
|
|
394
|
+
child.once("close", async (status, signal) => {
|
|
395
|
+
if (stopping && process.platform !== "win32") killGroup("SIGKILL");
|
|
396
|
+
await termination;
|
|
397
|
+
clearTimeout(timer);
|
|
398
|
+
clearTimeout(escalation);
|
|
399
|
+
options.signal?.removeEventListener("abort", stop);
|
|
400
|
+
if (options.signal?.aborted) {
|
|
401
|
+
reject(options.signal.reason);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (failure || status !== 0) {
|
|
405
|
+
const reason = failure && isObject(failure) && failure.code === "ENOENT" ? "is not available in PATH" : failure?.message ?? `exited with ${signal ?? status}`;
|
|
406
|
+
reject(new PublishCleanError(`${command} ${reason}${stderr.trim() ? `: ${stderr.trim()}` : ""}`, { cause: failure }));
|
|
407
|
+
} else resolve(stdout);
|
|
408
|
+
});
|
|
409
|
+
if (options.signal?.aborted) stop();
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
/** Probe in the package directory: version-manager shims resolve their toolchain from cwd. */
|
|
413
|
+
async function requireTool(name, cwd, signal) {
|
|
414
|
+
return (await run(name, ["--version"], cwd, {
|
|
415
|
+
signal,
|
|
416
|
+
timeout: TOOL_PROBE_TIMEOUT_MS
|
|
417
|
+
})).trim();
|
|
299
418
|
}
|
|
300
419
|
|
|
301
420
|
//#endregion
|
|
@@ -375,6 +494,17 @@ const MONOREPO_PROTOCOLS = [
|
|
|
375
494
|
* platform gating, so `devFields` is not allowed to name them.
|
|
376
495
|
*/
|
|
377
496
|
const RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
|
|
497
|
+
"config",
|
|
498
|
+
"deno",
|
|
499
|
+
"directories",
|
|
500
|
+
"jsdelivr",
|
|
501
|
+
"man",
|
|
502
|
+
"react-native",
|
|
503
|
+
"sass",
|
|
504
|
+
"style",
|
|
505
|
+
"styleModule",
|
|
506
|
+
"svelte",
|
|
507
|
+
"unpkg",
|
|
378
508
|
...DEP_FIELDS,
|
|
379
509
|
"bin",
|
|
380
510
|
"browser",
|
|
@@ -399,39 +529,20 @@ const RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
|
|
|
399
529
|
"typings",
|
|
400
530
|
"version"
|
|
401
531
|
]);
|
|
402
|
-
/**
|
|
403
|
-
* Fields npm's registry, website and CLI read, plus the de-facto entry points bundlers
|
|
404
|
-
* and CDNs look for. Recognised, so they raise no report, but a maintainer may legitimately
|
|
405
|
-
* strip any of them through `devFields`: none is load-bearing for an install.
|
|
406
|
-
*
|
|
407
|
-
* Together with RUNTIME_MANIFEST_FIELDS this is the answer to "does anything downstream
|
|
408
|
-
* read this key?". Anything outside both sets is, as far as this tool can tell, project
|
|
409
|
-
* bookkeeping that a consumer downloads and never uses.
|
|
410
|
-
*/
|
|
532
|
+
/** Registry metadata is recognised; consumer-resolved fields are protected separately. */
|
|
411
533
|
const REGISTRY_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
|
|
412
534
|
"author",
|
|
413
535
|
"bugs",
|
|
414
|
-
"config",
|
|
415
536
|
"contributors",
|
|
416
|
-
"deno",
|
|
417
537
|
"description",
|
|
418
|
-
"directories",
|
|
419
538
|
"funding",
|
|
420
539
|
"gitHead",
|
|
421
540
|
"homepage",
|
|
422
|
-
"jsdelivr",
|
|
423
541
|
"keywords",
|
|
424
542
|
"maintainers",
|
|
425
|
-
"man",
|
|
426
543
|
"preferGlobal",
|
|
427
|
-
"react-native",
|
|
428
544
|
"repository",
|
|
429
|
-
"
|
|
430
|
-
"scripts",
|
|
431
|
-
"style",
|
|
432
|
-
"styleModule",
|
|
433
|
-
"svelte",
|
|
434
|
-
"unpkg"
|
|
545
|
+
"scripts"
|
|
435
546
|
]);
|
|
436
547
|
/**
|
|
437
548
|
* Shown when another package manager started this tool, so the pnpm requirement is not a
|
|
@@ -448,13 +559,29 @@ function stripManifest(pkg, extraDevFields) {
|
|
|
448
559
|
for (const field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
|
|
449
560
|
const scripts = isObject(pkg.scripts) ? pkg.scripts : null;
|
|
450
561
|
if (scripts) {
|
|
451
|
-
|
|
452
|
-
for (const [name, value] of Object.entries(scripts)) if (CONSUMER_SCRIPTS.has(name) && typeof value === "string") kept[name] = value;
|
|
453
|
-
if (Object.keys(kept).length > 0) stripped.scripts = kept;
|
|
562
|
+
if (Object.entries(scripts).some(([name, value]) => CONSUMER_SCRIPTS.has(name) && typeof value === "string")) stripped.scripts = scripts;
|
|
454
563
|
else delete stripped.scripts;
|
|
455
564
|
}
|
|
456
565
|
return stripped;
|
|
457
566
|
}
|
|
567
|
+
/** npm gives a scope registry priority over the general registry setting. */
|
|
568
|
+
function packageScope(pkg) {
|
|
569
|
+
if (typeof pkg.name !== "string" || !pkg.name.startsWith("@")) return null;
|
|
570
|
+
const slash = pkg.name.indexOf("/");
|
|
571
|
+
return slash > 1 ? pkg.name.slice(0, slash) : null;
|
|
572
|
+
}
|
|
573
|
+
/** A misspelled registry must fail locally rather than fall back to a public destination. */
|
|
574
|
+
function assertRegistry(value) {
|
|
575
|
+
if (typeof value !== "string" || !URL.canParse(value)) throw new PublishCleanError("Registry must be an absolute HTTP(S) URL.");
|
|
576
|
+
const url = new URL(value);
|
|
577
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new PublishCleanError("Registry must be an absolute HTTP(S) URL.");
|
|
578
|
+
if (url.username || url.password) throw new PublishCleanError("Registry URLs must not contain credentials. Configure npm authentication separately.");
|
|
579
|
+
}
|
|
580
|
+
/** Check every registry destination in the artifact without disclosing its credentials. */
|
|
581
|
+
function assertRegistryDestinations(pkg) {
|
|
582
|
+
if (!isObject(pkg.publishConfig)) return;
|
|
583
|
+
for (const [key, value] of Object.entries(pkg.publishConfig)) if (key === "registry" || key.endsWith(":registry")) assertRegistry(value);
|
|
584
|
+
}
|
|
458
585
|
/**
|
|
459
586
|
* Pins the published manifest to a registry, when one was chosen.
|
|
460
587
|
*
|
|
@@ -468,8 +595,11 @@ function stripManifest(pkg, extraDevFields) {
|
|
|
468
595
|
*/
|
|
469
596
|
function withRegistry(pkg, registry) {
|
|
470
597
|
if (registry === null) return pkg;
|
|
598
|
+
assertRegistry(registry);
|
|
471
599
|
const publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
|
|
472
600
|
publishConfig.registry = registry;
|
|
601
|
+
const scope = packageScope(pkg);
|
|
602
|
+
if (scope) publishConfig[`${scope}:registry`] = registry;
|
|
473
603
|
return {
|
|
474
604
|
...pkg,
|
|
475
605
|
publishConfig
|
|
@@ -488,9 +618,8 @@ function withRegistry(pkg, registry) {
|
|
|
488
618
|
* introduced while rewriting the archive is caught as well as one introduced by stripping.
|
|
489
619
|
*
|
|
490
620
|
* `devFields` entries are exempt: removing those was the request. `scripts` is exempt
|
|
491
|
-
* because
|
|
492
|
-
*
|
|
493
|
-
* none.
|
|
621
|
+
* because its entire block survives when consumer lifecycle hooks exist, and otherwise
|
|
622
|
+
* the development-only block is removed.
|
|
494
623
|
*/
|
|
495
624
|
function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
|
|
496
625
|
const expected = /* @__PURE__ */ new Set([
|
|
@@ -520,7 +649,9 @@ function unrecognizedFieldsReport(pkg, kept) {
|
|
|
520
649
|
const acknowledged = new Set(kept);
|
|
521
650
|
const unrecognized = Object.keys(pkg).filter((field) => !RUNTIME_MANIFEST_FIELDS.has(field) && !REGISTRY_MANIFEST_FIELDS.has(field) && !acknowledged.has(field));
|
|
522
651
|
if (unrecognized.length === 0) return null;
|
|
523
|
-
|
|
652
|
+
const quoted = unrecognized.map((field) => JSON.stringify(field));
|
|
653
|
+
const list = quoted.join(", ");
|
|
654
|
+
return `publish-clean: these manifest fields are not recognised and are retained as-is:\n ${quoted.join("\n ")}\nStrip the ones consumers do not read, and acknowledge the ones they do:\n "publish-clean": { "devFields": [${list}] }\n "publish-clean": { "keepFields": [${list}] }`;
|
|
524
655
|
}
|
|
525
656
|
/**
|
|
526
657
|
* Refuses a manifest that still carries a spec only a workspace can resolve. Published
|
|
@@ -531,14 +662,23 @@ function unrecognizedFieldsReport(pkg, kept) {
|
|
|
531
662
|
* absent by construction. They are still checked, because a guard whose correctness depends on
|
|
532
663
|
* the order it happens to be called in fails silently the day someone reorders it.
|
|
533
664
|
*/
|
|
534
|
-
function assertNoMonorepoProtocols(pkg) {
|
|
665
|
+
function assertNoMonorepoProtocols(pkg, files = []) {
|
|
535
666
|
const failures = [];
|
|
667
|
+
const shipped = new Set(files);
|
|
536
668
|
for (const field of DEP_FIELDS) {
|
|
537
669
|
const map = pkg[field];
|
|
538
670
|
if (!isObject(map)) continue;
|
|
539
671
|
for (const [name, spec] of Object.entries(map)) {
|
|
540
672
|
if (typeof spec !== "string") continue;
|
|
541
|
-
|
|
673
|
+
const resolved = spec.startsWith("npm:") ? spec.slice(spec.lastIndexOf("@") + 1) : spec;
|
|
674
|
+
if (MONOREPO_PROTOCOLS.some((prefix) => resolved.startsWith(prefix))) failures.push(`${field}.${name}: ${spec}`);
|
|
675
|
+
if (/^(?:file:|git\+file:|\.{1,2}(?:[\\/]|$)|\/|~[\\/]|[a-z]:[\\/])/i.test(spec)) {
|
|
676
|
+
let local = null;
|
|
677
|
+
try {
|
|
678
|
+
local = normalizeDeclaredPath(decodeURIComponent(spec.replace(/^file:/i, "")));
|
|
679
|
+
} catch {}
|
|
680
|
+
if (!local || /[\\]/.test(local) || /^(?:git\+file:|~[\\/]|(?:file:)?[a-z]:[\\/])/i.test(spec) || !(/\.(?:tgz|tar\.gz|tar)$/.test(local) && shipped.has(local) || shipped.has(`${local}/package.json`))) failures.push(`${field}.${name}: ${spec} (local target is not in the artifact)`);
|
|
681
|
+
}
|
|
542
682
|
}
|
|
543
683
|
}
|
|
544
684
|
if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
|
|
@@ -548,8 +688,11 @@ function assertPublicPackage(pkg) {
|
|
|
548
688
|
}
|
|
549
689
|
function assertFilesField(pkg, skip) {
|
|
550
690
|
if (skip) return;
|
|
551
|
-
if (!Array.isArray(pkg.files) || pkg.files.length === 0) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
|
|
691
|
+
if (!Array.isArray(pkg.files) || pkg.files.length === 0 || pkg.files.some((file) => typeof file !== "string" || !file.trim())) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array of non-empty strings.");
|
|
552
692
|
}
|
|
693
|
+
|
|
694
|
+
//#endregion
|
|
695
|
+
//#region src/config.ts
|
|
553
696
|
/**
|
|
554
697
|
* Every key this tool reads out of the manifest's `publish-clean` block. Naming them is what
|
|
555
698
|
* makes a typo an error instead of a silent no-op — and a silent no-op here is not cosmetic:
|
|
@@ -565,9 +708,18 @@ const CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
|
565
708
|
]);
|
|
566
709
|
function packageConfig(pkg) {
|
|
567
710
|
const config = pkg["publish-clean"];
|
|
568
|
-
if (
|
|
711
|
+
if (config === void 0) return {};
|
|
712
|
+
if (!isObject(config)) throw new PublishCleanError("\"publish-clean\" must be an object.");
|
|
569
713
|
const unknown = Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
|
|
570
714
|
if (unknown.length > 0) throw new PublishCleanError(`Unknown "publish-clean" manifest options:\n${unknown.join("\n")}\nValid options: ${[...CONFIG_KEYS].join(", ")}`);
|
|
715
|
+
for (const key of [
|
|
716
|
+
"allowSuspicious",
|
|
717
|
+
"noGitChecks",
|
|
718
|
+
"skipFileCheck"
|
|
719
|
+
]) if (config[key] !== void 0 && typeof config[key] !== "boolean") throw new PublishCleanError(`publish-clean.${key} must be a boolean.`);
|
|
720
|
+
if (config.registry !== void 0) assertRegistry(config.registry);
|
|
721
|
+
stringList(config, "devFields");
|
|
722
|
+
stringList(config, "keepFields");
|
|
571
723
|
return config;
|
|
572
724
|
}
|
|
573
725
|
/**
|
|
@@ -606,63 +758,172 @@ function keptFields(config) {
|
|
|
606
758
|
}
|
|
607
759
|
|
|
608
760
|
//#endregion
|
|
609
|
-
//#region src/
|
|
761
|
+
//#region src/options.ts
|
|
762
|
+
const PUBLISH_OPTIONS = /* @__PURE__ */ new Map([
|
|
763
|
+
["access", "string"],
|
|
764
|
+
["tag", "string"],
|
|
765
|
+
["otp", "string"],
|
|
766
|
+
["registry", "string"],
|
|
767
|
+
["provenance-file", "string"],
|
|
768
|
+
["provenance", "boolean"],
|
|
769
|
+
["dry-run", "boolean"],
|
|
770
|
+
["ignore-scripts", "boolean"],
|
|
771
|
+
["json", "boolean"],
|
|
772
|
+
["loglevel", "string"]
|
|
773
|
+
]);
|
|
774
|
+
/** npm reparses even equals-form values as flags; reject flag-shaped values before forwarding. */
|
|
775
|
+
function publicationArgs(args) {
|
|
776
|
+
const result = [];
|
|
777
|
+
for (let index = 0; index < args.length; index++) {
|
|
778
|
+
const arg = args[index] ?? "";
|
|
779
|
+
const equal = arg.indexOf("=");
|
|
780
|
+
const flag = equal < 0 ? arg : arg.slice(0, equal);
|
|
781
|
+
const negative = flag.startsWith("--no-");
|
|
782
|
+
const name = flag.slice(negative ? 5 : 2);
|
|
783
|
+
const type = flag.startsWith("--") ? PUBLISH_OPTIONS.get(name) : void 0;
|
|
784
|
+
if (!type || negative && type !== "boolean") throw new PublishCleanError(`After --, use publication options only: ${[...PUBLISH_OPTIONS.keys()].join(", ")}. Package operands and workspace selectors are forbidden.`);
|
|
785
|
+
let value = equal < 0 ? void 0 : arg.slice(equal + 1);
|
|
786
|
+
if (value === void 0 && (type === "string" || args[index + 1] === "true" || args[index + 1] === "false")) value = args[++index];
|
|
787
|
+
if (type === "boolean") {
|
|
788
|
+
value ??= "true";
|
|
789
|
+
if (value !== "true" && value !== "false") throw new PublishCleanError(`--${name} requires true or false.`);
|
|
790
|
+
if (negative) value = value === "true" ? "false" : "true";
|
|
791
|
+
} else if (!value || value.startsWith("-")) throw new PublishCleanError(`--${name} requires a value that does not start with -. Use ./ for a filename starting with -.`);
|
|
792
|
+
if (name === "registry") assertRegistry(value);
|
|
793
|
+
result.push(`--${name}=${value}`);
|
|
794
|
+
}
|
|
795
|
+
return result;
|
|
796
|
+
}
|
|
610
797
|
/**
|
|
611
|
-
*
|
|
612
|
-
*
|
|
613
|
-
*
|
|
614
|
-
*
|
|
615
|
-
*
|
|
616
|
-
* re-derives it from the very field being cleaned and silently disagrees; rewriting the one
|
|
617
|
-
* member that changed keeps the first packer's selection, and its normalisation (uid/gid 0,
|
|
618
|
-
* a fixed mtime, mode 644) that a naive `tar` invocation leaks the build machine's identity
|
|
619
|
-
* into.
|
|
620
|
-
*
|
|
621
|
-
* Every entry other than the manifest is copied as opaque bytes and never decoded, so entry
|
|
622
|
-
* shapes this code does not model — pax extended headers, ustar prefix splitting — survive
|
|
623
|
-
* untouched. Only walking is universal: an entry's length is always its header block plus its
|
|
624
|
-
* size rounded up to a block, whatever the type.
|
|
625
|
-
*
|
|
626
|
-
* Reading here rather than through the `tar` binary is what makes the whole tool depend on
|
|
627
|
-
* nothing but Node: one archive is decompressed once and answers every question about it
|
|
628
|
-
* (file list, manifest bytes, rewrite), instead of one spawn and one decompression per
|
|
629
|
-
* question. It is also the stricter reader — `tar tzf` prints one name per line, so a path
|
|
630
|
-
* containing a newline arrives as two entries there and as itself here.
|
|
798
|
+
* The whole interface in one screen, because this is where an out-of-context reader lands:
|
|
799
|
+
* the flags, the manifest config block that sets the same policies durably, and the `--`
|
|
800
|
+
* convention that decides which arguments this tool reads and which npm does. Anything a
|
|
801
|
+
* user must know to publish correctly belongs here, not only in the README, which is not
|
|
802
|
+
* installed next to the binary.
|
|
631
803
|
*/
|
|
804
|
+
const HELP = `publish-clean [options] [package-dir] [-- npm publish args]
|
|
805
|
+
|
|
806
|
+
Packs with pnpm, strips developer-only fields from the packed manifest, validates the
|
|
807
|
+
artifact, and publishes that exact tarball with npm. Arguments after \`--\` go to
|
|
808
|
+
\`npm publish\` as publication options (e.g. --access public --tag next --provenance).
|
|
809
|
+
Allowed: ${[...PUBLISH_OPTIONS.keys()].map((name) => `--${name}`).join(", ")}.
|
|
810
|
+
Additional package operands and workspace selectors are rejected.
|
|
811
|
+
|
|
812
|
+
Options:
|
|
813
|
+
--dry-run Pack, clean and validate; print the file list and manifest, publish nothing.
|
|
814
|
+
--guard-only Validate a preview artifact; no file-list output or publish.
|
|
815
|
+
--tarball-out DIR Also write the validated tarball into DIR, for attestation or release upload.
|
|
816
|
+
--registry URL Publish to URL, and record it in the artifact's publishConfig.
|
|
817
|
+
--no-git-checks Publish from a working tree with uncommitted changes.
|
|
818
|
+
--skip-file-check Allow a manifest with no "files" array.
|
|
819
|
+
--allow-suspicious Allow tests, CI config, lockfiles or tsconfig in the published artifact.
|
|
820
|
+
-h, --help Show this help.
|
|
821
|
+
-v, --version Show the publish-clean version.
|
|
822
|
+
|
|
823
|
+
Manifest configuration, under a "publish-clean" key in package.json:
|
|
824
|
+
devFields string[] Extra fields to strip. Refused for fields consumers resolve.
|
|
825
|
+
keepFields string[] Fields to acknowledge, so they stop being reported as unrecognised.
|
|
826
|
+
registry string Default for --registry.
|
|
827
|
+
noGitChecks boolean Default for --no-git-checks.
|
|
828
|
+
skipFileCheck boolean Default for --skip-file-check.
|
|
829
|
+
allowSuspicious boolean Default for --allow-suspicious.
|
|
830
|
+
|
|
831
|
+
Preview modes do not test registry access, credentials or provenance eligibility.
|
|
832
|
+
Requires pnpm and npm on PATH. npm provenance additionally requires Node.js 22.14+ and
|
|
833
|
+
npm 11.5.1+, and only a cloud CI runner can produce it.`;
|
|
834
|
+
function parseOptions(rawArgs) {
|
|
835
|
+
const separator = rawArgs.indexOf("--");
|
|
836
|
+
const cliArgs = separator === -1 ? rawArgs : rawArgs.slice(0, separator);
|
|
837
|
+
const publishArgs = publicationArgs(separator === -1 ? [] : rawArgs.slice(separator + 1));
|
|
838
|
+
return {
|
|
839
|
+
...parseArgs({
|
|
840
|
+
args: cliArgs,
|
|
841
|
+
allowPositionals: true,
|
|
842
|
+
options: {
|
|
843
|
+
"allow-suspicious": {
|
|
844
|
+
type: "boolean",
|
|
845
|
+
default: false
|
|
846
|
+
},
|
|
847
|
+
"dry-run": {
|
|
848
|
+
type: "boolean",
|
|
849
|
+
default: false
|
|
850
|
+
},
|
|
851
|
+
"guard-only": {
|
|
852
|
+
type: "boolean",
|
|
853
|
+
default: false
|
|
854
|
+
},
|
|
855
|
+
help: {
|
|
856
|
+
type: "boolean",
|
|
857
|
+
short: "h",
|
|
858
|
+
default: false
|
|
859
|
+
},
|
|
860
|
+
"no-git-checks": {
|
|
861
|
+
type: "boolean",
|
|
862
|
+
default: false
|
|
863
|
+
},
|
|
864
|
+
registry: {
|
|
865
|
+
type: "string",
|
|
866
|
+
default: void 0
|
|
867
|
+
},
|
|
868
|
+
"skip-file-check": {
|
|
869
|
+
type: "boolean",
|
|
870
|
+
default: false
|
|
871
|
+
},
|
|
872
|
+
"tarball-out": {
|
|
873
|
+
type: "string",
|
|
874
|
+
default: void 0
|
|
875
|
+
},
|
|
876
|
+
version: {
|
|
877
|
+
type: "boolean",
|
|
878
|
+
short: "v",
|
|
879
|
+
default: false
|
|
880
|
+
}
|
|
881
|
+
},
|
|
882
|
+
strict: true
|
|
883
|
+
}),
|
|
884
|
+
publishArgs
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
//#endregion
|
|
889
|
+
//#region src/tarball.ts
|
|
890
|
+
/** Read effective archive paths and rewrite only the manifest, preserving every other raw entry. */
|
|
632
891
|
const BLOCK = 512;
|
|
633
892
|
const NAME_LEN = 100;
|
|
634
893
|
const SIZE_OFFSET = 124;
|
|
635
894
|
const CHECKSUM_OFFSET = 148;
|
|
636
895
|
const TYPE_OFFSET = 156;
|
|
637
|
-
/**
|
|
638
|
-
* The manifest is always at this exact path, and at 20 characters it can never be the entry
|
|
639
|
-
* that needs a pax header or a prefix split — so the one entry this code must identify is
|
|
640
|
-
* also the one whose name is guaranteed to be readable straight from the header block.
|
|
641
|
-
*/
|
|
642
896
|
const MANIFEST_PATH = "package/package.json";
|
|
643
|
-
/** Extended (`x`) and global (`g`) pax headers carry key/value overrides for other entries. */
|
|
644
897
|
const PAX_TYPES = /* @__PURE__ */ new Set(["x", "g"]);
|
|
645
|
-
/** Tar's flag for a directory entry. Directories are not files a consumer imports. */
|
|
646
898
|
const DIRECTORY_TYPE = "5";
|
|
647
|
-
|
|
648
|
-
* GNU's long-name entry, whose payload is the real path of the entry that follows it while
|
|
649
|
-
* that entry's own header reads `././@LongLink`.
|
|
650
|
-
*
|
|
651
|
-
* Refused for the same reason a pax `path=` override is: it renames the following entry, so it
|
|
652
|
-
* can point at `package/package.json` and the archive then extracts a manifest no guard here
|
|
653
|
-
* ever saw. pnpm emits pax and never this, so refusing costs nothing and closes the second way
|
|
654
|
-
* to rename an entry onto the one path this tool authors. `K` (long *link* name) is left alone:
|
|
655
|
-
* it renames a symlink target, which cannot collide with an entry path.
|
|
656
|
-
*/
|
|
657
|
-
const GNU_LONG_NAME = "L";
|
|
899
|
+
const UTF8 = new TextDecoder("utf-8", { fatal: true });
|
|
658
900
|
function field(block, offset, length) {
|
|
659
|
-
|
|
901
|
+
const bytes = block.subarray(offset, offset + length);
|
|
902
|
+
const nul = bytes.indexOf(0);
|
|
903
|
+
return UTF8.decode(nul < 0 ? bytes : bytes.subarray(0, nul));
|
|
660
904
|
}
|
|
661
905
|
function entrySize(block) {
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
906
|
+
const value = field(block, SIZE_OFFSET, 12).trim();
|
|
907
|
+
if (!/^[0-7]+$/.test(value)) throw new PublishCleanError("Tarball entry has an unreadable size field.");
|
|
908
|
+
return Number.parseInt(value, 8);
|
|
909
|
+
}
|
|
910
|
+
/** PAX lengths count bytes, including their own digits; values may contain newlines. */
|
|
911
|
+
function paxFields(payload) {
|
|
912
|
+
const fields = /* @__PURE__ */ new Map();
|
|
913
|
+
for (let offset = 0; offset < payload.length;) {
|
|
914
|
+
const space = payload.indexOf(32, offset);
|
|
915
|
+
const digits = payload.toString("ascii", offset, space < 0 ? offset : space);
|
|
916
|
+
const length = Number(digits);
|
|
917
|
+
const end = offset + length;
|
|
918
|
+
const equals = payload.indexOf(61, space + 1);
|
|
919
|
+
if (!/^[1-9][0-9]*$/.test(digits) || !Number.isSafeInteger(length) || end > payload.length || equals <= space + 1 || equals >= end - 1 || payload[end - 1] !== 10) throw new PublishCleanError("Tarball has a malformed PAX record.");
|
|
920
|
+
const key = UTF8.decode(payload.subarray(space + 1, equals));
|
|
921
|
+
const value = UTF8.decode(payload.subarray(equals + 1, end - 1));
|
|
922
|
+
if (key.includes("sparse") || key === "hdrcharset") throw new PublishCleanError(`Tarball uses unsupported PAX ${key}.`);
|
|
923
|
+
fields.set(key, value);
|
|
924
|
+
offset = end;
|
|
925
|
+
}
|
|
926
|
+
return fields;
|
|
666
927
|
}
|
|
667
928
|
/**
|
|
668
929
|
* Verifies a header block against the checksum tar stores inside it.
|
|
@@ -689,17 +950,6 @@ function assertChecksum(header, name) {
|
|
|
689
950
|
}
|
|
690
951
|
if (stored !== unsigned && stored !== signed) throw new PublishCleanError(`Tarball entry ${name} has a corrupt header checksum.`);
|
|
691
952
|
}
|
|
692
|
-
/**
|
|
693
|
-
* Rejects a pax header that renames another entry onto the manifest path.
|
|
694
|
-
*
|
|
695
|
-
* Without this the archive could extract a `package.json` that no check ever saw: the guards
|
|
696
|
-
* validate the entry rewritten here, while an extractor honours the pax override and writes
|
|
697
|
-
* a different one over it. The header's own name field is `PaxHeader`, so nothing about the
|
|
698
|
-
* substitution is visible from the walk alone.
|
|
699
|
-
*/
|
|
700
|
-
function assertNoManifestOverride(payload) {
|
|
701
|
-
for (const record of payload.toString("utf8").split("\n")) if (/^\d+ path=/.test(record) && record.slice(record.indexOf("=") + 1) === MANIFEST_PATH) throw new PublishCleanError(`Tarball contains a pax header renaming an entry to ${MANIFEST_PATH}.`);
|
|
702
|
-
}
|
|
703
953
|
/** Rebuilds a header for a changed payload size, keeping every other field of the original. */
|
|
704
954
|
function reheader(original, size) {
|
|
705
955
|
const header = Buffer.from(original);
|
|
@@ -723,26 +973,55 @@ function reheader(original, size) {
|
|
|
723
973
|
function readArchive(gzipped) {
|
|
724
974
|
const tar = gunzipSync(gzipped);
|
|
725
975
|
const entries = [];
|
|
976
|
+
const names = /* @__PURE__ */ new Set();
|
|
977
|
+
let local = null;
|
|
726
978
|
let tail = null;
|
|
727
979
|
for (let offset = 0; offset < tar.length;) {
|
|
728
980
|
const header = tar.subarray(offset, offset + BLOCK);
|
|
729
981
|
if (header.length < BLOCK) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
|
|
730
|
-
|
|
731
|
-
if (name === "") {
|
|
982
|
+
if (header.every((byte) => byte === 0)) {
|
|
732
983
|
tail = tar.subarray(offset);
|
|
984
|
+
if (tail.length < BLOCK * 2 || tail.length % BLOCK || tail.some((byte) => byte !== 0)) throw new PublishCleanError("Tarball has an invalid end-of-archive marker.");
|
|
733
985
|
break;
|
|
734
986
|
}
|
|
735
|
-
assertChecksum(header, name);
|
|
736
|
-
const size = entrySize(header);
|
|
737
|
-
const end = offset + BLOCK + BLOCK * Math.ceil(size / BLOCK);
|
|
738
|
-
if (end > tar.length) throw new PublishCleanError(`Tarball entry ${name} runs past the end of the archive.`);
|
|
739
987
|
const type = field(header, TYPE_OFFSET, 1);
|
|
988
|
+
const rawName = [field(header, 257, 6) === "ustar" ? field(header, 345, 155) : "", field(header, 0, NAME_LEN)].filter(Boolean).join("/");
|
|
989
|
+
assertChecksum(header, rawName);
|
|
990
|
+
const extended = PAX_TYPES.has(type);
|
|
991
|
+
const name = extended ? rawName : local?.get("path") || rawName;
|
|
992
|
+
let size = entrySize(header);
|
|
993
|
+
const sizeOverride = !extended && local?.get("size");
|
|
994
|
+
if (sizeOverride) {
|
|
995
|
+
if (!/^[0-9]+$/.test(sizeOverride) || !Number.isSafeInteger(Number(sizeOverride))) throw new PublishCleanError("Tarball has an invalid PAX size.");
|
|
996
|
+
size = Number(sizeOverride);
|
|
997
|
+
}
|
|
998
|
+
const end = offset + BLOCK + BLOCK * Math.ceil(size / BLOCK);
|
|
999
|
+
if (!Number.isSafeInteger(end) || end > tar.length) throw new PublishCleanError(`Tarball entry ${JSON.stringify(name)} runs past the end of the archive.`);
|
|
740
1000
|
const body = tar.subarray(offset + BLOCK, offset + BLOCK + size);
|
|
741
|
-
if (type ===
|
|
742
|
-
if (
|
|
743
|
-
|
|
744
|
-
if (
|
|
745
|
-
if (
|
|
1001
|
+
if (type === "L") throw new PublishCleanError("Tarball uses GNU long-name entries, which this tool refuses.");
|
|
1002
|
+
if (extended) {
|
|
1003
|
+
const fields = paxFields(body);
|
|
1004
|
+
if (fields.get("path") === MANIFEST_PATH) throw new PublishCleanError(`Tarball contains a pax header renaming an entry to ${MANIFEST_PATH}.`);
|
|
1005
|
+
if (type === "g") {
|
|
1006
|
+
if ([
|
|
1007
|
+
"path",
|
|
1008
|
+
"size",
|
|
1009
|
+
"linkpath"
|
|
1010
|
+
].some((key) => fields.has(key))) throw new PublishCleanError("Tarball has a global PAX path, linkpath or size override.");
|
|
1011
|
+
} else {
|
|
1012
|
+
if (local) throw new PublishCleanError("Tarball has consecutive PAX extended headers.");
|
|
1013
|
+
local = fields;
|
|
1014
|
+
}
|
|
1015
|
+
} else {
|
|
1016
|
+
if (name === MANIFEST_PATH) {
|
|
1017
|
+
if (type !== "0" && type !== "") throw new PublishCleanError(`${MANIFEST_PATH} is not a regular file in the tarball.`);
|
|
1018
|
+
if (sizeOverride) throw new PublishCleanError("Tarball manifest has a PAX size override that cannot survive rewriting.");
|
|
1019
|
+
}
|
|
1020
|
+
const parts = name.replace(/\/$/, "").split("/");
|
|
1021
|
+
if (parts[0] !== "package" || parts.some((part) => !part || part === "." || part === "..") || name.includes("\\") || name.includes("\0")) throw new PublishCleanError(`Tarball has an unsafe entry path: ${JSON.stringify(name)}.`);
|
|
1022
|
+
if (names.has(name)) throw new PublishCleanError(`Tarball contains ${JSON.stringify(name)} more than once.`);
|
|
1023
|
+
names.add(name);
|
|
1024
|
+
local = null;
|
|
746
1025
|
}
|
|
747
1026
|
entries.push({
|
|
748
1027
|
name,
|
|
@@ -754,11 +1033,20 @@ function readArchive(gzipped) {
|
|
|
754
1033
|
offset = end;
|
|
755
1034
|
}
|
|
756
1035
|
if (tail === null) throw new PublishCleanError("Tarball has no end-of-archive marker; the archive is truncated.");
|
|
1036
|
+
if (local) throw new PublishCleanError("Tarball ends with an unused PAX extended header.");
|
|
757
1037
|
return {
|
|
758
1038
|
entries,
|
|
759
1039
|
tail
|
|
760
1040
|
};
|
|
761
1041
|
}
|
|
1042
|
+
/** Check the final readback against the packed bytes, including entry order and metadata. */
|
|
1043
|
+
function assertPreservedArchive(before, after) {
|
|
1044
|
+
if (before.entries.length !== after.entries.length || !before.tail.equals(after.tail)) throw new PublishCleanError("Rewriting the manifest changed the archive structure.");
|
|
1045
|
+
for (const [index, original] of before.entries.entries()) {
|
|
1046
|
+
const result = after.entries[index];
|
|
1047
|
+
if (!result || original.name !== result.name || original.type !== result.type || (original.name === MANIFEST_PATH && !PAX_TYPES.has(original.type) ? !reheader(original.header, result.body.length).equals(result.header) : !original.raw.equals(result.raw))) throw new PublishCleanError(`Rewriting the manifest changed archive entry ${JSON.stringify(original.name)}.`);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
762
1050
|
/**
|
|
763
1051
|
* The paths a consumer's installer writes, with the `package/` prefix stripped — the list every
|
|
764
1052
|
* content guard judges. Directories and pax headers are dropped: neither is a file anyone
|
|
@@ -768,7 +1056,7 @@ function packageFiles(archive) {
|
|
|
768
1056
|
return archive.entries.filter((entry) => entry.type !== DIRECTORY_TYPE && !PAX_TYPES.has(entry.type)).map((entry) => entry.name.startsWith("package/") ? entry.name.slice(8) : entry.name).filter((name) => name.length > 0 && !name.endsWith("/")).sort();
|
|
769
1057
|
}
|
|
770
1058
|
function manifestEntry(archive) {
|
|
771
|
-
const entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH);
|
|
1059
|
+
const entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH && !PAX_TYPES.has(candidate.type));
|
|
772
1060
|
if (!entry) throw new PublishCleanError(`Tarball does not contain ${MANIFEST_PATH}.`);
|
|
773
1061
|
return entry;
|
|
774
1062
|
}
|
|
@@ -801,8 +1089,8 @@ function replaceManifest(archive, manifest) {
|
|
|
801
1089
|
* The floors npm's trusted publishing puts on the toolchain, each formatted into its own error
|
|
802
1090
|
* message so the version a reader is told to install is the version the comparison made.
|
|
803
1091
|
*
|
|
804
|
-
*
|
|
805
|
-
*
|
|
1092
|
+
* These floors apply to trusted publication; ordinary token-based publication can use the
|
|
1093
|
+
* lower Node floor declared by engines.node.
|
|
806
1094
|
*/
|
|
807
1095
|
const MIN_TRUSTED_NPM_VERSION = [
|
|
808
1096
|
11,
|
|
@@ -826,9 +1114,12 @@ function isAtLeast(actual, minimum) {
|
|
|
826
1114
|
return true;
|
|
827
1115
|
}
|
|
828
1116
|
function wantsTrustedPublish(pkg, publishArgs, env) {
|
|
829
|
-
if (
|
|
830
|
-
|
|
831
|
-
|
|
1117
|
+
if (env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL === "string") return true;
|
|
1118
|
+
for (let index = publishArgs.length - 1; index >= 0; index--) {
|
|
1119
|
+
if (publishArgs[index] === "--provenance=true" || publishArgs[index] === "--provenance") return true;
|
|
1120
|
+
if (publishArgs[index] === "--provenance=false") return false;
|
|
1121
|
+
}
|
|
1122
|
+
if (isObject(pkg.publishConfig) && pkg.publishConfig.provenance !== void 0) return Boolean(pkg.publishConfig.provenance);
|
|
832
1123
|
}
|
|
833
1124
|
function repositoryUrl(pkg) {
|
|
834
1125
|
if (typeof pkg.repository === "string") return pkg.repository;
|
|
@@ -850,8 +1141,7 @@ function githubRepositorySlug(url) {
|
|
|
850
1141
|
return null;
|
|
851
1142
|
}
|
|
852
1143
|
}
|
|
853
|
-
function assertRepositoryForTrustedPublish(pkg,
|
|
854
|
-
if (!wantsTrustedPublish(pkg, publishArgs, env)) return;
|
|
1144
|
+
function assertRepositoryForTrustedPublish(pkg, env) {
|
|
855
1145
|
if (env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY !== "string") return;
|
|
856
1146
|
const repoUrl = repositoryUrl(pkg);
|
|
857
1147
|
if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
|
|
@@ -861,40 +1151,6 @@ function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
|
|
|
861
1151
|
//#endregion
|
|
862
1152
|
//#region src/cli.ts
|
|
863
1153
|
/**
|
|
864
|
-
* The whole interface in one screen, because this is where an out-of-context reader lands:
|
|
865
|
-
* the flags, the manifest config block that sets the same policies durably, and the `--`
|
|
866
|
-
* convention that decides which arguments this tool reads and which npm does. Anything a
|
|
867
|
-
* user must know to publish correctly belongs here, not only in the README, which is not
|
|
868
|
-
* installed next to the binary.
|
|
869
|
-
*/
|
|
870
|
-
const HELP = `publish-clean [options] [package-dir] [-- npm publish args]
|
|
871
|
-
|
|
872
|
-
Packs with pnpm, strips developer-only fields from the packed manifest, validates the
|
|
873
|
-
artifact, and publishes that exact tarball with npm. Arguments after \`--\` go to
|
|
874
|
-
\`npm publish\` untouched (e.g. --access public --tag next --provenance).
|
|
875
|
-
|
|
876
|
-
Options:
|
|
877
|
-
--dry-run Pack, clean and validate; print the file list and manifest, publish nothing.
|
|
878
|
-
--guard-only Same checks, no output and no publish. For a pre-publish gate.
|
|
879
|
-
--tarball-out DIR Also write the validated tarball into DIR, for attestation or release upload.
|
|
880
|
-
--registry URL Publish to URL, and record it in the artifact's publishConfig.
|
|
881
|
-
--no-git-checks Publish from a working tree with uncommitted changes.
|
|
882
|
-
--skip-file-check Allow a manifest with no "files" array.
|
|
883
|
-
--allow-suspicious Allow tests, CI config, lockfiles or tsconfig in the published artifact.
|
|
884
|
-
-h, --help Show this help.
|
|
885
|
-
-v, --version Show the publish-clean version.
|
|
886
|
-
|
|
887
|
-
Manifest configuration, under a "publish-clean" key in package.json:
|
|
888
|
-
devFields string[] Extra fields to strip. Refused for fields consumers resolve.
|
|
889
|
-
keepFields string[] Fields to acknowledge, so they stop being reported as unrecognised.
|
|
890
|
-
registry string Default for --registry.
|
|
891
|
-
noGitChecks boolean Default for --no-git-checks.
|
|
892
|
-
skipFileCheck boolean Default for --skip-file-check.
|
|
893
|
-
allowSuspicious boolean Default for --allow-suspicious.
|
|
894
|
-
|
|
895
|
-
Requires pnpm and npm on PATH. npm provenance additionally requires Node.js 22.14+ and
|
|
896
|
-
npm 11.5.1+, and only a cloud CI runner can produce it.`;
|
|
897
|
-
/**
|
|
898
1154
|
* Read from the installed manifest rather than baked in at build time, so the number cannot
|
|
899
1155
|
* drift from the package a user actually has — which is the only reason anyone asks a tool
|
|
900
1156
|
* for its version.
|
|
@@ -923,8 +1179,8 @@ function readJson(file) {
|
|
|
923
1179
|
* is a compatibility claim (1.3.14 reports 24.3.0) about a runtime that never runs npm at all,
|
|
924
1180
|
* so reading it would answer a question nobody asked while looking exactly like a check.
|
|
925
1181
|
*/
|
|
926
|
-
function toolVersion(command) {
|
|
927
|
-
const raw =
|
|
1182
|
+
function toolVersion(command, version) {
|
|
1183
|
+
const raw = version.trim().replace(/^v/, "");
|
|
928
1184
|
const parts = raw.split(".").map((part) => Number.parseInt(part, 10));
|
|
929
1185
|
if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse ${command} version: ${raw}`);
|
|
930
1186
|
return [
|
|
@@ -945,11 +1201,10 @@ function publishEnv() {
|
|
|
945
1201
|
GITHUB_REPOSITORY: process.env.GITHUB_REPOSITORY
|
|
946
1202
|
};
|
|
947
1203
|
}
|
|
948
|
-
function assertTrustedPublishingRuntime(
|
|
949
|
-
|
|
950
|
-
const npm = toolVersion("npm");
|
|
1204
|
+
async function assertTrustedPublishingRuntime(cwd, npmVersion, signal) {
|
|
1205
|
+
const npm = toolVersion("npm", npmVersion);
|
|
951
1206
|
if (!isAtLeast(npm, MIN_TRUSTED_NPM_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires npm ${MIN_TRUSTED_NPM_VERSION.join(".")} or newer; found ${npm.join(".")}.`);
|
|
952
|
-
const node = toolVersion("node");
|
|
1207
|
+
const node = toolVersion("node", await requireTool("node", cwd, signal));
|
|
953
1208
|
if (isAtLeast(node, MIN_TRUSTED_NODE_VERSION)) return;
|
|
954
1209
|
throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${node.join(".")}.`);
|
|
955
1210
|
}
|
|
@@ -958,21 +1213,15 @@ function warnIfNonPnpmLifecycle() {
|
|
|
958
1213
|
if (!userAgent || userAgent.startsWith("pnpm/")) return;
|
|
959
1214
|
console.warn(`${PUBLISH_ADVISORY} Detected lifecycle user agent: ${userAgent}`);
|
|
960
1215
|
}
|
|
961
|
-
function assertCleanGit(packageDir, skip) {
|
|
1216
|
+
async function assertCleanGit(packageDir, skip, signal) {
|
|
962
1217
|
if (skip) return;
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
|
|
971
|
-
} catch (error) {
|
|
972
|
-
if (error instanceof PublishCleanError) throw error;
|
|
973
|
-
const stderr = outputFromError(error, "stderr");
|
|
974
|
-
throw new PublishCleanError(`Unable to verify source git status${stderr ? `: ${stderr}` : ""}.\nPass --no-git-checks to publish without this check.`, { cause: error });
|
|
975
|
-
}
|
|
1218
|
+
const output = (await run("git", [
|
|
1219
|
+
"status",
|
|
1220
|
+
"--porcelain",
|
|
1221
|
+
"--",
|
|
1222
|
+
"."
|
|
1223
|
+
], packageDir, { signal })).trim();
|
|
1224
|
+
if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
|
|
976
1225
|
}
|
|
977
1226
|
/**
|
|
978
1227
|
* Reads an archive from disk, so every judgement is made about bytes that exist as a file
|
|
@@ -1011,12 +1260,10 @@ async function soleTarball(packRoot) {
|
|
|
1011
1260
|
if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`pnpm pack left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
|
|
1012
1261
|
return path.join(packRoot, tarball);
|
|
1013
1262
|
}
|
|
1014
|
-
async function packAndClean(packageDir, opts) {
|
|
1015
|
-
requireTool("pnpm");
|
|
1016
|
-
requireTool("npm");
|
|
1263
|
+
async function packAndClean(packageDir, signal, opts) {
|
|
1264
|
+
const [, npmVersion] = await Promise.all([requireTool("pnpm", packageDir, signal), requireTool("npm", packageDir, signal)]);
|
|
1017
1265
|
warnIfNonPnpmLifecycle();
|
|
1018
1266
|
const sourcePkg = readJson(path.join(packageDir, "package.json"));
|
|
1019
|
-
if (!opts.guardOnly && !opts.dryRun) assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
|
|
1020
1267
|
const config = packageConfig(sourcePkg);
|
|
1021
1268
|
const skipFileCheck = opts.skipFileCheck || config.skipFileCheck === true;
|
|
1022
1269
|
const allowSuspicious = opts.allowSuspicious || config.allowSuspicious === true;
|
|
@@ -1025,33 +1272,38 @@ async function packAndClean(packageDir, opts) {
|
|
|
1025
1272
|
const extraDevFields = customDevFields(config);
|
|
1026
1273
|
const keepFields = keptFields(config);
|
|
1027
1274
|
assertPublicPackage(sourcePkg);
|
|
1028
|
-
assertCleanGit(packageDir, noGitChecks);
|
|
1275
|
+
await assertCleanGit(packageDir, noGitChecks, signal);
|
|
1029
1276
|
assertFilesField(sourcePkg, skipFileCheck);
|
|
1030
1277
|
const root = await mkdtemp(path.join(tmpdir(), "publish-clean-"));
|
|
1031
1278
|
try {
|
|
1032
|
-
run("pnpm", [
|
|
1279
|
+
await run("pnpm", [
|
|
1033
1280
|
"pack",
|
|
1034
1281
|
"--pack-destination",
|
|
1035
1282
|
root
|
|
1036
|
-
], packageDir
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1283
|
+
], packageDir, {
|
|
1284
|
+
signal,
|
|
1285
|
+
output: "pack"
|
|
1286
|
+
});
|
|
1287
|
+
const finalTarball = await soleTarball(root);
|
|
1288
|
+
const packed = await readTarball(finalTarball);
|
|
1289
|
+
const packedPkg = manifestOf(packed, "the packed tarball");
|
|
1290
|
+
assertPublicPackage(packedPkg);
|
|
1291
|
+
const cleanedPkg = withRegistry(stripManifest(packedPkg, extraDevFields), registry);
|
|
1292
|
+
const cleanedText = stringifyJson(cleanedPkg);
|
|
1040
1293
|
const unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
|
|
1041
1294
|
if (unrecognized) console.warn(unrecognized);
|
|
1042
|
-
|
|
1043
|
-
await mkdir(publishRoot);
|
|
1044
|
-
const finalTarball = path.join(publishRoot, path.basename(tarball));
|
|
1045
|
-
await writeFile(finalTarball, replaceManifest(packed, stringifyJson(cleanedPkg)));
|
|
1295
|
+
await writeFile(finalTarball, replaceManifest(packed, cleanedText));
|
|
1046
1296
|
const published = await readTarball(finalTarball);
|
|
1047
1297
|
const finalFiles = packageFiles(published);
|
|
1048
1298
|
assertSameEntries(packageFiles(packed), finalFiles);
|
|
1299
|
+
assertPreservedArchive(packed, published);
|
|
1049
1300
|
validatePackedFiles(finalFiles, allowSuspicious);
|
|
1050
|
-
assertDeclaredFiles(cleanedPkg, finalFiles);
|
|
1051
1301
|
const shippedPkg = manifestOf(published, "the published tarball");
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1302
|
+
assertRegistryDestinations(shippedPkg);
|
|
1303
|
+
assertDeclaredFiles(shippedPkg, finalFiles);
|
|
1304
|
+
assertNoMonorepoProtocols(shippedPkg, finalFiles);
|
|
1305
|
+
assertNoLostConsumerFields(packedPkg, shippedPkg, extraDevFields);
|
|
1306
|
+
if (manifestText(published) !== cleanedText) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
|
|
1055
1307
|
if (opts.tarballOut !== null) {
|
|
1056
1308
|
await mkdir(opts.tarballOut, { recursive: true });
|
|
1057
1309
|
const kept = path.join(opts.tarballOut, path.basename(finalTarball));
|
|
@@ -1060,24 +1312,43 @@ async function packAndClean(packageDir, opts) {
|
|
|
1060
1312
|
}
|
|
1061
1313
|
if (opts.dryRun) {
|
|
1062
1314
|
console.log(`[dry-run] ${finalFiles.length} files:`);
|
|
1063
|
-
for (const file of finalFiles) console.log(` ${file}`);
|
|
1064
|
-
console.log(`[dry-run] cleaned package.json:\n${
|
|
1315
|
+
for (const file of finalFiles) console.log(` ${JSON.stringify(file)}`);
|
|
1316
|
+
console.log(`[dry-run] cleaned package.json:\n${cleanedText}`);
|
|
1065
1317
|
return;
|
|
1066
1318
|
}
|
|
1067
1319
|
if (opts.guardOnly) return;
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1320
|
+
const env = publishEnv();
|
|
1321
|
+
let trusted = wantsTrustedPublish(shippedPkg, opts.publishArgs, env);
|
|
1322
|
+
if (trusted === void 0) {
|
|
1323
|
+
const value = (await run("npm", [
|
|
1324
|
+
"config",
|
|
1325
|
+
"get",
|
|
1326
|
+
"provenance"
|
|
1327
|
+
], packageDir, {
|
|
1328
|
+
signal,
|
|
1329
|
+
timeout: 1e4
|
|
1330
|
+
})).trim();
|
|
1331
|
+
if (value !== "true" && value !== "false") throw new PublishCleanError("npm config get provenance must return true or false.");
|
|
1332
|
+
trusted = value === "true";
|
|
1333
|
+
}
|
|
1334
|
+
if (trusted) {
|
|
1335
|
+
await assertTrustedPublishingRuntime(packageDir, npmVersion, signal);
|
|
1336
|
+
assertRepositoryForTrustedPublish(shippedPkg, env);
|
|
1337
|
+
}
|
|
1338
|
+
const scope = packageScope(shippedPkg);
|
|
1339
|
+
const publishArgs = [
|
|
1076
1340
|
"publish",
|
|
1077
1341
|
finalTarball,
|
|
1078
1342
|
...opts.publishArgs
|
|
1079
1343
|
];
|
|
1080
|
-
|
|
1344
|
+
if (registry) {
|
|
1345
|
+
publishArgs.push("--registry", registry);
|
|
1346
|
+
if (scope) publishArgs.push(`--${scope}:registry=${registry}`);
|
|
1347
|
+
}
|
|
1348
|
+
await run("npm", publishArgs, packageDir, {
|
|
1349
|
+
signal,
|
|
1350
|
+
output: "publish"
|
|
1351
|
+
});
|
|
1081
1352
|
} finally {
|
|
1082
1353
|
await rm(root, {
|
|
1083
1354
|
recursive: true,
|
|
@@ -1085,56 +1356,9 @@ async function packAndClean(packageDir, opts) {
|
|
|
1085
1356
|
});
|
|
1086
1357
|
}
|
|
1087
1358
|
}
|
|
1088
|
-
async function main() {
|
|
1089
|
-
const
|
|
1090
|
-
const
|
|
1091
|
-
const cliArgs = separator === -1 ? rawArgs : rawArgs.slice(0, separator);
|
|
1092
|
-
const publishArgs = separator === -1 ? [] : rawArgs.slice(separator + 1);
|
|
1093
|
-
const parsed = parseArgs({
|
|
1094
|
-
args: cliArgs,
|
|
1095
|
-
allowPositionals: true,
|
|
1096
|
-
options: {
|
|
1097
|
-
"allow-suspicious": {
|
|
1098
|
-
type: "boolean",
|
|
1099
|
-
default: false
|
|
1100
|
-
},
|
|
1101
|
-
"dry-run": {
|
|
1102
|
-
type: "boolean",
|
|
1103
|
-
default: false
|
|
1104
|
-
},
|
|
1105
|
-
"guard-only": {
|
|
1106
|
-
type: "boolean",
|
|
1107
|
-
default: false
|
|
1108
|
-
},
|
|
1109
|
-
help: {
|
|
1110
|
-
type: "boolean",
|
|
1111
|
-
short: "h",
|
|
1112
|
-
default: false
|
|
1113
|
-
},
|
|
1114
|
-
"no-git-checks": {
|
|
1115
|
-
type: "boolean",
|
|
1116
|
-
default: false
|
|
1117
|
-
},
|
|
1118
|
-
registry: {
|
|
1119
|
-
type: "string",
|
|
1120
|
-
default: void 0
|
|
1121
|
-
},
|
|
1122
|
-
"skip-file-check": {
|
|
1123
|
-
type: "boolean",
|
|
1124
|
-
default: false
|
|
1125
|
-
},
|
|
1126
|
-
"tarball-out": {
|
|
1127
|
-
type: "string",
|
|
1128
|
-
default: void 0
|
|
1129
|
-
},
|
|
1130
|
-
version: {
|
|
1131
|
-
type: "boolean",
|
|
1132
|
-
short: "v",
|
|
1133
|
-
default: false
|
|
1134
|
-
}
|
|
1135
|
-
},
|
|
1136
|
-
strict: true
|
|
1137
|
-
});
|
|
1359
|
+
async function main(signal) {
|
|
1360
|
+
const parsed = parseOptions(process.argv.slice(2));
|
|
1361
|
+
const { publishArgs } = parsed;
|
|
1138
1362
|
if (parsed.values.version) {
|
|
1139
1363
|
console.log(ownVersion());
|
|
1140
1364
|
return;
|
|
@@ -1144,7 +1368,7 @@ async function main() {
|
|
|
1144
1368
|
return;
|
|
1145
1369
|
}
|
|
1146
1370
|
if (parsed.positionals.length > 1) throw new PublishCleanError(`Unexpected positional arguments before --:\n${parsed.positionals.slice(1).join("\n")}`);
|
|
1147
|
-
await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), {
|
|
1371
|
+
await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), signal, {
|
|
1148
1372
|
allowSuspicious: parsed.values["allow-suspicious"] === true,
|
|
1149
1373
|
dryRun: parsed.values["dry-run"] === true,
|
|
1150
1374
|
guardOnly: parsed.values["guard-only"] === true,
|
|
@@ -1155,14 +1379,17 @@ async function main() {
|
|
|
1155
1379
|
tarballOut: typeof parsed.values["tarball-out"] === "string" ? parsed.values["tarball-out"] : null
|
|
1156
1380
|
});
|
|
1157
1381
|
}
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1382
|
+
const cancellation = new AbortController();
|
|
1383
|
+
let interrupted = false;
|
|
1384
|
+
for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143]]) process.on(signal, () => {
|
|
1385
|
+
interrupted = true;
|
|
1386
|
+
process.exitCode = code;
|
|
1387
|
+
cancellation.abort(new PublishCleanError(`Cancelled by ${signal}.`));
|
|
1388
|
+
});
|
|
1389
|
+
main(cancellation.signal).catch((error) => {
|
|
1390
|
+
console.error("publish-clean:", error instanceof PublishCleanError ? error.message : error);
|
|
1391
|
+
if (error instanceof PublishCleanError && error.cause) console.error("Caused by:", error.cause);
|
|
1392
|
+
if (!interrupted) process.exitCode = 1;
|
|
1166
1393
|
});
|
|
1167
1394
|
|
|
1168
1395
|
//#endregion
|