@anizoptera/publish-clean 0.7.1 → 0.7.3

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 (2) hide show
  1. package/dist/cli.js +369 -153
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,4 +1,6 @@
1
1
  #!/usr/bin/env node
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // @anizoptera/publish-clean 0.7.3 | https://github.com/Anizoptera/publish-clean#readme
2
4
  import { readFileSync } from "node:fs";
3
5
  import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
4
6
  import { tmpdir } from "node:os";
@@ -7,6 +9,7 @@ import { fileURLToPath } from "node:url";
7
9
  import { parseArgs } from "node:util";
8
10
  import { execFileSync } from "node:child_process";
9
11
  import { gunzipSync, gzipSync } from "node:zlib";
12
+
10
13
  //#region src/error.ts
11
14
  /**
12
15
  * The one failure type every module here throws, so `cli.ts` can tell a refusal this tool
@@ -15,13 +18,15 @@ import { gunzipSync, gzipSync } from "node:zlib";
15
18
  */
16
19
  var PublishCleanError = class extends Error {
17
20
  constructor(message, options) {
18
- super(message, options), this.name = "PublishCleanError";
21
+ super(message, options);
22
+ this.name = "PublishCleanError";
19
23
  }
20
24
  };
25
+
21
26
  //#endregion
22
27
  //#region src/json.ts
23
28
  function isObject(value) {
24
- return typeof value == "object" && !!value && !Array.isArray(value);
29
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
30
  }
26
31
  /**
27
32
  * The form written into the published tarball: npm's own two-space indentation with a trailing
@@ -39,8 +44,11 @@ function stableJson(value) {
39
44
  return JSON.stringify(stableValue(value));
40
45
  }
41
46
  function stableValue(value) {
42
- return Array.isArray(value) ? value.map(stableValue) : isObject(value) ? Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, stableValue(child)])) : 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)]));
43
50
  }
51
+
44
52
  //#endregion
45
53
  //#region src/artifact.ts
46
54
  /**
@@ -72,7 +80,8 @@ const CRITICAL_PATTERNS = [
72
80
  /(?:^|\/)\.npmrc$/i,
73
81
  /\.(?:pem|key|p12|pfx|p8|ppk|jks|keystore)$/i,
74
82
  /(?:^|\/)id_(?:rsa|dsa|ecdsa|ed25519)$/i
75
- ], SUSPICIOUS_PATTERNS = [
83
+ ];
84
+ const SUSPICIOUS_PATTERNS = [
76
85
  /(?:^|\/)(?:test|tests|__tests__|__snapshots__|coverage)(?:\/|$)/,
77
86
  /(?:^|\/)\.github(?:\/|$)/,
78
87
  /(?:^|\/)tsconfig[^/]*\.json$/,
@@ -80,10 +89,10 @@ const CRITICAL_PATTERNS = [
80
89
  /\.(?:test|spec)\.[cm]?[jt]sx?$/
81
90
  ];
82
91
  function validatePackedFiles(files, skipSuspicious) {
83
- let critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
92
+ const critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
84
93
  if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
85
94
  if (skipSuspicious) return;
86
- let suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
95
+ const suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
87
96
  if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
88
97
  }
89
98
  /**
@@ -101,7 +110,9 @@ function validatePackedFiles(files, skipSuspicious) {
101
110
  * `tar tzf` of the same tarball — an instrument that cannot share a mistake with this one.
102
111
  */
103
112
  function assertSameEntries(packed, published) {
104
- let before = new Set(packed), after = new Set(published), changed = [...packed.filter((file) => !after.has(file)).map((file) => `- ${file}`), ...published.filter((file) => !before.has(file)).map((file) => `+ ${file}`)];
113
+ const before = new Set(packed);
114
+ const after = new Set(published);
115
+ const changed = [...packed.filter((file) => !after.has(file)).map((file) => `- ${file}`), ...published.filter((file) => !before.has(file)).map((file) => `+ ${file}`)];
105
116
  if (changed.length > 0) throw new PublishCleanError(`Rewriting the tarball manifest changed its file set:\n${changed.join("\n")}`);
106
117
  }
107
118
  /**
@@ -123,23 +134,24 @@ function assertSameEntries(packed, published) {
123
134
  * `exports` condition values legitimately hold them.
124
135
  */
125
136
  function collectDeclaredPaths(value, out, mode) {
126
- if (typeof value == "string") {
127
- (mode === "every-string" || value.startsWith("./") || value.startsWith("../")) && out.push(value);
137
+ if (typeof value === "string") {
138
+ if (mode === "every-string" || value.startsWith("./") || value.startsWith("../")) out.push(value);
128
139
  return;
129
140
  }
130
- if (typeof value != "boolean") {
131
- if (Array.isArray(value)) {
132
- for (let item of value) collectDeclaredPaths(item, out, mode);
133
- return;
134
- }
135
- if (isObject(value)) for (let item of Object.values(value)) collectDeclaredPaths(item, out, mode);
141
+ if (typeof value === "boolean") return;
142
+ if (Array.isArray(value)) {
143
+ for (const item of value) collectDeclaredPaths(item, out, mode);
144
+ return;
136
145
  }
146
+ if (!isObject(value)) return;
147
+ for (const item of Object.values(value)) collectDeclaredPaths(item, out, mode);
137
148
  }
138
149
  function normalizeDeclaredPath(declared) {
139
- let withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
150
+ const withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
140
151
  if (!withoutDot || path.posix.isAbsolute(withoutDot)) return null;
141
- let normalized = path.posix.normalize(withoutDot);
142
- return normalized === "." || normalized === ".." || normalized.startsWith("../") ? null : normalized;
152
+ const normalized = path.posix.normalize(withoutDot);
153
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
154
+ return normalized;
143
155
  }
144
156
  /**
145
157
  * Refuses a manifest whose declared entry points are not in the tarball.
@@ -149,29 +161,33 @@ function normalizeDeclaredPath(declared) {
149
161
  * answer a question npm answers at install time.
150
162
  */
151
163
  function assertDeclaredFiles(pkg, published) {
152
- let declared = [];
153
- for (let field of [
164
+ const declared = [];
165
+ for (const field of [
154
166
  "main",
155
167
  "module",
156
168
  "types",
157
169
  "typings",
158
170
  "bin"
159
171
  ]) collectDeclaredPaths(pkg[field], declared, "every-string");
160
- typeof pkg.browser == "string" ? collectDeclaredPaths(pkg.browser, declared, "every-string") : collectDeclaredPaths(pkg.browser, declared, "relative-only");
161
- for (let field of [
172
+ if (typeof pkg.browser === "string") collectDeclaredPaths(pkg.browser, declared, "every-string");
173
+ else collectDeclaredPaths(pkg.browser, declared, "relative-only");
174
+ for (const field of [
162
175
  "exports",
163
176
  "imports",
164
177
  "sideEffects"
165
178
  ]) collectDeclaredPaths(pkg[field], declared, "relative-only");
166
179
  collectDeclaredPaths(pkg.typesVersions, declared, "every-string");
167
- let resolved = declared.map((declaredPath) => ({
180
+ const resolved = declared.map((declaredPath) => ({
168
181
  path: declaredPath,
169
182
  normalized: normalizeDeclaredPath(declaredPath)
170
- })), invalid = resolved.filter((item) => item.normalized === null);
183
+ }));
184
+ const invalid = resolved.filter((item) => item.normalized === null);
171
185
  if (invalid.length > 0) throw new PublishCleanError(`Manifest declares invalid package paths:\n${invalid.map((item) => item.path).join("\n")}`);
172
- let shipped = new Set(published), missing = resolved.filter((item) => !item.path.includes("*") && !shipped.has(String(item.normalized)));
186
+ const shipped = new Set(published);
187
+ const missing = resolved.filter((item) => !item.path.includes("*") && !shipped.has(String(item.normalized)));
173
188
  if (missing.length > 0) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((item) => item.path).join("\n")}`);
174
189
  }
190
+
175
191
  //#endregion
176
192
  //#region src/command.ts
177
193
  /**
@@ -203,7 +219,7 @@ const TOOL_PROBE_TIMEOUT_MS = 1e4;
203
219
  */
204
220
  function spawnArgs(command, args, platform) {
205
221
  if (platform !== "win32") return [command, [...args]];
206
- let unsafe = [command, ...args].filter((argument) => /[&|<>^%()]/.test(argument));
222
+ const unsafe = [command, ...args].filter((argument) => /[&|<>^%()]/.test(argument));
207
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")}\nMove the package to a path without & | < > ^ % ( ), or publish from Linux or macOS.`);
208
224
  return ["cmd.exe", [
209
225
  "/d",
@@ -246,8 +262,10 @@ function runAttached(command, args, cwd) {
246
262
  /** Child output survives only on the thrown error, and is lost unless read off it here. */
247
263
  function outputFromError(error, key) {
248
264
  if (!isObject(error)) return "";
249
- let output = error[key];
250
- return typeof output == "string" ? output.trim() : output instanceof Uint8Array ? Buffer.from(output).toString("utf8").trim() : "";
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 "";
251
269
  }
252
270
  /**
253
271
  * A required tool can fail three ways, and each one asks something different of the
@@ -262,7 +280,7 @@ function toolFailureReason(cause) {
262
280
  if (cause.code === "ENOENT") return "is not available in PATH";
263
281
  if (cause.code === "ETIMEDOUT") return `did not answer --version within ${TOOL_PROBE_TIMEOUT_MS}ms`;
264
282
  }
265
- let stderr = outputFromError(cause, "stderr");
283
+ const stderr = outputFromError(cause, "stderr");
266
284
  return `failed to run${stderr ? `: ${stderr}` : ""}`;
267
285
  }
268
286
  function requireTool(name) {
@@ -279,6 +297,7 @@ function requireTool(name) {
279
297
  throw new PublishCleanError(`Required tool "${name}" ${toolFailureReason(cause)}.`, { cause });
280
298
  }
281
299
  }
300
+
282
301
  //#endregion
283
302
  //#region src/manifest.ts
284
303
  /**
@@ -288,25 +307,74 @@ function requireTool(name) {
288
307
  * Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
289
308
  * argv here — so every rule is one input to one output. `cli.ts` owns the effects.
290
309
  */
291
- const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.catalogs.patchedDependencies.private.files.stylelint.trustedDependencies.wireit.devDependencies.overrides.resolutions.ava.c8.jest.mocha.nyc.tap.vitest.babel.biome.browserslist.eslintConfig.eslintIgnore.prettier.remarkConfig.xo.commitlint.husky.lint-staged.simple-git-hooks.clean-publish.publish-clean.semantic-release.packageManager.pnpm.volta.workspaces.nx.turbo".split(".")), CONSUMER_SCRIPTS = /* @__PURE__ */ new Set([
310
+ const DEV_FIELDS = /* @__PURE__ */ new Set([
311
+ "$schema",
312
+ "catalog",
313
+ "catalogs",
314
+ "patchedDependencies",
315
+ "private",
316
+ "files",
317
+ "stylelint",
318
+ "trustedDependencies",
319
+ "wireit",
320
+ "devDependencies",
321
+ "overrides",
322
+ "resolutions",
323
+ "ava",
324
+ "c8",
325
+ "jest",
326
+ "mocha",
327
+ "nyc",
328
+ "tap",
329
+ "vitest",
330
+ "babel",
331
+ "biome",
332
+ "browserslist",
333
+ "eslintConfig",
334
+ "eslintIgnore",
335
+ "prettier",
336
+ "remarkConfig",
337
+ "xo",
338
+ "commitlint",
339
+ "husky",
340
+ "lint-staged",
341
+ "simple-git-hooks",
342
+ "clean-publish",
343
+ "publish-clean",
344
+ "semantic-release",
345
+ "packageManager",
346
+ "pnpm",
347
+ "volta",
348
+ "workspaces",
349
+ "nx",
350
+ "turbo"
351
+ ]);
352
+ const CONSUMER_SCRIPTS = /* @__PURE__ */ new Set([
292
353
  "preinstall",
293
354
  "install",
294
355
  "postinstall",
295
356
  "prepare",
296
357
  "uninstall"
297
- ]), DEP_FIELDS = [
358
+ ]);
359
+ const DEP_FIELDS = [
298
360
  "dependencies",
299
361
  "devDependencies",
300
362
  "optionalDependencies",
301
363
  "peerDependencies",
302
364
  "overrides",
303
365
  "resolutions"
304
- ], MONOREPO_PROTOCOLS = [
366
+ ];
367
+ const MONOREPO_PROTOCOLS = [
305
368
  "catalog:",
306
369
  "workspace:",
307
370
  "link:",
308
371
  "portal:"
309
- ], RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
372
+ ];
373
+ /**
374
+ * Fields a consumer's toolchain resolves. Stripping one breaks installs, imports or
375
+ * platform gating, so `devFields` is not allowed to name them.
376
+ */
377
+ const RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
310
378
  ...DEP_FIELDS,
311
379
  "bin",
312
380
  "browser",
@@ -330,7 +398,17 @@ const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.cata
330
398
  "typesVersions",
331
399
  "typings",
332
400
  "version"
333
- ]), REGISTRY_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
401
+ ]);
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
+ */
411
+ const REGISTRY_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
334
412
  "author",
335
413
  "bugs",
336
414
  "config",
@@ -354,15 +432,26 @@ const DEV_FIELDS = /* @__PURE__ */ new Set(/* @__PURE__ */ "$schema.catalog.cata
354
432
  "styleModule",
355
433
  "svelte",
356
434
  "unpkg"
357
- ]), PUBLISH_ADVISORY = "publish-clean packs with pnpm: it resolves workspace: and catalog: specs from the packing package's own node_modules, so a Bun workspace works as-is and a Yarn one needs a pnpm-workspace.yaml plus one pnpm install. npm packs those specs unresolved.";
435
+ ]);
436
+ /**
437
+ * Shown when another package manager started this tool, so the pnpm requirement is not a
438
+ * surprise. It names the packer and the consequence for the reader's own layout, rather
439
+ * than claiming the alternatives are broken, because what a reader needs to do next
440
+ * depends on which package manager they came from.
441
+ *
442
+ * The measured comparison behind the choice of packer, and the standing rule against
443
+ * swapping it, live in this repository's AGENTS.md.
444
+ */
445
+ const PUBLISH_ADVISORY = "publish-clean packs with pnpm: it resolves workspace: and catalog: specs from the packing package's own node_modules, so a Bun workspace works as-is and a Yarn one needs a pnpm-workspace.yaml plus one pnpm install. npm packs those specs unresolved.";
358
446
  function stripManifest(pkg, extraDevFields) {
359
- let stripped = { ...pkg };
360
- for (let field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
361
- let scripts = isObject(pkg.scripts) ? pkg.scripts : null;
447
+ const stripped = { ...pkg };
448
+ for (const field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
449
+ const scripts = isObject(pkg.scripts) ? pkg.scripts : null;
362
450
  if (scripts) {
363
- let kept = {};
364
- for (let [name, value] of Object.entries(scripts)) CONSUMER_SCRIPTS.has(name) && typeof value == "string" && (kept[name] = value);
365
- Object.keys(kept).length > 0 ? stripped.scripts = kept : delete stripped.scripts;
451
+ const kept = {};
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;
454
+ else delete stripped.scripts;
366
455
  }
367
456
  return stripped;
368
457
  }
@@ -379,8 +468,9 @@ function stripManifest(pkg, extraDevFields) {
379
468
  */
380
469
  function withRegistry(pkg, registry) {
381
470
  if (registry === null) return pkg;
382
- let publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
383
- return publishConfig.registry = registry, {
471
+ const publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
472
+ publishConfig.registry = registry;
473
+ return {
384
474
  ...pkg,
385
475
  publishConfig
386
476
  };
@@ -403,11 +493,12 @@ function withRegistry(pkg, registry) {
403
493
  * none.
404
494
  */
405
495
  function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
406
- let expected = /* @__PURE__ */ new Set([
496
+ const expected = /* @__PURE__ */ new Set([
407
497
  ...DEV_FIELDS,
408
498
  ...removedOnRequest,
409
499
  "scripts"
410
- ]), lost = Object.keys(sourcePkg).filter((field) => (RUNTIME_MANIFEST_FIELDS.has(field) || REGISTRY_MANIFEST_FIELDS.has(field)) && !expected.has(field) && !(field in finalPkg));
500
+ ]);
501
+ const lost = Object.keys(sourcePkg).filter((field) => (RUNTIME_MANIFEST_FIELDS.has(field) || REGISTRY_MANIFEST_FIELDS.has(field)) && !expected.has(field) && !(field in finalPkg));
411
502
  if (lost.length > 0) throw new PublishCleanError(`The published manifest is missing fields the source declared and consumers read:\n${lost.join("\n")}`);
412
503
  }
413
504
  /**
@@ -426,8 +517,10 @@ function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
426
517
  * object, which two cases running side by side can clobber.
427
518
  */
428
519
  function unrecognizedFieldsReport(pkg, kept) {
429
- let acknowledged = new Set(kept), unrecognized = Object.keys(pkg).filter((field) => !RUNTIME_MANIFEST_FIELDS.has(field) && !REGISTRY_MANIFEST_FIELDS.has(field) && !acknowledged.has(field));
430
- return unrecognized.length === 0 ? null : `publish-clean: these manifest fields are not recognised and were published as-is:\n${unrecognized.map((field) => ` ${field}`).join("\n")}\nStrip the ones consumers do not read, and acknowledge the ones they do:\n "publish-clean": { "devFields": [${unrecognized.map((f) => `"${f}"`).join(", ")}] }\n "publish-clean": { "keepFields": [${unrecognized.map((f) => `"${f}"`).join(", ")}] }`;
520
+ const acknowledged = new Set(kept);
521
+ const unrecognized = Object.keys(pkg).filter((field) => !RUNTIME_MANIFEST_FIELDS.has(field) && !REGISTRY_MANIFEST_FIELDS.has(field) && !acknowledged.has(field));
522
+ if (unrecognized.length === 0) return null;
523
+ return `publish-clean: these manifest fields are not recognised and were published as-is:\n${unrecognized.map((field) => ` ${field}`).join("\n")}\nStrip the ones consumers do not read, and acknowledge the ones they do:\n "publish-clean": { "devFields": [${unrecognized.map((f) => `"${f}"`).join(", ")}] }\n "publish-clean": { "keepFields": [${unrecognized.map((f) => `"${f}"`).join(", ")}] }`;
431
524
  }
432
525
  /**
433
526
  * Refuses a manifest that still carries a spec only a workspace can resolve. Published
@@ -439,18 +532,23 @@ function unrecognizedFieldsReport(pkg, kept) {
439
532
  * the order it happens to be called in fails silently the day someone reorders it.
440
533
  */
441
534
  function assertNoMonorepoProtocols(pkg) {
442
- let failures = [];
443
- for (let field of DEP_FIELDS) {
444
- let map = pkg[field];
445
- if (isObject(map)) for (let [name, spec] of Object.entries(map)) typeof spec == "string" && MONOREPO_PROTOCOLS.some((prefix) => spec.includes(prefix)) && failures.push(`${field}.${name}: ${spec}`);
535
+ const failures = [];
536
+ for (const field of DEP_FIELDS) {
537
+ const map = pkg[field];
538
+ if (!isObject(map)) continue;
539
+ for (const [name, spec] of Object.entries(map)) {
540
+ if (typeof spec !== "string") continue;
541
+ if (MONOREPO_PROTOCOLS.some((prefix) => spec.includes(prefix))) failures.push(`${field}.${name}: ${spec}`);
542
+ }
446
543
  }
447
544
  if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
448
545
  }
449
546
  function assertPublicPackage(pkg) {
450
- if (pkg.private === !0) throw new PublishCleanError("Refusing to publish a package with private: true.");
547
+ if (pkg.private === true) throw new PublishCleanError("Refusing to publish a package with private: true.");
451
548
  }
452
549
  function assertFilesField(pkg, skip) {
453
- if (!skip && (!Array.isArray(pkg.files) || pkg.files.length === 0)) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
550
+ 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.");
454
552
  }
455
553
  /**
456
554
  * Every key this tool reads out of the manifest's `publish-clean` block. Naming them is what
@@ -466,9 +564,9 @@ const CONFIG_KEYS = /* @__PURE__ */ new Set([
466
564
  "skipFileCheck"
467
565
  ]);
468
566
  function packageConfig(pkg) {
469
- let config = pkg["publish-clean"];
567
+ const config = pkg["publish-clean"];
470
568
  if (!isObject(config)) return {};
471
- let unknown = Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
569
+ const unknown = Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
472
570
  if (unknown.length > 0) throw new PublishCleanError(`Unknown "publish-clean" manifest options:\n${unknown.join("\n")}\nValid options: ${[...CONFIG_KEYS].join(", ")}`);
473
571
  return config;
474
572
  }
@@ -478,15 +576,17 @@ function packageConfig(pkg) {
478
576
  * silently means the author's intent is lost with no signal anywhere.
479
577
  */
480
578
  function stringList(config, key) {
481
- let value = config[key];
579
+ const value = config[key];
482
580
  if (value === void 0) return [];
483
- if (!Array.isArray(value) || value.some((entry) => typeof entry != "string")) throw new PublishCleanError(`publish-clean.${key} must be an array of strings.`);
581
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) throw new PublishCleanError(`publish-clean.${key} must be an array of strings.`);
484
582
  return value;
485
583
  }
486
584
  function customDevFields(config) {
487
- let fields = stringList(config, "devFields"), kept = new Set(stringList(config, "keepFields")), contradictory = fields.filter((field) => kept.has(field));
585
+ const fields = stringList(config, "devFields");
586
+ const kept = new Set(stringList(config, "keepFields"));
587
+ const contradictory = fields.filter((field) => kept.has(field));
488
588
  if (contradictory.length > 0) throw new PublishCleanError(`These fields are listed as both devFields and keepFields, which asks to strip and to publish the same key:\n${contradictory.join("\n")}`);
489
- let unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
589
+ const unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
490
590
  if (unsafe.length > 0) throw new PublishCleanError(`publish-clean.devFields cannot remove runtime/public manifest fields:\n${unsafe.join("\n")}`);
491
591
  return fields;
492
592
  }
@@ -504,6 +604,7 @@ function customDevFields(config) {
504
604
  function keptFields(config) {
505
605
  return stringList(config, "keepFields");
506
606
  }
607
+
507
608
  //#endregion
508
609
  //#region src/tarball.ts
509
610
  /**
@@ -528,13 +629,38 @@ function keptFields(config) {
528
629
  * question. It is also the stricter reader — `tar tzf` prints one name per line, so a path
529
630
  * containing a newline arrives as two entries there and as itself here.
530
631
  */
531
- const MANIFEST_PATH = "package/package.json", PAX_TYPES = /* @__PURE__ */ new Set(["x", "g"]);
632
+ const BLOCK = 512;
633
+ const NAME_LEN = 100;
634
+ const SIZE_OFFSET = 124;
635
+ const CHECKSUM_OFFSET = 148;
636
+ 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
+ const MANIFEST_PATH = "package/package.json";
643
+ /** Extended (`x`) and global (`g`) pax headers carry key/value overrides for other entries. */
644
+ const PAX_TYPES = /* @__PURE__ */ new Set(["x", "g"]);
645
+ /** Tar's flag for a directory entry. Directories are not files a consumer imports. */
646
+ 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";
532
658
  function field(block, offset, length) {
533
659
  return block.toString("utf8", offset, offset + length).replace(/\0.*/s, "");
534
660
  }
535
661
  function entrySize(block) {
536
- if ((block[124] ?? 0) & 128) throw new PublishCleanError("Tarball uses base-256 entry sizes, which this tool cannot rewrite.");
537
- let size = Number.parseInt(field(block, 124, 12).trim(), 8);
662
+ if ((block[SIZE_OFFSET] ?? 0) & 128) throw new PublishCleanError("Tarball uses base-256 entry sizes, which this tool cannot rewrite.");
663
+ const size = Number.parseInt(field(block, SIZE_OFFSET, 12).trim(), 8);
538
664
  if (!Number.isFinite(size) || size < 0) throw new PublishCleanError("Tarball entry has an unreadable size field.");
539
665
  return size;
540
666
  }
@@ -553,10 +679,13 @@ function entrySize(block) {
553
679
  * the signed form would reject valid archives holding non-ASCII filenames.
554
680
  */
555
681
  function assertChecksum(header, name) {
556
- let stored = Number.parseInt(field(header, 148, 8).trim(), 8), unsigned = 0, signed = 0;
557
- for (let [index, byte] of header.entries()) {
558
- let value = index >= 148 && index < 156 ? 32 : byte;
559
- unsigned += value, signed += value > 127 ? value - 256 : value;
682
+ const stored = Number.parseInt(field(header, CHECKSUM_OFFSET, 8).trim(), 8);
683
+ let unsigned = 0;
684
+ let signed = 0;
685
+ for (const [index, byte] of header.entries()) {
686
+ const value = index >= CHECKSUM_OFFSET && index < 156 ? 32 : byte;
687
+ unsigned += value;
688
+ signed += value > 127 ? value - 256 : value;
560
689
  }
561
690
  if (stored !== unsigned && stored !== signed) throw new PublishCleanError(`Tarball entry ${name} has a corrupt header checksum.`);
562
691
  }
@@ -569,15 +698,17 @@ function assertChecksum(header, name) {
569
698
  * substitution is visible from the walk alone.
570
699
  */
571
700
  function assertNoManifestOverride(payload) {
572
- for (let 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}.`);
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}.`);
573
702
  }
574
703
  /** Rebuilds a header for a changed payload size, keeping every other field of the original. */
575
704
  function reheader(original, size) {
576
- let header = Buffer.from(original);
577
- header.write(size.toString(8).padStart(11, "0") + "\0", 124, 12, "ascii"), header.write(" ".repeat(8), 148, 8, "ascii");
705
+ const header = Buffer.from(original);
706
+ header.write(size.toString(8).padStart(11, "0") + "\0", SIZE_OFFSET, 12, "ascii");
707
+ header.write(" ".repeat(8), CHECKSUM_OFFSET, 8, "ascii");
578
708
  let sum = 0;
579
- for (let byte of header) sum += byte;
580
- return header.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "ascii"), header;
709
+ for (const byte of header) sum += byte;
710
+ header.write(sum.toString(8).padStart(6, "0") + "\0 ", CHECKSUM_OFFSET, 8, "ascii");
711
+ return header;
581
712
  }
582
713
  /**
583
714
  * Decodes a gzipped tarball into its entries, refusing every shape whose meaning this tool
@@ -590,21 +721,26 @@ function reheader(original, size) {
590
721
  * partial write becomes a published package.
591
722
  */
592
723
  function readArchive(gzipped) {
593
- let tar = gunzipSync(gzipped), entries = [], tail = null;
724
+ const tar = gunzipSync(gzipped);
725
+ const entries = [];
726
+ let tail = null;
594
727
  for (let offset = 0; offset < tar.length;) {
595
- let header = tar.subarray(offset, offset + 512);
596
- if (header.length < 512) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
597
- let name = field(header, 0, 100);
728
+ const header = tar.subarray(offset, offset + BLOCK);
729
+ if (header.length < BLOCK) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
730
+ const name = field(header, 0, NAME_LEN);
598
731
  if (name === "") {
599
732
  tail = tar.subarray(offset);
600
733
  break;
601
734
  }
602
735
  assertChecksum(header, name);
603
- let size = entrySize(header), end = offset + 512 + 512 * Math.ceil(size / 512);
736
+ const size = entrySize(header);
737
+ const end = offset + BLOCK + BLOCK * Math.ceil(size / BLOCK);
604
738
  if (end > tar.length) throw new PublishCleanError(`Tarball entry ${name} runs past the end of the archive.`);
605
- let type = field(header, 156, 1), body = tar.subarray(offset + 512, offset + 512 + size);
606
- if (type === "L") throw new PublishCleanError("Tarball uses GNU long-name entries, which this tool refuses.");
607
- if (PAX_TYPES.has(type) && assertNoManifestOverride(body), name === MANIFEST_PATH) {
739
+ const type = field(header, TYPE_OFFSET, 1);
740
+ const body = tar.subarray(offset + BLOCK, offset + BLOCK + size);
741
+ if (type === GNU_LONG_NAME) throw new PublishCleanError("Tarball uses GNU long-name entries, which this tool refuses.");
742
+ if (PAX_TYPES.has(type)) assertNoManifestOverride(body);
743
+ if (name === MANIFEST_PATH) {
608
744
  if (type !== "0" && type !== "") throw new PublishCleanError(`${MANIFEST_PATH} is not a regular file in the tarball.`);
609
745
  if (entries.some((entry) => entry.name === MANIFEST_PATH)) throw new PublishCleanError(`Tarball contains ${MANIFEST_PATH} more than once.`);
610
746
  }
@@ -614,7 +750,8 @@ function readArchive(gzipped) {
614
750
  header,
615
751
  body,
616
752
  raw: tar.subarray(offset, end)
617
- }), offset = end;
753
+ });
754
+ offset = end;
618
755
  }
619
756
  if (tail === null) throw new PublishCleanError("Tarball has no end-of-archive marker; the archive is truncated.");
620
757
  return {
@@ -628,10 +765,10 @@ function readArchive(gzipped) {
628
765
  * imports, and a pax header's own name (`PaxHeader`) names no file at all.
629
766
  */
630
767
  function packageFiles(archive) {
631
- return archive.entries.filter((entry) => entry.type !== "5" && !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();
768
+ 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();
632
769
  }
633
770
  function manifestEntry(archive) {
634
- let entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH);
771
+ const entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH);
635
772
  if (!entry) throw new PublishCleanError(`Tarball does not contain ${MANIFEST_PATH}.`);
636
773
  return entry;
637
774
  }
@@ -641,13 +778,17 @@ function manifestText(archive) {
641
778
  }
642
779
  /** Returns the gzipped tarball with `package/package.json` replaced by `manifest`. */
643
780
  function replaceManifest(archive, manifest) {
644
- let target = manifestEntry(archive), body = Buffer.from(manifest, "utf8"), parts = archive.entries.map((entry) => entry === target ? Buffer.concat([
781
+ const target = manifestEntry(archive);
782
+ const body = Buffer.from(manifest, "utf8");
783
+ const parts = archive.entries.map((entry) => entry === target ? Buffer.concat([
645
784
  reheader(entry.header, body.length),
646
785
  body,
647
- Buffer.alloc(512 * Math.ceil(body.length / 512) - body.length)
786
+ Buffer.alloc(BLOCK * Math.ceil(body.length / BLOCK) - body.length)
648
787
  ]) : entry.raw);
649
- return parts.push(archive.tail), gzipSync(Buffer.concat(parts), { level: 9 });
788
+ parts.push(archive.tail);
789
+ return gzipSync(Buffer.concat(parts), { level: 9 });
650
790
  }
791
+
651
792
  //#endregion
652
793
  //#region src/trusted-publish.ts
653
794
  /**
@@ -667,57 +808,100 @@ const MIN_TRUSTED_NPM_VERSION = [
667
808
  11,
668
809
  5,
669
810
  1
670
- ], MIN_TRUSTED_NODE_VERSION = [
811
+ ];
812
+ const MIN_TRUSTED_NODE_VERSION = [
671
813
  22,
672
814
  14,
673
815
  0
674
816
  ];
675
817
  function isAtLeast(actual, minimum) {
676
- for (let index of [
818
+ for (const index of [
677
819
  0,
678
820
  1,
679
821
  2
680
822
  ]) {
681
- if (actual[index] > minimum[index]) return !0;
682
- if (actual[index] < minimum[index]) return !1;
823
+ if (actual[index] > minimum[index]) return true;
824
+ if (actual[index] < minimum[index]) return false;
683
825
  }
684
- return !0;
826
+ return true;
685
827
  }
686
828
  function wantsTrustedPublish(pkg, publishArgs, env) {
687
- return publishArgs.includes("--provenance") || isObject(pkg.publishConfig) && pkg.publishConfig.provenance === !0 ? !0 : env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL == "string";
829
+ if (publishArgs.includes("--provenance")) return true;
830
+ if (isObject(pkg.publishConfig) && pkg.publishConfig.provenance === true) return true;
831
+ return env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL === "string";
688
832
  }
689
833
  function repositoryUrl(pkg) {
690
- return typeof pkg.repository == "string" ? pkg.repository : isObject(pkg.repository) && typeof pkg.repository.url == "string" ? pkg.repository.url : null;
834
+ if (typeof pkg.repository === "string") return pkg.repository;
835
+ if (isObject(pkg.repository) && typeof pkg.repository.url === "string") return pkg.repository.url;
836
+ return null;
691
837
  }
692
838
  function githubRepositorySlug(url) {
693
- let withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
839
+ const withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
694
840
  if (withoutGitPrefix.startsWith("git@github.com:")) {
695
- let slug = withoutGitPrefix.slice(15);
841
+ const slug = withoutGitPrefix.slice(15);
696
842
  return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
697
843
  }
698
844
  try {
699
- let parsed = new URL(withoutGitPrefix);
845
+ const parsed = new URL(withoutGitPrefix);
700
846
  if (parsed.hostname !== "github.com") return null;
701
- let slug = parsed.pathname.replace(/^\/+/, "");
847
+ const slug = parsed.pathname.replace(/^\/+/, "");
702
848
  return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
703
849
  } catch {
704
850
  return null;
705
851
  }
706
852
  }
707
853
  function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
708
- if (!wantsTrustedPublish(pkg, publishArgs, env) || env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY != "string") return;
709
- let repoUrl = repositoryUrl(pkg);
854
+ if (!wantsTrustedPublish(pkg, publishArgs, env)) return;
855
+ if (env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY !== "string") return;
856
+ const repoUrl = repositoryUrl(pkg);
710
857
  if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
711
858
  if (githubRepositorySlug(repoUrl) !== env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
712
859
  }
860
+
861
+ //#endregion
862
+ //#region src/cli.ts
863
+ /**
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.`;
713
897
  /**
714
898
  * Read from the installed manifest rather than baked in at build time, so the number cannot
715
899
  * drift from the package a user actually has — which is the only reason anyone asks a tool
716
900
  * for its version.
717
901
  */
718
902
  function ownVersion() {
719
- let manifest = readJson(fileURLToPath(new URL("../package.json", import.meta.url)));
720
- return typeof manifest.version == "string" ? manifest.version : "unknown";
903
+ const manifest = readJson(fileURLToPath(new URL("../package.json", import.meta.url)));
904
+ return typeof manifest.version === "string" ? manifest.version : "unknown";
721
905
  }
722
906
  function readJson(file) {
723
907
  let parsed;
@@ -740,7 +924,8 @@ function readJson(file) {
740
924
  * so reading it would answer a question nobody asked while looking exactly like a check.
741
925
  */
742
926
  function toolVersion(command) {
743
- let raw = run(command, ["--version"], process.cwd()).trim().replace(/^v/, ""), parts = raw.split(".").map((part) => Number.parseInt(part, 10));
927
+ const raw = run(command, ["--version"], process.cwd()).trim().replace(/^v/, "");
928
+ const parts = raw.split(".").map((part) => Number.parseInt(part, 10));
744
929
  if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse ${command} version: ${raw}`);
745
930
  return [
746
931
  parts[0] ?? 0,
@@ -762,18 +947,21 @@ function publishEnv() {
762
947
  }
763
948
  function assertTrustedPublishingRuntime(pkg, publishArgs) {
764
949
  if (!wantsTrustedPublish(pkg, publishArgs, publishEnv())) return;
765
- let npm = toolVersion("npm");
950
+ const npm = toolVersion("npm");
766
951
  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(".")}.`);
767
- let node = toolVersion("node");
768
- if (!isAtLeast(node, MIN_TRUSTED_NODE_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${node.join(".")}.`);
952
+ const node = toolVersion("node");
953
+ if (isAtLeast(node, MIN_TRUSTED_NODE_VERSION)) return;
954
+ throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${node.join(".")}.`);
769
955
  }
770
956
  function warnIfNonPnpmLifecycle() {
771
- let userAgent = process.env.npm_config_user_agent;
772
- !userAgent || userAgent.startsWith("pnpm/") || console.warn(`${PUBLISH_ADVISORY} Detected lifecycle user agent: ${userAgent}`);
957
+ const userAgent = process.env.npm_config_user_agent;
958
+ if (!userAgent || userAgent.startsWith("pnpm/")) return;
959
+ console.warn(`${PUBLISH_ADVISORY} Detected lifecycle user agent: ${userAgent}`);
773
960
  }
774
961
  function assertCleanGit(packageDir, skip) {
775
- if (!skip) try {
776
- let output = run("git", [
962
+ if (skip) return;
963
+ try {
964
+ const output = run("git", [
777
965
  "status",
778
966
  "--porcelain",
779
967
  "--",
@@ -782,7 +970,7 @@ function assertCleanGit(packageDir, skip) {
782
970
  if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
783
971
  } catch (error) {
784
972
  if (error instanceof PublishCleanError) throw error;
785
- let stderr = outputFromError(error, "stderr");
973
+ const stderr = outputFromError(error, "stderr");
786
974
  throw new PublishCleanError(`Unable to verify source git status${stderr ? `: ${stderr}` : ""}.\nPass --no-git-checks to publish without this check.`, { cause: error });
787
975
  }
788
976
  }
@@ -818,46 +1006,67 @@ function manifestOf(archive, label) {
818
1006
  * destination was not exclusive and the wrong artifact could be published.
819
1007
  */
820
1008
  async function soleTarball(packRoot) {
821
- let tarballs = (await readdir(packRoot)).filter((entry) => entry.endsWith(".tgz")), [tarball] = tarballs;
1009
+ const tarballs = (await readdir(packRoot)).filter((entry) => entry.endsWith(".tgz"));
1010
+ const [tarball] = tarballs;
822
1011
  if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`pnpm pack left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
823
1012
  return path.join(packRoot, tarball);
824
1013
  }
825
1014
  async function packAndClean(packageDir, opts) {
826
- requireTool("pnpm"), requireTool("npm"), warnIfNonPnpmLifecycle();
827
- let sourcePkg = readJson(path.join(packageDir, "package.json"));
828
- !opts.guardOnly && !opts.dryRun && assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
829
- let config = packageConfig(sourcePkg), skipFileCheck = opts.skipFileCheck || config.skipFileCheck === !0, allowSuspicious = opts.allowSuspicious || config.allowSuspicious === !0, noGitChecks = opts.noGitChecks || config.noGitChecks === !0, registry = opts.registry ?? (typeof config.registry == "string" ? config.registry : null), extraDevFields = customDevFields(config), keepFields = keptFields(config);
830
- assertPublicPackage(sourcePkg), assertCleanGit(packageDir, noGitChecks), assertFilesField(sourcePkg, skipFileCheck);
831
- let root = await mkdtemp(path.join(tmpdir(), "publish-clean-"));
1015
+ requireTool("pnpm");
1016
+ requireTool("npm");
1017
+ warnIfNonPnpmLifecycle();
1018
+ const sourcePkg = readJson(path.join(packageDir, "package.json"));
1019
+ if (!opts.guardOnly && !opts.dryRun) assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
1020
+ const config = packageConfig(sourcePkg);
1021
+ const skipFileCheck = opts.skipFileCheck || config.skipFileCheck === true;
1022
+ const allowSuspicious = opts.allowSuspicious || config.allowSuspicious === true;
1023
+ const noGitChecks = opts.noGitChecks || config.noGitChecks === true;
1024
+ const registry = opts.registry ?? (typeof config.registry === "string" ? config.registry : null);
1025
+ const extraDevFields = customDevFields(config);
1026
+ const keepFields = keptFields(config);
1027
+ assertPublicPackage(sourcePkg);
1028
+ assertCleanGit(packageDir, noGitChecks);
1029
+ assertFilesField(sourcePkg, skipFileCheck);
1030
+ const root = await mkdtemp(path.join(tmpdir(), "publish-clean-"));
832
1031
  try {
833
1032
  run("pnpm", [
834
1033
  "pack",
835
1034
  "--pack-destination",
836
1035
  root
837
1036
  ], packageDir);
838
- let tarball = await soleTarball(root), packed = await readTarball(tarball), cleanedPkg = withRegistry(stripManifest(manifestOf(packed, "the packed tarball"), extraDevFields), registry), unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
839
- unrecognized && console.warn(unrecognized);
840
- let publishRoot = path.join(root, "publish");
1037
+ const tarball = await soleTarball(root);
1038
+ const packed = await readTarball(tarball);
1039
+ const cleanedPkg = withRegistry(stripManifest(manifestOf(packed, "the packed tarball"), extraDevFields), registry);
1040
+ const unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
1041
+ if (unrecognized) console.warn(unrecognized);
1042
+ const publishRoot = path.join(root, "publish");
841
1043
  await mkdir(publishRoot);
842
- let finalTarball = path.join(publishRoot, path.basename(tarball));
1044
+ const finalTarball = path.join(publishRoot, path.basename(tarball));
843
1045
  await writeFile(finalTarball, replaceManifest(packed, stringifyJson(cleanedPkg)));
844
- let published = await readTarball(finalTarball), finalFiles = packageFiles(published);
845
- assertSameEntries(packageFiles(packed), finalFiles), validatePackedFiles(finalFiles, allowSuspicious), assertDeclaredFiles(cleanedPkg, finalFiles);
846
- let shippedPkg = manifestOf(published, "the published tarball");
847
- if (assertNoMonorepoProtocols(shippedPkg), assertNoLostConsumerFields(sourcePkg, shippedPkg, extraDevFields), stableJson(shippedPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
1046
+ const published = await readTarball(finalTarball);
1047
+ const finalFiles = packageFiles(published);
1048
+ assertSameEntries(packageFiles(packed), finalFiles);
1049
+ validatePackedFiles(finalFiles, allowSuspicious);
1050
+ assertDeclaredFiles(cleanedPkg, finalFiles);
1051
+ const shippedPkg = manifestOf(published, "the published tarball");
1052
+ assertNoMonorepoProtocols(shippedPkg);
1053
+ assertNoLostConsumerFields(sourcePkg, shippedPkg, extraDevFields);
1054
+ if (stableJson(shippedPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
848
1055
  if (opts.tarballOut !== null) {
849
- await mkdir(opts.tarballOut, { recursive: !0 });
850
- let kept = path.join(opts.tarballOut, path.basename(finalTarball));
851
- await copyFile(finalTarball, kept), console.log(`Final tarball kept at: ${kept}`);
1056
+ await mkdir(opts.tarballOut, { recursive: true });
1057
+ const kept = path.join(opts.tarballOut, path.basename(finalTarball));
1058
+ await copyFile(finalTarball, kept);
1059
+ console.log(`Final tarball kept at: ${kept}`);
852
1060
  }
853
1061
  if (opts.dryRun) {
854
1062
  console.log(`[dry-run] ${finalFiles.length} files:`);
855
- for (let file of finalFiles) console.log(` ${file}`);
1063
+ for (const file of finalFiles) console.log(` ${file}`);
856
1064
  console.log(`[dry-run] cleaned package.json:\n${stringifyJson(cleanedPkg)}`);
857
1065
  return;
858
1066
  }
859
1067
  if (opts.guardOnly) return;
860
- assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs, publishEnv()), runAttached("npm", registry ? [
1068
+ assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs, publishEnv());
1069
+ const publishArgs = registry ? [
861
1070
  "publish",
862
1071
  finalTarball,
863
1072
  "--registry",
@@ -867,39 +1076,44 @@ async function packAndClean(packageDir, opts) {
867
1076
  "publish",
868
1077
  finalTarball,
869
1078
  ...opts.publishArgs
870
- ], packageDir);
1079
+ ];
1080
+ runAttached("npm", publishArgs, packageDir);
871
1081
  } finally {
872
1082
  await rm(root, {
873
- recursive: !0,
874
- force: !0
1083
+ recursive: true,
1084
+ force: true
875
1085
  });
876
1086
  }
877
1087
  }
878
1088
  async function main() {
879
- let rawArgs = process.argv.slice(2), separator = rawArgs.indexOf("--"), cliArgs = separator === -1 ? rawArgs : rawArgs.slice(0, separator), publishArgs = separator === -1 ? [] : rawArgs.slice(separator + 1), parsed = parseArgs({
1089
+ const rawArgs = process.argv.slice(2);
1090
+ const separator = rawArgs.indexOf("--");
1091
+ const cliArgs = separator === -1 ? rawArgs : rawArgs.slice(0, separator);
1092
+ const publishArgs = separator === -1 ? [] : rawArgs.slice(separator + 1);
1093
+ const parsed = parseArgs({
880
1094
  args: cliArgs,
881
- allowPositionals: !0,
1095
+ allowPositionals: true,
882
1096
  options: {
883
1097
  "allow-suspicious": {
884
1098
  type: "boolean",
885
- default: !1
1099
+ default: false
886
1100
  },
887
1101
  "dry-run": {
888
1102
  type: "boolean",
889
- default: !1
1103
+ default: false
890
1104
  },
891
1105
  "guard-only": {
892
1106
  type: "boolean",
893
- default: !1
1107
+ default: false
894
1108
  },
895
1109
  help: {
896
1110
  type: "boolean",
897
1111
  short: "h",
898
- default: !1
1112
+ default: false
899
1113
  },
900
1114
  "no-git-checks": {
901
1115
  type: "boolean",
902
- default: !1
1116
+ default: false
903
1117
  },
904
1118
  registry: {
905
1119
  type: "string",
@@ -907,7 +1121,7 @@ async function main() {
907
1121
  },
908
1122
  "skip-file-check": {
909
1123
  type: "boolean",
910
- default: !1
1124
+ default: false
911
1125
  },
912
1126
  "tarball-out": {
913
1127
  type: "string",
@@ -916,38 +1130,40 @@ async function main() {
916
1130
  version: {
917
1131
  type: "boolean",
918
1132
  short: "v",
919
- default: !1
1133
+ default: false
920
1134
  }
921
1135
  },
922
- strict: !0
1136
+ strict: true
923
1137
  });
924
1138
  if (parsed.values.version) {
925
1139
  console.log(ownVersion());
926
1140
  return;
927
1141
  }
928
1142
  if (parsed.values.help) {
929
- console.log("publish-clean [options] [package-dir] [-- npm publish args]\n\nPacks with pnpm, strips developer-only fields from the packed manifest, validates the\nartifact, and publishes that exact tarball with npm. Arguments after `--` go to\n`npm publish` untouched (e.g. --access public --tag next --provenance).\n\nOptions:\n --dry-run Pack, clean and validate; print the file list and manifest, publish nothing.\n --guard-only Same checks, no output and no publish. For a pre-publish gate.\n --tarball-out DIR Also write the validated tarball into DIR, for attestation or release upload.\n --registry URL Publish to URL, and record it in the artifact's publishConfig.\n --no-git-checks Publish from a working tree with uncommitted changes.\n --skip-file-check Allow a manifest with no \"files\" array.\n --allow-suspicious Allow tests, CI config, lockfiles or tsconfig in the published artifact.\n -h, --help Show this help.\n -v, --version Show the publish-clean version.\n\nManifest configuration, under a \"publish-clean\" key in package.json:\n devFields string[] Extra fields to strip. Refused for fields consumers resolve.\n keepFields string[] Fields to acknowledge, so they stop being reported as unrecognised.\n registry string Default for --registry.\n noGitChecks boolean Default for --no-git-checks.\n skipFileCheck boolean Default for --skip-file-check.\n allowSuspicious boolean Default for --allow-suspicious.\n\nRequires pnpm and npm on PATH. npm provenance additionally requires Node.js 22.14+ and\nnpm 11.5.1+, and only a cloud CI runner can produce it.");
1143
+ console.log(HELP);
930
1144
  return;
931
1145
  }
932
1146
  if (parsed.positionals.length > 1) throw new PublishCleanError(`Unexpected positional arguments before --:\n${parsed.positionals.slice(1).join("\n")}`);
933
1147
  await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), {
934
- allowSuspicious: parsed.values["allow-suspicious"] === !0,
935
- dryRun: parsed.values["dry-run"] === !0,
936
- guardOnly: parsed.values["guard-only"] === !0,
937
- noGitChecks: parsed.values["no-git-checks"] === !0,
1148
+ allowSuspicious: parsed.values["allow-suspicious"] === true,
1149
+ dryRun: parsed.values["dry-run"] === true,
1150
+ guardOnly: parsed.values["guard-only"] === true,
1151
+ noGitChecks: parsed.values["no-git-checks"] === true,
938
1152
  publishArgs,
939
- registry: typeof parsed.values.registry == "string" ? parsed.values.registry : null,
940
- skipFileCheck: parsed.values["skip-file-check"] === !0,
941
- tarballOut: typeof parsed.values["tarball-out"] == "string" ? parsed.values["tarball-out"] : null
1153
+ registry: typeof parsed.values.registry === "string" ? parsed.values.registry : null,
1154
+ skipFileCheck: parsed.values["skip-file-check"] === true,
1155
+ tarballOut: typeof parsed.values["tarball-out"] === "string" ? parsed.values["tarball-out"] : null
942
1156
  });
943
1157
  }
944
1158
  main().catch((error) => {
945
- let details = [
1159
+ const details = [
946
1160
  error instanceof Error ? error.message : String(error),
947
1161
  outputFromError(error, "stdout"),
948
1162
  outputFromError(error, "stderr")
949
1163
  ].filter((detail) => detail.length > 0);
950
- console.error(`publish-clean: ${details.join("\n")}`), process.exitCode = 1;
1164
+ console.error(`publish-clean: ${details.join("\n")}`);
1165
+ process.exitCode = 1;
951
1166
  });
1167
+
952
1168
  //#endregion
953
- export {};
1169
+ export { };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anizoptera/publish-clean",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "Pre-publish npm package cleaner that strips common useless noise and crap from package.json; prevents accidental publication of unwanted things and unresolved dependencies. No deps, one JS file.",
5
5
  "keywords": [
6
6
  "bun",