@acceler-digital/karura 0.0.0-stage → 0.2.1

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 (75) hide show
  1. package/.claude/hooks/lint-text-style.py +876 -0
  2. package/.claude/settings.json +17 -0
  3. package/.claude/skills/d0-create-artifact-skill/SKILL.md +123 -0
  4. package/.claude/skills/d0-create-artifact-skill/skill-writing-rules.md +67 -0
  5. package/.claude/skills/d0-create-artifact-skill/template.md +63 -0
  6. package/.claude/skills/d1-actor-list/SKILL.md +66 -0
  7. package/.claude/skills/d1-actor-list/template.md +54 -0
  8. package/.claude/skills/d1-business-requirement-document/SKILL.md +116 -0
  9. package/.claude/skills/d1-business-requirement-document/template.md +251 -0
  10. package/.claude/skills/d1-domain-common-requirement-document/SKILL.md +112 -0
  11. package/.claude/skills/d1-domain-common-requirement-document/template.md +120 -0
  12. package/.claude/skills/d1-domain-definition-document/SKILL.md +67 -0
  13. package/.claude/skills/d1-domain-definition-document/template.md +113 -0
  14. package/.claude/skills/d1-domain-requirement-document/SKILL.md +119 -0
  15. package/.claude/skills/d1-domain-requirement-document/template.md +135 -0
  16. package/.claude/skills/d1-product-requirement-document/SKILL.md +104 -0
  17. package/.claude/skills/d1-product-requirement-document/template.md +287 -0
  18. package/.claude/skills/d1-screen-concepts/SKILL.md +154 -0
  19. package/.claude/skills/d1-screen-concepts/template.md +112 -0
  20. package/.claude/skills/d1-use-case-list/SKILL.md +137 -0
  21. package/.claude/skills/d1-use-case-list/template.md +29 -0
  22. package/.claude/skills/d1-user-story-list/SKILL.md +119 -0
  23. package/.claude/skills/d1-user-story-list/template.md +27 -0
  24. package/.claude/skills/d2-c4-level1-sequences/SKILL.md +162 -0
  25. package/.claude/skills/d2-c4-level1-sequences/example.md +83 -0
  26. package/.claude/skills/d2-c4-level1-sequences/template.md +47 -0
  27. package/.claude/skills/d2-c4-level1-system-context/SKILL.md +51 -0
  28. package/.claude/skills/d2-c4-level1-system-context/template.md +48 -0
  29. package/.claude/skills/d2-conceptual-data-model/SKILL.md +138 -0
  30. package/.claude/skills/d2-conceptual-data-model/example.md +75 -0
  31. package/.claude/skills/d2-conceptual-data-model/template.md +60 -0
  32. package/.claude/skills/d2-external-system-list/SKILL.md +33 -0
  33. package/.claude/skills/d2-external-system-list/template.md +15 -0
  34. package/.claude/skills/d2-function-list/SKILL.md +50 -0
  35. package/.claude/skills/d2-function-list/template.md +15 -0
  36. package/.claude/skills/d2-non-functional-requirements/SKILL.md +129 -0
  37. package/.claude/skills/d2-non-functional-requirements/template-chapter.md +32 -0
  38. package/.claude/skills/d2-non-functional-requirements/template-general.md +56 -0
  39. package/.claude/skills/d2-screen-flow-diagram/SKILL.md +85 -0
  40. package/.claude/skills/d2-screen-flow-diagram/template.md +32 -0
  41. package/.claude/skills/d2-screen-list/SKILL.md +93 -0
  42. package/.claude/skills/d2-screen-list/template.md +15 -0
  43. package/.claude/skills/d3-application-architecture/SKILL.md +110 -0
  44. package/.claude/skills/d3-application-architecture/template.md +123 -0
  45. package/.claude/skills/d3-c4-level2-container/SKILL.md +90 -0
  46. package/.claude/skills/d3-c4-level2-container/template.md +62 -0
  47. package/.claude/skills/d3-c4-level2-sequences/SKILL.md +121 -0
  48. package/.claude/skills/d3-c4-level2-sequences/template.md +85 -0
  49. package/.claude/skills/d3-er-diagram/SKILL.md +123 -0
  50. package/.claude/skills/d3-er-diagram/template.md +61 -0
  51. package/.claude/skills/d8-system-test-plan/SKILL.md +98 -0
  52. package/.claude/skills/d8-system-test-plan/template.md +128 -0
  53. package/.claude/skills/d9-test-data-requirements/SKILL.md +97 -0
  54. package/.claude/skills/d9-test-data-requirements/template.md +11 -0
  55. package/.claude/skills/d9-test-data-tool/SKILL.md +92 -0
  56. package/.claude/skills/d9-test-data-tool/template.md +23 -0
  57. package/.claude/skills/d9-test-perspectives/SKILL.md +118 -0
  58. package/.claude/skills/d9-test-perspectives/template.md +11 -0
  59. package/.claude/skills/d9-test-specification/SKILL.md +111 -0
  60. package/.claude/skills/d9-test-specification/template.md +11 -0
  61. package/CLAUDE.md +355 -0
  62. package/LICENSE +201 -0
  63. package/README.md +197 -2
  64. package/cli/assets/logo-ascii.txt +13 -0
  65. package/cli/assets/logo-wide-ascii.txt +14 -0
  66. package/cli/assets/logo-wide.txt +14 -0
  67. package/cli/assets/logo.txt +13 -0
  68. package/cli/bin/karura.js +163 -0
  69. package/cli/lib/banner.js +241 -0
  70. package/cli/lib/init.js +230 -0
  71. package/cli/lib/terminal.js +65 -0
  72. package/docs/D0.project-management/artifact-flow.drawio.svg +5263 -0
  73. package/docs/D0.project-management/artifact-flow.md +3 -0
  74. package/package.json +48 -4
  75. package/scripts/check-markers.sh +74 -0
@@ -0,0 +1,241 @@
1
+ import fs from 'node:fs';
2
+ import { ANSI_RESET, LOGO_GRADIENT, canDrawSymbols, detectColorMode, foregroundColor } from './terminal.js';
3
+
4
+ // ロゴは cli/assets/ の logo*.txt に置く。端末で表示できるもののうち、幅に収まる最大のものを選ぶ。
5
+ // - サイズ違いを足すときは、ファイルを置くだけでよい(例: 広い端末向けの logo-wide.txt)
6
+ // - ファイル中の {version} は、表示するときに KARURA のバージョンに置き換える
7
+ //
8
+ // ロゴは、ブロック文字(█ ▀ ▄)などの記号で描いた版と、ASCII だけで描いた版(logo*-ascii.txt)を、サイズごとに対で置く。
9
+ // 記号は、端末によっては崩れたり表示できなかったりする(どの端末かは terminal.js の canDrawSymbols を参照)。
10
+ // KARURA は企業の Windows 端末での利用も想定しており、そこでは記号が崩れる従来のコンソールがまだ多く使われている。
11
+ // そうした端末でもロゴを崩さず出せるよう、どの端末でも表示できる ASCII だけの版を用意している。
12
+ const ASSETS_DIR = new URL('../assets/', import.meta.url);
13
+ const LOGO_FILE_PATTERN = /^logo.*\.txt$/;
14
+ // 端末の幅が分からないときは、昔からの標準の 80 桁とみなす
15
+ const DEFAULT_COLUMNS = 80;
16
+
17
+ // ロゴの各ファイルに書いているキャッチコピー。ロゴの中から見つけて、グラデーションを掛けずに薄く表示する
18
+ const TAGLINE = 'Enterprise AI-Driven Development Framework';
19
+ // ロゴに掛けるグラデーションの色は、terminal.js の LOGO_GRADIENT で定める。
20
+ // グラデーションの進み具合のうち、横方向が占める割合(残りは縦方向)
21
+ const HORIZONTAL_WEIGHT = 0.8;
22
+ const ANSI_DIM = '\x1b[2m';
23
+ // 端末の高さが分からないときは、昔からの標準の 24 行とみなす
24
+ const DEFAULT_ROWS = 24;
25
+
26
+ // アニメーションは 3 段階で、全体で約 0.65 秒
27
+ // 1. 光の帯が左から右へ走って、ロゴを描き切る
28
+ const DRAW_DURATION_MS = 300;
29
+ // 2. 光の帯がロゴを抜け、グラデーションの色に落ち着く
30
+ const SETTLE_DURATION_MS = 200;
31
+ // 3. キャッチコピーを打ち出す
32
+ const TAGLINE_DURATION_MS = 150;
33
+ // 1 コマの表示時間(約 30 コマ/秒)
34
+ const FRAME_INTERVAL_MS = 33;
35
+ // 光の帯の幅(桁)と、傾き(1 行下がるごとに遅れる桁数)
36
+ const GLOW_WIDTH = 16;
37
+ const SWEEP_SLANT = 2;
38
+ const HIDE_CURSOR = '\x1b[?25l';
39
+ const SHOW_CURSOR = '\x1b[?25h';
40
+ // 1 コマをまとめて描かせる指示(synchronized output)。対応していない端末は無視する
41
+ const SYNCHRONIZED_START = '\x1b[?2026h';
42
+ const SYNCHRONIZED_END = '\x1b[?2026l';
43
+
44
+ /**
45
+ * @typedef {object} Logo
46
+ * @property {string} fileName
47
+ * @property {string[]} lines
48
+ * @property {number} width 最も長い行の文字数
49
+ * @property {boolean} asciiOnly ASCII だけで描いているか
50
+ */
51
+
52
+ function trimBlankLines(lines) {
53
+ const isBlank = (line) => line.trim() === '';
54
+ const start = lines.findIndex((line) => !isBlank(line));
55
+ const end = lines.findLastIndex((line) => !isBlank(line));
56
+ return start === -1 ? [] : lines.slice(start, end + 1);
57
+ }
58
+
59
+ /** @returns {Logo[]} */
60
+ export function readLogos(version) {
61
+ const fileNames = fs.readdirSync(ASSETS_DIR).filter((fileName) => LOGO_FILE_PATTERN.test(fileName));
62
+ return fileNames.map((fileName) => {
63
+ let text = fs.readFileSync(new URL(fileName, ASSETS_DIR), 'utf8');
64
+ // エディタが先頭に付けることがある BOM は、幅の計算を狂わせるため取り除く
65
+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
66
+ // Windows で改行が CRLF になっていても、同じ行に分ける
67
+ const lines = trimBlankLines(text.replaceAll('{version}', version).split(/\r?\n/));
68
+ return {
69
+ fileName,
70
+ lines,
71
+ width: Math.max(0, ...lines.map((line) => line.length)),
72
+ asciiOnly: /^[\x00-\x7f]*$/.test(text),
73
+ };
74
+ });
75
+ }
76
+
77
+ /**
78
+ * 表示できるロゴのうち、幅に収まる最大のものを返す。収まるものがなければ null を返す。
79
+ * @param {Logo[]} logos
80
+ * @param {{ columns: number, symbols: boolean }} terminal
81
+ */
82
+ export function chooseLogo(logos, { columns, symbols }) {
83
+ const candidates = logos.filter((logo) => (symbols || logo.asciiOnly) && logo.width <= columns);
84
+ // 幅が同じなら、記号を使った方を選ぶ
85
+ candidates.sort((a, b) => b.width - a.width || Number(a.asciiOnly) - Number(b.asciiOnly));
86
+ return candidates[0] ?? null;
87
+ }
88
+
89
+ // グラデーション上の位置 position(0〜1)の色を、RGB で返す
90
+ function gradientColorAt(position) {
91
+ const scaled = Math.min(1, Math.max(0, position)) * (LOGO_GRADIENT.length - 1);
92
+ const index = Math.min(Math.floor(scaled), LOGO_GRADIENT.length - 2);
93
+ const from = LOGO_GRADIENT[index];
94
+ const to = LOGO_GRADIENT[index + 1];
95
+ return from.map((channel, i) => Math.round(channel + (to[i] - channel) * (scaled - index)));
96
+ }
97
+
98
+ // 光の帯に近いほど、色を白に寄せて明るくする。glow は 0〜1 で、0 なら元の色のまま
99
+ const brighten = (rgb, glow) => rgb.map((channel) => Math.round(channel + (255 - channel) * glow * glow));
100
+
101
+ /**
102
+ * ロゴに左上から右下へのグラデーションを掛け、キャッチコピーは薄く表示する。
103
+ * frame を渡すと、アニメーションの途中の 1 コマを描く。省くと、描き終えた状態になる。
104
+ * @param {string[]} lines
105
+ * @param {'none' | 'ansi256' | 'truecolor'} colorMode
106
+ * @param {{ sweepFront?: number, taglineLength?: number }} [frame]
107
+ * sweepFront: 光の帯の先頭の桁。これより右はまだ描かない。
108
+ * taglineLength: キャッチコピーを先頭から何文字まで表示するか
109
+ */
110
+ export function colorizeLogo(lines, colorMode, { sweepFront = Infinity, taglineLength = Infinity } = {}) {
111
+ if (colorMode === 'none') return lines;
112
+ const width = Math.max(...lines.map((line) => line.length));
113
+ return lines.map((line, row) => {
114
+ const taglineStart = line.indexOf(TAGLINE);
115
+ const art = taglineStart === -1 ? line : line.slice(0, taglineStart);
116
+ // 光の帯は斜めに走る。下の行ほど遅れて届く
117
+ const rowFront = sweepFront - row * SWEEP_SLANT;
118
+ let colored = '';
119
+ let currentColor = '';
120
+ for (let column = 0; column < art.length; column++) {
121
+ if (art[column] === ' ' || column > rowFront) {
122
+ colored += ' ';
123
+ continue;
124
+ }
125
+ const position =
126
+ HORIZONTAL_WEIGHT * (column / Math.max(1, width - 1)) +
127
+ (1 - HORIZONTAL_WEIGHT) * (row / Math.max(1, lines.length - 1));
128
+ // 光の帯の中(先頭から GLOW_WIDTH 桁以内)だけ明るくする
129
+ const glow = Math.max(0, 1 - (rowFront - column) / GLOW_WIDTH);
130
+ const color = foregroundColor(brighten(gradientColorAt(position), glow), colorMode);
131
+ // 同じ色が続くときは、エスケープシーケンスを繰り返さない
132
+ if (color !== currentColor) colored += color;
133
+ currentColor = color;
134
+ colored += art[column];
135
+ }
136
+ if (taglineStart !== -1) {
137
+ colored += `${ANSI_RESET}${ANSI_DIM}${line.slice(taglineStart, taglineStart + taglineLength)}`;
138
+ }
139
+ return `${colored}${ANSI_RESET}`;
140
+ });
141
+ }
142
+
143
+ /**
144
+ * アニメーションの全コマ。光の帯が左から右へ走ってロゴを描き、続けてキャッチコピーを打ち出す。
145
+ * 最後のコマは、アニメーションしないときの表示と同じになる。
146
+ * @param {Logo} logo
147
+ * @returns {string[][]}
148
+ */
149
+ export function animationFrames(logo, colorMode) {
150
+ // 光の帯の先頭が、最も遅れて届く最下行の右端に達すると、ロゴを描き切る
151
+ const drawDistance = logo.width + (logo.lines.length - 1) * SWEEP_SLANT;
152
+ const taglineFullLength = Math.max(
153
+ 0,
154
+ ...logo.lines.map((line) => (line.includes(TAGLINE) ? line.length - line.indexOf(TAGLINE) : 0)),
155
+ );
156
+ const frames = [];
157
+ const addFrame = (frame) => frames.push(colorizeLogo(logo.lines, colorMode, frame));
158
+ // 各段階のコマを、その段階の進み具合(0 より大きく 1 以下)ごとに作る
159
+ const eachProgress = (durationMs, callback) => {
160
+ const frameCount = Math.max(1, Math.round(durationMs / FRAME_INTERVAL_MS));
161
+ for (let frame = 1; frame <= frameCount; frame++) callback(frame / frameCount);
162
+ };
163
+
164
+ // 1. ロゴを描く。待たせないよう速く走り出し、最後はゆっくり止まる
165
+ eachProgress(DRAW_DURATION_MS, (progress) => {
166
+ const eased = 1 - (1 - progress) ** 2;
167
+ addFrame({ sweepFront: eased * drawDistance, taglineLength: 0 });
168
+ });
169
+ // 2. 光の帯を、帯の幅だけ先へ進めてロゴから抜けさせる
170
+ eachProgress(SETTLE_DURATION_MS, (progress) => {
171
+ addFrame({ sweepFront: drawDistance + GLOW_WIDTH * progress, taglineLength: 0 });
172
+ });
173
+ // 3. キャッチコピーを打ち出す
174
+ eachProgress(TAGLINE_DURATION_MS, (progress) => {
175
+ addFrame({ taglineLength: Math.ceil(taglineFullLength * progress) });
176
+ });
177
+ return frames;
178
+ }
179
+
180
+ /**
181
+ * アニメーションさせてよいか。
182
+ * - 色を使えない端末では、光の帯を表せない
183
+ * - CI のログや、KARURA_NO_ANIMATION を設定した利用者の端末では、動きのある表示を避ける
184
+ * - 書き直しのためにカーソルを上へ戻すので、ロゴ全体が画面の高さに収まっている必要がある
185
+ */
186
+ export function shouldAnimate(logo, colorMode, { rows = DEFAULT_ROWS, env = process.env } = {}) {
187
+ if (colorMode === 'none' || env.CI || env.KARURA_NO_ANIMATION) return false;
188
+ return logo.lines.length + 2 <= rows;
189
+ }
190
+
191
+ /** コマを順に、同じ位置へ描き直して表示する */
192
+ export async function playAnimation(frames, stream = process.stdout) {
193
+ const height = frames[0].length;
194
+ const showCursor = () => stream.write(SHOW_CURSOR);
195
+ // 途中で Ctrl+C を押されても、カーソルを消したままにしない
196
+ const onInterrupt = () => {
197
+ showCursor();
198
+ process.exit(130);
199
+ };
200
+ process.once('SIGINT', onInterrupt);
201
+ stream.write(HIDE_CURSOR);
202
+ try {
203
+ for (const [index, frame] of frames.entries()) {
204
+ const moveUp = index === 0 ? '' : `\x1b[${height}A`;
205
+ // 行頭に戻って描き、前のコマの残りを行末まで消す
206
+ const body = frame.map((line) => `\r${line}\x1b[K\n`).join('');
207
+ // 対応する端末では、1 コマをまとめて描かせてちらつきを防ぐ
208
+ stream.write(`${SYNCHRONIZED_START}${moveUp}${body}${SYNCHRONIZED_END}`);
209
+ await new Promise((resolve) => setTimeout(resolve, FRAME_INTERVAL_MS));
210
+ }
211
+ } finally {
212
+ showCursor();
213
+ process.removeListener('SIGINT', onInterrupt);
214
+ }
215
+ }
216
+
217
+ function chooseTerminalLogo(version, stream, options) {
218
+ const terminal = { columns: stream.columns || DEFAULT_COLUMNS, symbols: canDrawSymbols(options) };
219
+ return chooseLogo(readLogos(version), terminal);
220
+ }
221
+
222
+ /**
223
+ * karura init の冒頭にロゴを表示する。アニメーションできる端末では、アニメーションさせる。
224
+ * 出力がパイプやファイルに渡されるとき(端末でないとき)は、受け取る側の邪魔になるため表示しない。
225
+ * @param {{ platform?: string, env?: object }} [options] 端末の判定に使う環境。省くと実行中の環境を使う
226
+ */
227
+ export async function showBanner(version, stream = process.stdout, options = {}) {
228
+ if (!stream.isTTY) return;
229
+ const logo = chooseTerminalLogo(version, stream, options);
230
+ const colorMode = detectColorMode(stream);
231
+ // ロゴの前後に、空行を 1 行ずつ置く
232
+ stream.write('\n');
233
+ if (logo && shouldAnimate(logo, colorMode, { rows: stream.rows, env: options.env })) {
234
+ await playAnimation(animationFrames(logo, colorMode), stream);
235
+ } else {
236
+ // どのロゴも収まらない狭い端末では、名前とキャッチコピーだけを出す
237
+ const lines = logo ? colorizeLogo(logo.lines, colorMode) : [` KARURA v${version}`, ` ${TAGLINE}`];
238
+ stream.write(lines.map((line) => `${line}\n`).join(''));
239
+ }
240
+ stream.write('\n');
241
+ }
@@ -0,0 +1,230 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { isDeepStrictEqual } from 'node:util';
7
+
8
+ // このファイル(cli/lib/init.js)の 2 つ上がパッケージ直下
9
+ export const PACKAGE_ROOT = fileURLToPath(new URL('../..', import.meta.url));
10
+ const PACKAGE_JSON = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
11
+ export const VERSION = PACKAGE_JSON.version;
12
+
13
+ // package.json の "files" のうち、CLI 自身(cli/)以外を導入先にコピーする。ディレクトリは配下をすべて含める。
14
+ // "files" にはパスをそのまま書く前提で、ワイルドカードは解釈しない。
15
+ const PATHS_TO_COPY = PACKAGE_JSON.files.filter((entry) => !entry.startsWith('cli/'));
16
+
17
+ // 既存があれば上書きせず、足りない設定だけを足す
18
+ const SETTINGS_FILE = '.claude/settings.json';
19
+ // KARURA が管理するファイルなので、既存と内容が違っても衝突にせず書き直す
20
+ export const MANIFEST_FILE = '.karura/manifest.json';
21
+
22
+ const WRITE_ACTIONS = new Set(['create', 'overwrite', 'merge']);
23
+
24
+ /**
25
+ * 導入先の 1 ファイルに対する操作。planInit が作り、applyPlan が実行する。
26
+ * @typedef {object} Step
27
+ * @property {string} relativePath 導入先から見た相対パス(区切りは /)
28
+ * @property {string} destPath 書き込み先の絶対パス
29
+ * @property {'create' | 'overwrite' | 'merge' | 'skip' | 'conflict'} action
30
+ * @property {Buffer} [content] 書き込む内容。conflict 以外で持つ
31
+ * @property {boolean} executable 書き込んだあとに実行権限を付けるか
32
+ * @property {string} [reason] conflict の理由
33
+ * @property {boolean} [forceable] conflict を --force で解消できるか
34
+ */
35
+
36
+ const toPosixPath = (nativePath) => nativePath.split(path.sep).join('/');
37
+ const sha256 = (content) => createHash('sha256').update(content).digest('hex');
38
+ const toJsonBuffer = (value) => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
39
+ const isPlainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
40
+
41
+ // 導入先の中のパスは導入先からの相対パスで示す。導入先そのものと導入先の外は絶対パスで示す
42
+ function toDisplayPath(targetDir, absolutePath) {
43
+ const relativePath = path.relative(targetDir, absolutePath);
44
+ const isOutsideTarget =
45
+ relativePath === '..' || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath);
46
+ if (relativePath === '' || isOutsideTarget) return absolutePath;
47
+ return toPosixPath(relativePath);
48
+ }
49
+
50
+ // ホームフォルダに導入すると、~/.claude/ と ~/CLAUDE.md がすべてのプロジェクトに効いてしまう
51
+ export function isHomeDirectory(dir) {
52
+ const homeDir = os.homedir();
53
+ if (path.resolve(dir) === path.resolve(homeDir)) return true;
54
+ try {
55
+ return fs.realpathSync.native(dir) === fs.realpathSync.native(homeDir);
56
+ } catch {
57
+ // dir がまだ無いなら、ホームフォルダではない
58
+ return false;
59
+ }
60
+ }
61
+
62
+ export function listFilesToCopy() {
63
+ const files = [];
64
+ for (const copyPath of PATHS_TO_COPY) {
65
+ const absolutePath = path.join(PACKAGE_ROOT, copyPath);
66
+ if (!fs.statSync(absolutePath).isDirectory()) {
67
+ files.push(copyPath);
68
+ continue;
69
+ }
70
+ // シンボリックリンクは isFile() が false になるため、コピー対象から外れる
71
+ for (const entry of fs.readdirSync(absolutePath, { recursive: true, withFileTypes: true })) {
72
+ if (!entry.isFile()) continue;
73
+ const entryPath = path.join(entry.parentPath, entry.name);
74
+ files.push(toPosixPath(path.relative(PACKAGE_ROOT, entryPath)));
75
+ }
76
+ }
77
+ return files.sort();
78
+ }
79
+
80
+ // existing の値を残したまま、additions にしかないキーと配列の要素だけを足す
81
+ export function addMissing(existing, additions) {
82
+ if (Array.isArray(existing) && Array.isArray(additions)) {
83
+ const merged = [...existing];
84
+ for (const item of additions) {
85
+ const alreadyIncluded = merged.some((current) => isDeepStrictEqual(current, item));
86
+ if (!alreadyIncluded) merged.push(item);
87
+ }
88
+ return merged;
89
+ }
90
+ if (isPlainObject(existing) && isPlainObject(additions)) {
91
+ const merged = { ...existing };
92
+ for (const [key, value] of Object.entries(additions)) {
93
+ merged[key] = Object.hasOwn(existing, key) ? addMissing(existing[key], value) : value;
94
+ }
95
+ return merged;
96
+ }
97
+ // 値どうし、または型が食い違う場合は、既存の値を優先する
98
+ return existing;
99
+ }
100
+
101
+ // 導入先のパスを根元から 1 つずつたどり、書き込めない理由があれば返す。なければ null を返す。
102
+ // - シンボリックリンク・ハードリンク: たどると導入先の外のファイルを書き換えるおそれがある
103
+ // - 途中のパスにあるファイル: フォルダを作れず、書き込みが途中で失敗する
104
+ function findUnwritableReason(targetDir, relativePath) {
105
+ const segments = relativePath.split('/');
106
+ let currentPath = targetDir;
107
+ for (const [index, segment] of segments.entries()) {
108
+ currentPath = path.join(currentPath, segment);
109
+ let stat;
110
+ try {
111
+ stat = fs.lstatSync(currentPath);
112
+ } catch (error) {
113
+ // ここから先はまだ無いので、新しく作れる
114
+ if (error.code === 'ENOENT') return null;
115
+ throw error;
116
+ }
117
+ const displayPath = toDisplayPath(targetDir, currentPath);
118
+ const isLastSegment = index === segments.length - 1;
119
+ if (stat.isSymbolicLink()) return `${displayPath} is a symbolic link`;
120
+ if (!isLastSegment && !stat.isDirectory()) return `${displayPath} is not a directory`;
121
+ if (isLastSegment && !stat.isFile()) return 'not a regular file';
122
+ if (isLastSegment && stat.nlink > 1) return 'hard-linked to another file';
123
+ }
124
+ return null;
125
+ }
126
+
127
+ function findNearestExistingDirectory(filePath) {
128
+ let dir = path.dirname(filePath);
129
+ // ルートまでたどったら止める(存在しないドライブを指定された場合など)
130
+ while (!fs.existsSync(dir) && path.dirname(dir) !== dir) dir = path.dirname(dir);
131
+ return dir;
132
+ }
133
+
134
+ // 書き込む操作について、書き込む権限がなければ理由を返す。権限があれば null を返す。
135
+ // 書き込みの途中で権限エラーになり、一部だけ書いた状態を残さないため。
136
+ function findPermissionDeniedReason(step, targetDir) {
137
+ if (!WRITE_ACTIONS.has(step.action)) return null;
138
+ // まだ無いファイルは、すでにある一番近いフォルダに書き込めるかで判断する
139
+ const checkedPath = step.action === 'create' ? findNearestExistingDirectory(step.destPath) : step.destPath;
140
+ try {
141
+ fs.accessSync(checkedPath, fs.constants.W_OK);
142
+ return null;
143
+ } catch {
144
+ return `no write permission for ${toDisplayPath(targetDir, checkedPath)}`;
145
+ }
146
+ }
147
+
148
+ function planSettingsMerge(karuraContent, destPath) {
149
+ const existingContent = fs.readFileSync(destPath);
150
+ let existingSettings;
151
+ try {
152
+ // Windows のエディタが先頭に付けることがある BOM は、JSON.parse では読めないため取り除く
153
+ existingSettings = JSON.parse(existingContent.toString('utf8').replace(/^\uFEFF/, ''));
154
+ } catch {
155
+ // 利用者の deny 設定などを失わないよう、--force を付けても上書きしない
156
+ return { action: 'conflict', reason: 'not valid JSON', forceable: false };
157
+ }
158
+ const karuraSettings = JSON.parse(karuraContent.toString('utf8'));
159
+ const mergedSettings = addMissing(existingSettings, karuraSettings);
160
+ if (isDeepStrictEqual(mergedSettings, existingSettings)) {
161
+ return { action: 'skip', content: existingContent };
162
+ }
163
+ return { action: 'merge', content: toJsonBuffer(mergedSettings) };
164
+ }
165
+
166
+ /** @returns {Step} */
167
+ function planFile(relativePath, targetDir, { force }) {
168
+ const sourcePath = path.join(PACKAGE_ROOT, relativePath);
169
+ const destPath = path.join(targetDir, relativePath);
170
+ const content = fs.readFileSync(sourcePath);
171
+ const executable = (fs.statSync(sourcePath).mode & 0o111) !== 0;
172
+ const step = { relativePath, destPath, executable };
173
+
174
+ const unwritableReason = findUnwritableReason(targetDir, relativePath);
175
+ if (unwritableReason) return { ...step, action: 'conflict', reason: unwritableReason, forceable: false };
176
+ if (!fs.existsSync(destPath)) return { ...step, action: 'create', content };
177
+ if (relativePath === SETTINGS_FILE) return { ...step, ...planSettingsMerge(content, destPath) };
178
+ if (content.equals(fs.readFileSync(destPath))) return { ...step, action: 'skip', content };
179
+ if (force) return { ...step, action: 'overwrite', content };
180
+ return { ...step, action: 'conflict', reason: 'differs from the existing file', forceable: true };
181
+ }
182
+
183
+ /** @returns {Step} */
184
+ function planManifest(targetDir, fileSteps) {
185
+ const destPath = path.join(targetDir, MANIFEST_FILE);
186
+ const step = { relativePath: MANIFEST_FILE, destPath, executable: false };
187
+ const unwritableReason = findUnwritableReason(targetDir, MANIFEST_FILE);
188
+ if (unwritableReason) return { ...step, action: 'conflict', reason: unwritableReason, forceable: false };
189
+
190
+ // 衝突したファイルは内容を持たない。衝突があれば何も書き込まないので、除いて記録してかまわない
191
+ const writableSteps = fileSteps.filter((fileStep) => fileStep.action !== 'conflict');
192
+ const hashes = Object.fromEntries(writableSteps.map((fileStep) => [fileStep.relativePath, sha256(fileStep.content)]));
193
+ const content = toJsonBuffer({ karuraVersion: VERSION, files: hashes });
194
+ if (!fs.existsSync(destPath)) return { ...step, action: 'create', content };
195
+ if (content.equals(fs.readFileSync(destPath))) return { ...step, action: 'skip', content };
196
+ return { ...step, action: 'overwrite', content };
197
+ }
198
+
199
+ /**
200
+ * 何も書き込まずに、導入記録を含むファイルごとの操作を決める。
201
+ * @returns {Step[]}
202
+ */
203
+ export function planInit(targetDir, { force = false } = {}) {
204
+ const fileSteps = listFilesToCopy().map((relativePath) => planFile(relativePath, targetDir, { force }));
205
+ const steps = [...fileSteps, planManifest(targetDir, fileSteps)];
206
+ return steps.map((step) => {
207
+ const permissionDeniedReason = findPermissionDeniedReason(step, targetDir);
208
+ if (!permissionDeniedReason) return step;
209
+ return { ...step, action: 'conflict', reason: permissionDeniedReason, forceable: false };
210
+ });
211
+ }
212
+
213
+ // 読める人にだけ実行権限を足す。0755 に固定すると、利用者が狭めていた既存のファイルの権限を広げてしまうため
214
+ function addExecutePermission(filePath) {
215
+ const permissions = fs.statSync(filePath).mode & 0o777;
216
+ fs.chmodSync(filePath, permissions | ((permissions & 0o444) >> 2));
217
+ }
218
+
219
+ /** @param {Step[]} steps */
220
+ export function applyPlan(steps) {
221
+ if (steps.some((step) => step.action === 'conflict')) {
222
+ throw new Error('Cannot write files while there are conflicts.');
223
+ }
224
+ for (const step of steps) {
225
+ if (!WRITE_ACTIONS.has(step.action)) continue;
226
+ fs.mkdirSync(path.dirname(step.destPath), { recursive: true });
227
+ fs.writeFileSync(step.destPath, step.content);
228
+ if (step.executable) addExecutePermission(step.destPath);
229
+ }
230
+ }
@@ -0,0 +1,65 @@
1
+ // 端末の機能(記号や色を表示できるか)を調べ、それに合わせて出力を飾る。飾りに使う配色も、ここで定める
2
+
3
+ export const ANSI_RESET = '\x1b[0m';
4
+ // ロゴに左上から右下へ掛けるグラデーションの色(RGB、左から順に)。ブランドの配色が決まったら差し替える。
5
+ // ロゴに合わせてグレーを基調にし、右端にだけ控えめな赤茶を差す。
6
+ // 白い背景でも黒い背景でも読めるよう、どの色も中間の明るさにして、両方とのコントラスト比を 3.5:1 以上にしている
7
+ export const LOGO_GRADIENT = [
8
+ [125, 125, 128],
9
+ [135, 132, 132],
10
+ [150, 138, 132],
11
+ [180, 110, 85],
12
+ ];
13
+ // 強調に使う色。ロゴのグラデーションの終わりの赤茶にそろえる
14
+ const ACCENT_COLOR = LOGO_GRADIENT.at(-1);
15
+
16
+ /**
17
+ * ブロック文字や絵文字などの記号を、崩さずに表示できる端末か。
18
+ * - 日本語環境の Windows では、従来のコンソールや Git Bash で記号が 2 文字幅で表示されて崩れる。
19
+ * そのため Windows では、Windows Terminal と VS Code のターミナルに限る
20
+ * - Linux のコンソール画面(TERM=linux)や機能のない端末(TERM=dumb)は、記号を表示できないことがある
21
+ * - 文字コードが UTF-8 でない端末では、記号が文字化けする
22
+ */
23
+ export function canDrawSymbols({ platform = process.platform, env = process.env } = {}) {
24
+ if (platform === 'win32') return Boolean(env.WT_SESSION) || env.TERM_PROGRAM === 'vscode';
25
+ if (env.TERM === 'linux' || env.TERM === 'dumb') return false;
26
+ const locale = env.LC_ALL || env.LC_CTYPE || env.LANG || '';
27
+ return /utf-?8/i.test(locale);
28
+ }
29
+
30
+ /**
31
+ * 端末が使える色の数。Node が NO_COLOR・FORCE_COLOR・TERM などの環境変数から判定した結果に従う。
32
+ * @returns {'none' | 'ansi256' | 'truecolor'}
33
+ */
34
+ export function detectColorMode(stream) {
35
+ const colorDepth = stream.getColorDepth?.() ?? 1;
36
+ if (colorDepth >= 24) return 'truecolor';
37
+ if (colorDepth >= 8) return 'ansi256';
38
+ return 'none';
39
+ }
40
+
41
+ // 文字色を変えるエスケープシーケンス。256 色の端末では、6 段階 × RGB の色(16〜231 番)のうち近いものに丸める
42
+ export function foregroundColor([red, green, blue], colorMode) {
43
+ if (colorMode === 'truecolor') return `\x1b[38;2;${red};${green};${blue}m`;
44
+ const toLevel = (value) => (value < 48 ? 0 : value < 115 ? 1 : Math.floor((value - 35) / 40));
45
+ return `\x1b[38;5;${16 + 36 * toLevel(red) + 6 * toLevel(green) + toLevel(blue)}m`;
46
+ }
47
+
48
+ /**
49
+ * 出力先に合わせて文字を飾る関数をまとめて返す。
50
+ * 端末でない(パイプやファイルに渡す)ときや、記号・色を表示できない端末では、飾らずにそのまま返す。
51
+ */
52
+ export function createDecorator(stream = process.stdout, options = {}) {
53
+ const isTerminal = Boolean(stream.isTTY);
54
+ const canShowEmoji = isTerminal && canDrawSymbols(options);
55
+ const colorMode = isTerminal ? detectColorMode(stream) : 'none';
56
+ const style = (start, end) => (text) => (colorMode === 'none' ? text : `${start}${text}${end}`);
57
+ return {
58
+ // 絵文字のあとに空白を 1 つ置く。表示できない端末では何も出さない
59
+ emoji: (emoji) => (canShowEmoji ? `${emoji} ` : ''),
60
+ bold: style('\x1b[1m', '\x1b[22m'),
61
+ accent: style(foregroundColor(ACCENT_COLOR, colorMode), '\x1b[39m'),
62
+ // 利用者が入力するコマンドは、水色で目立たせる
63
+ command: style('\x1b[36m', '\x1b[39m'),
64
+ };
65
+ }