@seangalie/precast 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/LICENSE +202 -0
  3. package/README.md +274 -2
  4. package/dist/bin.d.ts +2 -0
  5. package/dist/bin.js +3 -0
  6. package/dist/cli.d.ts +7 -0
  7. package/dist/cli.js +251 -0
  8. package/dist/collect.d.ts +17 -0
  9. package/dist/collect.js +143 -0
  10. package/dist/context.d.ts +38 -0
  11. package/dist/context.js +206 -0
  12. package/dist/errors.d.ts +8 -0
  13. package/dist/errors.js +8 -0
  14. package/dist/fnmatch.d.ts +9 -0
  15. package/dist/fnmatch.js +110 -0
  16. package/dist/generate.d.ts +23 -0
  17. package/dist/generate.js +76 -0
  18. package/dist/index.d.ts +7 -0
  19. package/dist/index.js +7 -0
  20. package/dist/output-path.d.ts +30 -0
  21. package/dist/output-path.js +84 -0
  22. package/dist/platforms.d.ts +22 -0
  23. package/dist/platforms.js +81 -0
  24. package/dist/profiles.d.ts +23 -0
  25. package/dist/profiles.js +79 -0
  26. package/dist/prompts.d.ts +30 -0
  27. package/dist/prompts.js +103 -0
  28. package/dist/style.d.ts +14 -0
  29. package/dist/style.js +34 -0
  30. package/dist/tiers.d.ts +23 -0
  31. package/dist/tiers.js +96 -0
  32. package/package.json +44 -4
  33. package/platforms/forgejo/files/.forgejo/CODEOWNERS.tmpl +2 -0
  34. package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/01_bug_report.yml.tmpl +83 -0
  35. package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/02_feature_request.yml.tmpl +57 -0
  36. package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/03_codebase_improvement.yml.tmpl +44 -0
  37. package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/04_support_question.yml.tmpl +47 -0
  38. package/platforms/forgejo/files/.forgejo/ISSUE_TEMPLATE/config.yml.tmpl +13 -0
  39. package/platforms/forgejo/files/.forgejo/PULL_REQUEST_TEMPLATE.md.tmpl +49 -0
  40. package/platforms/forgejo/files/.forgejo/SETUP.md.tmpl +65 -0
  41. package/platforms/forgejo/files/.forgejo/labels.yml.tmpl +99 -0
  42. package/platforms/forgejo/files/.forgejo/scripts/check-labels.sh.tmpl +91 -0
  43. package/platforms/forgejo/files/.forgejo/scripts/sync-labels.sh.tmpl +165 -0
  44. package/platforms/forgejo/files/.forgejo/workflows/labels.yml.tmpl +45 -0
  45. package/platforms/forgejo/files/.forgejo/workflows/lint.yml.tmpl +78 -0
  46. package/platforms/forgejo/files/.forgejo/workflows/pr-labels.yml.tmpl +51 -0
  47. package/platforms/forgejo/files/.forgejo/workflows/pre-commit.yml.tmpl +24 -0
  48. package/platforms/forgejo/files/.forgejo/workflows/release.yml.tmpl +130 -0
  49. package/platforms/forgejo/files/.forgejo/workflows/renovate.yml.tmpl +61 -0
  50. package/platforms/forgejo/files/.forgejo/workflows/stale.yml.tmpl +260 -0
  51. package/platforms/forgejo/files/renovate.json +36 -0
  52. package/platforms/forgejo/platform.json +41 -0
  53. package/platforms/github/files/.github/CODEOWNERS.tmpl +2 -0
  54. package/platforms/github/files/.github/ISSUE_TEMPLATE/01_bug_report.yml.tmpl +83 -0
  55. package/platforms/github/files/.github/ISSUE_TEMPLATE/02_feature_request.yml.tmpl +57 -0
  56. package/platforms/github/files/.github/ISSUE_TEMPLATE/03_codebase_improvement.yml.tmpl +44 -0
  57. package/platforms/github/files/.github/ISSUE_TEMPLATE/04_support_question.yml.tmpl +47 -0
  58. package/platforms/github/files/.github/ISSUE_TEMPLATE/config.yml.tmpl +16 -0
  59. package/platforms/github/files/.github/PULL_REQUEST_TEMPLATE.md.tmpl +49 -0
  60. package/platforms/github/files/.github/SETUP.md.tmpl +46 -0
  61. package/platforms/github/files/.github/dependabot.yml.tmpl +75 -0
  62. package/platforms/github/files/.github/labels.yml.tmpl +103 -0
  63. package/platforms/github/files/.github/release.yml.tmpl +47 -0
  64. package/platforms/github/files/.github/workflows/ci.yml.tmpl +55 -0
  65. package/platforms/github/files/.github/workflows/codeql.yml.tmpl +63 -0
  66. package/platforms/github/files/.github/workflows/labels.yml.tmpl +34 -0
  67. package/platforms/github/files/.github/workflows/lint-workflows.yml.tmpl +75 -0
  68. package/platforms/github/files/.github/workflows/lint.yml.tmpl +69 -0
  69. package/platforms/github/files/.github/workflows/lock.yml.tmpl +46 -0
  70. package/platforms/github/files/.github/workflows/pr-labels.yml.tmpl +26 -0
  71. package/platforms/github/files/.github/workflows/pre-commit.yml.tmpl +25 -0
  72. package/platforms/github/files/.github/workflows/release.yml.tmpl +101 -0
  73. package/platforms/github/files/.github/workflows/stale.yml.tmpl +57 -0
  74. package/platforms/github/platform.json +44 -0
  75. package/platforms/gitlab/files/.gitlab/CODEOWNERS.tmpl +2 -0
  76. package/platforms/gitlab/files/.gitlab/SETUP.md.tmpl +65 -0
  77. package/platforms/gitlab/files/.gitlab/issue_templates/01_bug_report.md +18 -0
  78. package/platforms/gitlab/files/.gitlab/issue_templates/02_feature_request.md +11 -0
  79. package/platforms/gitlab/files/.gitlab/issue_templates/03_codebase_improvement.md +11 -0
  80. package/platforms/gitlab/files/.gitlab/issue_templates/04_support_question.md +12 -0
  81. package/platforms/gitlab/files/.gitlab/labels.json +122 -0
  82. package/platforms/gitlab/files/.gitlab/merge_request_templates/Default.md +14 -0
  83. package/platforms/gitlab/files/.gitlab/scripts/project.py +159 -0
  84. package/platforms/gitlab/files/.gitlab-ci.yml.tmpl +56 -0
  85. package/platforms/gitlab/platform.json +38 -0
  86. package/template/.editorconfig.tmpl +54 -0
  87. package/template/.gitattributes +107 -0
  88. package/template/.gitignore.tmpl +244 -0
  89. package/template/.pre-commit-config.yaml.tmpl +55 -0
  90. package/template/.repo/check-secrets.py +40 -0
  91. package/template/.repo/ci-checks.sh +20 -0
  92. package/template/AGENTS.md.tmpl +78 -0
  93. package/template/CHANGELOG.md.tmpl +24 -0
  94. package/template/CLAUDE.md +1 -0
  95. package/template/LICENSE +202 -0
  96. package/template/README.md.tmpl +101 -0
  97. package/template/SETUP.md.tmpl +56 -0
  98. package/template/docs/CODE_OF_CONDUCT.md +85 -0
  99. package/template/docs/CONTRIBUTING.md.tmpl +59 -0
  100. package/template/docs/SECURITY.md.tmpl +26 -0
  101. package/template/docs/SUPPORT.md.tmpl +19 -0
  102. package/template/docs/logo.svg +84 -0
  103. package/template/docs/screenshot.png +0 -0
  104. package/tiers.json +10 -0
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Shell-style patterns with the semantics of Python's `fnmatch.fnmatchcase`,
3
+ * which the tier lists were written against: the pattern matches the whole
4
+ * path, `*` matches any characters including `/`, `?` matches one character,
5
+ * and `[...]` is a character class with `!` for negation.
6
+ */
7
+ /** Translate a pattern to a regular expression; throws a `SyntaxError` if JavaScript rejects it. */
8
+ export declare function compilePattern(pattern: string): RegExp;
9
+ export declare function fnmatch(name: string, pattern: string): boolean;
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Shell-style patterns with the semantics of Python's `fnmatch.fnmatchcase`,
3
+ * which the tier lists were written against: the pattern matches the whole
4
+ * path, `*` matches any characters including `/`, `?` matches one character,
5
+ * and `[...]` is a character class with `!` for negation.
6
+ */
7
+ const SYNTAX = new Set("^$\\.*+?()[]{}|/");
8
+ /** Translate a pattern to a regular expression; throws a `SyntaxError` if JavaScript rejects it. */
9
+ export function compilePattern(pattern) {
10
+ // Work in code points so `?` and ranges treat astral characters as one character.
11
+ const chars = [...pattern];
12
+ const length = chars.length;
13
+ let source = "";
14
+ let lastWasStar = false;
15
+ let index = 0;
16
+ while (index < length) {
17
+ const char = chars[index++];
18
+ if (char === "*") {
19
+ if (!lastWasStar)
20
+ source += ".*";
21
+ lastWasStar = true;
22
+ continue;
23
+ }
24
+ lastWasStar = false;
25
+ if (char === "?") {
26
+ source += ".";
27
+ }
28
+ else if (char === "[") {
29
+ let end = index;
30
+ if (end < length && chars[end] === "!")
31
+ end++;
32
+ if (end < length && chars[end] === "]")
33
+ end++;
34
+ while (end < length && chars[end] !== "]")
35
+ end++;
36
+ if (end >= length) {
37
+ source += "\\[";
38
+ }
39
+ else {
40
+ source += characterClass(chars.slice(index, end));
41
+ index = end + 1;
42
+ }
43
+ }
44
+ else {
45
+ source += SYNTAX.has(char) ? `\\${char}` : char;
46
+ }
47
+ }
48
+ return new RegExp(`^(?:${source})$`, "su");
49
+ }
50
+ /** Translate the contents of `[...]`, following Python's handling of ranges. */
51
+ function characterClass(stuff) {
52
+ let body;
53
+ if (!stuff.includes("-")) {
54
+ body = stuff.map(escapeInClass).join("");
55
+ }
56
+ else {
57
+ // Split at range hyphens. A leading `!` or the first character can never
58
+ // start a range, so the search for hyphens starts after them.
59
+ const chunks = [];
60
+ let start = 0;
61
+ let search = stuff[0] === "!" ? 2 : 1;
62
+ for (;;) {
63
+ const hyphen = stuff.indexOf("-", search);
64
+ if (hyphen < 0)
65
+ break;
66
+ chunks.push(stuff.slice(start, hyphen));
67
+ start = hyphen + 1;
68
+ search = hyphen + 3;
69
+ }
70
+ const rest = stuff.slice(start);
71
+ if (rest.length > 0) {
72
+ chunks.push(rest);
73
+ }
74
+ else {
75
+ chunks.at(-1)?.push("-");
76
+ }
77
+ // Drop empty ranges such as `z-a`, which are invalid in a regular expression.
78
+ for (let k = chunks.length - 1; k > 0; k--) {
79
+ const before = chunks[k - 1];
80
+ const after = chunks[k];
81
+ const last = before.at(-1);
82
+ const first = after[0];
83
+ if (last !== undefined && first !== undefined && codePoint(last) > codePoint(first)) {
84
+ chunks[k - 1] = [...before.slice(0, -1), ...after.slice(1)];
85
+ chunks.splice(k, 1);
86
+ }
87
+ }
88
+ body = chunks.map((chunk) => chunk.map(escapeInClass).join("")).join("-");
89
+ }
90
+ if (body === "") {
91
+ return "(?!)";
92
+ }
93
+ if (body === "!") {
94
+ return ".";
95
+ }
96
+ if (body.startsWith("!")) {
97
+ return `[^${body.slice(1)}]`;
98
+ }
99
+ return `[${body}]`;
100
+ }
101
+ function escapeInClass(char) {
102
+ // `^` only needs escaping first, but escaping it anywhere is harmless.
103
+ return "\\]^-[".includes(char) ? `\\${char}` : char;
104
+ }
105
+ function codePoint(char) {
106
+ return char.codePointAt(0) ?? 0;
107
+ }
108
+ export function fnmatch(name, pattern) {
109
+ return compilePattern(pattern).test(name);
110
+ }
@@ -0,0 +1,23 @@
1
+ import { type ContextOptions } from "./context.ts";
2
+ import { type Tier } from "./tiers.ts";
3
+ /** The package root, which holds `template/`, `platforms/`, and `tiers.json`. */
4
+ export declare const ROOT: string;
5
+ export interface GenerateOptions extends ContextOptions {
6
+ /** A new directory outside the source root. */
7
+ output: string;
8
+ tier?: Tier | undefined;
9
+ /** Validate and list the files without writing anything. */
10
+ dryRun?: boolean | undefined;
11
+ }
12
+ export interface GenerateResult {
13
+ destination: string;
14
+ /** POSIX relative paths, sorted. */
15
+ files: string[];
16
+ }
17
+ export declare function generate(options: GenerateOptions, root?: string): GenerateResult;
18
+ /**
19
+ * Resolve the output to the canonical path that will be written and check it:
20
+ * it must not exist yet and must be outside the source directory. Prompts use
21
+ * the same check so an answer is refused before any generation starts.
22
+ */
23
+ export declare function checkOutput(output: string, root?: string): string;
@@ -0,0 +1,76 @@
1
+ import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync, } from "node:fs";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { collectFiles, comparePaths } from "./collect.js";
5
+ import { makeContext } from "./context.js";
6
+ import { PrecastError } from "./errors.js";
7
+ import { canonicalPath } from "./output-path.js";
8
+ import { readPlatform } from "./platforms.js";
9
+ import { DEFAULT_TIER } from "./tiers.js";
10
+ /** The package root, which holds `template/`, `platforms/`, and `tiers.json`. */
11
+ export const ROOT = resolve(fileURLToPath(new URL("..", import.meta.url)));
12
+ export function generate(options, root = ROOT) {
13
+ const platform = readPlatform(root, options.platform);
14
+ const context = makeContext(options, platform);
15
+ const files = collectFiles(root, options.platform, context, options.tier ?? DEFAULT_TIER);
16
+ const destination = checkOutput(options.output, root);
17
+ const listing = [...files.keys()].sort(comparePaths);
18
+ if (options.dryRun) {
19
+ return { destination, files: listing };
20
+ }
21
+ const parent = dirname(destination);
22
+ mkdirSync(parent, { recursive: true });
23
+ // Stage every file before reserving the output directory. mkdir is exclusive,
24
+ // so a competing process cannot cause an existing repository to be replaced.
25
+ const staging = mkdtempSync(join(parent, ".precast-"));
26
+ try {
27
+ for (const [path, { data, mode }] of files) {
28
+ const target = join(staging, ...path.split("/"));
29
+ mkdirSync(dirname(target), { recursive: true });
30
+ writeFileSync(target, data);
31
+ chmodSync(target, mode);
32
+ }
33
+ mkdirSync(destination);
34
+ for (const entry of readdirSync(staging)) {
35
+ renameSync(join(staging, entry), join(destination, entry));
36
+ }
37
+ }
38
+ finally {
39
+ rmSync(staging, { recursive: true, force: true });
40
+ }
41
+ return { destination, files: listing };
42
+ }
43
+ /**
44
+ * Resolve the output to the canonical path that will be written and check it:
45
+ * it must not exist yet and must be outside the source directory. Prompts use
46
+ * the same check so an answer is refused before any generation starts.
47
+ */
48
+ export function checkOutput(output, root = ROOT) {
49
+ // The same canonical path is checked and written, so `..` after a symlink or a
50
+ // case-only alias of the source directory cannot slip past the checks.
51
+ const destination = canonicalPath(output);
52
+ if (exists(destination)) {
53
+ throw new PrecastError(`Output already exists; choose a new directory: ${destination}`);
54
+ }
55
+ if (isInside(destination, realpathSync.native(root))) {
56
+ throw new PrecastError("Output must be outside the Precast source directory");
57
+ }
58
+ return destination;
59
+ }
60
+ /** True for anything at the path, including a dangling symlink. */
61
+ function exists(path) {
62
+ try {
63
+ lstatSync(path);
64
+ return true;
65
+ }
66
+ catch (error) {
67
+ if (error.code === "ENOENT") {
68
+ return false;
69
+ }
70
+ throw error;
71
+ }
72
+ }
73
+ function isInside(path, directory) {
74
+ const offset = relative(directory, path);
75
+ return offset === "" || !(offset === ".." || offset.startsWith(`..${sep}`) || isAbsolute(offset));
76
+ }
@@ -0,0 +1,7 @@
1
+ export { collectFiles, type OutputFile, type OutputFiles } from "./collect.ts";
2
+ export { type Context, type ContextOptions, makeContext } from "./context.ts";
3
+ export { PrecastError } from "./errors.ts";
4
+ export { type GenerateOptions, type GenerateResult, generate, ROOT } from "./generate.ts";
5
+ export { type PlatformDescriptor, platformNames, readPlatform } from "./platforms.ts";
6
+ export { defaultConfigPath, type Profile, readProfile } from "./profiles.ts";
7
+ export { DEFAULT_TIER, TIERS, type Tier } from "./tiers.ts";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { collectFiles } from "./collect.js";
2
+ export { makeContext } from "./context.js";
3
+ export { PrecastError } from "./errors.js";
4
+ export { generate, ROOT } from "./generate.js";
5
+ export { platformNames, readPlatform } from "./platforms.js";
6
+ export { defaultConfigPath, readProfile } from "./profiles.js";
7
+ export { DEFAULT_TIER, TIERS } from "./tiers.js";
@@ -0,0 +1,30 @@
1
+ import { type PlatformPath } from "node:path";
2
+ /** The path rules and file-system lookups `canonicalPath` depends on. */
3
+ export interface PathHost {
4
+ path: PlatformPath;
5
+ cwd(): string;
6
+ /** The working directory for a Windows drive such as `D:`; unused elsewhere. */
7
+ driveCwd(drive: string): string;
8
+ /**
9
+ * The real path of an existing entry, or undefined when nothing is there.
10
+ * Throws `PrecastError` for an entry that exists but cannot be followed,
11
+ * such as a dangling or looping symlink.
12
+ */
13
+ realpath(entry: string): string | undefined;
14
+ /** Whether an existing entry is a directory, following symlinks. */
15
+ isDirectory(entry: string): boolean;
16
+ }
17
+ export declare const nodeHost: PathHost;
18
+ /**
19
+ * Resolve `output` the way the operating system would: each existing directory
20
+ * becomes its real path, with symlinks followed and letter case corrected,
21
+ * before the next `..` applies. Path normalization alone would apply `..` to
22
+ * a link's name instead. The final component stays as written, so a symlink
23
+ * there still counts as an existing output.
24
+ *
25
+ * Only the host's separators split the path, so a backslash is part of a name
26
+ * outside Windows, and the root (`/`, `C:\`, or `\\server\share\`) is never
27
+ * split. An existing file cannot be followed by more components, as the
28
+ * operating system would refuse it with ENOTDIR.
29
+ */
30
+ export declare function canonicalPath(output: string, host?: PathHost): string;
@@ -0,0 +1,84 @@
1
+ import { lstatSync, realpathSync, statSync } from "node:fs";
2
+ import path, {} from "node:path";
3
+ import { PrecastError } from "./errors.js";
4
+ export const nodeHost = {
5
+ path,
6
+ cwd: () => process.cwd(),
7
+ // On Windows, resolve uses the drive's own working directory when it has one.
8
+ driveCwd: (drive) => path.resolve(drive),
9
+ realpath(entry) {
10
+ try {
11
+ return realpathSync.native(entry);
12
+ }
13
+ catch (error) {
14
+ const code = error.code;
15
+ // Only a missing entry is treated as a directory still to be created.
16
+ // A dangling symlink is also ENOENT, so check for the entry itself.
17
+ if (code === "ENOENT" && !lstatSync(entry, { throwIfNoEntry: false })) {
18
+ return undefined;
19
+ }
20
+ throw new PrecastError(`Output path cannot be followed at ${entry}: ${code ?? error}`);
21
+ }
22
+ },
23
+ isDirectory: (entry) => statSync(entry).isDirectory(),
24
+ };
25
+ /**
26
+ * Resolve `output` the way the operating system would: each existing directory
27
+ * becomes its real path, with symlinks followed and letter case corrected,
28
+ * before the next `..` applies. Path normalization alone would apply `..` to
29
+ * a link's name instead. The final component stays as written, so a symlink
30
+ * there still counts as an existing output.
31
+ *
32
+ * Only the host's separators split the path, so a backslash is part of a name
33
+ * outside Windows, and the root (`/`, `C:\`, or `\\server\share\`) is never
34
+ * split. An existing file cannot be followed by more components, as the
35
+ * operating system would refuse it with ENOTDIR.
36
+ */
37
+ export function canonicalPath(output, host = nodeHost) {
38
+ const { path: paths } = host;
39
+ const absolute = absolutePath(output, host);
40
+ const root = paths.parse(absolute).root;
41
+ const separators = paths.sep === "\\" ? /[\\/]/ : /\//;
42
+ const parts = absolute
43
+ .slice(root.length)
44
+ .split(separators)
45
+ .filter((part) => part !== "" && part !== ".");
46
+ let current = paths.normalize(root);
47
+ parts.forEach((part, index) => {
48
+ if (part === "..") {
49
+ current = paths.dirname(current);
50
+ return;
51
+ }
52
+ const next = paths.join(current, part);
53
+ if (index === parts.length - 1) {
54
+ current = next;
55
+ return;
56
+ }
57
+ const real = host.realpath(next);
58
+ if (real !== undefined && !host.isDirectory(real)) {
59
+ throw new PrecastError(`Output path continues past a file: ${next}`);
60
+ }
61
+ current = real ?? next;
62
+ });
63
+ return current;
64
+ }
65
+ /**
66
+ * Make `output` absolute without collapsing `..`, which join and resolve would
67
+ * do lexically. On Windows, `C:demo` is relative to drive C's working
68
+ * directory and `\demo` to the root of the working directory's drive or share.
69
+ */
70
+ function absolutePath(output, host) {
71
+ const { path: paths } = host;
72
+ const cwd = host.cwd();
73
+ if (paths.sep === "\\") {
74
+ const root = paths.parse(output).root;
75
+ const cwdRoot = paths.parse(cwd).root;
76
+ if (/^[A-Za-z]:$/.test(root)) {
77
+ return `${host.driveCwd(root)}${paths.sep}${output.slice(root.length)}`;
78
+ }
79
+ if (root === "\\" || root === "/") {
80
+ return `${cwdRoot.replace(/[\\/]$/, "")}${output}`;
81
+ }
82
+ }
83
+ return paths.isAbsolute(output) ? output : `${cwd}${paths.sep}${output}`;
84
+ }
@@ -0,0 +1,22 @@
1
+ /** The contents of `platforms/<id>/platform.json`; see docs/ARCHITECTURE.md. */
2
+ export interface PlatformDescriptor {
3
+ server_url: string;
4
+ nested_namespaces: boolean;
5
+ runner: string;
6
+ codeowners_pattern: string;
7
+ tiers?: Record<string, string[]>;
8
+ /** Ordered values; later entries may refer to earlier ones with `{KEY}`. */
9
+ context: Record<string, string>;
10
+ /**
11
+ * Replacements for `context` entries that apply only when generating for
12
+ * `server_url` itself, such as a hosted instance's default CI image.
13
+ */
14
+ default_server_context?: Record<string, string>;
15
+ }
16
+ /** Platform IDs are the names of directories that contain a descriptor. */
17
+ export declare function platformNames(root: string): string[];
18
+ /** Read a descriptor's JSON without checking its shape; tier lists are validated separately. */
19
+ export declare function readRawPlatform(root: string, name: string): Record<string, unknown>;
20
+ export declare function readPlatform(root: string, name: string): PlatformDescriptor;
21
+ export declare function parseDescriptor(value: Record<string, unknown>, name: string): PlatformDescriptor;
22
+ export declare function readJson(path: string): unknown;
@@ -0,0 +1,81 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { PrecastError } from "./errors.js";
4
+ import { isPlainObject } from "./tiers.js";
5
+ const STRING_FIELDS = ["server_url", "runner", "codeowners_pattern"];
6
+ const KNOWN_FIELDS = new Set([
7
+ ...STRING_FIELDS,
8
+ "nested_namespaces",
9
+ "tiers",
10
+ "context",
11
+ "default_server_context",
12
+ ]);
13
+ /** Platform IDs are the names of directories that contain a descriptor. */
14
+ export function platformNames(root) {
15
+ const directory = join(root, "platforms");
16
+ if (!existsSync(directory)) {
17
+ return [];
18
+ }
19
+ return readdirSync(directory, { withFileTypes: true })
20
+ .filter((entry) => entry.isDirectory() && existsSync(join(directory, entry.name, "platform.json")))
21
+ .map((entry) => entry.name)
22
+ .sort();
23
+ }
24
+ /** Read a descriptor's JSON without checking its shape; tier lists are validated separately. */
25
+ export function readRawPlatform(root, name) {
26
+ if (!platformNames(root).includes(name)) {
27
+ throw new PrecastError(`Unknown platform: ${name}`);
28
+ }
29
+ const value = readJson(join(root, "platforms", name, "platform.json"));
30
+ if (!isPlainObject(value)) {
31
+ throw new PrecastError(`Platform descriptor ${name} must be a JSON object`);
32
+ }
33
+ return value;
34
+ }
35
+ export function readPlatform(root, name) {
36
+ return parseDescriptor(readRawPlatform(root, name), name);
37
+ }
38
+ export function parseDescriptor(value, name) {
39
+ const label = `Platform descriptor ${name}`;
40
+ for (const field of Object.keys(value)) {
41
+ if (!KNOWN_FIELDS.has(field)) {
42
+ throw new PrecastError(`${label} has an unknown field: ${field}`);
43
+ }
44
+ }
45
+ for (const field of STRING_FIELDS) {
46
+ if (typeof value[field] !== "string") {
47
+ throw new PrecastError(`${label} needs a string ${field}`);
48
+ }
49
+ }
50
+ if (typeof value.nested_namespaces !== "boolean") {
51
+ throw new PrecastError(`${label} needs a boolean nested_namespaces`);
52
+ }
53
+ const context = value.context;
54
+ if (!isPlainObject(context) ||
55
+ !Object.values(context).every((entry) => typeof entry === "string")) {
56
+ throw new PrecastError(`${label} needs a context object of strings`);
57
+ }
58
+ const hosted = value.default_server_context;
59
+ if (hosted !== undefined) {
60
+ if (!isPlainObject(hosted) ||
61
+ !Object.values(hosted).every((entry) => typeof entry === "string")) {
62
+ throw new PrecastError(`${label} needs a default_server_context object of strings`);
63
+ }
64
+ // Only replacements are allowed, so every server renders the same tokens.
65
+ for (const key of Object.keys(hosted)) {
66
+ if (!Object.hasOwn(context, key)) {
67
+ throw new PrecastError(`${label} default_server_context replaces no context key: ${key}`);
68
+ }
69
+ }
70
+ }
71
+ return value;
72
+ }
73
+ export function readJson(path) {
74
+ const text = readFileSync(path, "utf8");
75
+ try {
76
+ return JSON.parse(text);
77
+ }
78
+ catch (error) {
79
+ throw new PrecastError(`Invalid JSON in ${path}: ${error.message}`);
80
+ }
81
+ }
@@ -0,0 +1,23 @@
1
+ import { type Tier } from "./tiers.ts";
2
+ /**
3
+ * Saved defaults for one server, such as a self-hosted Forgejo or an internal
4
+ * GitLab. Values a command line gives explicitly win over the profile's.
5
+ */
6
+ export interface Profile {
7
+ platform: string;
8
+ serverUrl?: string;
9
+ namespace?: string;
10
+ author?: string;
11
+ description?: string;
12
+ defaultBranch?: string;
13
+ codeowner?: string;
14
+ runner?: string;
15
+ tier?: Tier;
16
+ }
17
+ /**
18
+ * Where profiles live unless `--config` names another file: the XDG config
19
+ * directory on macOS and Linux, and the roaming application data folder on Windows.
20
+ */
21
+ export declare function defaultConfigPath(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, home?: string): string;
22
+ /** Read one named profile from a settings file shaped as `{"profiles": {...}}`. */
23
+ export declare function readProfile(file: string, name: string): Profile;
@@ -0,0 +1,79 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import { PrecastError } from "./errors.js";
5
+ import { readJson } from "./platforms.js";
6
+ import { isPlainObject, isTier } from "./tiers.js";
7
+ const STRING_FIELDS = [
8
+ "platform",
9
+ "serverUrl",
10
+ "namespace",
11
+ "author",
12
+ "description",
13
+ "defaultBranch",
14
+ "codeowner",
15
+ "runner",
16
+ ];
17
+ const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
18
+ /**
19
+ * Where profiles live unless `--config` names another file: the XDG config
20
+ * directory on macOS and Linux, and the roaming application data folder on Windows.
21
+ */
22
+ export function defaultConfigPath(env = process.env, platform = process.platform, home = homedir()) {
23
+ // Relative values are ignored, as the XDG base directory specification
24
+ // requires, so a settings file is never read from the working directory.
25
+ if (platform === "win32") {
26
+ const appData = env.APPDATA && path.win32.isAbsolute(env.APPDATA) ? env.APPDATA : undefined;
27
+ return path.win32.join(appData ?? path.win32.join(home, "AppData", "Roaming"), "precast", "config.json");
28
+ }
29
+ const xdg = env.XDG_CONFIG_HOME && path.posix.isAbsolute(env.XDG_CONFIG_HOME)
30
+ ? env.XDG_CONFIG_HOME
31
+ : undefined;
32
+ return path.posix.join(xdg ?? path.posix.join(home, ".config"), "precast", "config.json");
33
+ }
34
+ /** Read one named profile from a settings file shaped as `{"profiles": {...}}`. */
35
+ export function readProfile(file, name) {
36
+ if (!PROFILE_NAME.test(name)) {
37
+ throw new PrecastError(`Invalid profile name: '${name}'`);
38
+ }
39
+ if (!existsSync(file)) {
40
+ throw new PrecastError(`No settings file at ${file}; create it to use --profile`);
41
+ }
42
+ const settings = readJson(file);
43
+ if (!isPlainObject(settings) || !isPlainObject(settings.profiles)) {
44
+ throw new PrecastError(`${file} must be a JSON object with a "profiles" object`);
45
+ }
46
+ for (const key of Object.keys(settings)) {
47
+ if (key !== "profiles") {
48
+ throw new PrecastError(`${file} has an unknown field: ${key}`);
49
+ }
50
+ }
51
+ const profiles = settings.profiles;
52
+ if (!Object.hasOwn(profiles, name)) {
53
+ const known = Object.keys(profiles).sort();
54
+ throw new PrecastError(`No profile '${name}' in ${file}${known.length > 0 ? `; it has: ${known.join(", ")}` : ""}`);
55
+ }
56
+ return parseProfile(profiles[name], `Profile '${name}' in ${file}`);
57
+ }
58
+ function parseProfile(value, label) {
59
+ if (!isPlainObject(value)) {
60
+ throw new PrecastError(`${label} must be an object`);
61
+ }
62
+ for (const [key, field] of Object.entries(value)) {
63
+ if (key === "tier") {
64
+ if (typeof field !== "string" || !isTier(field)) {
65
+ throw new PrecastError(`${label} has an unknown tier: ${JSON.stringify(field)}`);
66
+ }
67
+ }
68
+ else if (!STRING_FIELDS.includes(key)) {
69
+ throw new PrecastError(`${label} has an unknown field: ${key}`);
70
+ }
71
+ else if (typeof field !== "string") {
72
+ throw new PrecastError(`${label} needs a string ${key}`);
73
+ }
74
+ }
75
+ if (typeof value.platform !== "string") {
76
+ throw new PrecastError(`${label} needs a platform`);
77
+ }
78
+ return value;
79
+ }
@@ -0,0 +1,30 @@
1
+ import { type Tier } from "./tiers.ts";
2
+ /** The values every generation needs; any of them may still be missing. */
3
+ export interface RequiredValues {
4
+ platform?: string | undefined;
5
+ namespace?: string | undefined;
6
+ repo?: string | undefined;
7
+ output?: string | undefined;
8
+ }
9
+ /** The answers a prompted session collects; `tier` only when it was asked. */
10
+ export type Answers = Record<keyof RequiredValues, string> & {
11
+ tier?: Tier;
12
+ };
13
+ /** Ask one question; resolves undefined when the person cancels or input ends. */
14
+ export type Ask = (question: string) => Promise<string | undefined>;
15
+ /** Thrown when the person cancels a prompt, so nothing is generated. */
16
+ export declare class Cancelled extends Error {
17
+ constructor();
18
+ }
19
+ /**
20
+ * Ask for each missing required value in turn. Answers go through the same
21
+ * checks as command-line options, and an invalid answer is asked again.
22
+ */
23
+ export declare function promptForMissing(values: RequiredValues, ask: Ask, write: (text: string) => void, root: string, { stream, askTier }?: {
24
+ stream?: NodeJS.WritableStream;
25
+ askTier?: boolean;
26
+ }): Promise<Answers>;
27
+ /** Ask questions on the terminal, treating Ctrl+C and Ctrl+D as cancelling. */
28
+ export declare function withTerminal<T>(input: NodeJS.ReadableStream, output: NodeJS.WritableStream, use: (ask: Ask) => Promise<T>): Promise<T>;
29
+ /** Quote an argument for a POSIX shell only when it needs it. */
30
+ export declare function shellQuote(value: string): string;