create-mapringg-repo 0.0.0-stage → 1.15.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mapringg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/cli.mjs ADDED
@@ -0,0 +1,324 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, dirname, join, resolve } from "node:path";
6
+ import { stdin, stdout } from "node:process";
7
+ import { createInterface } from "node:readline/promises";
8
+ import { parseArgs } from "node:util";
9
+
10
+ import { command, github, githubRepo } from "./github.mjs";
11
+ import { configure } from "./setup.mjs";
12
+
13
+ const TEMPLATE = "mapringg/monorepo";
14
+ const SETUP_BRANCH = "mapring/setup-standard-";
15
+ const SETUP_TITLE = "Set up the shared repository standard";
16
+ const LOCAL_STATE = "mapring.creator";
17
+ const REPO_NAME = /^(?!\.{1,2}$)[a-z\d][a-z\d._-]{0,99}$/i;
18
+
19
+ const { values: flags } = parseArgs({
20
+ options: {
21
+ type: { type: "string" },
22
+ name: { type: "string" },
23
+ new: { type: "boolean" },
24
+ public: { type: "boolean" },
25
+ private: { type: "boolean" },
26
+ "no-wait": { type: "boolean" },
27
+ help: { type: "boolean", short: "h" },
28
+ },
29
+ });
30
+
31
+ const git = (cwd, args, options) => command(cwd, "git", args, options);
32
+ const gh = (cwd, args, options) => command(cwd, "gh", args, options);
33
+ const print = console.log;
34
+
35
+ async function ask(question, fallback) {
36
+ if (!stdin.isTTY) {
37
+ if (fallback) return fallback;
38
+ throw new Error(`Supply ${question} as a command-line option (see --help).`);
39
+ }
40
+ const prompt = createInterface({ input: stdin, output: stdout });
41
+ try {
42
+ return (await prompt.question(`${question}${fallback ? ` [${fallback}]` : ""} `)).trim() || fallback;
43
+ } finally {
44
+ prompt.close();
45
+ }
46
+ }
47
+
48
+ function stateAt(root) {
49
+ const state = git(root, ["config", "--local", "--get", LOCAL_STATE], { allowFailure: true });
50
+ return state.ok ? JSON.parse(state.output) : null;
51
+ }
52
+
53
+ function saveState(root, state) {
54
+ git(root, ["config", "--local", LOCAL_STATE, JSON.stringify(state)]);
55
+ }
56
+
57
+ function hasCommit(root) {
58
+ return git(root, ["rev-parse", "--verify", "HEAD"], { allowFailure: true }).ok;
59
+ }
60
+
61
+ function copyTemplate(root, scratch) {
62
+ const template = join(scratch, "template");
63
+ gh(root, ["repo", "clone", TEMPLATE, template, "--", "--depth=1", "--no-tags"], { stream: true });
64
+ const paths = git(template, ["ls-files", "-z"]).output.split("\0").filter(Boolean);
65
+ for (const path of paths) {
66
+ const to = join(root, path);
67
+ mkdirSync(dirname(to), { recursive: true });
68
+ cpSync(join(template, path), to, { dereference: false, verbatimSymlinks: true });
69
+ }
70
+ }
71
+
72
+ function checks(root, kind, updateLock, initial) {
73
+ const path = join(root, "package.json");
74
+ if ((kind !== "app" && !updateLock) || !existsSync(path)) return;
75
+ const manifest = JSON.parse(readFileSync(path, "utf8"));
76
+ const runner = existsSync(join(root, "pnpm-lock.yaml"))
77
+ ? "pnpm"
78
+ : existsSync(join(root, "package-lock.json"))
79
+ ? "npm"
80
+ : null;
81
+ if (!runner) {
82
+ if (updateLock) throw new Error("Refresh this repository’s dependency lockfile before adopting Standard.");
83
+ return;
84
+ }
85
+ if (updateLock) {
86
+ const args =
87
+ runner === "pnpm" ? ["install", "--lockfile-only", "--no-frozen-lockfile"] : ["install", "--package-lock-only"];
88
+ command(root, runner, args, { stream: true });
89
+ }
90
+ command(root, runner, runner === "pnpm" ? ["install", "--frozen-lockfile"] : ["ci"], { stream: true });
91
+ const scripts = ["lint", "format:check", "knip", ...(initial ? ["test"] : [])];
92
+ for (const script of scripts) {
93
+ if (manifest.scripts?.[script]) command(root, runner, ["run", script], { stream: true });
94
+ }
95
+ }
96
+
97
+ function configureProtection(host, base, check) {
98
+ if (host.requireCheck(base, check)) {
99
+ print(`GitHub requires ${check} on ${base}.`);
100
+ } else {
101
+ print(`GitHub Free cannot require ${check} on this private repo. Wait for a green check before merging.`);
102
+ }
103
+ }
104
+
105
+ function push(root, scratch, refs) {
106
+ const hooks = join(scratch, "empty-hooks");
107
+ mkdirSync(hooks, { recursive: true });
108
+ git(root, ["-c", `core.hooksPath=${hooks}`, "push", "-u", "origin", ...refs], { stream: true });
109
+ }
110
+
111
+ async function create(root, state, scratch) {
112
+ const host = github(root, state.repo);
113
+ let remote = host.lookup();
114
+ if (!hasCommit(root)) {
115
+ if (remote) throw new Error(`GitHub already has ${state.repo}. Use an existing checkout to adopt it.`);
116
+ if (!state.scaffolded) {
117
+ if (state.kind === "app") copyTemplate(root, scratch);
118
+ const readme = join(root, "README.md");
119
+ const title = `# ${basename(root)}`;
120
+ if (!existsSync(readme))
121
+ writeFileSync(
122
+ readme,
123
+ `${title}\n\nAdd a short project overview here.\n\n## Quick start\n\nAdd setup steps here.\n`,
124
+ );
125
+ else if (state.kind === "app")
126
+ writeFileSync(readme, readFileSync(readme, "utf8").replace(/^# monorepo\r?$/im, title));
127
+ saveState(root, { ...state, scaffolded: true });
128
+ }
129
+ const { check, updateLock } = configure(root, basename(root), { kind: state.kind, initial: true });
130
+ checks(root, state.kind, updateLock, true);
131
+ git(root, ["add", "--all"]);
132
+ git(root, ["commit", "-m", "Initial commit"], { stream: true });
133
+ state.check = check;
134
+ saveState(root, state);
135
+ }
136
+ const sha = git(root, ["rev-parse", "refs/heads/main"]).output;
137
+ if (!state.check) {
138
+ state.check = configure(root, basename(root), { kind: state.kind, initial: true }).check;
139
+ saveState(root, state);
140
+ }
141
+ if (!remote) {
142
+ gh(
143
+ root,
144
+ ["repo", "create", state.repo, state.visibility === "public" ? "--public" : "--private", "--source", root],
145
+ { stream: true },
146
+ );
147
+ remote = host.lookup();
148
+ }
149
+ if (!remote?.permissions?.admin) throw new Error(`Admin access is required for ${state.repo}.`);
150
+ if (remote.visibility !== state.visibility)
151
+ throw new Error(`Visibility differs for ${state.repo}. Review the existing GitHub repo.`);
152
+ if (!git(root, ["config", "--get", "remote.origin.url"], { allowFailure: true }).ok) {
153
+ git(root, ["remote", "add", "origin", remote.clone_url]);
154
+ }
155
+ if (
156
+ githubRepo(git(root, ["config", "--get", "remote.origin.url"]).output).toLowerCase() !== state.repo.toLowerCase()
157
+ ) {
158
+ throw new Error("The local origin points to a different repository.");
159
+ }
160
+ const refs = git(root, ["ls-remote", "--heads", "origin"]).output;
161
+ const current = refs
162
+ .split("\n")
163
+ .find((line) => line.endsWith("\trefs/heads/main"))
164
+ ?.split("\t")[0];
165
+ if (current && current !== sha)
166
+ throw new Error("GitHub main already has different content. Rerun from a checkout of that branch to adopt it.");
167
+ if (!current && refs) throw new Error("GitHub already has another branch. Use an existing checkout to adopt it.");
168
+ host.configureMerge(remote);
169
+ if (!current) push(root, scratch, ["main"]);
170
+ configureProtection(host, "main", state.check);
171
+ if (!flags["no-wait"]) await host.waitForCheck(sha, state.check);
172
+ git(root, ["config", "--local", "--unset", LOCAL_STATE]);
173
+ print(`${remote.html_url}\n${root}`);
174
+ }
175
+
176
+ function existingSource(root) {
177
+ const url = git(root, ["config", "--get", "remote.origin.url"]).output;
178
+ if (!url) throw new Error("Set a GitHub origin before adopting this repository.");
179
+ return { url, repo: githubRepo(url) };
180
+ }
181
+
182
+ function setupBody(check, local) {
183
+ return `## Summary
184
+
185
+ \`\`\`text
186
+ Repository
187
+ PR writing and Capture
188
+ ${check}
189
+ Squash merge
190
+ \`\`\`
191
+
192
+ ## Evidence
193
+
194
+ - **Before:** The repository was missing part of the shared PR workflow.
195
+ - **After:** The setup diff aligns the skill links and PR check. ${local}
196
+
197
+ ## Merge Danger
198
+
199
+ **Door:** two-way
200
+
201
+ **Blast Radius:** repository
202
+ `;
203
+ }
204
+
205
+ async function adopt(root, kind, scratch) {
206
+ const { url, repo } = existingSource(root);
207
+ const host = github(root, repo);
208
+ const remote = host.lookup();
209
+ if (!remote?.permissions?.admin) throw new Error(`Admin access is required for ${repo}.`);
210
+ const base = remote.default_branch;
211
+ const work = join(scratch, "checkout");
212
+ git(root, ["clone", "--single-branch", "--no-tags", "--branch", base, url, work], { stream: true });
213
+ const baseSha = git(work, ["rev-parse", "HEAD"]).output;
214
+ const branch = `${SETUP_BRANCH}${baseSha.slice(0, 12)}`;
215
+ const { check, updateLock } = configure(work, remote.name, { kind });
216
+ const modified = git(work, ["status", "--porcelain"]).output;
217
+ host.configureMerge(remote);
218
+ if (!modified) {
219
+ configureProtection(host, base, check);
220
+ print(`Already aligned.\n${remote.html_url}\n${root}`);
221
+ return;
222
+ }
223
+ const open = host.pulls(base).find((pull) => !pull.isCrossRepository && pull.headRefName.startsWith(SETUP_BRANCH));
224
+ if (open) {
225
+ print(`Setup PR: ${open.url}`);
226
+ if (!flags["no-wait"]) await host.waitForCheck(open.headRefOid, check);
227
+ configureProtection(host, base, check);
228
+ return;
229
+ }
230
+ checks(work, kind, updateLock, false);
231
+ for (const file of [
232
+ "AGENTS.md",
233
+ "mise.toml",
234
+ ".mise.toml",
235
+ "package.json",
236
+ "pnpm-lock.yaml",
237
+ "package-lock.json",
238
+ ".github/workflows",
239
+ ".github/dependabot.yml",
240
+ ]) {
241
+ if (existsSync(join(work, file))) git(work, ["add", "--", file]);
242
+ }
243
+ const tree = git(work, ["write-tree"]).output;
244
+ const known = git(work, ["ls-remote", "--heads", "origin", `refs/heads/${branch}`]).output;
245
+ let head;
246
+ if (known) {
247
+ git(work, ["fetch", "origin", branch]);
248
+ head = git(work, ["rev-parse", "FETCH_HEAD"]).output;
249
+ const parents = git(work, ["show", "-s", "--format=%P", head]).output;
250
+ if (git(work, ["rev-parse", `${head}^{tree}`]).output !== tree || parents !== baseSha) {
251
+ throw new Error(`The existing setup branch ${branch} has different changes. Review it before rerunning.`);
252
+ }
253
+ } else {
254
+ git(work, ["switch", "-c", branch]);
255
+ git(work, ["commit", "-m", SETUP_TITLE], { stream: true });
256
+ head = git(work, ["rev-parse", "HEAD"]).output;
257
+ push(work, scratch, [branch]);
258
+ }
259
+ const evidence =
260
+ kind === "app"
261
+ ? "Applicable local project checks passed."
262
+ : "The setup diff preserves the repository’s files and checks.";
263
+ const pr = host.createPull(base, branch, SETUP_TITLE, setupBody(check, evidence));
264
+ print(`Setup PR: ${pr}\n${root}`);
265
+ if (!flags["no-wait"]) await host.waitForCheck(head, check);
266
+ configureProtection(host, base, check);
267
+ }
268
+
269
+ async function main() {
270
+ if (flags.help) {
271
+ print(
272
+ "Usage: create-mapringg-repo [--type app|plain] [--new --name NAME] [--public|--private] [--no-wait]\n\nRun in an existing GitHub checkout to adopt it, or outside Git to create a repo.",
273
+ );
274
+ return;
275
+ }
276
+ if (flags.public && flags.private) throw new Error("Choose one visibility.");
277
+ const cwd = resolve(".");
278
+ const located = git(cwd, ["rev-parse", "--show-toplevel"], { allowFailure: true });
279
+ let root = located.ok && !flags.new && !flags.name ? located.output : null;
280
+ let state = root ? stateAt(root) : null;
281
+ if (!root) {
282
+ const name = flags.name ?? (await ask("Repository name"));
283
+ if (!name || !REPO_NAME.test(name))
284
+ throw new Error("Use a GitHub repository name with letters, numbers, periods, underscores, or hyphens.");
285
+ root = join(cwd, name);
286
+ if (existsSync(root) && readdirSync(root).length > 0) {
287
+ const child = git(root, ["rev-parse", "--show-toplevel"], { allowFailure: true });
288
+ if (!child.ok || child.output !== root)
289
+ throw new Error(`${root} already exists and is not an initialized setup folder.`);
290
+ state = stateAt(root);
291
+ } else {
292
+ const kind = flags.type ?? (await ask("App or plain?", "plain"));
293
+ if (!["app", "plain"].includes(kind)) throw new Error("Choose app or plain.");
294
+ const visibility = flags.public
295
+ ? "public"
296
+ : flags.private
297
+ ? "private"
298
+ : await ask("Private or public?", "private");
299
+ if (!["private", "public"].includes(visibility)) throw new Error("Choose private or public.");
300
+ const owner = gh(cwd, ["api", "user", "--jq", ".login"]).output;
301
+ mkdirSync(root, { recursive: true });
302
+ git(root, ["init", "-b", "main"], { stream: true });
303
+ state = { repo: `${owner}/${name}`, kind, visibility };
304
+ saveState(root, state);
305
+ }
306
+ }
307
+ const kind =
308
+ state?.kind ?? flags.type ?? (await ask("App or plain?", existsSync(join(root, "package.json")) ? "app" : "plain"));
309
+ if (!["app", "plain"].includes(kind)) throw new Error("Choose app or plain.");
310
+ const scratch = mkdtempSync(join(tmpdir(), "create-mapringg-repo-"));
311
+ try {
312
+ if (state) await create(root, state, scratch);
313
+ else await adopt(root, kind, scratch);
314
+ } finally {
315
+ rmSync(scratch, { recursive: true, force: true });
316
+ }
317
+ }
318
+
319
+ try {
320
+ await main();
321
+ } catch (error) {
322
+ console.error(error.message);
323
+ process.exitCode = 1;
324
+ }
package/github.mjs ADDED
@@ -0,0 +1,128 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { setTimeout } from "node:timers/promises";
3
+
4
+ export function command(cwd, bin, args, options = {}) {
5
+ const result = spawnSync(bin, args, {
6
+ cwd,
7
+ encoding: "utf8",
8
+ stdio: options.stream ? "inherit" : ["pipe", "pipe", "pipe"],
9
+ input: options.input,
10
+ maxBuffer: 8 * 1024 * 1024,
11
+ });
12
+ if (result.error) throw result.error;
13
+ if (result.status !== 0 && !options.allowFailure) {
14
+ throw new Error(`${bin} ${args[0]} failed${result.stderr?.trim() ? `: ${result.stderr.trim()}` : "."}`);
15
+ }
16
+ return { ok: result.status === 0, output: result.stdout?.trim() ?? "", error: result.stderr?.trim() ?? "" };
17
+ }
18
+
19
+ export function github(cwd, repo) {
20
+ const endpoint = `repos/${repo}`;
21
+ const api = (path, method = "GET", body) => {
22
+ const args = ["api", "--method", method, path];
23
+ if (body !== undefined) args.push("--input", "-");
24
+ const result = command(cwd, "gh", args, { input: JSON.stringify(body), allowFailure: true });
25
+ if (result.ok) return result.output ? JSON.parse(result.output) : null;
26
+ const status = /HTTP (\d{3})/.exec(result.error)?.[1];
27
+ const message = result.error.split("\n")[0];
28
+ throw Object.assign(new Error(message || "GitHub API request failed."), { status });
29
+ };
30
+
31
+ return {
32
+ lookup() {
33
+ try {
34
+ return api(endpoint);
35
+ } catch (error) {
36
+ if (error.status === "404") return null;
37
+ throw error;
38
+ }
39
+ },
40
+ configureMerge(current) {
41
+ const desired = {
42
+ allow_merge_commit: false,
43
+ allow_rebase_merge: false,
44
+ allow_squash_merge: true,
45
+ squash_merge_commit_title: "PR_TITLE",
46
+ squash_merge_commit_message: "BLANK",
47
+ };
48
+ if (Object.entries(desired).some(([key, value]) => current[key] !== value)) api(endpoint, "PATCH", desired);
49
+ },
50
+ requireCheck(base, check) {
51
+ const path = `${endpoint}/branches/${encodeURIComponent(base)}/protection`;
52
+ const required = { strict: false, contexts: [check] };
53
+ try {
54
+ let protection = null;
55
+ try {
56
+ protection = api(path);
57
+ } catch (error) {
58
+ if (error.status !== "404") throw error;
59
+ }
60
+ if (!protection) {
61
+ api(path, "PUT", {
62
+ required_status_checks: required,
63
+ enforce_admins: false,
64
+ required_pull_request_reviews: null,
65
+ restrictions: null,
66
+ });
67
+ } else if (!protection.required_status_checks) {
68
+ api(`${path}/required_status_checks`, "PATCH", required);
69
+ } else if (!protection.required_status_checks.contexts.includes(check)) {
70
+ api(`${path}/required_status_checks/contexts`, "POST", { contexts: [check] });
71
+ }
72
+ return true;
73
+ } catch (error) {
74
+ if (/upgrade to github pro|make this repository public/i.test(error.message)) return false;
75
+ throw error;
76
+ }
77
+ },
78
+ pulls(base) {
79
+ const args = [
80
+ "pr",
81
+ "list",
82
+ "--repo",
83
+ repo,
84
+ "--state",
85
+ "open",
86
+ "--base",
87
+ base,
88
+ "--limit",
89
+ "100",
90
+ "--json",
91
+ "number,url,headRefName,headRefOid,isCrossRepository",
92
+ ];
93
+ return JSON.parse(command(cwd, "gh", args).output);
94
+ },
95
+ createPull(base, branch, title, body) {
96
+ return command(
97
+ cwd,
98
+ "gh",
99
+ ["pr", "create", "--repo", repo, "--base", base, "--head", branch, "--title", title, "--body-file", "-"],
100
+ { input: body },
101
+ ).output;
102
+ },
103
+ async waitForCheck(sha, check) {
104
+ const deadline = Date.now() + 15 * 60_000;
105
+ while (Date.now() < deadline) {
106
+ const name = new URLSearchParams({ check_name: check, filter: "latest", per_page: "30" });
107
+ const entries = api(`${endpoint}/commits/${sha}/check-runs?${name}`).check_runs;
108
+ if (entries.length && entries.every((entry) => entry.status === "completed")) {
109
+ const failed = entries.find((entry) => entry.conclusion !== "success");
110
+ if (failed) throw new Error(`${check} finished with ${failed.conclusion}. ${failed.html_url}`);
111
+ console.log(`${check} passed.`);
112
+ return;
113
+ }
114
+ await setTimeout(5000);
115
+ }
116
+ throw new Error(`Timed out waiting for ${check}. Rerun setup to resume checking.`);
117
+ },
118
+ };
119
+ }
120
+
121
+ export function githubRepo(url) {
122
+ const match =
123
+ /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(
124
+ url,
125
+ );
126
+ if (!match) throw new Error("Use a github.com origin.");
127
+ return `${match[1]}/${match[2]}`;
128
+ }
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "create-mapringg-repo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.15.4",
4
+ "description": "Create or adopt a GitHub repository with the Mapringg PR workflow.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/mapringg/standard.git",
9
+ "directory": "packages/create-mapringg-repo"
10
+ },
11
+ "bin": {
12
+ "create-mapringg-repo": "./cli.mjs"
13
+ },
14
+ "files": [
15
+ "*.mjs",
16
+ "LICENSE"
17
+ ],
18
+ "type": "module",
19
+ "dependencies": {
20
+ "yaml": "2.9.1"
21
+ },
22
+ "engines": {
23
+ "node": ">=26"
24
+ }
25
+ }
package/release.mjs ADDED
@@ -0,0 +1,52 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ const STANDARD_REMOTE = "https://github.com/mapringg/standard";
6
+ const STANDARD_MANIFEST = join(import.meta.dirname, "..", "..", "package.json");
7
+ const SEMVER_TAG = /^v(\d+)\.(\d+)\.(\d+)$/;
8
+
9
+ let tags;
10
+ let tag;
11
+
12
+ function remoteTags() {
13
+ tags ??= new Map(
14
+ execFileSync("git", ["ls-remote", "--tags", STANDARD_REMOTE], { encoding: "utf8" })
15
+ .trim()
16
+ .split("\n")
17
+ .filter(Boolean)
18
+ .map((line) => {
19
+ const [sha, ref] = line.split("\t");
20
+ return [ref.replace("refs/tags/", ""), sha];
21
+ }),
22
+ );
23
+ return tags;
24
+ }
25
+
26
+ function bundledTag() {
27
+ if (!existsSync(STANDARD_MANIFEST)) return null;
28
+ const { name, version } = JSON.parse(readFileSync(STANDARD_MANIFEST, "utf8"));
29
+ return name === "@mapringg/standard" ? `v${version}` : null;
30
+ }
31
+
32
+ function newestTag() {
33
+ const released = [...remoteTags().keys()].filter((name) => SEMVER_TAG.test(name));
34
+ if (released.length === 0) throw new Error(`No Standard release tags found at ${STANDARD_REMOTE}.`);
35
+ const parts = (name) => SEMVER_TAG.exec(name).slice(1).map(Number);
36
+ return released.toSorted((a, b) => {
37
+ const [x, y] = [parts(a), parts(b)];
38
+ return y[0] - x[0] || y[1] - x[1] || y[2] - x[2];
39
+ })[0];
40
+ }
41
+
42
+ export function releaseTag() {
43
+ tag ??= bundledTag() ?? newestTag();
44
+ return tag;
45
+ }
46
+
47
+ export function releaseSha() {
48
+ const name = releaseTag();
49
+ const sha = remoteTags().get(`${name}^{}`) ?? remoteTags().get(name);
50
+ if (!sha) throw new Error(`Standard ${name} is not tagged yet. Run a tagged release of the creator.`);
51
+ return sha;
52
+ }
package/setup.mjs ADDED
@@ -0,0 +1,224 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ import { isMap, isSeq, parseDocument } from "yaml";
5
+
6
+ import { releaseSha, releaseTag } from "./release.mjs";
7
+
8
+ const PACKAGE = "@mapringg/standard";
9
+ const GROUP = "mapringg-standard";
10
+ const AUTOMERGE = join(".github", "workflows", "standard-updates.yml");
11
+ const ACTION = "mapringg/standard/.github/actions/check-pr@";
12
+ const CHECKOUT = "actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09";
13
+ const EVENTS = ["opened", "synchronize", "reopened", "edited"];
14
+ const SKILLS =
15
+ /@mapringg\/standard\/\.claude\/skills\/(?:pr|capture|test-audit|review-standard|upgrade-standard)\/SKILL\.md|github\.com\/mapringg\/standard\/blob\/[^/]+\/\.claude\/skills\/(?:pr|capture)\/SKILL\.md/;
16
+
17
+ function read(path) {
18
+ return existsSync(path) ? readFileSync(path, "utf8") : null;
19
+ }
20
+
21
+ function write(path, text) {
22
+ if (read(path) === text) return;
23
+ mkdirSync(dirname(path), { recursive: true });
24
+ writeFileSync(path, text);
25
+ }
26
+
27
+ function agents(root, installed) {
28
+ const path = join(root, "AGENTS.md");
29
+ const skillsRoot = installed
30
+ ? "node_modules/@mapringg/standard/.claude/skills"
31
+ : "https://github.com/mapringg/standard/blob/main/.claude/skills";
32
+ const original = read(path) ?? "# AGENTS.md\n";
33
+ const shared = original.split("\n").filter((line) => SKILLS.test(line));
34
+ if (
35
+ shared.length === 2 &&
36
+ ["pr", "capture"].every((skill) => shared.some((line) => line.includes(`${skillsRoot}/${skill}/SKILL.md)`)))
37
+ )
38
+ return;
39
+ const lines = original
40
+ .trimEnd()
41
+ .split("\n")
42
+ .filter((line) => !(/^\s*[-*] /.test(line) && SKILLS.test(line)));
43
+ const links = [
44
+ `- Use [PR writing](${skillsRoot}/pr/SKILL.md) when writing a pull request.`,
45
+ `- Follow [Capture](${skillsRoot}/capture/SKILL.md) when preparing pull request evidence.`,
46
+ ];
47
+ const sources = lines.indexOf("## Sources");
48
+ if (sources === -1) {
49
+ lines.push("", "## Sources", "", ...links);
50
+ } else {
51
+ let start = sources + 1;
52
+ while (lines[start] === "") start += 1;
53
+ lines.splice(sources + 1, start - sources - 1, "", ...links);
54
+ if (lines[sources + 4]?.startsWith("#")) lines.splice(sources + 4, 0, "");
55
+ }
56
+ write(path, `${lines.join("\n").trimEnd()}\n`);
57
+ }
58
+
59
+ function workflowFiles(root) {
60
+ const dir = join(root, ".github", "workflows");
61
+ if (!existsSync(dir)) return [];
62
+ return readdirSync(dir)
63
+ .filter((name) => /\.ya?ml$/.test(name))
64
+ .map((name) => {
65
+ const path = join(dir, name);
66
+ const doc = parseDocument(read(path));
67
+ if (doc.errors.length > 0) throw new Error(`Fix invalid workflow YAML in ${name} before adopting Standard.`);
68
+ return { path, name, doc, data: doc.toJS() ?? {} };
69
+ });
70
+ }
71
+
72
+ function hasPr(on) {
73
+ if (typeof on === "string") return on === "pull_request";
74
+ if (Array.isArray(on)) return on.includes("pull_request");
75
+ return Boolean(on && Object.hasOwn(on, "pull_request"));
76
+ }
77
+
78
+ function enablePrEdits(doc) {
79
+ const on = doc.get("on", true);
80
+ if (!isMap(on)) {
81
+ const values = isSeq(on) ? on.items.map((item) => item.value) : on?.value ? [on.value] : [];
82
+ doc.set("on", Object.fromEntries(values.map((event) => [event, null])));
83
+ }
84
+ const path = ["on", "pull_request"];
85
+ const existing = doc.getIn(path, true);
86
+ if (!isMap(existing)) doc.setIn(path, {});
87
+ const types = doc.getIn([...path, "types"], true);
88
+ const events = isSeq(types) ? types.items.map((item) => item.value) : [];
89
+ if (EVENTS.some((event) => !events.includes(event)))
90
+ doc.setIn([...path, "types"], [...new Set([...events, ...EVENTS])]);
91
+ }
92
+
93
+ function configureCheck(root, installed) {
94
+ const jobs = workflowFiles(root).flatMap((workflow) =>
95
+ Object.entries(workflow.data.jobs ?? {}).map(([id, job]) => ({ ...workflow, id, job })),
96
+ );
97
+ const candidates = jobs.filter(({ job }) => Array.isArray(job.steps));
98
+ const shared = candidates.find(({ job }) => job.steps.some((s) => s.uses?.startsWith(ACTION)));
99
+ const lint =
100
+ installed &&
101
+ read(join(root, ".oxlintrc.json"))?.includes("@mapringg/standard/oxlint.json") &&
102
+ candidates.find(
103
+ ({ job, data }) =>
104
+ hasPr(data.on) &&
105
+ job.steps.some((s) => /(?:\bpnpm\s+(?:run\s+)?lint\b|\.githooks\/pre-push)/.test(s.run ?? "")),
106
+ );
107
+ const check = shared || lint;
108
+ if (check) {
109
+ const { doc, path, id, job } = check;
110
+ const before = doc.toString();
111
+ enablePrEdits(doc);
112
+ const actionIndex = job.steps.findIndex((s) => s.uses?.startsWith(ACTION));
113
+ if (
114
+ actionIndex !== -1 &&
115
+ job.steps[actionIndex].uses !== `${ACTION}${releaseTag()}` &&
116
+ job.steps[actionIndex].uses !== `${ACTION}${releaseSha()}`
117
+ ) {
118
+ doc.setIn(["jobs", id, "steps", actionIndex, "uses"], `${ACTION}${releaseSha()}`);
119
+ }
120
+ if (doc.toString() !== before) write(path, doc.toString());
121
+ return { name: job.name ?? id, workflow: check.data.name ?? `.github/workflows/${check.name}` };
122
+ }
123
+ const name = jobs.some(({ id, job }) => (job.name ?? id).toLowerCase() === "check") ? "Standard PR" : "Check";
124
+ const path = join(root, ".github", "workflows", "standard-pr.yml");
125
+ if (existsSync(path)) throw new Error("Resolve the existing standard-pr.yml before adopting Standard.");
126
+ write(
127
+ path,
128
+ `name: Standard\n\non:\n pull_request:\n types: [${EVENTS.join(", ")}]\n push:\n branches: [main, develop]\n\npermissions:\n contents: read\n\njobs:\n check:\n name: ${name}\n runs-on: ubuntu-latest\n steps:\n - uses: ${CHECKOUT}\n with:\n persist-credentials: false\n - run: test -s AGENTS.md\n - uses: ${ACTION}${releaseSha()} # ${releaseTag()}\n`,
129
+ );
130
+ return { name, workflow: "Standard" };
131
+ }
132
+
133
+ function updateEntry(ecosystem, pattern) {
134
+ return {
135
+ "package-ecosystem": ecosystem,
136
+ directory: "/",
137
+ schedule: { interval: "daily" },
138
+ allow: [{ "dependency-name": pattern }],
139
+ groups: { [GROUP]: { patterns: [pattern] } },
140
+ };
141
+ }
142
+
143
+ function dependabot(root, hasPackage) {
144
+ const path = join(root, ".github", "dependabot.yml");
145
+ const doc = parseDocument(read(path) ?? "version: 2\nupdates: []\n");
146
+ if (doc.errors.length > 0) throw new Error("Fix invalid YAML in dependabot.yml before adopting Standard.");
147
+ const before = doc.toString({ flowCollectionPadding: false });
148
+ const wanted = [["github-actions", "mapringg/standard*"], ...(hasPackage ? [["npm", PACKAGE]] : [])];
149
+ const updates = doc.get("updates", true);
150
+ for (const [ecosystem, pattern] of wanted) {
151
+ const index = (updates?.items ?? []).findIndex((item) => {
152
+ const entry = item.toJSON();
153
+ const directories = entry.directories ?? [entry.directory];
154
+ return entry["package-ecosystem"] === ecosystem && directories.includes("/");
155
+ });
156
+ if (index === -1) {
157
+ doc.addIn(["updates"], doc.createNode(updateEntry(ecosystem, pattern)));
158
+ continue;
159
+ }
160
+ const groups = doc.getIn(["updates", index, "groups"], true);
161
+ if (isMap(groups) && groups.has(GROUP)) continue;
162
+ const rest = isMap(groups) ? groups.items : [];
163
+ const group = doc.createNode({ [GROUP]: { patterns: [pattern] } });
164
+ group.items.push(...rest);
165
+ doc.setIn(["updates", index, "groups"], group);
166
+ }
167
+ const options = { flowCollectionPadding: false };
168
+ if (doc.toString(options) !== before) write(path, doc.toString(options));
169
+ }
170
+
171
+ function automerge(root, workflow) {
172
+ write(
173
+ join(root, AUTOMERGE),
174
+ `name: Standard updates\n\non:\n workflow_run:\n workflows: [${JSON.stringify(workflow)}]\n types: [completed]\n\npermissions:\n contents: write\n pull-requests: write\n\njobs:\n merge:\n if: >-\n github.event.workflow_run.conclusion == 'success' &&\n github.event.workflow_run.event == 'pull_request' &&\n github.event.workflow_run.actor.login == 'dependabot[bot]' &&\n contains(github.event.workflow_run.head_branch, '${GROUP}')\n runs-on: ubuntu-latest\n steps:\n - env:\n GH_TOKEN: \${{ github.token }}\n BRANCH: \${{ github.event.workflow_run.head_branch }}\n SHA: \${{ github.event.workflow_run.head_sha }}\n run: gh pr merge "$BRANCH" --repo "$GITHUB_REPOSITORY" --squash --match-head-commit "$SHA"\n`,
175
+ );
176
+ }
177
+
178
+ function pinBrowser(root) {
179
+ const canonical = join(root, "mise.toml");
180
+ const alternate = join(root, ".mise.toml");
181
+ const path = existsSync(alternate) && !existsSync(canonical) ? alternate : canonical;
182
+ const contents = read(path) ?? "";
183
+ if (contents.includes("agent-browser")) return;
184
+ const tool = '"npm:agent-browser" = "0.43.0"\n';
185
+ const tools = /^\[tools\][ \t]*\n/m;
186
+ write(
187
+ path,
188
+ tools.test(contents)
189
+ ? contents.replace(tools, `$&${tool}`)
190
+ : `${contents ? `${contents.trimEnd()}\n\n` : ""}[tools]\n${tool}`,
191
+ );
192
+ }
193
+
194
+ export function configure(root, name, { kind = "plain", initial = false } = {}) {
195
+ const isNewApp = kind === "app" && initial;
196
+ const path = join(root, "package.json");
197
+ const original = read(path);
198
+ const manifest = original ? JSON.parse(original) : {};
199
+ const current = manifest.devDependencies?.["@mapringg/standard"] ?? manifest.dependencies?.["@mapringg/standard"];
200
+ const installed = typeof current === "string";
201
+ const wanted = releaseTag().slice(1);
202
+ const updateLock = installed && current !== wanted;
203
+ if (updateLock || isNewApp) {
204
+ let next = original ?? "{}\n";
205
+ if (updateLock) next = next.replaceAll(`"${current}"`, `"${wanted}"`);
206
+ if (isNewApp) next = next.replace(/"name":\s*"monorepo"/, `"name": ${JSON.stringify(name.toLowerCase())}`);
207
+ write(path, next);
208
+ }
209
+ if (isNewApp) {
210
+ const deploy = join(root, ".github", "workflows", "deploy-production.yml");
211
+ const contents = read(deploy);
212
+ if (contents) {
213
+ const doc = parseDocument(contents);
214
+ doc.set("on", "workflow_dispatch");
215
+ write(deploy, doc.toString());
216
+ }
217
+ }
218
+ if (kind === "app") pinBrowser(root);
219
+ agents(root, installed);
220
+ const check = configureCheck(root, installed);
221
+ dependabot(root, Boolean(original));
222
+ automerge(root, check.workflow);
223
+ return { check: check.name, updateLock };
224
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.