@anizoptera/publish-clean 0.2.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.
Files changed (4) hide show
  1. package/LICENSE +204 -0
  2. package/README.md +271 -0
  3. package/dist/cli.js +485 -0
  4. package/package.json +48 -0
package/LICENSE ADDED
@@ -0,0 +1,204 @@
1
+ Copyright 2026 Anizoptera
2
+ Copyright 2026 Art Shendrik
3
+
4
+ Apache License
5
+ Version 2.0, January 2004
6
+ http://www.apache.org/licenses/
7
+
8
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9
+
10
+ 1. Definitions.
11
+
12
+ "License" shall mean the terms and conditions for use, reproduction,
13
+ and distribution as defined by Sections 1 through 9 of this document.
14
+
15
+ "Licensor" shall mean the copyright owner or entity authorized by
16
+ the copyright owner that is granting the License.
17
+
18
+ "Legal Entity" shall mean the union of the acting entity and all
19
+ other entities that control, are controlled by, or are under common
20
+ control with that entity. For the purposes of this definition,
21
+ "control" means (i) the power, direct or indirect, to cause the
22
+ direction or management of such entity, whether by contract or
23
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
24
+ outstanding shares, or (iii) beneficial ownership of such entity.
25
+
26
+ "You" (or "Your") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "Source" form shall mean the preferred form for making modifications,
30
+ including but not limited to software source code, documentation
31
+ source, and configuration files.
32
+
33
+ "Object" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but
35
+ not limited to compiled object code, generated documentation,
36
+ and conversions to other media types.
37
+
38
+ "Work" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work
41
+ (an example is provided in the Appendix below).
42
+
43
+ "Derivative Works" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "Contribution" shall mean any work of authorship, including
52
+ the original version of the Work and any modifications or additions
53
+ to that Work or Derivative Works thereof, that is intentionally
54
+ submitted to Licensor for inclusion in the Work by the copyright owner
55
+ or by an individual or Legal Entity authorized to submit on behalf of
56
+ the copyright owner. For the purposes of this definition, "submitted"
57
+ means any form of electronic, verbal, or written communication sent
58
+ to the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "Not a Contribution."
64
+
65
+ "Contributor" shall mean Licensor and any individual or Legal Entity
66
+ on behalf of whom a Contribution has been received by Licensor and
67
+ subsequently incorporated within the Work.
68
+
69
+ 2. Grant of Copyright License. Subject to the terms and conditions of
70
+ this License, each Contributor hereby grants to You a perpetual,
71
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72
+ copyright license to reproduce, prepare Derivative Works of,
73
+ publicly display, publicly perform, sublicense, and distribute the
74
+ Work and such Derivative Works in Source or Object form.
75
+
76
+ 3. Grant of Patent License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ (except as stated in this section) patent license to make, have made,
80
+ use, offer to sell, sell, import, and otherwise transfer the Work,
81
+ where such license applies only to those patent claims licensable
82
+ by such Contributor that are necessarily infringed by their
83
+ Contribution(s) alone or by combination of their Contribution(s)
84
+ with the Work to which such Contribution(s) was submitted. If You
85
+ institute patent litigation against any entity (including a
86
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
87
+ or a Contribution incorporated within the Work constitutes direct
88
+ or contributory patent infringement, then any patent licenses
89
+ granted to You under this License for that Work shall terminate
90
+ as of the date such litigation is filed.
91
+
92
+ 4. Redistribution. You may reproduce and distribute copies of the
93
+ Work or Derivative Works thereof in any medium, with or without
94
+ modifications, and in Source or Object form, provided that You
95
+ meet the following conditions:
96
+
97
+ (a) You must give any other recipients of the Work or
98
+ Derivative Works a copy of this License; and
99
+
100
+ (b) You must cause any modified files to carry prominent notices
101
+ stating that You changed the files; and
102
+
103
+ (c) You must retain, in the Source form of any Derivative Works
104
+ that You distribute, all copyright, patent, trademark, and
105
+ attribution notices from the Source form of the Work,
106
+ excluding those notices that do not pertain to any part of
107
+ the Derivative Works; and
108
+
109
+ (d) If the Work includes a "NOTICE" text file as part of its
110
+ distribution, then any Derivative Works that You distribute must
111
+ include a readable copy of the attribution notices contained
112
+ within such NOTICE file, excluding those notices that do not
113
+ pertain to any part of the Derivative Works, in at least one
114
+ of the following places: within a NOTICE text file distributed
115
+ as part of the Derivative Works; within the Source form or
116
+ documentation, if provided along with the Derivative Works; or,
117
+ within a display generated by the Derivative Works, if and
118
+ wherever such third-party notices normally appear. The contents
119
+ of the NOTICE file are for informational purposes only and
120
+ do not modify the License. You may add Your own attribution
121
+ notices within Derivative Works that You distribute, alongside
122
+ or as an addendum to the NOTICE text from the Work, provided
123
+ that such additional attribution notices cannot be construed
124
+ as modifying the License.
125
+
126
+ You may add Your own copyright statement to Your modifications and
127
+ may provide additional or different license terms and conditions
128
+ for use, reproduction, or distribution of Your modifications, or
129
+ for any such Derivative Works as a whole, provided Your use,
130
+ reproduction, and distribution of the Work otherwise complies with
131
+ the conditions stated in this License.
132
+
133
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
134
+ any Contribution intentionally submitted for inclusion in the Work
135
+ by You to the Licensor shall be under the terms and conditions of
136
+ this License, without any additional terms or conditions.
137
+ Notwithstanding the above, nothing herein shall supersede or modify
138
+ the terms of any separate license agreement you may have executed
139
+ with Licensor regarding such Contributions.
140
+
141
+ 6. Trademarks. This License does not grant permission to use the trade
142
+ names, trademarks, service marks, or product names of the Licensor,
143
+ except as required for reasonable and customary use in describing the
144
+ origin of the Work and reproducing the content of the NOTICE file.
145
+
146
+ 7. Disclaimer of Warranty. Unless required by applicable law or
147
+ agreed to in writing, Licensor provides the Work (and each
148
+ Contributor provides its Contributions) on an "AS IS" BASIS,
149
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150
+ implied, including, without limitation, any warranties or conditions
151
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152
+ PARTICULAR PURPOSE. You are solely responsible for determining the
153
+ appropriateness of using or redistributing the Work and assume any
154
+ risks associated with Your exercise of permissions under this License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright [yyyy] [name of copyright owner]
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,271 @@
1
+ # @anizoptera/publish-clean
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@anizoptera/publish-clean?label=npm)](https://www.npmjs.com/package/@anizoptera/publish-clean)
4
+ [![CI](https://github.com/Anizoptera/publish-clean/actions/workflows/check.yml/badge.svg?branch=main)](https://github.com/Anizoptera/publish-clean/actions/workflows/check.yml)
5
+ [![Node >=20](https://img.shields.io/badge/node-%3E%3D20-339933?logo=node.js&logoColor=white)](package.json)
6
+ [![pnpm pack + npm publish](https://img.shields.io/badge/pnpm_pack%20%2B%20npm_publish-f69220?logo=pnpm&logoColor=white)](https://pnpm.io/cli/pack)
7
+ [![Bun checked](https://img.shields.io/badge/Bun-checked-000000?logo=bun&logoColor=white)](https://bun.sh/docs/cli/test)
8
+ [![Runtime deps](https://img.shields.io/badge/runtime_deps-0-2ea44f)](package.json)
9
+ [![License](https://img.shields.io/github/license/Anizoptera/publish-clean)](LICENSE)
10
+
11
+ Publish a pnpm package from the tarball you actually intend to ship.
12
+
13
+ This is pnpm-first on purpose. `publish-clean` is built for packages that rely on
14
+ pnpm workspace, catalog, and publish behavior.
15
+
16
+ `publish-clean` runs `pnpm pack`, opens the packed package, checks for files and
17
+ manifest entries that should not ship, removes development-only metadata from
18
+ the extracted copy, asks npm to pack that cleaned copy, validates the final npm
19
+ tarball, and publishes that tarball with `npm publish`.
20
+
21
+ Your working tree is left alone.
22
+
23
+ ## Why use this
24
+
25
+ `pnpm pack` is good at workspace packages. It understands pnpm's workspace and
26
+ catalog behavior in a way generic cleanup scripts usually do not.
27
+
28
+ The rough edge is the packed manifest. It can still carry maintainer-only
29
+ fields: dev dependencies, test runner config, workspace tooling, local
30
+ overrides, and other project metadata consumers do not need.
31
+
32
+ `publish-clean` keeps pnpm in charge of deciding what the package is, then uses
33
+ npm for the final registry upload so trusted publishing and provenance follow
34
+ npm's first-party path.
35
+
36
+ It is for packages that want the npm artifact to contain only what was meant to
37
+ ship:
38
+
39
+ - built files
40
+ - README
41
+ - license
42
+ - package metadata
43
+ - any other files the package intentionally exposes
44
+
45
+ No accidental tests, CI config, local agent docs, lockfiles, private keys, or
46
+ workspace-only dependency specs.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pnpm add -D @anizoptera/publish-clean
52
+ ```
53
+
54
+ Requirements:
55
+
56
+ - Node.js 20 or newer
57
+ - `pnpm`
58
+ - `npm`
59
+ - `tar`
60
+
61
+ Trusted publishing with `--provenance` requires Node.js 22.14.0 or newer and
62
+ npm 11.5.1 or newer.
63
+
64
+ The CLI runs on Node. This repository uses Bun for fast local checks and tests.
65
+ Package creation intentionally goes through pnpm. The final registry upload
66
+ goes through npm. Yarn and Bun are not treated as equivalent pack/publish
67
+ backends.
68
+
69
+ ## Basic setup
70
+
71
+ ```json
72
+ {
73
+ "scripts": {
74
+ "check": "bun run typecheck && bun run test && bun run build",
75
+ "prepublishOnly": "node -e \"console.error('Use pnpm run publish:clean to publish the cleaned artifact.'); process.exit(1)\"",
76
+ "publish:clean": "bun run check && publish-clean -- --access public --tag latest --provenance"
77
+ },
78
+ "devDependencies": {
79
+ "@anizoptera/publish-clean": "^0.1.0"
80
+ }
81
+ }
82
+ ```
83
+
84
+ Then publish with:
85
+
86
+ ```bash
87
+ pnpm run publish:clean
88
+ ```
89
+
90
+ Use a script name like `publish:clean` or `release`. Avoid naming it `publish`;
91
+ that collides too easily with npm lifecycle behavior.
92
+
93
+ ## Commands
94
+
95
+ ```bash
96
+ publish-clean --dry-run
97
+ publish-clean --guard-only
98
+ publish-clean --registry https://registry.npmjs.org -- --access public --tag latest --provenance
99
+ publish-clean packages/my-lib -- --access public --tag next
100
+ ```
101
+
102
+ Start with `--dry-run`. It prints the temporary extracted package path, so you
103
+ can inspect the cleaned package and final npm tarball that would be published.
104
+
105
+ ## What happens
106
+
107
+ ```text
108
+ source package
109
+ -> pnpm pack
110
+ -> inspect tarball contents
111
+ -> write cleaned package.json
112
+ -> validate declared package paths
113
+ -> npm pack the cleaned package
114
+ -> validate the final npm tarball
115
+ -> npm publish the final tarball
116
+ ```
117
+
118
+ With `--dry-run` or `--guard-only`, the publish step is skipped.
119
+
120
+ ## Options
121
+
122
+ ```bash
123
+ publish-clean [options] [package-dir] [-- npm-publish-args]
124
+ ```
125
+
126
+ - `--dry-run`: pack, check, clean, and print the cleaned package and final
127
+ tarball paths.
128
+ - `--guard-only`: run the full pack, clean, and final-tarball guard without
129
+ publishing.
130
+ - `--registry URL`: set `publishConfig.registry` on the cleaned manifest.
131
+ - `--skip-file-check`: skip suspicious-file checks and the required `files`
132
+ array check. Critical leak checks still run.
133
+ - `--no-git-checks`: skip the source git cleanliness check.
134
+ - `-h`, `--help`: print usage.
135
+
136
+ Arguments after `--` go to `npm publish`, which publishes the final cleaned
137
+ tarball.
138
+
139
+ Pass the npm dist-tag explicitly. For normal public releases, use
140
+ `--tag latest`.
141
+
142
+ ## Package config
143
+
144
+ Stable project defaults can live in `package.json`:
145
+
146
+ ```json
147
+ {
148
+ "publish-clean": {
149
+ "registry": "https://registry.npmjs.org",
150
+ "skipFileCheck": false,
151
+ "noGitChecks": false,
152
+ "devFields": ["customBuildOnlyField"]
153
+ }
154
+ }
155
+ ```
156
+
157
+ Keep one-off choices on the command line. Dist-tags are a good example.
158
+
159
+ ## What it checks
160
+
161
+ `publish-clean` refuses to continue when:
162
+
163
+ - the package is `private: true`
164
+ - the source package has uncommitted changes, unless disabled
165
+ - the package has no non-empty `files` array, unless disabled
166
+ - the tarball contains critical leaks like `.env`, `.npmrc`, `.git`,
167
+ `node_modules`, or private-key files
168
+ - dependency specs still use `catalog:`, `workspace:`, `link:`, or `portal:`
169
+ - declared export, type, import, browser, bin, or side-effect paths are missing
170
+ from the cleaned package
171
+ - the final npm tarball drops files that were present in the cleaned package
172
+ - trusted GitHub publication uses `--provenance` but package repository metadata
173
+ does not match the workflow repository
174
+
175
+ It also warns when a package-manager lifecycle looks like npm, Yarn, or Bun.
176
+ That warning is intentional: this tool relies on pnpm's pack and publish
177
+ behavior.
178
+
179
+ Critical leak checks cannot be disabled.
180
+
181
+ For restricted npm packages, use `publishConfig.access: "restricted"` or pass
182
+ `--access restricted`; do not set `private: true`, because npm treats that as a
183
+ publish block.
184
+
185
+ ## What it removes
186
+
187
+ From the extracted package manifest, `publish-clean` removes maintainer-only
188
+ fields such as:
189
+
190
+ - `devDependencies`
191
+ - `workspaces`
192
+ - `pnpm`
193
+ - test, lint, format, coverage, build-system, and release-tool config fields
194
+ - scripts except consumer install lifecycle scripts
195
+
196
+ The repository files are not changed.
197
+
198
+ ## What it does not do
199
+
200
+ This is not a release manager. It does not choose versions, write changelogs,
201
+ create tags, push commits, create GitHub releases, set up npm trusted
202
+ publishing, or decide your dist-tag policy.
203
+
204
+ Use tools like Changesets, release-please, semantic-release, release-it, or np
205
+ for that. Use `publish-clean` as the guard or final publish command.
206
+
207
+ It also does not replace package validators. Run `publint` and
208
+ `@arethetypeswrong/cli` for package compatibility checks.
209
+
210
+ ## Public and private packages
211
+
212
+ For public npm packages, use npm trusted publishing in GitHub Actions and pass:
213
+
214
+ ```bash
215
+ publish-clean -- --access public --tag latest --provenance
216
+ ```
217
+
218
+ For restricted npm packages, use the same clean artifact pipeline and usually
219
+ pass:
220
+
221
+ ```bash
222
+ publish-clean -- --access restricted --tag latest
223
+ ```
224
+
225
+ Do not set `private: true` for a package you intend to publish. Private package
226
+ install credentials are separate from publish credentials.
227
+ Trusted publishing authenticates the publish operation; it does not grant
228
+ consumers access to private dependencies.
229
+
230
+ ## Related tools
231
+
232
+ This package borrows the useful part of
233
+ [`clean-publish`](https://github.com/shashkovdanil/clean-publish): publish from
234
+ a cleaned copy, not from a rewritten source tree.
235
+
236
+ It deliberately stays close to package-manager behavior instead of inventing its
237
+ own file-selection rules. The relevant tools and specs are
238
+ [`npm-packlist`](https://github.com/npm/npm-packlist),
239
+ [`npm pack`](https://docs.npmjs.com/cli/v11/commands/npm-pack/),
240
+ [`npm publish`](https://docs.npmjs.com/cli/v11/commands/npm-publish/),
241
+ [`pnpm pack`](https://pnpm.io/cli/pack), and pnpm
242
+ [`publishConfig`](https://pnpm.io/package_json#publishconfig).
243
+
244
+ For preview installs, see
245
+ [`pkg-pr-new`](https://github.com/stackblitz-labs/pkg.pr.new). For provenance,
246
+ use [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/). Both
247
+ are useful layers. Neither one cleans the package contents.
248
+
249
+ ## Development
250
+
251
+ ```bash
252
+ bun install --frozen-lockfile
253
+ bun run check
254
+ ```
255
+
256
+ Before committing workflow changes:
257
+
258
+ ```bash
259
+ actions-up --yes
260
+ ```
261
+
262
+ This package has no runtime dependencies.
263
+
264
+ ## Alternatives and references
265
+
266
+ - [`clean-publish`](https://github.com/shashkovdanil/clean-publish)
267
+ - [`npm-packlist`](https://github.com/npm/npm-packlist)
268
+
269
+ ## License
270
+
271
+ Apache-2.0. Copyright 2026 Anizoptera and Art Shendrik.
package/dist/cli.js ADDED
@@ -0,0 +1,485 @@
1
+ #!/usr/bin/env node
2
+ import { execFileSync } from "node:child_process";
3
+ import { readFileSync, statSync } from "node:fs";
4
+ import { copyFile, mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { parseArgs } from "node:util";
8
+ //#region src/cli.ts
9
+ const DEV_FIELDS = new Set(/* @__PURE__ */ "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 = new Set([
10
+ "preinstall",
11
+ "install",
12
+ "postinstall",
13
+ "prepare",
14
+ "uninstall"
15
+ ]), DEP_FIELDS = [
16
+ "dependencies",
17
+ "devDependencies",
18
+ "optionalDependencies",
19
+ "peerDependencies",
20
+ "overrides",
21
+ "resolutions"
22
+ ], MONOREPO_PROTOCOLS = [
23
+ "catalog:",
24
+ "workspace:",
25
+ "link:",
26
+ "portal:"
27
+ ], RUNTIME_MANIFEST_FIELDS = new Set([
28
+ ...DEP_FIELDS,
29
+ "bin",
30
+ "browser",
31
+ "bundleDependencies",
32
+ "bundledDependencies",
33
+ "cpu",
34
+ "engines",
35
+ "exports",
36
+ "files",
37
+ "imports",
38
+ "license",
39
+ "main",
40
+ "module",
41
+ "name",
42
+ "optionalDependencies",
43
+ "os",
44
+ "peerDependenciesMeta",
45
+ "publishConfig",
46
+ "sideEffects",
47
+ "type",
48
+ "types",
49
+ "typesVersions",
50
+ "typings",
51
+ "version"
52
+ ]), CRITICAL_PATTERNS = [
53
+ /(?:^|\/)node_modules(?:\/|$)/,
54
+ /(?:^|\/)\.git(?:\/|$)/,
55
+ /(?:^|\/)\.env(?:\.|$)/,
56
+ /(?:^|\/)\.npmrc$/,
57
+ /\.(?:pem|key|p12|pfx)$/
58
+ ], SUSPICIOUS_PATTERNS = [
59
+ /(?:^|\/)(?:test|tests|__tests__|__snapshots__|coverage)(?:\/|$)/,
60
+ /(?:^|\/)\.github(?:\/|$)/,
61
+ /(?:^|\/)tsconfig[^/]*\.json$/,
62
+ /(?:^|\/)(?:pnpm-lock\.yaml|bun\.lock|package-lock\.json)$/,
63
+ /\.(?:test|spec)\.[cm]?[jt]sx?$/
64
+ ], PUBLISH_ADVISORY = "publish-clean uses pnpm pack intentionally; npm, yarn, and bun pack do not reliably normalize pnpm workspace/catalog manifests.", MIN_TRUSTED_NPM_VERSION = [
65
+ 11,
66
+ 5,
67
+ 1
68
+ ];
69
+ var PublishCleanError = class extends Error {
70
+ constructor(message, options) {
71
+ super(message, options), this.name = "PublishCleanError";
72
+ }
73
+ };
74
+ function isObject(value) {
75
+ return typeof value == "object" && !!value && !Array.isArray(value);
76
+ }
77
+ function readJson(file) {
78
+ let parsed;
79
+ try {
80
+ parsed = JSON.parse(readFileSync(file, "utf8"));
81
+ } catch (cause) {
82
+ throw new PublishCleanError(`Unable to parse JSON file: ${file}`, { cause });
83
+ }
84
+ if (!isObject(parsed)) throw new PublishCleanError(`${file} must contain a JSON object.`);
85
+ return parsed;
86
+ }
87
+ function stringifyJson(value) {
88
+ return `${JSON.stringify(value, null, 2)}\n`;
89
+ }
90
+ function stableJson(value) {
91
+ return JSON.stringify(stableValue(value));
92
+ }
93
+ function stableValue(value) {
94
+ 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;
95
+ }
96
+ function run(command, args, cwd) {
97
+ return execFileSync(command, [...args], {
98
+ cwd,
99
+ encoding: "utf8",
100
+ stdio: [
101
+ "ignore",
102
+ "pipe",
103
+ "pipe"
104
+ ]
105
+ });
106
+ }
107
+ function outputFromError(error, key) {
108
+ if (!isObject(error)) return "";
109
+ let output = error[key];
110
+ return typeof output == "string" ? output.trim() : output instanceof Uint8Array ? Buffer.from(output).toString("utf8").trim() : "";
111
+ }
112
+ function requireTool(name) {
113
+ try {
114
+ execFileSync(name, ["--version"], { stdio: "ignore" });
115
+ } catch (cause) {
116
+ throw new PublishCleanError(`Required tool "${name}" is not available in PATH.`, { cause });
117
+ }
118
+ }
119
+ function npmVersion() {
120
+ let raw = run("npm", ["--version"], process.cwd()).trim(), parts = raw.split(".").map((part) => Number.parseInt(part, 10));
121
+ if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse npm version: ${raw}`);
122
+ return [
123
+ parts[0] ?? 0,
124
+ parts[1] ?? 0,
125
+ parts[2] ?? 0
126
+ ];
127
+ }
128
+ function isAtLeast(actual, minimum) {
129
+ for (let index of [
130
+ 0,
131
+ 1,
132
+ 2
133
+ ]) {
134
+ if (actual[index] > minimum[index]) return !0;
135
+ if (actual[index] < minimum[index]) return !1;
136
+ }
137
+ return !0;
138
+ }
139
+ function wantsTrustedPublish(pkg, publishArgs) {
140
+ return publishArgs.includes("--provenance") || isObject(pkg.publishConfig) && pkg.publishConfig.provenance === !0 ? !0 : process.env.GITHUB_ACTIONS === "true" && typeof process.env.ACTIONS_ID_TOKEN_REQUEST_URL == "string";
141
+ }
142
+ function assertTrustedPublishingRuntime(pkg, publishArgs) {
143
+ if (!wantsTrustedPublish(pkg, publishArgs)) return;
144
+ let actual = npmVersion();
145
+ if (!isAtLeast(actual, MIN_TRUSTED_NPM_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires npm ${MIN_TRUSTED_NPM_VERSION.join(".")} or newer; found ${actual.join(".")}.`);
146
+ let node = process.versions.node.split(".").map(Number);
147
+ if (!isAtLeast([
148
+ node[0] ?? 0,
149
+ node[1] ?? 0,
150
+ node[2] ?? 0
151
+ ], [
152
+ 22,
153
+ 14,
154
+ 0
155
+ ])) throw new PublishCleanError(`Trusted npm publishing requires Node.js 22.14.0 or newer; found ${process.versions.node}.`);
156
+ }
157
+ function warnIfNonPnpmLifecycle() {
158
+ let userAgent = process.env.npm_config_user_agent;
159
+ !userAgent || userAgent.startsWith("pnpm/") || console.warn(`${PUBLISH_ADVISORY} Detected lifecycle user agent: ${userAgent}`);
160
+ }
161
+ function assertCleanGit(packageDir, skip) {
162
+ if (!skip) try {
163
+ let output = run("git", [
164
+ "status",
165
+ "--porcelain",
166
+ "--",
167
+ "."
168
+ ], packageDir).trim();
169
+ if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
170
+ } catch (error) {
171
+ throw error instanceof PublishCleanError ? error : new PublishCleanError("Unable to verify source git status.", { cause: error });
172
+ }
173
+ }
174
+ function assertPublicPackage(pkg) {
175
+ if (pkg.private === !0) throw new PublishCleanError("Refusing to publish a package with private: true.");
176
+ }
177
+ function repositoryUrl(pkg) {
178
+ return typeof pkg.repository == "string" ? pkg.repository : isObject(pkg.repository) && typeof pkg.repository.url == "string" ? pkg.repository.url : null;
179
+ }
180
+ function githubRepositorySlug(url) {
181
+ let withoutGitPrefix = url.startsWith("git+") ? url.slice(4) : url;
182
+ if (withoutGitPrefix.startsWith("git@github.com:")) {
183
+ let slug = withoutGitPrefix.slice(15);
184
+ return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
185
+ }
186
+ try {
187
+ let parsed = new URL(withoutGitPrefix);
188
+ if (parsed.hostname !== "github.com") return null;
189
+ let slug = parsed.pathname.replace(/^\/+/, "");
190
+ return slug.endsWith(".git") ? slug.slice(0, -4) : slug;
191
+ } catch {
192
+ return null;
193
+ }
194
+ }
195
+ function assertRepositoryForTrustedPublish(pkg, publishArgs) {
196
+ if (!wantsTrustedPublish(pkg, publishArgs) || process.env.GITHUB_ACTIONS !== "true" || typeof process.env.GITHUB_REPOSITORY != "string") return;
197
+ let repoUrl = repositoryUrl(pkg);
198
+ if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
199
+ if (githubRepositorySlug(repoUrl) !== process.env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${process.env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
200
+ }
201
+ function stripManifest(pkg, extraDevFields) {
202
+ let stripped = { ...pkg };
203
+ for (let field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
204
+ let scripts = isObject(pkg.scripts) ? pkg.scripts : null;
205
+ if (scripts) {
206
+ let kept = {};
207
+ for (let [name, value] of Object.entries(scripts)) CONSUMER_SCRIPTS.has(name) && typeof value == "string" && (kept[name] = value);
208
+ Object.keys(kept).length > 0 ? stripped.scripts = kept : delete stripped.scripts;
209
+ }
210
+ return stripped;
211
+ }
212
+ function assertNoMonorepoProtocols(pkg) {
213
+ let failures = [];
214
+ for (let field of DEP_FIELDS) {
215
+ let map = pkg[field];
216
+ 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}`);
217
+ }
218
+ let pnpm = pkg.pnpm;
219
+ if (isObject(pnpm) && isObject(pnpm.overrides)) for (let [name, spec] of Object.entries(pnpm.overrides)) typeof spec == "string" && MONOREPO_PROTOCOLS.some((prefix) => spec.includes(prefix)) && failures.push(`pnpm.overrides.${name}: ${spec}`);
220
+ if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
221
+ }
222
+ function customDevFields(config) {
223
+ if (!Array.isArray(config.devFields)) return [];
224
+ let fields = config.devFields.filter((field) => typeof field == "string"), unsafe = fields.filter((field) => RUNTIME_MANIFEST_FIELDS.has(field));
225
+ if (unsafe.length > 0) throw new PublishCleanError(`publish-clean.devFields cannot remove runtime/public manifest fields:\n${unsafe.join("\n")}`);
226
+ return fields;
227
+ }
228
+ async function walkFiles(dir, root, files) {
229
+ let entries = await readdir(dir, { withFileTypes: !0 });
230
+ for (let entry of entries) {
231
+ let absolute = path.join(dir, entry.name), relative = path.relative(root, absolute).replaceAll(path.sep, "/");
232
+ if (entry.isDirectory()) {
233
+ await walkFiles(absolute, root, files);
234
+ continue;
235
+ }
236
+ entry.isFile() && files.push(relative);
237
+ }
238
+ }
239
+ function assertFilesField(pkg, skip) {
240
+ if (!skip && (!Array.isArray(pkg.files) || pkg.files.length === 0)) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
241
+ }
242
+ function validatePackedFiles(files, skipSuspicious) {
243
+ let critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
244
+ if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
245
+ if (skipSuspicious) return;
246
+ let suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
247
+ if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
248
+ }
249
+ function listTarballFiles(tarball, cwd) {
250
+ return run("tar", ["tzf", tarball], cwd).trim().split("\n").filter(Boolean).map((file) => file.replaceAll(path.sep, "/")).map((file) => file.startsWith("package/") ? file.slice(8) : file).filter((file) => file.length > 0 && !file.endsWith("/")).sort();
251
+ }
252
+ function readTarballJson(tarball, file, cwd) {
253
+ let parsed;
254
+ try {
255
+ parsed = JSON.parse(run("tar", [
256
+ "xOzf",
257
+ tarball,
258
+ `package/${file}`
259
+ ], cwd));
260
+ } catch (cause) {
261
+ throw new PublishCleanError(`Unable to read JSON from final npm tarball: ${file}`, { cause });
262
+ }
263
+ if (!isObject(parsed)) throw new PublishCleanError(`Final npm tarball ${file} must contain a JSON object.`);
264
+ return parsed;
265
+ }
266
+ /**
267
+ * Locates the tarball a packer just produced by reading its destination directory.
268
+ *
269
+ * Every pack here targets a directory this process created and owns exclusively, so
270
+ * the result is discoverable without interpreting the packer's output at all. That
271
+ * matters because `pack` runs the package's `prepare`/`prepack` lifecycle scripts and
272
+ * forwards their stdout: any build tool that logs — most of them — lands ahead of the
273
+ * `--json` payload and breaks a parse of that stream. Reading the directory is immune
274
+ * to whatever a foreign package's scripts choose to print.
275
+ *
276
+ * Exactly one tarball is the invariant, not a convenience: more than one means the
277
+ * destination was not exclusive and the wrong artifact could be published.
278
+ */
279
+ async function soleTarball(packRoot, packer) {
280
+ let tarballs = (await readdir(packRoot)).filter((entry) => entry.endsWith(".tgz")), [tarball] = tarballs;
281
+ if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`${packer} left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
282
+ return path.join(packRoot, tarball);
283
+ }
284
+ function assertFinalTarballIncludesCleanedFiles(cleanedFiles, finalFiles) {
285
+ let missing = cleanedFiles.filter((file) => !finalFiles.includes(file)).sort();
286
+ if (missing.length !== 0) throw new PublishCleanError(`Final npm tarball dropped files from the cleaned package:\n${missing.join("\n")}`);
287
+ }
288
+ function collectDeclaredPaths(value, out) {
289
+ if (typeof value == "string") {
290
+ out.push(value);
291
+ return;
292
+ }
293
+ if (typeof value != "boolean") {
294
+ if (Array.isArray(value)) {
295
+ for (let item of value) collectDeclaredPaths(item, out);
296
+ return;
297
+ }
298
+ if (isObject(value)) for (let item of Object.values(value)) collectDeclaredPaths(item, out);
299
+ }
300
+ }
301
+ function collectRelativeDeclaredPaths(value, out) {
302
+ if (typeof value == "string") {
303
+ (value.startsWith("./") || value.startsWith("../")) && out.push(value);
304
+ return;
305
+ }
306
+ if (typeof value != "boolean") {
307
+ if (Array.isArray(value)) {
308
+ for (let item of value) collectRelativeDeclaredPaths(item, out);
309
+ return;
310
+ }
311
+ if (isObject(value)) for (let item of Object.values(value)) collectRelativeDeclaredPaths(item, out);
312
+ }
313
+ }
314
+ function normalizeDeclaredPath(declared) {
315
+ let withoutDot = declared.startsWith("./") ? declared.slice(2) : declared;
316
+ if (!withoutDot || path.posix.isAbsolute(withoutDot)) return null;
317
+ let normalized = path.posix.normalize(withoutDot);
318
+ return normalized === "." || normalized === ".." || normalized.startsWith("../") ? null : normalized;
319
+ }
320
+ function assertDeclaredFiles(pkg, packageDir) {
321
+ let paths = [];
322
+ for (let field of [
323
+ "main",
324
+ "module",
325
+ "types",
326
+ "typings",
327
+ "bin"
328
+ ]) collectDeclaredPaths(pkg[field], paths);
329
+ typeof pkg.browser == "string" ? collectDeclaredPaths(pkg.browser, paths) : collectRelativeDeclaredPaths(pkg.browser, paths);
330
+ for (let field of [
331
+ "exports",
332
+ "imports",
333
+ "sideEffects"
334
+ ]) collectRelativeDeclaredPaths(pkg[field], paths);
335
+ collectDeclaredPaths(pkg.typesVersions, paths);
336
+ let normalized = paths.map((declared) => ({
337
+ declared,
338
+ normalized: normalizeDeclaredPath(declared)
339
+ })), invalid = normalized.filter((item) => item.normalized === null);
340
+ if (invalid.length > 0) throw new PublishCleanError(`Manifest declares invalid package paths:\n${invalid.map((item) => item.declared).join("\n")}`);
341
+ let missing = normalized.filter((declared) => !declared.declared.includes("*") && !exists(path.join(packageDir, String(declared.normalized))));
342
+ if (missing.length > 0) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((item) => item.declared).join("\n")}`);
343
+ }
344
+ function exists(file) {
345
+ try {
346
+ return !!statSync(file).isFile();
347
+ } catch {
348
+ return !1;
349
+ }
350
+ }
351
+ function packageConfig(pkg) {
352
+ let config = pkg["publish-clean"];
353
+ return isObject(config) ? config : {};
354
+ }
355
+ async function packAndClean(packageDir, opts) {
356
+ requireTool("pnpm"), requireTool("npm"), requireTool("tar"), warnIfNonPnpmLifecycle();
357
+ let sourcePkg = readJson(path.join(packageDir, "package.json"));
358
+ !opts.guardOnly && !opts.dryRun && assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
359
+ let config = packageConfig(sourcePkg), skipFileCheck = opts.skipFileCheck || config.skipFileCheck === !0, noGitChecks = opts.noGitChecks || config.noGitChecks === !0, registry = opts.registry ?? (typeof config.registry == "string" ? config.registry : null), extraDevFields = customDevFields(config);
360
+ assertPublicPackage(sourcePkg), assertCleanGit(packageDir, noGitChecks), assertFilesField(sourcePkg, skipFileCheck);
361
+ let root = await mkdtemp(path.join(tmpdir(), "publish-clean-")), keepRoot = !1;
362
+ try {
363
+ run("pnpm", [
364
+ "pack",
365
+ "--pack-destination",
366
+ root
367
+ ], packageDir), run("tar", [
368
+ "xzf",
369
+ await soleTarball(root, "pnpm pack"),
370
+ "-C",
371
+ root
372
+ ], packageDir);
373
+ let extracted = path.join(root, "package");
374
+ if (!(await stat(extracted)).isDirectory()) throw new PublishCleanError("Extracted tarball did not contain package/ directory.");
375
+ let files = [];
376
+ await walkFiles(extracted, extracted, files), validatePackedFiles(files, skipFileCheck);
377
+ let packedPkgPath = path.join(extracted, "package.json"), cleanedPkg = stripManifest(readJson(packedPkgPath), extraDevFields);
378
+ if (registry) {
379
+ let publishConfig = isObject(cleanedPkg.publishConfig) ? { ...cleanedPkg.publishConfig } : {};
380
+ publishConfig.registry = registry, cleanedPkg.publishConfig = publishConfig;
381
+ }
382
+ assertNoMonorepoProtocols(cleanedPkg), await writeFile(packedPkgPath, stringifyJson(cleanedPkg)), assertDeclaredFiles(cleanedPkg, extracted);
383
+ let cleanedFiles = [];
384
+ await walkFiles(extracted, extracted, cleanedFiles);
385
+ let finalPackRoot = path.join(root, "npm-pack");
386
+ await mkdir(finalPackRoot), run("npm", [
387
+ "pack",
388
+ "--ignore-scripts",
389
+ "--pack-destination",
390
+ finalPackRoot
391
+ ], extracted);
392
+ let finalTarball = await soleTarball(finalPackRoot, "npm pack"), finalFiles = listTarballFiles(finalTarball, extracted);
393
+ validatePackedFiles(finalFiles, skipFileCheck), assertFinalTarballIncludesCleanedFiles(cleanedFiles, finalFiles);
394
+ let finalPkg = readTarballJson(finalTarball, "package.json", extracted);
395
+ if (assertNoMonorepoProtocols(finalPkg), stableJson(finalPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Final npm tarball manifest differs from the cleaned manifest.");
396
+ if (opts.tarballOut !== null) {
397
+ await mkdir(opts.tarballOut, { recursive: !0 });
398
+ let kept = path.join(opts.tarballOut, path.basename(finalTarball));
399
+ await copyFile(finalTarball, kept), console.log(`Final tarball kept at: ${kept}`);
400
+ }
401
+ if (opts.guardOnly || opts.dryRun) {
402
+ if (!opts.dryRun) return;
403
+ keepRoot = !0, console.log(`[dry-run] Extracted package at: ${extracted}`), console.log(`[dry-run] Final tarball at: ${finalTarball}`);
404
+ return;
405
+ }
406
+ assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs), run("npm", registry ? [
407
+ "publish",
408
+ finalTarball,
409
+ "--registry",
410
+ registry,
411
+ ...opts.publishArgs
412
+ ] : [
413
+ "publish",
414
+ finalTarball,
415
+ ...opts.publishArgs
416
+ ], extracted);
417
+ } finally {
418
+ keepRoot || await rm(root, {
419
+ recursive: !0,
420
+ force: !0
421
+ });
422
+ }
423
+ }
424
+ async function main() {
425
+ 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({
426
+ args: cliArgs,
427
+ allowPositionals: !0,
428
+ options: {
429
+ "dry-run": {
430
+ type: "boolean",
431
+ default: !1
432
+ },
433
+ "guard-only": {
434
+ type: "boolean",
435
+ default: !1
436
+ },
437
+ help: {
438
+ type: "boolean",
439
+ short: "h",
440
+ default: !1
441
+ },
442
+ "no-git-checks": {
443
+ type: "boolean",
444
+ default: !1
445
+ },
446
+ registry: {
447
+ type: "string",
448
+ default: void 0
449
+ },
450
+ "skip-file-check": {
451
+ type: "boolean",
452
+ default: !1
453
+ },
454
+ "tarball-out": {
455
+ type: "string",
456
+ default: void 0
457
+ }
458
+ },
459
+ strict: !0
460
+ });
461
+ if (parsed.values.help) {
462
+ console.log("publish-clean [--dry-run] [--guard-only] [--no-git-checks] [--registry URL] [--skip-file-check] [--tarball-out DIR] [package-dir] [-- npm-publish-args]");
463
+ return;
464
+ }
465
+ if (parsed.positionals.length > 1) throw new PublishCleanError(`Unexpected positional arguments before --:\n${parsed.positionals.slice(1).join("\n")}`);
466
+ await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), {
467
+ dryRun: parsed.values["dry-run"] === !0,
468
+ guardOnly: parsed.values["guard-only"] === !0,
469
+ noGitChecks: parsed.values["no-git-checks"] === !0,
470
+ publishArgs,
471
+ registry: typeof parsed.values.registry == "string" ? parsed.values.registry : null,
472
+ skipFileCheck: parsed.values["skip-file-check"] === !0,
473
+ tarballOut: typeof parsed.values["tarball-out"] == "string" ? parsed.values["tarball-out"] : null
474
+ });
475
+ }
476
+ main().catch((error) => {
477
+ let details = [
478
+ error instanceof Error ? error.message : String(error),
479
+ outputFromError(error, "stdout"),
480
+ outputFromError(error, "stderr")
481
+ ].filter((detail) => detail.length > 0);
482
+ console.error(`publish-clean: ${details.join("\n")}`), process.exitCode = 1;
483
+ });
484
+ //#endregion
485
+ export {};
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@anizoptera/publish-clean",
3
+ "version": "0.2.0",
4
+ "description": "Publish pnpm workspace packages from a cleaned, validated package tarball.",
5
+ "keywords": [
6
+ "bun",
7
+ "cleanup",
8
+ "monorepo",
9
+ "npm",
10
+ "pack",
11
+ "package",
12
+ "pnpm",
13
+ "publish"
14
+ ],
15
+ "homepage": "https://github.com/Anizoptera/publish-clean#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/Anizoptera/publish-clean/issues"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "author": "Anizoptera",
21
+ "contributors": [
22
+ "Art Shendrik"
23
+ ],
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/Anizoptera/publish-clean.git"
27
+ },
28
+ "bin": {
29
+ "publish-clean": "./dist/cli.js"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "type": "module",
37
+ "sideEffects": false,
38
+ "exports": {
39
+ "./package.json": "./package.json"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public",
43
+ "provenance": true
44
+ },
45
+ "engines": {
46
+ "node": ">=20"
47
+ }
48
+ }