@git.zone/cli 8.5.1 → 8.7.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 (40) hide show
  1. package/assets/templates/asset_tspack_release_gitea/.gitea/workflows/release.yml +12 -18
  2. package/assets/templates/asset_tspack_release_gitea/scripts/gitzone-gitea-tag.d.mts +22 -0
  3. package/assets/templates/asset_tspack_release_gitea/scripts/gitzone-gitea-tag.mjs +48 -0
  4. package/assets/templates/asset_tspack_release_gitea/scripts/gitzone-release-api.mjs +244 -74
  5. package/assets/templates/asset_tspack_release_gitea/scripts/gitzone-sealed-release.mjs +103 -38
  6. package/assets/templates/vscode/.vscode/settings.json +57 -0
  7. package/dist_ts/00_commitinfo_data.js +1 -1
  8. package/dist_ts/classes.gitzoneconfig.d.ts +3 -0
  9. package/dist_ts/classes.gitzoneconfig.js +1 -1
  10. package/dist_ts/helpers.objects.d.ts +2 -0
  11. package/dist_ts/helpers.objects.js +3 -0
  12. package/dist_ts/helpers.packagefiles.d.ts +74 -0
  13. package/dist_ts/helpers.packagefiles.js +177 -0
  14. package/dist_ts/helpers.workflow.d.ts +18 -0
  15. package/dist_ts/helpers.workflow.js +45 -2
  16. package/dist_ts/mod_config/index.js +69 -2
  17. package/dist_ts/mod_format/formatters/assets.formatter.js +2 -1
  18. package/dist_ts/mod_format/formatters/packagejson.formatter.js +8 -27
  19. package/dist_ts/mod_release/helpers.giteaassets.d.ts +4 -14
  20. package/dist_ts/mod_release/helpers.giteaassets.js +20 -35
  21. package/dist_ts/mod_release/helpers.npmartifactcheck.d.ts +93 -0
  22. package/dist_ts/mod_release/helpers.npmartifactcheck.js +279 -0
  23. package/dist_ts/mod_release/index.d.ts +15 -0
  24. package/dist_ts/mod_release/index.js +82 -17
  25. package/dist_ts/plugins.d.ts +2 -1
  26. package/dist_ts/plugins.js +3 -2
  27. package/package.json +2 -1
  28. package/readme.md +147 -33
  29. package/ts/00_commitinfo_data.ts +1 -1
  30. package/ts/classes.gitzoneconfig.ts +3 -0
  31. package/ts/helpers.objects.ts +5 -0
  32. package/ts/helpers.packagefiles.ts +273 -0
  33. package/ts/helpers.workflow.ts +70 -1
  34. package/ts/mod_config/index.ts +78 -0
  35. package/ts/mod_format/formatters/assets.formatter.ts +1 -0
  36. package/ts/mod_format/formatters/packagejson.formatter.ts +7 -27
  37. package/ts/mod_release/helpers.giteaassets.ts +28 -44
  38. package/ts/mod_release/helpers.npmartifactcheck.ts +397 -0
  39. package/ts/mod_release/index.ts +115 -26
  40. package/ts/plugins.ts +2 -0
package/readme.md CHANGED
@@ -186,7 +186,7 @@ Before interactive confirmation or source mutation, a Docker release verifies th
186
186
 
187
187
  The release core is not configurable plumbing. It always follows the same professional release transaction:
188
188
 
189
- 1. Verify the release branch, clean state, and worktree ownership of `main` (or of the maintenance branch a release line names). A release that builds or packs a commit with a `package.json` also proves here that the source commit carries a `pnpm-lock.yaml` its checkout can install with `--frozen-lockfile`. An npm release then reads every registry's dist-tags for every package it publishes: `latest` never moves downwards, and a line never takes `latest` (step `preflight.npmDistTags`).
189
+ 1. Verify the release branch, clean state, and worktree ownership of `main` (or of the maintenance branch a release line names). A project that configures `packageFiles` must carry exactly the `files` list it generates (step `preflight.packageFiles`, see [Package contents](#package-contents)). A release that builds or packs a commit with a `package.json` also proves here that the source commit carries a `pnpm-lock.yaml` its checkout can install with `--frozen-lockfile`. An npm release then reads every registry's dist-tags for every package it publishes: `latest` never moves downwards, and a line never takes `latest` (step `preflight.npmDistTags`).
190
190
  2. Read `changelog.md` `## Pending` entries and infer or accept a semver bump, raised to `release.versionFloor` when that is higher.
191
191
  3. Run configured tests.
192
192
  4. With `--merge`, fast-forward and lease-push `main` before release metadata is created.
@@ -194,7 +194,7 @@ The release core is not configurable plumbing. It always follows the same profes
194
194
  6. Move pending changelog entries into the new version section.
195
195
  7. Create the local release commit and tag on `main`, and record the release intent, so any later failure is resumable (see [Resuming a release that failed before its journal](#resuming-a-release-that-failed-before-its-journal)).
196
196
  8. Create a disposable detached checkout of that release commit, install its locked dependencies when the commit carries a `package.json`, and run the configured release build there. An active Docker target additionally builds the release worktree its qualification reads.
197
- 9. When npm is selected, prepare every named tspublish module outside the repository, then pack each module and the public root package once into an exact tarball from that checkout.
197
+ 9. When npm is selected, prepare every named tspublish module outside the repository, then pack each module and the public root package once into an exact tarball from that checkout. Every tarball must then carry each entry point its packed `package.json` names (`core.packNpmArtifact.entryPoints`), and its estimated publish body must fit each registry's `maxPublishBytes` (`core.packNpmArtifact.publishSize`, planned only when a limit is configured); the packed size and the body per registry are printed either way. See [Package contents](#package-contents).
198
198
  10. Atomically install a durable journal before final publication. A release that publishes only the root package to npm uses journal schema 1, one that also or only publishes tspublish modules uses schema 3, a Docker release uses schema 2 with or without modules, and a Gitea asset release uses schema 4, all in the same storage tree.
199
199
  11. For schema 2, run the project-local tSDocker qualification build and configured image tests, then durably record the candidate digest graph and complete ordered promotion set.
200
200
  12. Publish and verify Git, then every npm package at every registry, modules first and the root package last, then each Docker destination. Remove only the exact qualified candidate after every destination is verified, or after a terminal qualification destination conflict before Git/npm publication.
@@ -264,7 +264,9 @@ Consequences worth knowing before upgrading:
264
264
  of it is never dropped.
265
265
  - The `--plan` step list names the isolated work: `preflight.lockfile` for a
266
266
  project with a `package.json`, then `core.releaseCheckout`,
267
- `core.releaseCheckout.build`, then `core.packNpmArtifact`.
267
+ `core.releaseCheckout.build`, then `core.packNpmArtifact` and its checks
268
+ `core.packNpmArtifact.entryPoints` and, with a configured limit,
269
+ `core.packNpmArtifact.publishSize`.
268
270
 
269
271
  An active `docker` target additionally runs the build in the release worktree,
270
272
  as before, and the plan shows that step as `core.build`. tSDocker binds
@@ -978,9 +980,12 @@ intent before it builds, packs or checks the remote again:
978
980
  The intent binds the release commit and tag object, the version floor record,
979
981
  the targets and release-build choice the command line selected, and, for a Git
980
982
  target, the remote name, the hashed push destination and the remote `main` the
981
- push will lease. Any failure between the tag and the installed journal — the
983
+ push will lease. A failure between the tag and the installed journal — the
982
984
  release build, packing, freezing Gitea assets, Docker validation, or a remote
983
- that cannot be inspected — is then resumable:
985
+ that cannot be inspected — is then resumable with the command below. A failed
986
+ check of the packed tarballs (entry points, publish size, or a tarball too
987
+ large to inspect) is not: the release commit causes it, so it needs the
988
+ abandon steps further down.
984
989
 
985
990
  ```bash
986
991
  gitzone release resume 6.0.0 -y
@@ -1004,6 +1009,14 @@ you delete the local tag and reset `main` to the commit before the release
1004
1009
  commit), delete its intent file as well; otherwise a later tag of the same version
1005
1010
  is handed to a resume that refuses it.
1006
1011
 
1012
+ A resume packs the same commit with the configuration that commit carries, so a
1013
+ failure that the commit itself causes — a build that always fails, a missing
1014
+ entry point, a publish body over its limit — fails the resume again. Abandon
1015
+ such a release as described above, fix the project, and release again. For a
1016
+ failed tarball check the error spells these steps out with `git -C` on the
1017
+ checkout that holds the release commit, which can differ from the folder the
1018
+ release started in (`--merge`).
1019
+
1007
1020
  ### Recovering a tag without a recorded intent
1008
1021
 
1009
1022
  For a Git release with npm and/or Docker targets whose local release commit
@@ -1203,7 +1216,10 @@ CLI workflow config lives under `@git.zone/cli` in `.smartconfig.json`. Docker r
1203
1216
  "registries": ["https://registry.npmjs.org"],
1204
1217
  "accessLevel": "public",
1205
1218
  "alreadyPublished": "success",
1206
- "verificationWindowMinutes": 15
1219
+ "verificationWindowMinutes": 15,
1220
+ "maxPublishBytes": {
1221
+ "https://registry.npmjs.org": 10485760
1222
+ }
1207
1223
  },
1208
1224
  "docker": {
1209
1225
  "enabled": false,
@@ -1289,6 +1305,75 @@ gitzone config migrate 2
1289
1305
 
1290
1306
  `@ship.zone/szci` belongs to szci, which GitZone no longer uses or reads. `gitzone config migrate` and `gitzone format` remove only an empty `npmGlobalTools` list, szci's default, and delete a block left empty; every other key stays. szci still reads two keys, and no migration deletes or moves them. `npmRegistryUrl` is the registry `szci npm prepare` installs from, for example in a Dockerfile that installs private packages. It is not a publish registry, even when `release.targets.npm.registries` lists the same URL, so no migration, the one from schema 1 included, moves or copies it into the publish registries: a registry list alone enables the npm target. `npmAccessLevel` is the access level `szci git mirror` checks. GitZone publishes with `release.targets.npm.accessLevel`, so the migration copies `npmAccessLevel` there when that key is absent and keeps it in the block: the duplicate is deliberate. `gitzone config doctor` names the current home of each kept key GitZone once read, for example `@git.zone/tsdocker.registryRepoMap` for `dockerRegistryRepoMap` and `@git.zone/tsdocker.buildArgEnvMap` for `dockerBuildargEnvMap`, and reports `npmRegistryUrl` and `npmAccessLevel` as szci's own. A block that holds only these two keys needs no step once `release.targets.npm.accessLevel` is set.
1291
1307
 
1308
+ ### Package contents
1309
+
1310
+ `gitzone format` writes the `files` list of `package.json`, and nothing else
1311
+ should. By default it writes the list every gitzone project has always had. A
1312
+ project that needs different contents describes them in `.smartconfig.json`:
1313
+
1314
+ ```json
1315
+ {
1316
+ "@git.zone/cli": {
1317
+ "packageFiles": {
1318
+ "sets": ["source", "dist", "assets", "config", "docs"],
1319
+ "include": ["third-party-notices.md", "licenses/**/*"],
1320
+ "exclude": ["dist_bundle/**/*", "html/**/*"]
1321
+ }
1322
+ }
1323
+ }
1324
+ ```
1325
+
1326
+ `sets` picks named groups of entries; without `packageFiles`, or without
1327
+ `sets`, every set applies:
1328
+
1329
+ | Set | Entries |
1330
+ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
1331
+ | `source` | `ts/**/*`, `ts_web/**/*`, excluding `ts/tsconfig.json` and `ts_web/tsconfig.json` |
1332
+ | `dist` | `dist/**/*`, `dist_*/**/*`, `dist_ts/**/*`, `dist_ts_web/**/*` |
1333
+ | `assets` | `assets/**/*` |
1334
+ | `cli` | `cli.js` |
1335
+ | `config` | `.smartconfig.json` |
1336
+ | `docs` | `readme.md` |
1337
+ | `binary` | With managed `denoBinaryCli` assets: the installer (`install.sh` or `assets.installer.file`) and, with the npm wrapper, `bin/` and its postinstall script; empty otherwise |
1338
+
1339
+ The list carries the entries of the selected sets in this order, then
1340
+ `include`, then every exclusion: those of the sets first, then `exclude`, each
1341
+ written with a leading `!`. Exclusions come last because pnpm 10 and 12 apply
1342
+ an exclusion only after the entries that include the file. A repeated entry
1343
+ keeps its first position. Write `exclude` entries without the `!`.
1344
+
1345
+ pnpm packs some files whatever `files` says: `package.json`, every root file
1346
+ whose name starts with `readme`, `license` or `licence` (any case), the `main`
1347
+ file and every `bin` file. An exclusion naming one of them would have no
1348
+ effect, so `gitzone format` refuses it, as it refuses an unknown set name.
1349
+ Nested files such as `docs/readme.md` are not packed implicitly.
1350
+
1351
+ A release checks the package it builds:
1352
+
1353
+ - `preflight.packageFiles`, before anything is created and only when
1354
+ `packageFiles` is configured: `package.json` `files` must equal the generated
1355
+ list. Otherwise run `gitzone format`, commit, and release again.
1356
+ - `core.packNpmArtifact.entryPoints`, after packing and before Git is pushed:
1357
+ every `main`, `module`, `types`/`typings`, `bin` and `exports` target of the
1358
+ packed `package.json` (all conditions; a `*` pattern must match at least one
1359
+ file) must be in the tarball. `main` also resolves the way Node does (`.js`,
1360
+ `.json`, `.node`, or a folder's `index`).
1361
+ - The packed size and the estimated publish body per registry are printed.
1362
+ The body is what `pnpm publish` uploads: the tarball as base64 plus the
1363
+ packed manifest with its readme, which is about 4/3 of the tarball size. With
1364
+ `release.targets.npm.maxPublishBytes` (registry URL to bytes; every key must
1365
+ be a configured registry) the release stops when a body exceeds its
1366
+ registry's limit (`core.packNpmArtifact.publishSize`). There is no default
1367
+ limit, because registries differ.
1368
+
1369
+ The two artifact checks run after the local release commit and tag exist and
1370
+ before anything is pushed, so a failure leaves the release where a failed
1371
+ build or pack leaves it: commit and tag local, intent recorded, no journal,
1372
+ nothing pushed. Because the commit itself causes the failure, the error does
1373
+ not suggest a resume; it names the steps to abandon the release (see [Resuming a release that failed before its journal](#resuming-a-release-that-failed-before-its-journal)).
1374
+ Then fix the package and release again. `gitzone config doctor` validates
1375
+ `packageFiles` and `maxPublishBytes` and reports a `files` list that differs.
1376
+
1292
1377
  ### Managed Assets
1293
1378
 
1294
1379
  Projects can opt into generated, updateable repository assets through `@git.zone/cli.assets`. The first supported kind is `denoBinaryCli`, which manages installer scripts, npm binary wrappers, postinstall downloaders, and Gitea release workflows for Deno-compiled CLI binaries.
@@ -1386,7 +1471,7 @@ For a component that already builds and packages with `@git.zone/tspack`, select
1386
1471
  `assets.kind: "tspackRelease"`. GitZone manages the tag-triggered workflow and its
1387
1472
  release scripts. Compilation stays in the component's command, and TsPack owns
1388
1473
  archive creation and verification. The project must install `@git.zone/tspack`
1389
- 1.1.0 or later and ignore both configured output and `dist_gitzone_retained/` in Git.
1474
+ 1.4.0 or later and ignore both configured output and `dist_gitzone_retained/` in Git.
1390
1475
  Pin pnpm 11 or later in `package.json` using `packageManager`. The workflow installs
1391
1476
  that version directly with the pinned official `pnpm/setup` action before the
1392
1477
  explicit frozen dependency install. This avoids an older container-provided pnpm
@@ -1415,38 +1500,67 @@ this setup does not require a separate Deno action.
1415
1500
  Both commands return exactly one JSON object on stdout with `directory` and
1416
1501
  `manifestSha256`. Preparation creates a clean tagged release directly beneath
1417
1502
  the configured output root and saves every input descriptor needed for reuse.
1418
- Verification restores that same result without compiling or repacking. Commands
1419
- are explicit executable/argument arrays; GitZone does not interpolate a shell.
1503
+ Verification restores that same result without compiling or repacking; the
1504
+ workflow runs it right after preparation and requires the same directory and
1505
+ manifest digest. Commands are explicit executable/argument arrays; GitZone does
1506
+ not interpolate a shell.
1420
1507
  A command's stderr goes straight to the job log, so write build progress and
1421
1508
  diagnostics there and keep stdout for the JSON result. The command runs without
1422
1509
  `GITHUB_TOKEN` and `ACTIONS_RUNTIME_TOKEN`. When it exits non-zero or is killed,
1423
1510
  the release step fails with a line that names the command and its exit code or
1424
1511
  signal, below the command's own stderr. A command that writes more than 1 MiB to
1425
1512
  stdout or runs longer than 30 minutes is stopped and fails the step by name.
1426
- Run `gitzone format --only assets --write --yes` and commit the generated files.
1427
- The normal authorized `gitzone release -y` pushes the tag that triggers this CI flow.
1428
-
1429
- The runner must support Gitea's v4 artifact protocol through the stock artifact
1430
- actions: use Gitea Runner 3.3.2 or later with its cache/results service enabled and
1431
- reachable from job containers, and keep `runner.patch_actions` enabled. The pinned
1432
- actions run on Node.js 24. Follow the [Gitea runner upgrade guide](https://docs.gitea.com/runner/develop/upgrade/)
1433
- when upgrading an older runner; legacy v3 artifacts are absent from Gitea's REST
1434
- artifact inventory and cannot satisfy this workflow's retention check.
1435
-
1436
- Before any release mutation, the workflow retains the complete output root for
1437
- 90 days using Gitea's v4 Actions artifact protocol, downloads it into a fresh
1438
- directory, checks the component's reuse result, and verifies every archive through
1439
- TsPack. The remote tag must match the sealed source commit. Publication creates a
1440
- draft, downloads and checks existing attachments, uploads only missing files, and
1441
- publishes after complete readback. It never replaces an attachment or deletes a
1442
- release. HTTPS object-store redirects do not receive the Gitea job token.
1443
-
1444
- Retry the **original Gitea run** after an interruption. A retained set from another
1445
- run identifies the run to resume. Expired or missing retention, conflicting
1446
- attachments, unexpected API responses, and changed source identities stop before
1447
- publication. Keep the original artifact until publication is verified; if its
1448
- retention has expired, recover its exact bytes before retrying. Rerunning an already
1449
- published release only verifies its existing attachments.
1513
+ Run `gitzone format --only assets --write --yes` and commit the generated files
1514
+ (`.gitea/workflows/release.yml` and three scripts in `scripts/`). The normal
1515
+ authorized `gitzone release -y` pushes the tag that triggers this CI flow.
1516
+
1517
+ The draft Gitea release is the retention. The workflow does not use Actions
1518
+ artifacts: Gitea scopes them to one run attempt, so a rerun could not read them,
1519
+ and Gitea 1.27 finalizes an upload by merging its chunks inside the request, which
1520
+ outlasts the artifact client's 3-minute timeout for a few hundred megabytes and
1521
+ then fails every retry because the merge already consumed the chunks. Release
1522
+ attachments belong to the tag, and the job token can write them.
1523
+
1524
+ 1. **Discover** reads the tag's release with the job token and anonymously. With
1525
+ no release, the job builds. A release must name its manifest digest in its
1526
+ description; its `tspack-manifest.json` attachment must hash to that digest,
1527
+ TsPack must accept the manifest and `SHA256SUMS.txt` for the tagged commit, and
1528
+ the attachments must be exactly the sealed set. Discovery then downloads every
1529
+ archive into `dist_gitzone_retained/` and hashes it against the manifest. A
1530
+ complete set is retained and nothing is built. A draft that is not complete is
1531
+ rebuilt. A published release that is not complete stops the job.
1532
+ 2. **Prepare** runs the component's prepare command, verifies the result with
1533
+ TsPack, runs the verify command on it, and writes the release receipt.
1534
+ 3. **Retain** waits until Gitea has processed the pushed tag before it creates a
1535
+ draft, because Gitea publishes a release it finds for a tag when it processes
1536
+ the push (the same wait `gitzone release` uses; see [Gitea release attachments before npm](#gitea-release-attachments-before-npm)). The
1537
+ draft's description names the manifest digest. Uploads run one at a time; every
1538
+ upload reads the release again first, then the attachment is downloaded and
1539
+ hashed. Attachments that already match are kept.
1540
+ 4. **Restore** moves the retained download into the output root and verifies it
1541
+ with TsPack against the manifest digest and the tagged commit. A resumed job
1542
+ does not run the component's verify command: the restored bytes are
1543
+ hash-bound to the digest the description names, which was written only after
1544
+ the verify command passed on the job that built them.
1545
+ 5. **Publish** checks that the draft holds exactly the attachments this job
1546
+ hashed (Gitea stores an attachment's bytes under its UUID, and its API can only
1547
+ rename one, so id, name and UUID identify hashed bytes), checks the remote tag
1548
+ again, publishes the draft and confirms the release and its attachment list
1549
+ anonymously.
1550
+
1551
+ A published attachment is never replaced and a release is never deleted. A draft
1552
+ has never been public, so a draft attachment that conflicts with the sealed set
1553
+ (an interrupted earlier attempt whose rebuild produced different bytes, or a file
1554
+ outside the set) is replaced: right before each deletion the release must still
1555
+ read back as a draft with the token and be invisible anonymously, and the job log
1556
+ names the attachment and both digests. A draft that turns public meanwhile stops
1557
+ the job before the next change.
1558
+
1559
+ After an interruption, rerun the job. A rerun after a complete draft or a
1560
+ published release resumes from its bytes without building; a rerun after an
1561
+ incomplete draft rebuilds and completes it. The remote tag must match the sealed
1562
+ source commit. Unexpected API responses, a publicly visible draft, an incomplete
1563
+ published release and changed source identities stop before publication.
1450
1564
 
1451
1565
  ## Formatting
1452
1566
 
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@git.zone/cli',
6
- version: '8.5.1',
6
+ version: '8.7.0',
7
7
  description: 'A comprehensive CLI tool for enhancing and managing local development workflows with gitzone utilities, focusing on project setup, version control, code formatting, and template management.'
8
8
  }
@@ -1,5 +1,6 @@
1
1
  import * as plugins from './plugins.js';
2
2
  import * as paths from './paths.js';
3
+ import type { IPackageFilesConfig } from './helpers.packagefiles.js';
3
4
 
4
5
  export type TGitzoneProjectType = 'npm' | 'service' | 'wcc' | 'website';
5
6
 
@@ -20,6 +21,8 @@ export interface IGitzoneConfigData {
20
21
  legalUrl: string;
21
22
  };
22
23
  copy: { [key: string]: string };
24
+ /** What package.json `files` ships; `gitzone format` writes it, a release checks it. */
25
+ packageFiles?: IPackageFilesConfig;
23
26
  }
24
27
 
25
28
  /**
@@ -0,0 +1,5 @@
1
+ /** A JSON object: not null, not an array. */
2
+ export const isPlainObject = (
3
+ valueArg: unknown,
4
+ ): valueArg is Record<string, unknown> =>
5
+ typeof valueArg === "object" && valueArg !== null && !Array.isArray(valueArg);
@@ -0,0 +1,273 @@
1
+ import * as plugins from "./plugins.js";
2
+ import { getCliNamespaceConfig, readSmartconfigFile } from "./helpers.smartconfig.js";
3
+ import { isPlainObject } from "./helpers.objects.js";
4
+
5
+ /**
6
+ * The named groups of package.json `files` entries, in the order the generated
7
+ * list carries them. Without a `packageFiles.sets` selection every set applies,
8
+ * which reproduces the list gitzone has always written.
9
+ */
10
+ export const packageFileSetNames = [
11
+ "source",
12
+ "dist",
13
+ "assets",
14
+ "cli",
15
+ "config",
16
+ "docs",
17
+ "binary",
18
+ ] as const;
19
+
20
+ export type TPackageFileSetName = (typeof packageFileSetNames)[number];
21
+
22
+ /** `@git.zone/cli.packageFiles` in `.smartconfig.json`. */
23
+ export interface IPackageFilesConfig {
24
+ /** Named sets to ship; all of them when omitted. */
25
+ sets?: TPackageFileSetName[];
26
+ /** Further paths or globs, written after the entries of the sets. */
27
+ include?: string[];
28
+ /** Paths or globs to leave out, written without `!` and placed last. */
29
+ exclude?: string[];
30
+ }
31
+
32
+ /** The managed asset settings that add package files. */
33
+ export interface IPackageFilesAssetsConfig {
34
+ enabled?: boolean;
35
+ kind?: string;
36
+ installer?: { enabled?: boolean; file?: string };
37
+ npmWrapper?: { enabled?: boolean; postinstallFile?: string };
38
+ }
39
+
40
+ /** The package.json fields npm and pnpm pack whatever `files` says. */
41
+ export interface IPackageFilesManifest {
42
+ main?: unknown;
43
+ bin?: unknown;
44
+ }
45
+
46
+ export interface IPackageFileSet {
47
+ include: string[];
48
+ /** Exclusions without their `!`. */
49
+ exclude: string[];
50
+ }
51
+
52
+ export interface IResolvePackageFilesOptions {
53
+ /** The raw `@git.zone/cli.packageFiles` value; validated here. */
54
+ packageFiles: unknown;
55
+ /** The raw `@git.zone/cli.assets` value. */
56
+ assets?: IPackageFilesAssetsConfig;
57
+ manifest: IPackageFilesManifest;
58
+ }
59
+
60
+ const configPath = "@git.zone/cli.packageFiles";
61
+
62
+
63
+ /**
64
+ * The sets as they stand for one project. `binary` carries the installer and
65
+ * npm wrapper of managed `denoBinaryCli` assets and is empty otherwise.
66
+ */
67
+ export const getPackageFileSets = (
68
+ assetsArg: IPackageFilesAssetsConfig | undefined,
69
+ ): Record<TPackageFileSetName, IPackageFileSet> => {
70
+ const assets = assetsArg?.enabled === false ? undefined : assetsArg;
71
+ const binary: string[] = [];
72
+ if (assets?.kind === "denoBinaryCli" && assets.installer?.enabled !== false) {
73
+ binary.push(assets.installer?.file || "install.sh");
74
+ }
75
+ if (assets?.kind === "denoBinaryCli" && assets.npmWrapper?.enabled) {
76
+ binary.push("bin/");
77
+ binary.push(assets.npmWrapper.postinstallFile || "scripts/install-binary.js");
78
+ }
79
+ return {
80
+ // @git.zone/tsbuild reads a folder's compiler options from <folder>/tsconfig.json,
81
+ // which extends the root tsconfig.json. The package does not ship the root file,
82
+ // so a shipped folder file would extend a file that is not there.
83
+ source: {
84
+ include: ["ts/**/*", "ts_web/**/*"],
85
+ exclude: ["ts/tsconfig.json", "ts_web/tsconfig.json"],
86
+ },
87
+ dist: {
88
+ include: ["dist/**/*", "dist_*/**/*", "dist_ts/**/*", "dist_ts_web/**/*"],
89
+ exclude: [],
90
+ },
91
+ assets: { include: ["assets/**/*"], exclude: [] },
92
+ cli: { include: ["cli.js"], exclude: [] },
93
+ config: { include: [".smartconfig.json"], exclude: [] },
94
+ docs: { include: ["readme.md"], exclude: [] },
95
+ binary: { include: binary, exclude: [] },
96
+ };
97
+ };
98
+
99
+ const normalizePackagePath = (pathArg: string): string =>
100
+ pathArg.replace(/^(\.\/)+/, "").replace(/\/+$/, "");
101
+
102
+ const readBinPaths = (binArg: unknown): string[] => {
103
+ if (typeof binArg === "string") return [binArg];
104
+ if (isPlainObject(binArg))
105
+ return Object.values(binArg).filter(
106
+ (valueArg): valueArg is string => typeof valueArg === "string",
107
+ );
108
+ return [];
109
+ };
110
+
111
+ /**
112
+ * pnpm packs these files whatever `files` says, so an exclusion naming one of
113
+ * them has no effect: `package.json`, every root file whose name starts with
114
+ * `readme`, `license` or `licence` (any case), the `main` file and every `bin`
115
+ * file. Returns why the entry is ignored, or undefined.
116
+ */
117
+ export const describeForceIncludedPackagePath = (
118
+ entryArg: string,
119
+ manifestArg: IPackageFilesManifest,
120
+ ): string | undefined => {
121
+ const entry = normalizePackagePath(entryArg);
122
+ if (entry === "package.json") return "package.json is always packed";
123
+ if (!entry.includes("/") && /^(readme|licen[cs]e)/i.test(entry))
124
+ return "root readme and license files are always packed";
125
+ if (
126
+ typeof manifestArg.main === "string" &&
127
+ normalizePackagePath(manifestArg.main) === entry
128
+ )
129
+ return "the package.json main file is always packed";
130
+ if (
131
+ readBinPaths(manifestArg.bin).some(
132
+ (binPathArg) => normalizePackagePath(binPathArg) === entry,
133
+ )
134
+ )
135
+ return "package.json bin files are always packed";
136
+ return undefined;
137
+ };
138
+
139
+ const parseEntryList = (
140
+ valueArg: unknown,
141
+ keyArg: "include" | "exclude",
142
+ ): string[] => {
143
+ if (valueArg === undefined) return [];
144
+ if (!Array.isArray(valueArg))
145
+ throw new Error(`${configPath}.${keyArg} must be an array of paths or globs.`);
146
+ return valueArg.map((entryArg, indexArg) => {
147
+ if (typeof entryArg !== "string" || entryArg.trim() === "")
148
+ throw new Error(
149
+ `${configPath}.${keyArg}[${indexArg}] must be a non-empty path or glob.`,
150
+ );
151
+ if (entryArg !== entryArg.trim())
152
+ throw new Error(
153
+ `${configPath}.${keyArg}[${indexArg}] must not start or end with whitespace.`,
154
+ );
155
+ if (entryArg.startsWith("!"))
156
+ throw new Error(
157
+ keyArg === "include"
158
+ ? `${configPath}.include[${indexArg}] "${entryArg}" is an exclusion; list it under exclude without the "!".`
159
+ : `${configPath}.exclude[${indexArg}] "${entryArg}" must be written without the "!"; gitzone adds it.`,
160
+ );
161
+ if (entryArg.startsWith("/"))
162
+ throw new Error(
163
+ `${configPath}.${keyArg}[${indexArg}] "${entryArg}" must be relative to the package root.`,
164
+ );
165
+ return entryArg;
166
+ });
167
+ };
168
+
169
+ /** Validates `@git.zone/cli.packageFiles`; undefined when it is absent. */
170
+ export const parsePackageFilesConfig = (
171
+ valueArg: unknown,
172
+ ): IPackageFilesConfig | undefined => {
173
+ if (valueArg === undefined) return undefined;
174
+ if (!isPlainObject(valueArg))
175
+ throw new Error(
176
+ `${configPath} must be an object with sets, include and/or exclude.`,
177
+ );
178
+ const unknownKeys = Object.keys(valueArg).filter(
179
+ (keyArg) => !["sets", "include", "exclude"].includes(keyArg),
180
+ );
181
+ if (unknownKeys.length > 0)
182
+ throw new Error(
183
+ `${configPath} has unknown key(s) ${unknownKeys.join(", ")}; use sets, include and exclude.`,
184
+ );
185
+ const config: IPackageFilesConfig = {};
186
+ if (valueArg.sets !== undefined) {
187
+ if (!Array.isArray(valueArg.sets))
188
+ throw new Error(
189
+ `${configPath}.sets must be an array of set names: ${packageFileSetNames.join(", ")}.`,
190
+ );
191
+ config.sets = valueArg.sets.map((setArg) => {
192
+ if (
193
+ typeof setArg !== "string" ||
194
+ !(packageFileSetNames as readonly string[]).includes(setArg)
195
+ )
196
+ throw new Error(
197
+ `${configPath}.sets names unknown set ${JSON.stringify(setArg)}; known sets: ${packageFileSetNames.join(", ")}.`,
198
+ );
199
+ return setArg as TPackageFileSetName;
200
+ });
201
+ }
202
+ const include = parseEntryList(valueArg.include, "include");
203
+ const exclude = parseEntryList(valueArg.exclude, "exclude");
204
+ if (valueArg.include !== undefined) config.include = include;
205
+ if (valueArg.exclude !== undefined) config.exclude = exclude;
206
+ return config;
207
+ };
208
+
209
+ /**
210
+ * The package.json `files` list: the entries of the selected sets in set
211
+ * order, then `include`, then every exclusion. pnpm 10 and 12 apply an
212
+ * exclusion only after the entries that include the file, so the exclusions
213
+ * of the sets and of `exclude` come last. Repeated entries keep their first
214
+ * position. Without `packageFiles`, or without `sets`, every set applies.
215
+ */
216
+ export const resolvePackageFiles = (
217
+ optionsArg: IResolvePackageFilesOptions,
218
+ ): string[] => {
219
+ const config = parsePackageFilesConfig(optionsArg.packageFiles) ?? {};
220
+ for (const [indexArg, entryArg] of (config.exclude ?? []).entries()) {
221
+ const reason = describeForceIncludedPackagePath(entryArg, optionsArg.manifest);
222
+ if (reason)
223
+ throw new Error(
224
+ `${configPath}.exclude[${indexArg}] "${entryArg}" has no effect: ${reason}, so npm and pnpm ignore the exclusion. Remove it.`,
225
+ );
226
+ }
227
+ const sets = getPackageFileSets(optionsArg.assets);
228
+ const selected = packageFileSetNames.filter(
229
+ (nameArg) => !config.sets || config.sets.includes(nameArg),
230
+ );
231
+ const files = [
232
+ ...selected.flatMap((nameArg) => sets[nameArg].include),
233
+ ...(config.include ?? []),
234
+ ...selected.flatMap((nameArg) => sets[nameArg].exclude).map((entryArg) => `!${entryArg}`),
235
+ ...(config.exclude ?? []).map((entryArg) => `!${entryArg}`),
236
+ ];
237
+ return [...new Set(files)];
238
+ };
239
+
240
+ /**
241
+ * A release of a project that configures `packageFiles` ships what that
242
+ * configuration generates, and `gitzone format` is the one writer of the list.
243
+ * Projects without `packageFiles` are not checked.
244
+ */
245
+ export const assertPackageJsonFilesCurrent = async (
246
+ cwdArg: string,
247
+ ): Promise<void> => {
248
+ const cliConfig = getCliNamespaceConfig(await readSmartconfigFile(cwdArg));
249
+ if (cliConfig.packageFiles === undefined) return;
250
+ let manifest: unknown;
251
+ try {
252
+ manifest = JSON.parse(
253
+ await plugins.fs.readFile(plugins.path.join(cwdArg, "package.json"), "utf8"),
254
+ );
255
+ } catch (error) {
256
+ throw new Error(
257
+ `${configPath} is configured, but package.json cannot be read.`,
258
+ { cause: error },
259
+ );
260
+ }
261
+ if (!isPlainObject(manifest))
262
+ throw new Error("package.json must contain a JSON object.");
263
+ const expected = resolvePackageFiles({
264
+ packageFiles: cliConfig.packageFiles,
265
+ assets: isPlainObject(cliConfig.assets) ? cliConfig.assets : undefined,
266
+ manifest,
267
+ });
268
+ if (JSON.stringify(manifest.files) !== JSON.stringify(expected)) {
269
+ throw new Error(
270
+ `package.json files does not match ${configPath}: expected ${JSON.stringify(expected)}, found ${JSON.stringify(manifest.files ?? null)}. Run \`gitzone format\`, commit the result, and release again.`,
271
+ );
272
+ }
273
+ };