create-gtkx 2.0.0-beta.9 → 2.0.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 (71) hide show
  1. package/README.md +8 -166
  2. package/dependency-ranges.json +7 -0
  3. package/dist/build-allowance.d.ts +43 -2
  4. package/dist/build-allowance.d.ts.map +1 -1
  5. package/dist/build-allowance.js +360 -9
  6. package/dist/build-allowance.js.map +1 -1
  7. package/dist/cli.js +1 -1
  8. package/dist/cli.js.map +1 -1
  9. package/dist/command.d.ts +3 -2
  10. package/dist/command.d.ts.map +1 -1
  11. package/dist/command.js +93 -90
  12. package/dist/command.js.map +1 -1
  13. package/dist/errors.d.ts.map +1 -1
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +1 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/manifest.d.ts.map +1 -1
  19. package/dist/manifest.js +2 -10
  20. package/dist/manifest.js.map +1 -1
  21. package/dist/package-managers.d.ts +6 -3
  22. package/dist/package-managers.d.ts.map +1 -1
  23. package/dist/package-managers.js +6 -3
  24. package/dist/package-managers.js.map +1 -1
  25. package/dist/project-name.d.ts +4 -2
  26. package/dist/project-name.d.ts.map +1 -1
  27. package/dist/project-name.js +12 -2
  28. package/dist/project-name.js.map +1 -1
  29. package/dist/scaffolder.d.ts.map +1 -1
  30. package/dist/scaffolder.js +199 -199
  31. package/dist/scaffolder.js.map +1 -1
  32. package/dist/templates/.claude/settings.json.ejs +4 -3
  33. package/dist/templates/.gitignore.ejs +4 -0
  34. package/dist/templates/.mcp.json.ejs +1 -1
  35. package/dist/templates/gtkx.config.ts.ejs +2 -2
  36. package/dist/templates/package.json.ejs +4 -1
  37. package/dist/templates/src/app.tsx.ejs +1 -1
  38. package/dist/templates/src/gtkx-env.d.ts.ejs +0 -1
  39. package/dist/templates/tsconfig.json.ejs +4 -2
  40. package/dist/templates.d.ts +3 -0
  41. package/dist/templates.d.ts.map +1 -1
  42. package/dist/templates.js +10 -6
  43. package/dist/templates.js.map +1 -1
  44. package/dist/workspace-mcp.d.ts +33 -0
  45. package/dist/workspace-mcp.d.ts.map +1 -0
  46. package/dist/workspace-mcp.js +75 -0
  47. package/dist/workspace-mcp.js.map +1 -0
  48. package/package.json +20 -39
  49. package/src/build-allowance.ts +486 -9
  50. package/src/cli.ts +1 -1
  51. package/src/command.ts +114 -110
  52. package/src/index.ts +1 -0
  53. package/src/manifest.ts +2 -10
  54. package/src/package-managers.ts +6 -3
  55. package/src/project-name.ts +19 -2
  56. package/src/scaffolder.ts +294 -286
  57. package/src/templates/.claude/settings.json.ejs +4 -3
  58. package/src/templates/.gitignore.ejs +4 -0
  59. package/src/templates/.mcp.json.ejs +1 -1
  60. package/src/templates/gtkx.config.ts.ejs +2 -2
  61. package/src/templates/package.json.ejs +4 -1
  62. package/src/templates/src/app.tsx.ejs +1 -1
  63. package/src/templates/src/gtkx-env.d.ts.ejs +0 -1
  64. package/src/templates/tsconfig.json.ejs +4 -2
  65. package/src/templates.ts +17 -8
  66. package/src/workspace-mcp.ts +111 -0
  67. package/dist/install-hints.d.ts +0 -3
  68. package/dist/install-hints.d.ts.map +0 -1
  69. package/dist/install-hints.js +0 -35
  70. package/dist/install-hints.js.map +0 -1
  71. package/src/install-hints.ts +0 -54
package/README.md CHANGED
@@ -1,177 +1,19 @@
1
- <p align="center">
2
- <img src="https://raw.githubusercontent.com/gtkx-org/gtkx/main/logo.svg" alt="GTKX" width="100" />
3
- </p>
1
+ # create-gtkx
4
2
 
5
- <h1 align="center">GTKX</h1>
3
+ Create native GTK and Adwaita apps with React and GTKX.
6
4
 
7
- <p align="center">
8
- The React framework for Linux.<br />
9
- Write native GNOME applications with React and TypeScript.
10
- Real Adwaita and GTK4 widgets with standard web tooling.
11
- </p>
5
+ Scaffold an app with TypeScript or JavaScript, an Adwaita window, and optional Vitest support.
12
6
 
13
- <p align="center">
14
- <a href="https://www.npmjs.com/package/create-gtkx"><img src="https://img.shields.io/npm/v/create-gtkx?color=cb3837&logo=npm&label=create-gtkx" alt="npm version" /></a>
15
- <a href="https://www.npmjs.com/package/create-gtkx"><img src="https://img.shields.io/npm/dm/create-gtkx?color=cb3837&logo=npm&label=downloads" alt="npm downloads" /></a>
16
- <img src="https://img.shields.io/badge/node-%E2%89%A526.7-339933?logo=node.js&logoColor=white" alt="Node >= 26.7" />
17
- <a href="https://github.com/gtkx-org/gtkx/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MPL--2.0-blue.svg" alt="License: MPL-2.0" /></a>
18
- <a href="https://github.com/gtkx-org/gtkx/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/gtkx-org/gtkx/ci.yml?branch=main&logo=github&label=CI" alt="CI status" /></a>
19
- <img src="https://img.shields.io/badge/TypeScript-strict-3178c6?logo=typescript&logoColor=white" alt="TypeScript" />
20
- </p>
21
-
22
- <p align="center">
23
- <a href="https://gtkx.dev">Homepage</a> &middot;
24
- <a href="https://gtkx.dev/guide/getting-started">Documentation</a> &middot;
25
- <a href="https://github.com/gtkx-org/gtkx/tree/main/examples">Examples</a> &middot;
26
- <a href="https://github.com/gtkx-org/gtkx/blob/main/CONTRIBUTING.md">Contributing</a>
27
- </p>
28
-
29
- ---
30
-
31
- <p align="center">
32
- <img src="https://raw.githubusercontent.com/gtkx-org/gtkx/main/examples/tutorial/assets/screenshot.png" alt="The Tasks app: an Adwaita window with a sidebar of smart views and colored lists on the left, and a boxed task list on the right." />
33
- </p>
34
-
35
- <p align="center">
36
- <em>The Tasks app you build in the <a href="https://gtkx.dev/tutorial/">tutorial</a>.</em>
37
- </p>
38
-
39
- ## Demo
40
-
41
- This app starts with an Adwaita application shell, renders native GTK4 widgets inside it, and uses ordinary React hooks and events:
42
-
43
- ```tsx
44
- import * as Gtk from "@gtkx/gi/gtk";
45
- import { AdwApplication, AdwApplicationWindow, AdwHeaderBar, AdwToolbarView } from "@gtkx/jsx/adw";
46
- import { GtkBox, GtkButton, GtkLabel } from "@gtkx/jsx/gtk";
47
- import { createRoot, quit } from "@gtkx/react";
48
- import { useState } from "react";
49
-
50
- const Counter = () => {
51
- const [count, setCount] = useState(0);
52
-
53
- return (
54
- <AdwApplicationWindow
55
- title="Hello GTKX"
56
- defaultWidth={400}
57
- defaultHeight={300}
58
- onCloseRequest={quit}
59
- >
60
- <AdwToolbarView topBar={<AdwHeaderBar />}>
61
- <GtkBox
62
- orientation={Gtk.Orientation.VERTICAL}
63
- spacing={20}
64
- marginTop={40}
65
- marginBottom={40}
66
- marginStart={40}
67
- marginEnd={40}
68
- valign={Gtk.Align.CENTER}
69
- halign={Gtk.Align.CENTER}
70
- >
71
- <GtkLabel cssClasses={["title-1"]}>Welcome to GTKX!</GtkLabel>
72
- <GtkLabel cssClasses={["title-2"]}>{`Count: ${String(count)}`}</GtkLabel>
73
- <GtkButton
74
- label="Increment"
75
- onClicked={() => setCount((c) => c + 1)}
76
- cssClasses={["suggested-action", "pill"]}
77
- />
78
- </GtkBox>
79
- </AdwToolbarView>
80
- </AdwApplicationWindow>
81
- );
82
- };
83
-
84
- const App = () => (
85
- <AdwApplication>
86
- <Counter />
87
- </AdwApplication>
88
- );
89
-
90
- createRoot().render(<App />);
91
- ```
92
-
93
- This is the [`hello-world`](https://github.com/gtkx-org/gtkx/tree/main/examples/hello-world) example, with `app.tsx` and `index.tsx` combined into a single snippet. `@gtkx/gi` and `@gtkx/jsx` are per-project bindings generated by the CLI, not packages you install from npm.
94
-
95
- ## Why GTKX
96
-
97
- ### Adwaita-first application development
98
-
99
- GTKX uses Adwaita as the foundation for applications, windows, navigation, dialogs, and adaptive layouts, with the complete GTK4 toolkit underneath. It adds a declarative React layer and an integrated TypeScript toolchain to the GNOME platform:
100
-
101
- - a React reconciler that exposes every GObject as a JSX element,
102
- - a CLI for scaffolding, development, and production builds,
103
- - a dev server with Fast Refresh that patches your running UI in place,
104
- - CSS-in-JS styling, React Hook Form-powered Adwaita controls, gettext-backed react-i18next localization, React Spring animations, React Navigation stack, tab, drawer, and split view navigators, and high-level list, grid, and dialog components,
105
- - a Testing Library-style API for querying and driving your widgets in tests,
106
- - and a Model Context Protocol (MCP) server that exposes your live app to AI agents.
107
-
108
- ### Native GNOME widgets, without a compatibility layer
109
-
110
- React Native and similar frameworks hide the native toolkit so one API can run everywhere. GTKX renders real Adwaita and GTK4 widgets and exposes any other GObject-Introspection library on your system. It is GNOME-native and Linux-only by design.
111
-
112
- ### Why Node.js, and why generated bindings
113
-
114
- GTKX runs on Node.js, which puts native modules, the npm ecosystem, and the tooling built for Node.js APIs within reach. GJS is GNOME's own runtime, built on SpiderMonkey rather than V8; node-gtk runs on Node.js but is lightly maintained, on the older nan/V8 ABI rather than N-API, and still centered on GTK3. The [Why GTKX guide](https://gtkx.dev/guide/why-gtkx) covers what running on Node.js means day to day.
115
-
116
- GTKX generates the TypeScript types and native FFI calls from the same GObject-Introspection data, so the types cannot drift from the calls they back. `Adw-1` is the sole default GIR root; its GIR include pulls in `Gtk-4.0`, so codegen covers both complete API surfaces. Neither belongs in a GTKX 2 `libraries` list.
117
-
118
- At runtime, the native Rust core calls straight into the system Adwaita, GTK4, and GLib libraries through libffi, without loading libgirepository at all.
119
-
120
- ## Quick start
121
-
122
- GTKX is Linux-only and needs Node.js 26.7 or later. See [Requirements](#requirements).
123
-
124
- Scaffold a new app with the `create-gtkx` initializer:
125
-
126
- ```sh
127
- npm create gtkx@beta
128
- ```
129
-
130
- The same command works with other package managers: `pnpm create gtkx@beta` or `yarn create gtkx@beta`.
131
-
132
- Then run your new app:
7
+ Start on Linux with Node.js and the [native prerequisites](https://gtkx.dev/guide/getting-started#what-you-need) installed:
133
8
 
134
9
  ```sh
10
+ npm create gtkx@latest my-app
135
11
  cd my-app
136
12
  npm run dev
137
13
  ```
138
14
 
139
- To go further, follow the [tutorial](https://gtkx.dev/tutorial/).
140
-
141
- ## Documentation
142
-
143
- The documentation at **[gtkx.dev](https://gtkx.dev)** includes a step-by-step tutorial that builds a complete GNOME app, from scaffolding to packaging and shipping, plus guides and a full API reference.
144
-
145
- **[Read the docs &rarr;](https://gtkx.dev/guide/why-gtkx)**
146
-
147
- ## Requirements
148
-
149
- GTKX is Linux-only. You need:
150
-
151
- - Linux with the Adwaita (1.8 or later), GTK4 (4.20 or later), and GLib development libraries
152
- - Node.js 26.7 or later
153
-
154
- The `@gtkx/native` addon ships prebuilt for x64 and arm64 glibc Linux; other targets need to build it from the GTKX repository, which requires a Rust toolchain.
155
-
156
- ## Examples
157
-
158
- Explore the [example apps](https://github.com/gtkx-org/gtkx/tree/main/examples):
159
-
160
- - [`hello-world`](https://github.com/gtkx-org/gtkx/tree/main/examples/hello-world): the Adwaita counter above.
161
- - [`gtk-demo`](https://github.com/gtkx-org/gtkx/tree/main/examples/gtk-demo): the official GTK4 widget showcase in an Adwaita application shell, covering lists, dialogs, gestures, CSS, and OpenGL.
162
- - [`browser`](https://github.com/gtkx-org/gtkx/tree/main/examples/browser): an Adwaita browser built around `WebKitWebView`.
163
- - [`animations`](https://github.com/gtkx-org/gtkx/tree/main/examples/animations): an Adwaita showcase for `@gtkx/animated`, with React Spring animations driven by the GTK frame clock.
164
- - [`navigation`](https://github.com/gtkx-org/gtkx/tree/main/examples/navigation): a tour of `@gtkx/navigation`, React Navigation's stack, tab, and drawer navigators rendered with libadwaita.
165
- - [`tutorial`](https://github.com/gtkx-org/gtkx/tree/main/examples/tutorial): the Tasks app the documentation builds.
166
-
167
- ## Status
168
-
169
- GTKX is stable and ready for production use.
170
-
171
- ## Contributing
172
-
173
- Contributions are welcome. See [CONTRIBUTING.md](https://github.com/gtkx-org/gtkx/blob/main/CONTRIBUTING.md), the [Code of Conduct](https://github.com/gtkx-org/gtkx/blob/main/CODE_OF_CONDUCT.md), and the [security policy](https://github.com/gtkx-org/gtkx/blob/main/SECURITY.md). Building the repo needs Node.js 26.7 or later, pnpm, and a Rust toolchain.
15
+ For the application ID, language, tests, package manager and other options, see [Scaffold Options](https://gtkx.dev/guide/scaffold-options).
174
16
 
175
- ## License
17
+ [Guide](https://gtkx.dev/guide/getting-started) · [GTKX](https://gtkx.dev)
176
18
 
177
- GTKX is licensed under [MPL-2.0](https://github.com/gtkx-org/gtkx/blob/main/LICENSE).
19
+ [MPL-2.0](https://github.com/gtkx-org/gtkx/blob/main/LICENSE).
@@ -0,0 +1,7 @@
1
+ {
2
+ "react": "^19.3.0",
3
+ "@types/react": "^19.3.0",
4
+ "vitest": "^5.0.0",
5
+ "vite": "^8.4.0",
6
+ "@types/node": "^26"
7
+ }
@@ -1,4 +1,45 @@
1
1
  import type { PackageManager } from "./package-managers.js";
2
- declare const writeBuildAllowance: (root: string, packageManager: PackageManager) => void;
3
- export { writeBuildAllowance };
2
+ type MissingSetting = {
3
+ file: string;
4
+ section: string | null;
5
+ entries: string;
6
+ };
7
+ type Workspace = {
8
+ packageManager: PackageManager;
9
+ root: string;
10
+ member: string;
11
+ missingSettings: MissingSetting[];
12
+ };
13
+ /**
14
+ * Configures the package manager to run the build scripts of the scaffold's native dependencies and to exempt
15
+ * GTKX's own packages from its release-age gate, so a project created on the day of a GTKX release installs it.
16
+ * Adds to an existing `pnpm-workspace.yaml`, `.yarnrc.yml` or `.npmrc` instead of replacing it.
17
+ */
18
+ declare const writePackageManagerSettings: (root: string, packageManager: PackageManager) => void;
19
+ /**
20
+ * Exempts GTKX's own packages from the release-age gate of the package manager that installs the project or
21
+ * workspace at `root`, adding only the entries its `pnpm-workspace.yaml`, `.yarnrc.yml` (Yarn 4.10 or newer)
22
+ * or `.npmrc` lacks and keeping everything else in it, and returns the files it changed.
23
+ */
24
+ declare const writeReleaseAgeExemptions: (root: string, packageManager: PackageManager) => string[];
25
+ declare const PACKAGE_MANAGER_CONFIG_FILES: Record<PackageManager, string[]>;
26
+ /**
27
+ * The `packageManager` field for the new `package.json`: the existing project's pin when it names
28
+ * `packageManager`, otherwise, outside an enclosing workspace whose root owns the pin, the Yarn 2 or newer
29
+ * release that installs the project.
30
+ */
31
+ declare const packageManagerPin: (root: string, packageManager: PackageManager, isInWorkspace: boolean) => string | null;
32
+ /**
33
+ * The pnpm, npm or Yarn workspace above `root` that includes it, with the settings its root configuration
34
+ * still lacks for the app, or null when `root` is not part of an enclosing workspace. pnpm reads
35
+ * `allowBuilds` and `minimumReleaseAgeExclude`, npm `allowScripts` and `min-release-age-exclude`, and Yarn
36
+ * `nodeLinker`, `npmPreapprovedPackages` and `dependenciesMeta` only for the whole workspace, from its root.
37
+ */
38
+ declare const enclosingWorkspace: (root: string, packageManager: PackageManager) => Workspace | null;
39
+ /**
40
+ * Whether `yarn` in the workspace at `root` is Yarn 1, judged by the release it runs there, and Yarn 1 when no
41
+ * release can be determined.
42
+ */
43
+ declare const isClassicYarn: (root: string) => boolean;
44
+ export { PACKAGE_MANAGER_CONFIG_FILES, enclosingWorkspace, isClassicYarn, packageManagerPin, type Workspace, writePackageManagerSettings, writeReleaseAgeExemptions, };
4
45
  //# sourceMappingURL=build-allowance.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"build-allowance.d.ts","sourceRoot":"","sources":["../src/build-allowance.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AA2B5D,QAAA,MAAM,mBAAmB,GAAI,MAAM,MAAM,EAAE,gBAAgB,cAAc,KAAG,IAc3E,CAAC;AAEF,OAAO,EAAE,mBAAmB,EAAE,CAAC"}
1
+ {"version":3,"file":"build-allowance.d.ts","sourceRoot":"","sources":["../src/build-allowance.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAG5D,KAAK,cAAc,GAAG;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,KAAK,SAAS,GAAG;IACb,cAAc,EAAE,cAAc,CAAC;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,cAAc,EAAE,CAAC;CACrC,CAAC;AA6MF;;;;GAIG;AACH,QAAA,MAAM,2BAA2B,SAAU,MAAM,kBAAkB,cAAc,KAAG,IAcnF,CAAC;AAWF;;;;GAIG;AACH,QAAA,MAAM,yBAAyB,SAAU,MAAM,kBAAkB,cAAc,KAAG,MAAM,EACjC,CAAC;AAExD,QAAA,MAAM,4BAA4B,EAAE,MAAM,CAAC,cAAc,EAAE,MAAM,EAAE,CAIlE,CAAC;AAsCF;;;;GAIG;AACH,QAAA,MAAM,iBAAiB,SAAU,MAAM,kBAAkB,cAAc,iBAAiB,OAAO,KAAG,MAAM,GAAG,IAEzB,CAAC;AAuKnF;;;;;GAKG;AACH,QAAA,MAAM,kBAAkB,SAAU,MAAM,kBAAkB,cAAc,KAAG,SAAS,GAAG,IAkBtF,CAAC;AAEF;;;GAGG;AACH,QAAA,MAAM,aAAa,SAAU,MAAM,KAAG,OAIrC,CAAC;AAEF,OAAO,EACH,4BAA4B,EAC5B,kBAAkB,EAClB,aAAa,EACb,iBAAiB,EACjB,KAAK,SAAS,EACd,2BAA2B,EAC3B,yBAAyB,GAC5B,CAAC"}
@@ -1,26 +1,173 @@
1
- import { writeFileSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { tryResolveExecutable } from "@gtkx/utils";
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, lstatSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { dirname, join, matchesGlob, posix, relative, sep } from "node:path";
5
+ import { isMap, isSeq, parse, parseDocument, stringify } from "yaml";
3
6
  import { updateManifest } from "./manifest.js";
4
7
  const BUILT_DEPENDENCIES = ["@swc/core", "esbuild"];
8
+ const RELEASE_AGE_EXEMPT_PACKAGES = ["@gtkx/*", "create-gtkx"];
9
+ const YARN_NODE_LINKER = "node-modules";
5
10
  const PNPM_WORKSPACE_FILE = "pnpm-workspace.yaml";
6
- const SAFE_YAML_KEY = /^[A-Za-z][A-Za-z0-9-]*$/;
7
- const PNPM_PACKAGES_BLOCK = "packages:\n - '.'\n";
8
- const quoteYamlKey = (name) => (SAFE_YAML_KEY.test(name) ? name : `'${name}'`);
11
+ const YARN_CONFIG_FILE = ".yarnrc.yml";
12
+ const NPM_CONFIG_FILE = ".npmrc";
13
+ const PACKAGE_JSON_FILE = "package.json";
14
+ const PNPM_RELEASE_AGE_EXCLUDE = "minimumReleaseAgeExclude";
15
+ const YARN_PREAPPROVED_PACKAGES = "npmPreapprovedPackages";
16
+ const NPM_RELEASE_AGE_EXCLUDE = "min-release-age-exclude[]";
17
+ const NPM_RELEASE_AGE_EXCLUDE_PATTERN = /^\s*min-release-age-exclude(?:\[\])?\s*=\s*(["']?)(.*?)\1\s*$/;
18
+ const NEGATION_PREFIX = "!";
19
+ const YARN_USER_AGENT_PATTERN = /^yarn\/(\d+\.\d+\.\d+\S*)/;
20
+ const FIRST_PINNED_YARN_MAJOR = 2;
21
+ const YARN_PIN_PREFIX = "yarn@";
22
+ const YARN_RELEASE_PATTERN = /^(\d+)\.(\d+)\./;
23
+ const FIRST_PREAPPROVING_YARN = { major: 4, minor: 10 };
24
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
25
+ const readSettings = (path, read) => {
26
+ try {
27
+ return read(readFileSync(path, "utf8"));
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ };
33
+ /**
34
+ * Writes `contents` to a new file at `path` in place of a file or symlink there, keeping the permissions of a
35
+ * replaced file, such as a private `.npmrc` that holds registry credentials.
36
+ */
37
+ const replaceFile = (path, contents) => {
38
+ const replaced = lstatSync(path, { throwIfNoEntry: false });
39
+ rmSync(path, { force: true });
40
+ writeFileSync(path, contents, { mode: replaced?.isFile() ? replaced.mode & 0o777 : undefined });
41
+ };
42
+ const updateYamlFile = (path, update) => {
43
+ const document = parseDocument(existsSync(path) ? readFileSync(path, "utf8") : "");
44
+ update(document);
45
+ replaceFile(path, document.toString());
46
+ };
47
+ const missingExemptions = (exempted) => RELEASE_AGE_EXEMPT_PACKAGES.filter((name) => !Array.isArray(exempted) || !exempted.includes(name));
48
+ const addReleaseAgeExemptions = (document, key) => {
49
+ const current = document.get(key);
50
+ const missing = missingExemptions(isSeq(current) ? current.toJSON() : []);
51
+ if (!isSeq(current)) {
52
+ document.set(key, document.createNode([]));
53
+ }
54
+ for (const name of missing) {
55
+ document.addIn([key], name);
56
+ }
57
+ };
58
+ const npmExemptions = (source) => source.split(/\r?\n/).flatMap((line) => {
59
+ const value = NPM_RELEASE_AGE_EXCLUDE_PATTERN.exec(line)?.[2];
60
+ return value === undefined ? [] : [value];
61
+ });
62
+ const npmExemptionLines = (names) => names.map((name) => `${NPM_RELEASE_AGE_EXCLUDE}=${name}`).join("\n");
63
+ const writeNpmExemptions = (root) => {
64
+ const path = join(root, NPM_CONFIG_FILE);
65
+ const source = existsSync(path) ? readFileSync(path, "utf8") : "";
66
+ const missing = missingExemptions(npmExemptions(source));
67
+ if (missing.length === 0) {
68
+ return [];
69
+ }
70
+ const separator = source === "" || source.endsWith("\n") ? "" : "\n";
71
+ replaceFile(path, `${source}${separator}${npmExemptionLines(missing)}\n`);
72
+ return [path];
73
+ };
74
+ const writeYamlExemptions = (path, key) => {
75
+ const settings = readSettings(path, parse);
76
+ if (missingExemptions(isRecord(settings) ? settings[key] : undefined).length === 0) {
77
+ return [];
78
+ }
79
+ updateYamlFile(path, (document) => addReleaseAgeExemptions(document, key));
80
+ return [path];
81
+ };
82
+ const reportedYarnRelease = (root) => {
83
+ const corepack = tryResolveExecutable("corepack");
84
+ const command = corepack ?? tryResolveExecutable("yarn");
85
+ if (command === undefined) {
86
+ return null;
87
+ }
88
+ try {
89
+ return execFileSync(command, corepack === undefined ? ["--version"] : ["yarn", "--version"], {
90
+ cwd: root,
91
+ encoding: "utf8",
92
+ stdio: ["ignore", "pipe", "ignore"],
93
+ }).trim();
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ };
99
+ /**
100
+ * The Yarn release that installs a project without a pin at `root`: the Yarn running the scaffold, otherwise the
101
+ * one `yarn --version` reports there through Corepack.
102
+ */
103
+ const installingYarnRelease = (root) => YARN_USER_AGENT_PATTERN.exec(process.env.npm_config_user_agent ?? "")?.[1] ?? reportedYarnRelease(root);
104
+ /**
105
+ * The Yarn release that `yarn` runs in the project or workspace at `root`: the one `yarn --version` reports
106
+ * there when its `.yarnrc.yml` sets `yarnPath`, which overrides a pin, otherwise the release its
107
+ * `packageManager` field pins, otherwise the Yarn running the scaffold, otherwise the one `yarn --version`
108
+ * reports there through Corepack.
109
+ */
110
+ const yarnRelease = (root) => {
111
+ const settings = readSettings(join(root, YARN_CONFIG_FILE), parse);
112
+ if (isRecord(settings) && typeof settings.yarnPath === "string") {
113
+ return reportedYarnRelease(root);
114
+ }
115
+ const manifest = readSettings(join(root, PACKAGE_JSON_FILE), JSON.parse);
116
+ const pin = isRecord(manifest) && typeof manifest.packageManager === "string" ? manifest.packageManager : "";
117
+ if (pin.startsWith(YARN_PIN_PREFIX)) {
118
+ return pin.slice(YARN_PIN_PREFIX.length);
119
+ }
120
+ return installingYarnRelease(root);
121
+ };
122
+ /**
123
+ * Whether the Yarn installing the project at `root` reads `npmPreapprovedPackages`. Yarn 4.10 added it next to
124
+ * its release-age gate, and older releases refuse to run with a setting they do not know.
125
+ */
126
+ const readsPreapprovedPackages = (root) => {
127
+ const matched = YARN_RELEASE_PATTERN.exec(yarnRelease(root) ?? "");
128
+ const major = Number(matched?.[1]);
129
+ const minor = Number(matched?.[2]);
130
+ return (major > FIRST_PREAPPROVING_YARN.major ||
131
+ (major === FIRST_PREAPPROVING_YARN.major && minor >= FIRST_PREAPPROVING_YARN.minor));
132
+ };
9
133
  const writePnpmAllowance = (root) => {
10
- const entries = BUILT_DEPENDENCIES.map((name) => ` ${quoteYamlKey(name)}: true`).join("\n");
11
- writeFileSync(join(root, PNPM_WORKSPACE_FILE), `${PNPM_PACKAGES_BLOCK}allowBuilds:\n${entries}\n`);
134
+ updateYamlFile(join(root, PNPM_WORKSPACE_FILE), (document) => {
135
+ if (!document.has("packages")) {
136
+ document.set("packages", document.createNode(["."]));
137
+ }
138
+ if (!isMap(document.get("allowBuilds"))) {
139
+ document.set("allowBuilds", document.createNode({}));
140
+ }
141
+ for (const name of BUILT_DEPENDENCIES) {
142
+ document.setIn(["allowBuilds", name], true);
143
+ }
144
+ addReleaseAgeExemptions(document, PNPM_RELEASE_AGE_EXCLUDE);
145
+ });
12
146
  };
13
147
  const writeNpmAllowance = (root) => {
14
148
  updateManifest(root, (manifest) => {
15
149
  manifest.allowScripts = Object.fromEntries(BUILT_DEPENDENCIES.map((name) => [name, true]));
16
150
  });
151
+ writeNpmExemptions(root);
17
152
  };
18
153
  const writeYarnAllowance = (root) => {
154
+ const isPreapproving = readsPreapprovedPackages(root);
155
+ updateYamlFile(join(root, YARN_CONFIG_FILE), (document) => {
156
+ document.set("nodeLinker", YARN_NODE_LINKER);
157
+ if (isPreapproving) {
158
+ addReleaseAgeExemptions(document, YARN_PREAPPROVED_PACKAGES);
159
+ }
160
+ });
19
161
  updateManifest(root, (manifest) => {
20
162
  manifest.dependenciesMeta = Object.fromEntries(BUILT_DEPENDENCIES.map((name) => [name, { built: true }]));
21
163
  });
22
164
  };
23
- const writeBuildAllowance = (root, packageManager) => {
165
+ /**
166
+ * Configures the package manager to run the build scripts of the scaffold's native dependencies and to exempt
167
+ * GTKX's own packages from its release-age gate, so a project created on the day of a GTKX release installs it.
168
+ * Adds to an existing `pnpm-workspace.yaml`, `.yarnrc.yml` or `.npmrc` instead of replacing it.
169
+ */
170
+ const writePackageManagerSettings = (root, packageManager) => {
24
171
  if (packageManager === "pnpm") {
25
172
  writePnpmAllowance(root);
26
173
  return;
@@ -31,5 +178,209 @@ const writeBuildAllowance = (root, packageManager) => {
31
178
  }
32
179
  writeNpmAllowance(root);
33
180
  };
34
- export { writeBuildAllowance };
181
+ const RELEASE_AGE_EXEMPTION_WRITERS = {
182
+ pnpm: (root) => writeYamlExemptions(join(root, PNPM_WORKSPACE_FILE), PNPM_RELEASE_AGE_EXCLUDE),
183
+ yarn: (root) => readsPreapprovedPackages(root)
184
+ ? writeYamlExemptions(join(root, YARN_CONFIG_FILE), YARN_PREAPPROVED_PACKAGES)
185
+ : [],
186
+ npm: writeNpmExemptions,
187
+ };
188
+ /**
189
+ * Exempts GTKX's own packages from the release-age gate of the package manager that installs the project or
190
+ * workspace at `root`, adding only the entries its `pnpm-workspace.yaml`, `.yarnrc.yml` (Yarn 4.10 or newer)
191
+ * or `.npmrc` lacks and keeping everything else in it, and returns the files it changed.
192
+ */
193
+ const writeReleaseAgeExemptions = (root, packageManager) => RELEASE_AGE_EXEMPTION_WRITERS[packageManager](root);
194
+ const PACKAGE_MANAGER_CONFIG_FILES = {
195
+ pnpm: [PNPM_WORKSPACE_FILE],
196
+ yarn: [YARN_CONFIG_FILE],
197
+ npm: [NPM_CONFIG_FILE],
198
+ };
199
+ /**
200
+ * The `packageManager` field of the project's existing `package.json` when it names `packageManager`, so
201
+ * replacing the manifest keeps the version the project pins.
202
+ */
203
+ const pinnedPackageManager = (root, packageManager) => {
204
+ const path = join(root, PACKAGE_JSON_FILE);
205
+ if (!existsSync(path)) {
206
+ return null;
207
+ }
208
+ try {
209
+ const manifest = JSON.parse(readFileSync(path, "utf8"));
210
+ const pin = isRecord(manifest) ? manifest.packageManager : undefined;
211
+ return typeof pin === "string" && pin.startsWith(`${packageManager}@`) ? pin : null;
212
+ }
213
+ catch {
214
+ return null;
215
+ }
216
+ };
217
+ const nearestDirectory = (path) => existsSync(path) || dirname(path) === path ? path : nearestDirectory(dirname(path));
218
+ /**
219
+ * The `packageManager` pin for the Yarn 2 or newer release that installs a new project at `root`, as
220
+ * `yarn init -2` writes it, or null when that is Yarn 1. The project may not exist yet, so Corepack is asked in
221
+ * its nearest existing directory, which resolves the same release for a project without a pin.
222
+ */
223
+ const installingYarnPin = (root) => {
224
+ const release = installingYarnRelease(nearestDirectory(root));
225
+ const major = Number(YARN_RELEASE_PATTERN.exec(release ?? "")?.[1]);
226
+ return release !== null && major >= FIRST_PINNED_YARN_MAJOR ? `${YARN_PIN_PREFIX}${release}` : null;
227
+ };
228
+ /**
229
+ * The `packageManager` field for the new `package.json`: the existing project's pin when it names
230
+ * `packageManager`, otherwise, outside an enclosing workspace whose root owns the pin, the Yarn 2 or newer
231
+ * release that installs the project.
232
+ */
233
+ const packageManagerPin = (root, packageManager, isInWorkspace) => pinnedPackageManager(root, packageManager) ??
234
+ (packageManager === "yarn" && !isInWorkspace ? installingYarnPin(root) : null);
235
+ /**
236
+ * The workspace globs of `field`, given as a list or, as npm and Yarn also accept, as an object with a
237
+ * `packages` list.
238
+ */
239
+ const workspacePatterns = (settings, field) => {
240
+ const value = isRecord(settings) ? settings[field] : undefined;
241
+ const patterns = isRecord(value) ? value.packages : value;
242
+ return Array.isArray(patterns) ? patterns.filter((pattern) => typeof pattern === "string") : [];
243
+ };
244
+ const matchesWorkspacePattern = (project, pattern) => matchesGlob(project, posix.normalize(pattern).replace(/\/+$/, ""));
245
+ const includesProject = (patterns, project) => patterns.some((pattern) => !pattern.startsWith(NEGATION_PREFIX) && matchesWorkspacePattern(project, pattern)) &&
246
+ !patterns.some((pattern) => pattern.startsWith(NEGATION_PREFIX) &&
247
+ matchesWorkspacePattern(project, pattern.slice(NEGATION_PREFIX.length)));
248
+ const ancestorFiles = (root, name) => {
249
+ const files = [];
250
+ for (let directory = dirname(root);; directory = dirname(directory)) {
251
+ const file = join(directory, name);
252
+ if (existsSync(file)) {
253
+ files.push(file);
254
+ }
255
+ if (dirname(directory) === directory) {
256
+ return files;
257
+ }
258
+ }
259
+ };
260
+ const projectPath = (file, root) => relative(dirname(file), root).split(sep).join(posix.sep);
261
+ const recordField = (settings, field) => isRecord(settings) && isRecord(settings[field]) ? settings[field] : {};
262
+ const missingBuilds = (allowances) => BUILT_DEPENDENCIES.filter((name) => !Object.hasOwn(allowances, name));
263
+ const settingsToAdd = (settings) => settings.filter((setting) => setting !== null);
264
+ const missingYamlExemptions = (file, settings, key) => {
265
+ const listed = isRecord(settings) ? settings[key] : undefined;
266
+ const missing = missingExemptions(listed);
267
+ if (missing.length === 0) {
268
+ return null;
269
+ }
270
+ return Array.isArray(listed)
271
+ ? { file, section: key, entries: stringify(missing).trimEnd().replace(/^/gm, " ") }
272
+ : { file, section: null, entries: stringify({ [key]: missing }).trimEnd() };
273
+ };
274
+ const pnpmWorkspaceAt = (file, project) => {
275
+ const settings = parse(readFileSync(file, "utf8"));
276
+ if (!includesProject(workspacePatterns(settings, "packages"), project)) {
277
+ return null;
278
+ }
279
+ const allowances = recordField(settings, "allowBuilds");
280
+ const missing = BUILT_DEPENDENCIES.filter((name) => typeof allowances[name] !== "boolean");
281
+ const required = Object.fromEntries(missing.map((name) => [name, true]));
282
+ const setting = isRecord(settings) && isRecord(settings.allowBuilds)
283
+ ? { file, section: "allowBuilds", entries: stringify(required).trimEnd().replace(/^/gm, " ") }
284
+ : { file, section: null, entries: stringify({ allowBuilds: required }).trimEnd() };
285
+ return {
286
+ packageManager: "pnpm",
287
+ root: dirname(file),
288
+ member: project,
289
+ missingSettings: settingsToAdd([
290
+ missing.length > 0 ? setting : null,
291
+ missingYamlExemptions(file, settings, PNPM_RELEASE_AGE_EXCLUDE),
292
+ ]),
293
+ };
294
+ };
295
+ const npmWorkspaceAt = (file, project) => {
296
+ const manifest = JSON.parse(readFileSync(file, "utf8"));
297
+ if (!includesProject(workspacePatterns(manifest, "workspaces"), project)) {
298
+ return null;
299
+ }
300
+ const missing = missingBuilds(recordField(manifest, "allowScripts"));
301
+ const entries = `"allowScripts": ${JSON.stringify(Object.fromEntries(missing.map((name) => [name, true])), null, 4)}`;
302
+ const configFile = join(dirname(file), NPM_CONFIG_FILE);
303
+ const exemptions = missingExemptions(npmExemptions(existsSync(configFile) ? readFileSync(configFile, "utf8") : ""));
304
+ return {
305
+ packageManager: "npm",
306
+ root: dirname(file),
307
+ member: project,
308
+ missingSettings: settingsToAdd([
309
+ missing.length > 0 ? { file, section: null, entries } : null,
310
+ exemptions.length > 0 ? { file: configFile, section: null, entries: npmExemptionLines(exemptions) } : null,
311
+ ]),
312
+ };
313
+ };
314
+ /**
315
+ * The `nodeLinker` Yarn applies in `directory`: Yarn merges the `.yarnrc.yml` files of a project and its
316
+ * ancestors, and the closest one that sets a value wins.
317
+ */
318
+ const yarnNodeLinker = (directory) => {
319
+ for (const file of [join(directory, YARN_CONFIG_FILE), ...ancestorFiles(directory, YARN_CONFIG_FILE)]) {
320
+ const settings = existsSync(file) ? parse(readFileSync(file, "utf8")) : undefined;
321
+ if (isRecord(settings) && Object.hasOwn(settings, "nodeLinker")) {
322
+ return settings.nodeLinker;
323
+ }
324
+ }
325
+ return undefined;
326
+ };
327
+ const yarnWorkspaceAt = (file, project) => {
328
+ const manifest = JSON.parse(readFileSync(file, "utf8"));
329
+ if (!includesProject(workspacePatterns(manifest, "workspaces"), project)) {
330
+ return null;
331
+ }
332
+ const missing = missingBuilds(recordField(manifest, "dependenciesMeta"));
333
+ const dependenciesMeta = Object.fromEntries(missing.map((name) => [name, { built: true }]));
334
+ const configFile = join(dirname(file), YARN_CONFIG_FILE);
335
+ const exemptions = readsPreapprovedPackages(dirname(file))
336
+ ? missingYamlExemptions(configFile, readSettings(configFile, parse), YARN_PREAPPROVED_PACKAGES)
337
+ : null;
338
+ return {
339
+ packageManager: "yarn",
340
+ root: dirname(file),
341
+ member: project,
342
+ missingSettings: settingsToAdd([
343
+ yarnNodeLinker(dirname(file)) === YARN_NODE_LINKER
344
+ ? null
345
+ : { file: configFile, section: null, entries: stringify({ nodeLinker: YARN_NODE_LINKER }).trimEnd() },
346
+ missing.length > 0
347
+ ? { file, section: null, entries: `"dependenciesMeta": ${JSON.stringify(dependenciesMeta, null, 4)}` }
348
+ : null,
349
+ exemptions,
350
+ ]),
351
+ };
352
+ };
353
+ const MANIFEST_WORKSPACES = {
354
+ npm: npmWorkspaceAt,
355
+ yarn: yarnWorkspaceAt,
356
+ };
357
+ /**
358
+ * The pnpm, npm or Yarn workspace above `root` that includes it, with the settings its root configuration
359
+ * still lacks for the app, or null when `root` is not part of an enclosing workspace. pnpm reads
360
+ * `allowBuilds` and `minimumReleaseAgeExclude`, npm `allowScripts` and `min-release-age-exclude`, and Yarn
361
+ * `nodeLinker`, `npmPreapprovedPackages` and `dependenciesMeta` only for the whole workspace, from its root.
362
+ */
363
+ const enclosingWorkspace = (root, packageManager) => {
364
+ if (packageManager === "pnpm") {
365
+ const [nearest] = ancestorFiles(root, PNPM_WORKSPACE_FILE);
366
+ return nearest === undefined ? null : pnpmWorkspaceAt(nearest, projectPath(nearest, root));
367
+ }
368
+ const workspaceAt = MANIFEST_WORKSPACES[packageManager];
369
+ for (const file of ancestorFiles(root, PACKAGE_JSON_FILE)) {
370
+ const workspace = workspaceAt(file, projectPath(file, root));
371
+ if (workspace !== null) {
372
+ return workspace;
373
+ }
374
+ }
375
+ return null;
376
+ };
377
+ /**
378
+ * Whether `yarn` in the workspace at `root` is Yarn 1, judged by the release it runs there, and Yarn 1 when no
379
+ * release can be determined.
380
+ */
381
+ const isClassicYarn = (root) => {
382
+ const major = Number(YARN_RELEASE_PATTERN.exec(yarnRelease(root) ?? "")?.[1]);
383
+ return Number.isNaN(major) || major < FIRST_PINNED_YARN_MAJOR;
384
+ };
385
+ export { PACKAGE_MANAGER_CONFIG_FILES, enclosingWorkspace, isClassicYarn, packageManagerPin, writePackageManagerSettings, writeReleaseAgeExemptions, };
35
386
  //# sourceMappingURL=build-allowance.js.map