@alxwlw/stack 1.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/canon/catalogs.json +50 -0
  3. package/canon/files/dependabot.template.yml +10 -0
  4. package/canon/files/dependency-cruiser.base.cjs +179 -0
  5. package/canon/files/editorconfig +13 -0
  6. package/canon/files/gitleaks-canon.toml +75 -0
  7. package/canon/files/gitleaks-local.template.toml +12 -0
  8. package/canon/files/knip.base.json +7 -0
  9. package/canon/files/markdownlint-cli2.jsonc +123 -0
  10. package/canon/files/markdownlintignore.template +4 -0
  11. package/canon/files/moon-tasks/bun-test.yml +17 -0
  12. package/canon/files/moon-tasks/oxfmt.yml +14 -0
  13. package/canon/files/moon-tasks/oxlint.yml +34 -0
  14. package/canon/files/moon-tasks/stack.yml +15 -0
  15. package/canon/files/moon-tasks/typescript.yml +32 -0
  16. package/canon/files/oxfmtrc.jsonc +23 -0
  17. package/canon/files/oxlintrc.template.json +6 -0
  18. package/canon/files/prettierignore.template +1 -0
  19. package/canon/files/proto-plugins/actionlint.toml +27 -0
  20. package/canon/files/proto-plugins/gitleaks.toml +27 -0
  21. package/canon/files/proto-plugins/shellcheck.toml +23 -0
  22. package/canon/files/prototools +18 -0
  23. package/canon/files/tsconfig.options.template.json +5 -0
  24. package/canon/files/workflow-stack-check-infra.yml +10 -0
  25. package/canon/files/workflow-stack-check.yml +8 -0
  26. package/canon/files/workflow-stack-sync.yml +16 -0
  27. package/canon/files/yamllint +66 -0
  28. package/canon/files/yamllint-canon-ignores +14 -0
  29. package/canon/files/yamllint-local-ignores.template +5 -0
  30. package/canon/manifest.json +158 -0
  31. package/package.json +27 -0
  32. package/schema.json +48 -0
  33. package/src/catalogs.ts +101 -0
  34. package/src/check.ts +27 -0
  35. package/src/cli.ts +75 -0
  36. package/src/config.ts +70 -0
  37. package/src/deps.ts +134 -0
  38. package/src/files.ts +75 -0
  39. package/src/findings.ts +19 -0
  40. package/src/init.ts +29 -0
  41. package/src/manifest.ts +33 -0
package/src/config.ts ADDED
@@ -0,0 +1,70 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ import { parse as parseJsonc, type ParseError } from 'jsonc-parser';
5
+
6
+ export const STACK_CONFIG_FILE = '.stack.jsonc';
7
+ export const PROFILES = ['node', 'contracts', 'infra'] as const;
8
+ export type Profile = (typeof PROFILES)[number];
9
+
10
+ export interface Exception {
11
+ file?: string;
12
+ catalog?: string;
13
+ name?: string;
14
+ reason: string;
15
+ }
16
+
17
+ export interface StackConfig {
18
+ profile: Profile;
19
+ with: string[];
20
+ exceptions: Exception[];
21
+ }
22
+
23
+ export class StackConfigError extends Error {}
24
+
25
+ export function readStackConfig(repoRoot: string): StackConfig {
26
+ const path = join(repoRoot, STACK_CONFIG_FILE);
27
+ if (!existsSync(path)) {
28
+ throw new StackConfigError(
29
+ `${STACK_CONFIG_FILE} not found. Create it: stack init --profile <profile>`,
30
+ );
31
+ }
32
+ const errors: ParseError[] = [];
33
+ const raw = parseJsonc(readFileSync(path, 'utf8'), errors, { allowTrailingComma: true }) as
34
+ | Partial<StackConfig>
35
+ | undefined;
36
+ if (errors.length || raw == null || typeof raw !== 'object') {
37
+ throw new StackConfigError(`${STACK_CONFIG_FILE}: does not parse as JSONC`);
38
+ }
39
+ const profile = raw.profile;
40
+ if (!PROFILES.includes(profile as Profile)) {
41
+ throw new StackConfigError(
42
+ `${STACK_CONFIG_FILE}: profile="${String(profile)}", expected one of: ${PROFILES.join(', ')}`,
43
+ );
44
+ }
45
+ const groups = raw.with ?? [];
46
+ if (!Array.isArray(groups) || groups.some((g) => typeof g !== 'string')) {
47
+ throw new StackConfigError(`${STACK_CONFIG_FILE}: "with" must be an array of strings`);
48
+ }
49
+ const exceptions = raw.exceptions ?? [];
50
+ if (!Array.isArray(exceptions))
51
+ throw new StackConfigError(`${STACK_CONFIG_FILE}: "exceptions" must be an array`);
52
+ const present = (v: unknown): boolean => v !== undefined;
53
+ const nonEmpty = (v: unknown): boolean => typeof v === 'string' && v !== '';
54
+ // exceptions пришёл из JSON и типизирован через "as" — реальный элемент массива может быть
55
+ // null/undefined, даже когда тип обещает Exception; проверяем честно, не полагаясь на "as".
56
+ for (const e of exceptions as (Exception | null | undefined)[]) {
57
+ if (e == null || !e.reason)
58
+ throw new StackConfigError(
59
+ `${STACK_CONFIG_FILE}: exception is missing "reason": ${JSON.stringify(e)}`,
60
+ );
61
+ const isFileOnly = nonEmpty(e.file) && !present(e.catalog) && !present(e.name);
62
+ const isEntryOnly = nonEmpty(e.catalog) && nonEmpty(e.name) && !present(e.file);
63
+ if (!isFileOnly && !isEntryOnly) {
64
+ throw new StackConfigError(
65
+ `${STACK_CONFIG_FILE}: an exception must address either "file" or a "catalog"+"name" pair: ${JSON.stringify(e)}`,
66
+ );
67
+ }
68
+ }
69
+ return { profile: profile as Profile, with: groups, exceptions };
70
+ }
package/src/deps.ts ADDED
@@ -0,0 +1,134 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ import { Glob } from 'bun';
5
+ import { parse as parseYaml } from 'yaml';
6
+
7
+ import { catalogsFor } from './catalogs.ts';
8
+ import type { StackConfig } from './config.ts';
9
+ import type { Finding } from './findings.ts';
10
+ import { canonDir, filesFor } from './manifest.ts';
11
+
12
+ const SKIP = /node_modules|\.worktrees|\.moon\/cache|(^|\/)(dist|build)\//;
13
+
14
+ export function canonNodePin(cfg: StackConfig, dir: string = canonDir()): string {
15
+ const entry = filesFor(cfg, dir).find((f) => f.dest === '.prototools');
16
+ if (!entry) throw new Error('canon manifest has no .prototools entry for profile ' + cfg.profile);
17
+ const pin = /^node\s*=\s*"([^"]+)"/m.exec(readFileSync(join(dir, entry.src), 'utf8'));
18
+ if (!pin?.[1]) throw new Error('canon .prototools has no node pin');
19
+ return pin[1];
20
+ }
21
+
22
+ export function checkInlineVersions(
23
+ repoRoot: string,
24
+ cfg: StackConfig,
25
+ dir: string = canonDir(),
26
+ ): Finding[] {
27
+ if (!existsSync(join(repoRoot, 'pnpm-workspace.yaml'))) return [];
28
+ const canonNames = new Set(Object.values(catalogsFor(cfg, dir)).flatMap((e) => Object.keys(e)));
29
+ const findings: Finding[] = [];
30
+ for (const file of new Glob('**/package.json').scanSync({ cwd: repoRoot })) {
31
+ if (SKIP.test(file)) continue;
32
+ let pkg: Record<string, unknown>;
33
+ try {
34
+ pkg = JSON.parse(readFileSync(join(repoRoot, file), 'utf8')) as Record<string, unknown>;
35
+ } catch (err) {
36
+ findings.push({
37
+ code: 'unreadable-file',
38
+ target: file,
39
+ message: `${file} does not parse: ${err instanceof Error ? err.message : String(err)}`,
40
+ });
41
+ continue;
42
+ }
43
+ for (const section of ['dependencies', 'devDependencies'] as const) {
44
+ for (const [name, spec] of Object.entries((pkg[section] ?? {}) as Record<string, string>)) {
45
+ if (!canonNames.has(name) || spec.startsWith('catalog:') || spec.startsWith('workspace:')) {
46
+ continue;
47
+ }
48
+ const exception = cfg.exceptions.find((e) => e.name === name);
49
+ findings.push({
50
+ code: 'inline-version',
51
+ target: `${file}:${name}`,
52
+ message: `${name} is declared as "${spec}" instead of catalog:`,
53
+ ...(exception ? { suppressedBy: exception } : {}),
54
+ });
55
+ }
56
+ }
57
+ }
58
+ return findings;
59
+ }
60
+
61
+ export function checkEnginesNode(
62
+ repoRoot: string,
63
+ cfg: StackConfig,
64
+ dir: string = canonDir(),
65
+ ): Finding[] {
66
+ const path = join(repoRoot, 'package.json');
67
+ if (!existsSync(path)) return [];
68
+ let pkg: { engines?: { node?: string } };
69
+ try {
70
+ pkg = JSON.parse(readFileSync(path, 'utf8')) as { engines?: { node?: string } };
71
+ } catch (err) {
72
+ return [
73
+ {
74
+ code: 'unreadable-file',
75
+ target: 'package.json',
76
+ message: `package.json does not parse: ${err instanceof Error ? err.message : String(err)}`,
77
+ },
78
+ ];
79
+ }
80
+ const range = pkg.engines?.node;
81
+ if (!range) return [];
82
+ const pin = canonNodePin(cfg, dir);
83
+ if (Bun.semver.satisfies(pin, range)) return [];
84
+ return [
85
+ {
86
+ code: 'engines-node',
87
+ target: 'package.json:engines.node',
88
+ message: `"${range}" doesn't cover the canon pin ${pin} — proto will rewrite .prototools from engines`,
89
+ },
90
+ ];
91
+ }
92
+
93
+ // Формы дальше — только то, что нужно прочитать; настоящий dependabot.yml несёт больше полей.
94
+ interface DependabotYaml {
95
+ updates?: unknown;
96
+ }
97
+
98
+ function ignoresAlxwlw(doc: unknown): boolean {
99
+ const updates = (doc as DependabotYaml | null)?.updates;
100
+ if (!Array.isArray(updates)) return false;
101
+ return updates.some((u) => {
102
+ const ignore = (u as { ignore?: unknown } | null)?.ignore;
103
+ return (
104
+ Array.isArray(ignore) &&
105
+ ignore.some(
106
+ (i) => (i as { 'dependency-name'?: unknown } | null)?.['dependency-name'] === '@alxwlw/*',
107
+ )
108
+ );
109
+ });
110
+ }
111
+
112
+ export function checkDependabotIgnore(repoRoot: string, _cfg: StackConfig): Finding[] {
113
+ if (!existsSync(join(repoRoot, 'pnpm-workspace.yaml'))) return [];
114
+ const path = join(repoRoot, '.github/dependabot.yml');
115
+ if (!existsSync(path)) return [];
116
+ const finding: Finding = {
117
+ code: 'dependabot-ignore',
118
+ target: '.github/dependabot.yml',
119
+ message: 'missing an ignore for "@alxwlw/*" — the bot will fight the canon rollout',
120
+ };
121
+ let doc: unknown;
122
+ try {
123
+ doc = parseYaml(readFileSync(path, 'utf8'));
124
+ } catch {
125
+ return [
126
+ {
127
+ code: 'unreadable-file',
128
+ target: '.github/dependabot.yml',
129
+ message: '.github/dependabot.yml does not parse as YAML',
130
+ },
131
+ ];
132
+ }
133
+ return ignoresAlxwlw(doc) ? [] : [finding];
134
+ }
package/src/files.ts ADDED
@@ -0,0 +1,75 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+
4
+ import type { StackConfig } from './config.ts';
5
+ import type { Finding } from './findings.ts';
6
+ import { canonDir, filesFor } from './manifest.ts';
7
+
8
+ export interface FileChange {
9
+ dest: string;
10
+ action: 'written' | 'seeded' | 'unchanged';
11
+ }
12
+
13
+ export function syncFiles(
14
+ repoRoot: string,
15
+ cfg: StackConfig,
16
+ dir: string = canonDir(),
17
+ ): FileChange[] {
18
+ const changes: FileChange[] = [];
19
+ for (const f of filesFor(cfg, dir)) {
20
+ const target = join(repoRoot, f.dest);
21
+ const want = readFileSync(join(dir, f.src), 'utf8');
22
+ const exists = existsSync(target);
23
+ if (f.strategy === 'create-if-absent') {
24
+ // Файл принадлежит репозиторию после первого засева — содержимое не трогаем.
25
+ if (exists) {
26
+ changes.push({ dest: f.dest, action: 'unchanged' });
27
+ continue;
28
+ }
29
+ mkdirSync(dirname(target), { recursive: true });
30
+ writeFileSync(target, want);
31
+ changes.push({ dest: f.dest, action: 'seeded' });
32
+ continue;
33
+ }
34
+ if (exists && readFileSync(target, 'utf8') === want) {
35
+ changes.push({ dest: f.dest, action: 'unchanged' });
36
+ continue;
37
+ }
38
+ mkdirSync(dirname(target), { recursive: true });
39
+ writeFileSync(target, want);
40
+ changes.push({ dest: f.dest, action: 'written' });
41
+ }
42
+ return changes;
43
+ }
44
+
45
+ export function checkFiles(
46
+ repoRoot: string,
47
+ cfg: StackConfig,
48
+ dir: string = canonDir(),
49
+ ): Finding[] {
50
+ const findings: Finding[] = [];
51
+ for (const f of filesFor(cfg, dir)) {
52
+ const target = join(repoRoot, f.dest);
53
+ const exception = cfg.exceptions.find((e) => e.file === f.dest);
54
+ if (!existsSync(target)) {
55
+ findings.push({
56
+ code: 'file-missing',
57
+ target: f.dest,
58
+ message: `canon file missing: ${f.dest}`,
59
+ ...(exception ? { suppressedBy: exception } : {}),
60
+ });
61
+ continue;
62
+ }
63
+ // create-if-absent принадлежит репозиторию: расхождением считается только отсутствие.
64
+ if (f.strategy === 'create-if-absent') continue;
65
+ if (readFileSync(target, 'utf8') !== readFileSync(join(dir, f.src), 'utf8')) {
66
+ findings.push({
67
+ code: 'file-drift',
68
+ target: f.dest,
69
+ message: `${f.dest} differs from canon`,
70
+ ...(exception ? { suppressedBy: exception } : {}),
71
+ });
72
+ }
73
+ }
74
+ return findings;
75
+ }
@@ -0,0 +1,19 @@
1
+ import type { Exception } from './config.ts';
2
+
3
+ export type FindingCode =
4
+ | 'file-drift'
5
+ | 'file-missing'
6
+ | 'catalog-drift'
7
+ | 'catalog-missing'
8
+ | 'inline-version'
9
+ | 'engines-node'
10
+ | 'dependabot-ignore'
11
+ | 'unreadable-file'
12
+ | 'stale-exception';
13
+
14
+ export interface Finding {
15
+ code: FindingCode;
16
+ target: string;
17
+ message: string;
18
+ suppressedBy?: Exception;
19
+ }
package/src/init.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { existsSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ import { type Profile, STACK_CONFIG_FILE, StackConfigError } from './config.ts';
5
+
6
+ // oxfmt (canon .oxfmtrc.jsonc, printWidth 100) collapses a short JSON array onto one line;
7
+ // plain `JSON.stringify(…, null, '\t')` never does. Without this, the file `stack init` just
8
+ // created fails the very `oxfmt --check` gate canon seeds in the same `sync` — a repo's first
9
+ // `moon run :format` after adopting the canon goes red on canon's own seed, before a single line
10
+ // of product code changed. ponytail: hand-collapsed for this fixed 4-field shape, only holds
11
+ // while `with` stays short enough to fit printWidth (today's known groups all do); a group list
12
+ // long enough to wrap would need real oxfmt-style width math, not string-length arithmetic.
13
+ function jsonArrayLine(items: readonly string[]): string {
14
+ return `[${items.map((s) => JSON.stringify(s)).join(', ')}]`;
15
+ }
16
+
17
+ export function initConfig(repoRoot: string, opts: { profile: Profile; with?: string[] }): string {
18
+ const path = join(repoRoot, STACK_CONFIG_FILE);
19
+ if (existsSync(path)) throw new StackConfigError(`${STACK_CONFIG_FILE} already exists`);
20
+ const body =
21
+ '{\n' +
22
+ '\t"$schema": "./node_modules/@alxwlw/stack/schema.json",\n' +
23
+ `\t"profile": ${JSON.stringify(opts.profile)},\n` +
24
+ `\t"with": ${jsonArrayLine(opts.with ?? [])},\n` +
25
+ '\t"exceptions": [],\n' +
26
+ '}\n';
27
+ writeFileSync(path, body);
28
+ return path;
29
+ }
@@ -0,0 +1,33 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ import type { Profile, StackConfig } from './config.ts';
6
+
7
+ export type SyncStrategy = 'verbatim' | 'create-if-absent';
8
+
9
+ export interface CanonFile {
10
+ src: string;
11
+ dest: string;
12
+ appliesTo: Profile[];
13
+ strategy?: SyncStrategy;
14
+ /** Группа, включаемая через `with` в .stack.jsonc. Без группы файл обязателен всем. */
15
+ group?: string;
16
+ }
17
+
18
+ export function canonDir(): string {
19
+ return join(dirname(fileURLToPath(import.meta.url)), '..', 'canon');
20
+ }
21
+
22
+ export function loadManifest(dir: string = canonDir()): CanonFile[] {
23
+ const raw = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')) as {
24
+ files: CanonFile[];
25
+ };
26
+ return raw.files;
27
+ }
28
+
29
+ export function filesFor(cfg: StackConfig, dir: string = canonDir()): CanonFile[] {
30
+ return loadManifest(dir).filter(
31
+ (f) => f.appliesTo.includes(cfg.profile) && (f.group == null || cfg.with.includes(f.group)),
32
+ );
33
+ }