@mapringg/standard 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.
Files changed (45) hide show
  1. package/.claude/skills/adopt-standard/SKILL.md +196 -0
  2. package/.claude/skills/capture/SKILL.md +27 -0
  3. package/.claude/skills/pr/LICENSE +21 -0
  4. package/.claude/skills/pr/SKILL.md +170 -0
  5. package/.claude/skills/pr/UPSTREAM.md +4 -0
  6. package/.claude/skills/review-standard/SKILL.md +12 -0
  7. package/.claude/skills/test-audit/SKILL.md +25 -0
  8. package/.claude/skills/upgrade-standard/SKILL.md +25 -0
  9. package/LICENSE +21 -0
  10. package/README.md +10 -2
  11. package/bin/check-pr.mjs +11 -0
  12. package/bin/upload-evidence.mjs +120 -0
  13. package/knip.json +25 -0
  14. package/oxfmt.json +8 -0
  15. package/oxlint.json +464 -0
  16. package/package.json +66 -4
  17. package/packages/create-mapringg-repo/LICENSE +21 -0
  18. package/packages/create-mapringg-repo/cli.mjs +324 -0
  19. package/packages/create-mapringg-repo/github.mjs +128 -0
  20. package/packages/create-mapringg-repo/package.json +25 -0
  21. package/packages/create-mapringg-repo/release.mjs +52 -0
  22. package/packages/create-mapringg-repo/setup.mjs +224 -0
  23. package/src/plugin/agent-docs.mjs +240 -0
  24. package/src/plugin/design-system.mjs +75 -0
  25. package/src/plugin/feature-imports.mjs +38 -0
  26. package/src/plugin/hono.mjs +186 -0
  27. package/src/plugin/index.mjs +42 -0
  28. package/src/plugin/markdown-lines.mjs +35 -0
  29. package/src/plugin/next-data.mjs +124 -0
  30. package/src/plugin/next-routes.mjs +63 -0
  31. package/src/plugin/no-chained-assertions.mjs +22 -0
  32. package/src/plugin/no-comments.mjs +23 -0
  33. package/src/plugin/no-return-types.mjs +48 -0
  34. package/src/plugin/no-typeof.mjs +27 -0
  35. package/src/plugin/owners.mjs +428 -0
  36. package/src/plugin/params.mjs +75 -0
  37. package/src/plugin/paths.mjs +192 -0
  38. package/src/plugin/pr-check.mjs +141 -0
  39. package/src/plugin/query-client.mjs +49 -0
  40. package/src/plugin/reducer.mjs +84 -0
  41. package/src/plugin/repo-shape.mjs +351 -0
  42. package/src/plugin/repository-docs.mjs +119 -0
  43. package/src/plugin/server-actions.mjs +60 -0
  44. package/src/plugin/tests.mjs +222 -0
  45. package/tsconfig.json +23 -0
@@ -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
+ }
@@ -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
+ }
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "create-mapringg-repo",
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
+ }
@@ -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
+ }