create-krispya 0.7.0 → 0.9.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.
package/dist/cli.mjs ADDED
@@ -0,0 +1,2704 @@
1
+ #!/usr/bin/env node
2
+ import * as p from '@clack/prompts';
3
+ import color from 'chalk';
4
+ import { Command } from 'commander';
5
+ import { constants as constants$2 } from 'node:fs';
6
+ import { mkdir as mkdir$1, writeFile as writeFile$1, unlink, access as access$1, readFile as readFile$1 } from 'node:fs/promises';
7
+ import { createRequire } from 'node:module';
8
+ import { join as join$1, dirname as dirname$1, resolve } from 'node:path';
9
+ import { cwd } from 'node:process';
10
+ import { fetch } from 'undici';
11
+ import { g as getEngineName, a as getBaseTemplate, b as getLanguageFromTemplate, c as getPackageManagerName, d as generateRandomName, e as detectTooling, r as resolveMonorepoRootPackageVersions, f as generateAiFiles, A as ALL_AI_PLATFORMS, h as generateVscodeFiles, i as generateTypescriptConfigPackage, j as generateOxlintConfigPackage, k as generateEslintConfigPackage, l as generateOxfmtConfigPackage, m as generatePrettierConfigPackage, n as generateGitignore, o as getResolvedPackageVersion, p as parseWorkspaceYamlContent, q as formatResolvedPackageVersion, s as resolvePackageManager, t as resolveEngine, u as resolveProjectPackageVersions, v as generate, w as parsePackageManager, x as parseEngine, y as AI_PLATFORM_LABELS, z as AI_PLATFORM_HINTS, B as validatePackageName } from './chunks/index.mjs';
12
+ import Conf from 'conf';
13
+ import { readFile, mkdir, writeFile, rm, access, readdir, constants as constants$1 } from 'fs/promises';
14
+ import { constants } from 'fs';
15
+ import { join, dirname } from 'path';
16
+
17
+ function formatConfigSummary(options, inherited) {
18
+ const lines = [];
19
+ const VALUE_COL = 27;
20
+ const formatRow = (label, value, isInherited = false, indent = "") => {
21
+ const fullLabel = indent + label;
22
+ const dotCount = Math.max(1, VALUE_COL - fullLabel.length - 1);
23
+ const dots = color.gray(".".repeat(dotCount));
24
+ const displayValue = isInherited ? `${value} \u{1F512}` : value;
25
+ return `${indent}${label} ${dots} ${displayValue}`;
26
+ };
27
+ const formatLanguage = (lang) => {
28
+ return lang === "typescript" ? "TypeScript" : lang === "javascript" ? "JavaScript" : lang;
29
+ };
30
+ const projectType = options.projectType ?? "app";
31
+ const baseTemplate = options.template ? getBaseTemplate(options.template) : "vanilla";
32
+ if (baseTemplate === "react") {
33
+ lines.push(formatRow("Framework", "React"));
34
+ } else if (baseTemplate === "r3f") {
35
+ lines.push(formatRow("Framework", "React Three Fiber"));
36
+ }
37
+ const language = options.template ? getLanguageFromTemplate(options.template) : "typescript";
38
+ lines.push(formatRow("Language", formatLanguage(language)));
39
+ if (projectType === "library") {
40
+ lines.push(formatRow("Bundler", options.libraryBundler ?? "unbuild"));
41
+ } else {
42
+ lines.push(formatRow("Bundler", "vite"));
43
+ }
44
+ const engineInherited = inherited?.engine !== void 0;
45
+ lines.push(
46
+ formatRow(
47
+ "Engine",
48
+ `${getEngineName(options.engine)}@${options.engine?.version ?? "latest"}`,
49
+ engineInherited
50
+ )
51
+ );
52
+ const pmInherited = inherited?.packageManager !== void 0;
53
+ lines.push(
54
+ formatRow("Package manager", getPackageManagerName(options.packageManager), pmInherited)
55
+ );
56
+ if (getPackageManagerName(options.packageManager) === "pnpm") {
57
+ const versionManaged = options.pnpmManageVersions ? "yes" : "no";
58
+ const pnpmVersionInherited = inherited?.pnpmManageVersions !== void 0;
59
+ lines.push(formatRow("\u21B3 Version managed", versionManaged, pnpmVersionInherited, ""));
60
+ }
61
+ if (options.linter) {
62
+ const linterInherited = inherited?.linter !== void 0;
63
+ lines.push(formatRow("Linter", options.linter, linterInherited));
64
+ }
65
+ if (options.formatter) {
66
+ const formatterInherited = inherited?.formatter !== void 0;
67
+ lines.push(formatRow("Formatter", options.formatter, formatterInherited));
68
+ }
69
+ const testing = options.testing ?? (projectType === "library" ? "vitest" : "none");
70
+ lines.push(formatRow("Testing", testing));
71
+ if (!inherited) {
72
+ const configStrategy = options.configStrategy ?? "stealth";
73
+ lines.push(formatRow("Config strategy", configStrategy));
74
+ }
75
+ if (options.template && getBaseTemplate(options.template) === "r3f") {
76
+ const integrationNames = [
77
+ options.drei && "drei",
78
+ options.handle && "handle",
79
+ options.leva && "leva",
80
+ options.postprocessing && "postproc",
81
+ options.rapier && "rapier",
82
+ options.xr && "xr",
83
+ options.uikit && "uikit",
84
+ options.offscreen && "offscreen",
85
+ options.zustand && "zustand",
86
+ options.koota && "koota",
87
+ options.triplex && "triplex",
88
+ options.viverse && "viverse"
89
+ ].filter(Boolean);
90
+ lines.push("");
91
+ lines.push(color.dim("Integrations"));
92
+ for (let i = 0; i < integrationNames.length; i += 2) {
93
+ const left = `${color.green("\u25CF")} ${integrationNames[i]}`;
94
+ const right = integrationNames[i + 1] ? `${color.green("\u25CF")} ${integrationNames[i + 1]}` : "";
95
+ const spacing = " ".repeat(Math.max(1, 16 - integrationNames[i].length));
96
+ lines.push(` ${left}${spacing}${right}`);
97
+ }
98
+ }
99
+ return lines.join("\n");
100
+ }
101
+ function formatMonorepoConfigSummary(options) {
102
+ const lines = [];
103
+ const VALUE_COL = 27;
104
+ const formatRow = (label, value, indent = "") => {
105
+ const fullLabel = indent + label;
106
+ const dotCount = Math.max(1, VALUE_COL - fullLabel.length - 1);
107
+ const dots = color.gray(".".repeat(dotCount));
108
+ return `${indent}${label} ${dots} ${value}`;
109
+ };
110
+ lines.push(
111
+ formatRow("Engine", `${getEngineName(options.engine)}@${options.engine.version ?? "latest"}`)
112
+ );
113
+ lines.push(formatRow("Package manager", options.packageManager));
114
+ if (options.packageManager === "pnpm") {
115
+ const versionManaged = options.pnpmManageVersions ? "yes" : "no";
116
+ lines.push(formatRow("\u21B3 Version managed", versionManaged, ""));
117
+ }
118
+ lines.push(formatRow("Linter", options.linter));
119
+ lines.push(formatRow("Formatter", options.formatter));
120
+ return lines.join("\n");
121
+ }
122
+
123
+ const config = new Conf({
124
+ projectName: "create-krispya"
125
+ });
126
+ function getAiPlatforms() {
127
+ return config.get("aiPlatforms");
128
+ }
129
+ function getConfigStrategy() {
130
+ return config.get("configStrategy") ?? "stealth";
131
+ }
132
+ function clearConfig() {
133
+ config.clear();
134
+ }
135
+ function getConfigPath() {
136
+ return config.path;
137
+ }
138
+ function getCustomTemplates() {
139
+ return config.get("customTemplates") ?? {};
140
+ }
141
+
142
+ function getDefaultOptions(template, name, projectType = "app", libraryBundler, integrations, inheritedSettings) {
143
+ const baseTemplate = getBaseTemplate(template);
144
+ const base = {
145
+ name,
146
+ template,
147
+ projectType,
148
+ libraryBundler: projectType === "library" ? libraryBundler ?? "unbuild" : void 0,
149
+ packageManager: inheritedSettings?.packageManager ?? { name: "pnpm" },
150
+ pnpmManageVersions: inheritedSettings?.pnpmManageVersions ?? true,
151
+ engine: inheritedSettings?.engine ?? { name: "node", version: "latest" },
152
+ linter: inheritedSettings?.linter ?? "oxlint",
153
+ formatter: inheritedSettings?.formatter ?? "prettier",
154
+ // Libraries get vitest by default, apps don't
155
+ testing: projectType === "library" ? "vitest" : "none",
156
+ configStrategy: getConfigStrategy()
157
+ };
158
+ if (baseTemplate === "r3f" && integrations) {
159
+ return {
160
+ ...base,
161
+ drei: integrations.includes("drei") ? {} : void 0,
162
+ handle: integrations.includes("handle") ? {} : void 0,
163
+ leva: integrations.includes("leva") ? {} : void 0,
164
+ postprocessing: integrations.includes("postprocessing") ? {} : void 0,
165
+ rapier: integrations.includes("rapier") ? {} : void 0,
166
+ xr: integrations.includes("xr") ? {} : void 0,
167
+ uikit: integrations.includes("uikit") ? {} : void 0,
168
+ offscreen: integrations.includes("offscreen") ? {} : void 0,
169
+ zustand: integrations.includes("zustand") ? {} : void 0,
170
+ koota: integrations.includes("koota") ? {} : void 0,
171
+ triplex: integrations.includes("triplex") ? {} : void 0,
172
+ viverse: integrations.includes("viverse") ? {} : void 0
173
+ };
174
+ }
175
+ return base;
176
+ }
177
+ function getDefaultProjectName(template) {
178
+ const base = getBaseTemplate(template);
179
+ switch (base) {
180
+ case "vanilla":
181
+ return `vanilla-${generateRandomName()}`;
182
+ case "react":
183
+ return `react-${generateRandomName()}`;
184
+ case "r3f":
185
+ return `react-three-${generateRandomName()}`;
186
+ }
187
+ }
188
+ async function promptForR3fIntegrations(presets) {
189
+ const initialValues = [];
190
+ if (presets) {
191
+ if (presets.drei) initialValues.push("drei");
192
+ if (presets.handle) initialValues.push("handle");
193
+ if (presets.leva) initialValues.push("leva");
194
+ if (presets.postprocessing) initialValues.push("postprocessing");
195
+ if (presets.rapier) initialValues.push("rapier");
196
+ if (presets.xr) initialValues.push("xr");
197
+ if (presets.uikit) initialValues.push("uikit");
198
+ if (presets.offscreen) initialValues.push("offscreen");
199
+ if (presets.zustand) initialValues.push("zustand");
200
+ if (presets.koota) initialValues.push("koota");
201
+ if (presets.triplex) initialValues.push("triplex");
202
+ if (presets.viverse) initialValues.push("viverse");
203
+ }
204
+ const selected = await p.multiselect({
205
+ message: "R3F integrations",
206
+ options: [
207
+ { value: "drei", label: "Drei" },
208
+ { value: "handle", label: "Handle" },
209
+ { value: "leva", label: "Leva" },
210
+ { value: "postprocessing", label: "Postprocessing" },
211
+ { value: "rapier", label: "Rapier" },
212
+ { value: "xr", label: "XR" },
213
+ { value: "uikit", label: "UIKit" },
214
+ { value: "offscreen", label: "Offscreen" },
215
+ { value: "zustand", label: "Zustand" },
216
+ { value: "koota", label: "Koota" },
217
+ { value: "triplex", label: "Triplex" },
218
+ { value: "viverse", label: "Viverse" }
219
+ ],
220
+ initialValues: initialValues.length > 0 ? initialValues : ["drei"],
221
+ required: false
222
+ });
223
+ if (p.isCancel(selected)) {
224
+ p.cancel("Operation cancelled.");
225
+ process.exit(0);
226
+ }
227
+ return selected;
228
+ }
229
+ async function promptForCustomization(template, name, projectType, integrations, inheritedSettings, presets) {
230
+ let libraryBundler;
231
+ if (projectType === "library") {
232
+ const bundler = await p.select({
233
+ message: "Library bundler",
234
+ options: [
235
+ { value: "unbuild", label: "unbuild", hint: "unjs, simple config" },
236
+ { value: "tsdown", label: "tsdown", hint: "fast, esbuild-based" }
237
+ ],
238
+ initialValue: presets?.bundler ?? "unbuild"
239
+ });
240
+ if (p.isCancel(bundler)) {
241
+ p.cancel("Operation cancelled.");
242
+ process.exit(0);
243
+ }
244
+ libraryBundler = bundler;
245
+ }
246
+ let engine = inheritedSettings?.engine ?? presets?.engine ?? { name: "node", version: "latest" };
247
+ let finalPackageManager = inheritedSettings?.packageManager?.name ?? presets?.packageManager ?? "pnpm";
248
+ let pnpmManageVersions = inheritedSettings?.pnpmManageVersions ?? presets?.pnpmManageVersions ?? true;
249
+ if (!inheritedSettings?.engine?.version) {
250
+ const nodeVersionInput = await p.text({
251
+ message: "Node.js version",
252
+ placeholder: presets?.engine?.version ?? "latest",
253
+ defaultValue: presets?.engine?.version ?? "latest",
254
+ validate: (value) => {
255
+ if (!value.length) return "Required";
256
+ if (value !== "latest" && !/^\d+(\.\d+(\.\d+)?)?$/.test(value)) {
257
+ return 'Must be "latest" or a valid semver (e.g., "22" or "22.13.0")';
258
+ }
259
+ }
260
+ });
261
+ if (p.isCancel(nodeVersionInput)) {
262
+ p.cancel("Operation cancelled.");
263
+ process.exit(0);
264
+ }
265
+ engine = { name: "node", version: nodeVersionInput };
266
+ }
267
+ if (!inheritedSettings?.packageManager) {
268
+ const packageManager = await p.select({
269
+ message: "Package manager",
270
+ options: [
271
+ { value: "pnpm", label: "pnpm" },
272
+ { value: "npm", label: "npm" },
273
+ { value: "yarn", label: "yarn" }
274
+ ],
275
+ initialValue: presets?.packageManager ?? "pnpm"
276
+ });
277
+ if (p.isCancel(packageManager)) {
278
+ p.cancel("Operation cancelled.");
279
+ process.exit(0);
280
+ }
281
+ finalPackageManager = packageManager;
282
+ if (packageManager === "pnpm") {
283
+ const managePnpm = await p.confirm({
284
+ message: "Enable manage-package-manager-versions?",
285
+ initialValue: presets?.pnpmManageVersions ?? true
286
+ });
287
+ if (p.isCancel(managePnpm)) {
288
+ p.cancel("Operation cancelled.");
289
+ process.exit(0);
290
+ }
291
+ pnpmManageVersions = managePnpm;
292
+ }
293
+ }
294
+ let linter = inheritedSettings?.linter ?? presets?.linter ?? "oxlint";
295
+ let formatter = inheritedSettings?.formatter ?? presets?.formatter ?? "prettier";
296
+ if (!inheritedSettings?.linter) {
297
+ const linterChoice = await p.select({
298
+ message: "Linter",
299
+ options: [
300
+ { value: "oxlint", label: "Oxlint", hint: "fast, from OXC" },
301
+ { value: "eslint", label: "ESLint", hint: "classic" },
302
+ { value: "biome", label: "Biome", hint: "all-in-one" }
303
+ ],
304
+ initialValue: presets?.linter ?? "oxlint"
305
+ });
306
+ if (p.isCancel(linterChoice)) {
307
+ p.cancel("Operation cancelled.");
308
+ process.exit(0);
309
+ }
310
+ linter = linterChoice;
311
+ }
312
+ if (!inheritedSettings?.formatter) {
313
+ const formatterChoice = await p.select({
314
+ message: "Formatter",
315
+ options: [
316
+ { value: "prettier", label: "Prettier", hint: "widely adopted" },
317
+ { value: "oxfmt", label: "Oxfmt", hint: "fast, Prettier-compatible" },
318
+ { value: "biome", label: "Biome", hint: "all-in-one" }
319
+ ],
320
+ initialValue: presets?.formatter ?? "prettier"
321
+ });
322
+ if (p.isCancel(formatterChoice)) {
323
+ p.cancel("Operation cancelled.");
324
+ process.exit(0);
325
+ }
326
+ formatter = formatterChoice;
327
+ }
328
+ const testing = await p.select({
329
+ message: "Testing",
330
+ options: [
331
+ { value: "vitest", label: "Vitest", hint: "fast, Vite-native" },
332
+ { value: "none", label: "None" }
333
+ ],
334
+ initialValue: projectType === "library" ? "vitest" : "none"
335
+ });
336
+ if (p.isCancel(testing)) {
337
+ p.cancel("Operation cancelled.");
338
+ process.exit(0);
339
+ }
340
+ const language = await p.select({
341
+ message: "Language",
342
+ options: [
343
+ { value: "typescript", label: "TypeScript" },
344
+ { value: "javascript", label: "JavaScript" }
345
+ ],
346
+ initialValue: "typescript"
347
+ });
348
+ if (p.isCancel(language)) {
349
+ p.cancel("Operation cancelled.");
350
+ process.exit(0);
351
+ }
352
+ const configStrategyChoice = await p.select({
353
+ message: "Config strategy",
354
+ options: [
355
+ { value: "stealth", label: "stealth", hint: "configs in .config/" },
356
+ { value: "root", label: "root", hint: "configs at project root" }
357
+ ],
358
+ initialValue: getConfigStrategy()
359
+ });
360
+ if (p.isCancel(configStrategyChoice)) {
361
+ p.cancel("Operation cancelled.");
362
+ process.exit(0);
363
+ }
364
+ const baseTemplate = getBaseTemplate(template);
365
+ const finalTemplate = language === "javascript" ? `${baseTemplate}-js` : baseTemplate;
366
+ const base = {
367
+ name,
368
+ template: finalTemplate,
369
+ projectType,
370
+ libraryBundler: projectType === "library" ? libraryBundler : void 0,
371
+ engine,
372
+ packageManager: { name: finalPackageManager },
373
+ pnpmManageVersions,
374
+ linter,
375
+ formatter,
376
+ testing,
377
+ configStrategy: configStrategyChoice
378
+ };
379
+ if (baseTemplate === "r3f" && integrations) {
380
+ return {
381
+ ...base,
382
+ drei: integrations.includes("drei") ? {} : void 0,
383
+ handle: integrations.includes("handle") ? {} : void 0,
384
+ leva: integrations.includes("leva") ? {} : void 0,
385
+ postprocessing: integrations.includes("postprocessing") ? {} : void 0,
386
+ rapier: integrations.includes("rapier") ? {} : void 0,
387
+ xr: integrations.includes("xr") ? {} : void 0,
388
+ uikit: integrations.includes("uikit") ? {} : void 0,
389
+ offscreen: integrations.includes("offscreen") ? {} : void 0,
390
+ zustand: integrations.includes("zustand") ? {} : void 0,
391
+ koota: integrations.includes("koota") ? {} : void 0,
392
+ triplex: integrations.includes("triplex") ? {} : void 0,
393
+ viverse: integrations.includes("viverse") ? {} : void 0
394
+ };
395
+ }
396
+ return base;
397
+ }
398
+ async function promptForInitialPackage() {
399
+ const choice = await p.select({
400
+ message: "Add an initial package?",
401
+ options: [
402
+ { value: "app", label: "Application" },
403
+ { value: "library", label: "Library" },
404
+ { value: "skip", label: "Skip" }
405
+ ],
406
+ initialValue: "app"
407
+ });
408
+ if (p.isCancel(choice)) {
409
+ p.cancel("Operation cancelled.");
410
+ process.exit(0);
411
+ }
412
+ return choice;
413
+ }
414
+ function getDefaultMonorepoOptions(name) {
415
+ return {
416
+ name,
417
+ projectType: "monorepo",
418
+ packageManager: { name: "pnpm" },
419
+ pnpmManageVersions: true,
420
+ engine: { name: "node", version: "latest" },
421
+ linter: "oxlint",
422
+ formatter: "prettier"
423
+ };
424
+ }
425
+ async function promptForMonorepoCustomization(name, presets) {
426
+ const nodeVersion = await p.text({
427
+ message: "Node.js version",
428
+ placeholder: presets?.engine?.version ?? "latest",
429
+ defaultValue: presets?.engine?.version ?? "latest",
430
+ validate: (value) => {
431
+ if (!value.length) return "Required";
432
+ if (value !== "latest" && !/^\d+(\.\d+(\.\d+)?)?$/.test(value)) {
433
+ return 'Must be "latest" or a valid semver (e.g., "22" or "22.13.0")';
434
+ }
435
+ }
436
+ });
437
+ if (p.isCancel(nodeVersion)) {
438
+ p.cancel("Operation cancelled.");
439
+ process.exit(0);
440
+ }
441
+ const managePnpm = await p.confirm({
442
+ message: "Enable manage-package-manager-versions?",
443
+ initialValue: presets?.pnpmManageVersions ?? true
444
+ });
445
+ if (p.isCancel(managePnpm)) {
446
+ p.cancel("Operation cancelled.");
447
+ process.exit(0);
448
+ }
449
+ const linter = await p.select({
450
+ message: "Linter",
451
+ options: [
452
+ { value: "oxlint", label: "Oxlint", hint: "fast, from OXC" },
453
+ { value: "eslint", label: "ESLint", hint: "classic" },
454
+ { value: "biome", label: "Biome", hint: "all-in-one" }
455
+ ],
456
+ initialValue: presets?.linter ?? "oxlint"
457
+ });
458
+ if (p.isCancel(linter)) {
459
+ p.cancel("Operation cancelled.");
460
+ process.exit(0);
461
+ }
462
+ const formatter = await p.select({
463
+ message: "Formatter",
464
+ options: [
465
+ { value: "prettier", label: "Prettier", hint: "widely adopted" },
466
+ { value: "oxfmt", label: "Oxfmt", hint: "fast, Prettier-compatible" },
467
+ { value: "biome", label: "Biome", hint: "all-in-one" }
468
+ ],
469
+ initialValue: presets?.formatter ?? "prettier"
470
+ });
471
+ if (p.isCancel(formatter)) {
472
+ p.cancel("Operation cancelled.");
473
+ process.exit(0);
474
+ }
475
+ return {
476
+ name,
477
+ projectType: "monorepo",
478
+ engine: { name: "node", version: nodeVersion },
479
+ packageManager: { name: "pnpm" },
480
+ pnpmManageVersions: managePnpm,
481
+ linter,
482
+ formatter
483
+ };
484
+ }
485
+ async function promptForMonorepo(workspaceName, presets) {
486
+ const defaultOptions = getDefaultMonorepoOptions(workspaceName);
487
+ if (presets) {
488
+ if (presets.linter) defaultOptions.linter = presets.linter;
489
+ if (presets.formatter) defaultOptions.formatter = presets.formatter;
490
+ if (presets.engine) defaultOptions.engine = presets.engine;
491
+ if (presets.pnpmManageVersions !== void 0)
492
+ defaultOptions.pnpmManageVersions = presets.pnpmManageVersions;
493
+ }
494
+ p.note(
495
+ formatMonorepoConfigSummary({
496
+ name: defaultOptions.name,
497
+ engine: defaultOptions.engine ?? { name: "node", version: "latest" },
498
+ packageManager: getPackageManagerName(defaultOptions.packageManager),
499
+ pnpmManageVersions: defaultOptions.pnpmManageVersions,
500
+ linter: defaultOptions.linter ?? "oxlint",
501
+ formatter: defaultOptions.formatter ?? "prettier"
502
+ }),
503
+ "Workspace Configuration"
504
+ );
505
+ const proceed = await p.select({
506
+ message: "Proceed with these settings?",
507
+ options: [
508
+ { value: "continue", label: "Yes, continue" },
509
+ { value: "customize", label: "No, customize settings" }
510
+ ],
511
+ initialValue: "continue"
512
+ });
513
+ if (p.isCancel(proceed)) {
514
+ p.cancel("Operation cancelled.");
515
+ process.exit(0);
516
+ }
517
+ if (proceed === "continue") {
518
+ return defaultOptions;
519
+ }
520
+ return promptForMonorepoCustomization(workspaceName, presets);
521
+ }
522
+ async function promptForOptions(name, presets) {
523
+ let projectName = name;
524
+ if (!projectName) {
525
+ const nameResult = await p.text({
526
+ message: "What is your project named?",
527
+ placeholder: generateRandomName(),
528
+ defaultValue: generateRandomName(),
529
+ validate: (value) => {
530
+ if (!value.length) return "Project name is required";
531
+ }
532
+ });
533
+ if (p.isCancel(nameResult)) {
534
+ p.cancel("Operation cancelled.");
535
+ process.exit(0);
536
+ }
537
+ projectName = nameResult;
538
+ }
539
+ const projectType = await p.select({
540
+ message: "Project type",
541
+ options: [
542
+ { value: "app", label: "Application" },
543
+ { value: "library", label: "Library" },
544
+ { value: "monorepo", label: "Monorepo", hint: "experimental" }
545
+ ],
546
+ initialValue: presets?.type ?? "app"
547
+ });
548
+ if (p.isCancel(projectType)) {
549
+ p.cancel("Operation cancelled.");
550
+ process.exit(0);
551
+ }
552
+ if (projectType === "monorepo") {
553
+ return promptForMonorepo(projectName, presets);
554
+ }
555
+ return promptForPackageOptions(projectName, projectType, void 0, presets);
556
+ }
557
+ function customTemplateToOptions(customTemplate, name, projectType, inheritedSettings) {
558
+ const baseTemplate = customTemplate.baseTemplate;
559
+ const template = baseTemplate;
560
+ const base = {
561
+ name,
562
+ template,
563
+ projectType,
564
+ packageManager: inheritedSettings?.packageManager ?? { name: "pnpm" },
565
+ pnpmManageVersions: inheritedSettings?.pnpmManageVersions ?? true,
566
+ engine: inheritedSettings?.engine ?? { name: "node", version: "latest" },
567
+ linter: inheritedSettings?.linter ?? customTemplate.linter,
568
+ formatter: inheritedSettings?.formatter ?? customTemplate.formatter,
569
+ testing: customTemplate.testing,
570
+ configStrategy: customTemplate.configStrategy ?? getConfigStrategy()
571
+ };
572
+ if (baseTemplate === "r3f" && customTemplate.integrations) {
573
+ const integrations = customTemplate.integrations;
574
+ return {
575
+ ...base,
576
+ drei: integrations.includes("drei") ? {} : void 0,
577
+ handle: integrations.includes("handle") ? {} : void 0,
578
+ leva: integrations.includes("leva") ? {} : void 0,
579
+ postprocessing: integrations.includes("postprocessing") ? {} : void 0,
580
+ rapier: integrations.includes("rapier") ? {} : void 0,
581
+ xr: integrations.includes("xr") ? {} : void 0,
582
+ uikit: integrations.includes("uikit") ? {} : void 0,
583
+ offscreen: integrations.includes("offscreen") ? {} : void 0,
584
+ zustand: integrations.includes("zustand") ? {} : void 0,
585
+ koota: integrations.includes("koota") ? {} : void 0,
586
+ triplex: integrations.includes("triplex") ? {} : void 0,
587
+ viverse: integrations.includes("viverse") ? {} : void 0
588
+ };
589
+ }
590
+ return base;
591
+ }
592
+ function presetsToInheritedSettings(presets) {
593
+ if (!presets) return void 0;
594
+ return {
595
+ linter: presets.linter,
596
+ formatter: presets.formatter,
597
+ packageManager: presets.packageManager ? { name: presets.packageManager } : void 0,
598
+ engine: presets.engine,
599
+ pnpmManageVersions: presets.pnpmManageVersions
600
+ };
601
+ }
602
+ async function promptForPackageOptions(projectName, projectType, inheritedSettings, presets) {
603
+ const builtInOptions = [
604
+ { value: "vanilla", label: "Vanilla" },
605
+ { value: "react", label: "React", hint: "experimental" },
606
+ { value: "r3f", label: "React Three Fiber", hint: "experimental" }
607
+ ];
608
+ const customTemplates = getCustomTemplates();
609
+ const customOptions = Object.keys(customTemplates).map((name) => ({
610
+ value: `custom:${name}`,
611
+ label: name,
612
+ hint: "saved template"
613
+ }));
614
+ const allOptions = [...builtInOptions, ...customOptions];
615
+ const templateSelection = await p.select({
616
+ message: "Select a template",
617
+ options: allOptions,
618
+ initialValue: presets?.template ?? "vanilla"
619
+ });
620
+ if (p.isCancel(templateSelection)) {
621
+ p.cancel("Operation cancelled.");
622
+ process.exit(0);
623
+ }
624
+ const selection = templateSelection;
625
+ if (selection.startsWith("custom:")) {
626
+ const customName = selection.slice(7);
627
+ const customTemplate = customTemplates[customName];
628
+ const defaultOptions2 = customTemplateToOptions(
629
+ customTemplate,
630
+ projectName,
631
+ projectType,
632
+ inheritedSettings
633
+ );
634
+ const configTitle2 = inheritedSettings ? `Template: ${customName} (using workspace settings)` : `Template: ${customName}`;
635
+ p.note(formatConfigSummary(defaultOptions2, inheritedSettings), configTitle2);
636
+ const proceed2 = await p.select({
637
+ message: "Proceed with these settings?",
638
+ options: [
639
+ { value: "continue", label: "Yes, continue" },
640
+ { value: "customize", label: "No, customize settings" }
641
+ ],
642
+ initialValue: "continue"
643
+ });
644
+ if (p.isCancel(proceed2)) {
645
+ p.cancel("Operation cancelled.");
646
+ process.exit(0);
647
+ }
648
+ if (proceed2 === "continue") {
649
+ return defaultOptions2;
650
+ }
651
+ return promptForCustomization(
652
+ customTemplate.baseTemplate,
653
+ projectName,
654
+ projectType,
655
+ customTemplate.integrations,
656
+ inheritedSettings
657
+ );
658
+ }
659
+ const template = selection;
660
+ const baseTemplate = getBaseTemplate(template);
661
+ let integrations;
662
+ if (baseTemplate === "r3f") {
663
+ integrations = await promptForR3fIntegrations(presets);
664
+ }
665
+ const defaultOptions = getDefaultOptions(
666
+ template,
667
+ projectName,
668
+ projectType,
669
+ presets?.bundler,
670
+ integrations,
671
+ inheritedSettings ?? presetsToInheritedSettings(presets)
672
+ );
673
+ const configTitle = inheritedSettings ? "Template Configuration (using workspace settings)" : "Template Configuration";
674
+ p.note(formatConfigSummary(defaultOptions, inheritedSettings), configTitle);
675
+ const proceed = await p.select({
676
+ message: "Proceed with these settings?",
677
+ options: [
678
+ { value: "continue", label: "Yes, continue" },
679
+ { value: "customize", label: "No, customize settings" }
680
+ ],
681
+ initialValue: "continue"
682
+ });
683
+ if (p.isCancel(proceed)) {
684
+ p.cancel("Operation cancelled.");
685
+ process.exit(0);
686
+ }
687
+ if (proceed === "continue") {
688
+ return defaultOptions;
689
+ }
690
+ return promptForCustomization(
691
+ template,
692
+ projectName,
693
+ projectType,
694
+ integrations,
695
+ inheritedSettings,
696
+ presets
697
+ );
698
+ }
699
+
700
+ async function detectCurrentConfig(root, isMonorepo = true) {
701
+ let name = root.split(/[/\\]/).pop() ?? "workspace";
702
+ let packageManager = "pnpm";
703
+ try {
704
+ const pkgPath = join(root, "package.json");
705
+ const content = await readFile(pkgPath, "utf-8");
706
+ const pkgJson = JSON.parse(content);
707
+ if (pkgJson.name) {
708
+ name = pkgJson.name.replace(/^@/, "").replace(/\/.*$/, "");
709
+ }
710
+ if (pkgJson.packageManager) {
711
+ packageManager = pkgJson.packageManager.split("@")[0] ?? packageManager;
712
+ }
713
+ } catch {
714
+ }
715
+ const tooling = await detectTooling(root);
716
+ const configStrategy = isMonorepo ? void 0 : await detectStandaloneConfigStrategy(root);
717
+ return {
718
+ name,
719
+ linter: tooling.linter ?? "oxlint",
720
+ formatter: tooling.formatter ?? "prettier",
721
+ packageManager,
722
+ isMonorepo,
723
+ configStrategy
724
+ };
725
+ }
726
+ async function detectStandaloneConfigStrategy(root) {
727
+ const hasStealthConfig = await Promise.all([
728
+ fileExists$1(join(root, ".config/tsconfig.app.json")),
729
+ fileExists$1(join(root, ".config/tsconfig.node.json")),
730
+ fileExists$1(join(root, ".config/prettier.json")),
731
+ fileExists$1(join(root, ".config/oxlint.json"))
732
+ ]).then((matches) => matches.some(Boolean));
733
+ return hasStealthConfig ? "stealth" : "root";
734
+ }
735
+ async function generateExpectedFiles(config) {
736
+ const { name, linter, formatter, packageManager, isMonorepo, configStrategy } = config;
737
+ const versions = linter === "biome" || formatter === "biome" ? await resolveMonorepoRootPackageVersions({ linter, formatter }) : {};
738
+ const aiFilesMap = {};
739
+ generateAiFiles(aiFilesMap, {
740
+ name,
741
+ packageManager,
742
+ linter,
743
+ formatter,
744
+ isMonorepo,
745
+ configStrategy,
746
+ platforms: ALL_AI_PLATFORMS
747
+ });
748
+ const vscodeFiles = {};
749
+ generateVscodeFiles(vscodeFiles, linter, formatter);
750
+ const configPackages = {};
751
+ if (isMonorepo) {
752
+ generateTypescriptConfigPackage(configPackages);
753
+ if (linter === "oxlint") {
754
+ generateOxlintConfigPackage(configPackages);
755
+ } else if (linter === "eslint") {
756
+ generateEslintConfigPackage(configPackages);
757
+ }
758
+ if (formatter === "oxfmt") {
759
+ generateOxfmtConfigPackage(configPackages);
760
+ } else if (formatter === "prettier") {
761
+ generatePrettierConfigPackage(configPackages);
762
+ }
763
+ }
764
+ const workspaceConfig = {};
765
+ const rootConfig = {};
766
+ rootConfig[".gitignore"] = generateGitignore(isMonorepo ? "workspace-root" : "standalone");
767
+ rootConfig[".gitattributes"] = {
768
+ type: "text",
769
+ content: `* text=auto eol=lf
770
+ *.{cmd,[cC][mM][dD]} text eol=crlf
771
+ *.{bat,[bB][aA][tT]} text eol=crlf
772
+ `
773
+ };
774
+ if (linter === "biome" || formatter === "biome") {
775
+ const biomeVersion = getResolvedPackageVersion(versions, "@biomejs/biome");
776
+ const biomeConfig = {
777
+ $schema: `https://biomejs.dev/schemas/${biomeVersion}/schema.json`,
778
+ vcs: {
779
+ enabled: true,
780
+ clientKind: "git",
781
+ useIgnoreFile: true
782
+ },
783
+ linter: {
784
+ enabled: linter === "biome",
785
+ rules: {
786
+ recommended: true
787
+ }
788
+ },
789
+ formatter: {
790
+ enabled: formatter === "biome"
791
+ }
792
+ };
793
+ rootConfig["biome.json"] = {
794
+ type: "text",
795
+ content: JSON.stringify(biomeConfig, null, 2)
796
+ };
797
+ }
798
+ return {
799
+ "ai-files": aiFilesMap,
800
+ vscode: vscodeFiles,
801
+ "config-packages": configPackages,
802
+ "workspace-config": workspaceConfig,
803
+ "root-config": rootConfig
804
+ };
805
+ }
806
+ async function fileExists$1(path) {
807
+ try {
808
+ await access(path, constants.F_OK);
809
+ return true;
810
+ } catch {
811
+ return false;
812
+ }
813
+ }
814
+ async function compareWithDisk(expected, root) {
815
+ const categoryLabels = {
816
+ "ai-files": "AI Files",
817
+ vscode: "VS Code",
818
+ "config-packages": "Config Packages",
819
+ "workspace-config": "Workspace Config",
820
+ "root-config": "Root Config"
821
+ };
822
+ const categories = [];
823
+ for (const [category, files] of Object.entries(expected)) {
824
+ const changes = [];
825
+ for (const [filePath, file] of Object.entries(files)) {
826
+ if (file.type !== "text") continue;
827
+ const fullPath = join(root, filePath);
828
+ const newContent = file.content;
829
+ if (await fileExists$1(fullPath)) {
830
+ const currentContent = await readFile(fullPath, "utf-8");
831
+ if (currentContent === newContent) {
832
+ changes.push({
833
+ path: filePath,
834
+ status: "unchanged",
835
+ currentContent,
836
+ newContent
837
+ });
838
+ } else {
839
+ changes.push({
840
+ path: filePath,
841
+ status: "modified",
842
+ currentContent,
843
+ newContent
844
+ });
845
+ }
846
+ } else {
847
+ changes.push({
848
+ path: filePath,
849
+ status: "added",
850
+ newContent
851
+ });
852
+ }
853
+ }
854
+ if (changes.length === 0) continue;
855
+ const hasUserModifications = changes.some((c) => c.status === "modified");
856
+ categories.push({
857
+ category,
858
+ label: categoryLabels[category],
859
+ changes,
860
+ hasUserModifications
861
+ });
862
+ }
863
+ return categories;
864
+ }
865
+ async function getWorkspaceConfigUpdates(root) {
866
+ const workspacePath = join(root, "pnpm-workspace.yaml");
867
+ const changes = [];
868
+ let currentContent = "";
869
+ let exists = false;
870
+ try {
871
+ currentContent = await readFile(workspacePath, "utf-8");
872
+ exists = true;
873
+ } catch {
874
+ }
875
+ if (!exists) {
876
+ const newContent = `manage-package-manager-versions: true
877
+
878
+ packages:
879
+ - ".config/*"
880
+ - "apps/*"
881
+ - "packages/*"
882
+
883
+ onlyBuiltDependencies:
884
+ - esbuild
885
+ `;
886
+ changes.push({
887
+ path: "pnpm-workspace.yaml",
888
+ status: "added",
889
+ newContent
890
+ });
891
+ return changes;
892
+ }
893
+ let updatedContent = currentContent;
894
+ let needsUpdate = false;
895
+ if (!currentContent.includes("manage-package-manager-versions")) {
896
+ updatedContent = `manage-package-manager-versions: true
897
+
898
+ ${updatedContent}`;
899
+ needsUpdate = true;
900
+ }
901
+ if (!currentContent.includes("onlyBuiltDependencies")) {
902
+ updatedContent = `${updatedContent.trimEnd()}
903
+
904
+ onlyBuiltDependencies:
905
+ - esbuild
906
+ `;
907
+ needsUpdate = true;
908
+ }
909
+ if (!currentContent.includes(".config/*") && !currentContent.includes('".config/*"')) {
910
+ const lines = updatedContent.split("\n");
911
+ const packagesIndex = lines.findIndex((line) => line.trim().startsWith("packages:"));
912
+ if (packagesIndex !== -1) {
913
+ lines.splice(packagesIndex + 1, 0, ' - ".config/*"');
914
+ updatedContent = lines.join("\n");
915
+ needsUpdate = true;
916
+ }
917
+ }
918
+ if (needsUpdate) {
919
+ changes.push({
920
+ path: "pnpm-workspace.yaml",
921
+ status: "modified",
922
+ currentContent,
923
+ newContent: updatedContent
924
+ });
925
+ } else {
926
+ changes.push({
927
+ path: "pnpm-workspace.yaml",
928
+ status: "unchanged",
929
+ currentContent,
930
+ newContent: currentContent
931
+ });
932
+ }
933
+ return changes;
934
+ }
935
+ async function applyUpdates(changes, root) {
936
+ for (const change of changes) {
937
+ if (change.status === "unchanged") continue;
938
+ const fullPath = join(root, change.path);
939
+ await mkdir(dirname(fullPath), { recursive: true });
940
+ await writeFile(fullPath, change.newContent);
941
+ }
942
+ }
943
+ function formatFileChange(change) {
944
+ const icon = change.status === "added" ? "+" : change.status === "modified" ? "~" : "=";
945
+ return ` ${icon} ${change.path}`;
946
+ }
947
+ const LINTER_DEPS = {
948
+ oxlint: "oxlint",
949
+ eslint: "eslint",
950
+ biome: "@biomejs/biome"
951
+ };
952
+ const FORMATTER_DEPS = {
953
+ oxfmt: "oxfmt",
954
+ prettier: "prettier",
955
+ biome: "@biomejs/biome"
956
+ };
957
+ const LINTER_CONFIG_PACKAGES = {
958
+ oxlint: "@config/oxlint",
959
+ eslint: "@config/eslint",
960
+ biome: null
961
+ // biome uses root biome.json
962
+ };
963
+ const FORMATTER_CONFIG_PACKAGES = {
964
+ oxfmt: "@config/oxfmt",
965
+ prettier: "@config/prettier",
966
+ biome: null
967
+ // biome uses root biome.json
968
+ };
969
+ function needsMigration(current, target) {
970
+ const linterChange = target.linter && target.linter !== current.linter;
971
+ const formatterChange = target.formatter && target.formatter !== current.formatter;
972
+ return linterChange || formatterChange || false;
973
+ }
974
+ async function getMigrationPlan(current, target, root) {
975
+ const toLinter = target.linter ?? current.linter;
976
+ const toFormatter = target.formatter ?? current.formatter;
977
+ const targetVersions = toLinter === "biome" || toFormatter === "biome" ? await resolveMonorepoRootPackageVersions({
978
+ linter: toLinter,
979
+ formatter: toFormatter
980
+ }) : {};
981
+ const biomeSchemaUrl = toLinter === "biome" || toFormatter === "biome" ? `https://biomejs.dev/schemas/${getResolvedPackageVersion(
982
+ targetVersions,
983
+ "@biomejs/biome"
984
+ )}/schema.json` : "";
985
+ const changes = [];
986
+ if (toLinter !== current.linter) {
987
+ if (current.linter !== "biome") {
988
+ changes.push({
989
+ type: "remove-dir",
990
+ path: `.config/${current.linter}`,
991
+ description: `Remove @config/${current.linter} package`
992
+ });
993
+ }
994
+ if (toLinter !== "biome") {
995
+ const files = {};
996
+ if (toLinter === "oxlint") {
997
+ generateOxlintConfigPackage(files);
998
+ } else if (toLinter === "eslint") {
999
+ generateEslintConfigPackage(files);
1000
+ }
1001
+ for (const [path, file] of Object.entries(files)) {
1002
+ if (file.type === "text") {
1003
+ changes.push({
1004
+ type: "add-file",
1005
+ path,
1006
+ description: `Add ${path}`,
1007
+ content: file.content
1008
+ });
1009
+ }
1010
+ }
1011
+ }
1012
+ if (toLinter === "biome" && toFormatter === "biome") {
1013
+ changes.push({
1014
+ type: "add-file",
1015
+ path: "biome.json",
1016
+ description: "Add biome.json config",
1017
+ content: JSON.stringify(
1018
+ {
1019
+ $schema: biomeSchemaUrl,
1020
+ vcs: { enabled: true, clientKind: "git", useIgnoreFile: true },
1021
+ linter: { enabled: true, rules: { recommended: true } },
1022
+ formatter: { enabled: true }
1023
+ },
1024
+ null,
1025
+ 2
1026
+ )
1027
+ });
1028
+ } else if (toLinter === "biome" && toFormatter !== "biome") {
1029
+ changes.push({
1030
+ type: "add-file",
1031
+ path: "biome.json",
1032
+ description: "Add biome.json config (linter only)",
1033
+ content: JSON.stringify(
1034
+ {
1035
+ $schema: biomeSchemaUrl,
1036
+ vcs: { enabled: true, clientKind: "git", useIgnoreFile: true },
1037
+ linter: { enabled: true, rules: { recommended: true } },
1038
+ formatter: { enabled: false }
1039
+ },
1040
+ null,
1041
+ 2
1042
+ )
1043
+ });
1044
+ }
1045
+ if (current.linter === "biome" && toLinter !== "biome" && current.formatter !== "biome" && toFormatter !== "biome") {
1046
+ changes.push({
1047
+ type: "remove-file",
1048
+ path: "biome.json",
1049
+ description: "Remove biome.json"
1050
+ });
1051
+ }
1052
+ }
1053
+ if (toFormatter !== current.formatter) {
1054
+ const formatterSameAsLinter = current.formatter === current.linter;
1055
+ if (current.formatter !== "biome" && !formatterSameAsLinter) {
1056
+ changes.push({
1057
+ type: "remove-dir",
1058
+ path: `.config/${current.formatter}`,
1059
+ description: `Remove @config/${current.formatter} package`
1060
+ });
1061
+ }
1062
+ const newFormatterSameAsLinter = toFormatter === toLinter;
1063
+ if (toFormatter !== "biome" && !newFormatterSameAsLinter) {
1064
+ const files = {};
1065
+ if (toFormatter === "oxfmt") {
1066
+ generateOxfmtConfigPackage(files);
1067
+ } else if (toFormatter === "prettier") {
1068
+ generatePrettierConfigPackage(files);
1069
+ }
1070
+ for (const [path, file] of Object.entries(files)) {
1071
+ if (file.type === "text") {
1072
+ changes.push({
1073
+ type: "add-file",
1074
+ path,
1075
+ description: `Add ${path}`,
1076
+ content: file.content
1077
+ });
1078
+ }
1079
+ }
1080
+ }
1081
+ if (toFormatter === "biome" && toLinter !== "biome") {
1082
+ changes.push({
1083
+ type: "add-file",
1084
+ path: "biome.json",
1085
+ description: "Add biome.json config (formatter only)",
1086
+ content: JSON.stringify(
1087
+ {
1088
+ $schema: biomeSchemaUrl,
1089
+ vcs: { enabled: true, clientKind: "git", useIgnoreFile: true },
1090
+ linter: { enabled: false },
1091
+ formatter: { enabled: true }
1092
+ },
1093
+ null,
1094
+ 2
1095
+ )
1096
+ });
1097
+ }
1098
+ if (current.formatter === "biome" && toFormatter !== "biome" && current.linter !== "biome" && toLinter !== "biome") {
1099
+ changes.push({
1100
+ type: "remove-file",
1101
+ path: "biome.json",
1102
+ description: "Remove biome.json"
1103
+ });
1104
+ }
1105
+ }
1106
+ changes.push({
1107
+ type: "update-package-json",
1108
+ path: "package.json",
1109
+ description: "Update root package.json (devDependencies, scripts)"
1110
+ });
1111
+ const subPackageUpdates = await getSubPackageUpdates(root, current, toLinter, toFormatter);
1112
+ return {
1113
+ fromLinter: current.linter,
1114
+ toLinter,
1115
+ fromFormatter: current.formatter,
1116
+ toFormatter,
1117
+ changes,
1118
+ subPackageUpdates
1119
+ };
1120
+ }
1121
+ async function getSubPackageUpdates(root, current, toLinter, toFormatter) {
1122
+ const updates = [];
1123
+ const workspacePath = join(root, "pnpm-workspace.yaml");
1124
+ let workspaceContent;
1125
+ try {
1126
+ workspaceContent = await readFile(workspacePath, "utf-8");
1127
+ } catch {
1128
+ return updates;
1129
+ }
1130
+ const packageGlobs = parseWorkspaceYamlContent(workspaceContent);
1131
+ for (const glob of packageGlobs) {
1132
+ if (glob.includes(".config")) continue;
1133
+ const baseDir = glob.replace(/\/\*$/, "").replace(/^["']|["']$/g, "");
1134
+ const basePath = join(root, baseDir);
1135
+ try {
1136
+ const entries = await readdir(basePath, { withFileTypes: true });
1137
+ for (const entry of entries) {
1138
+ if (!entry.isDirectory()) continue;
1139
+ const pkgJsonPath = join(basePath, entry.name, "package.json");
1140
+ try {
1141
+ const content = await readFile(pkgJsonPath, "utf-8");
1142
+ const pkg = JSON.parse(content);
1143
+ const devDeps = pkg.devDependencies ?? {};
1144
+ const remove = [];
1145
+ const add = [];
1146
+ const oldLinterPkg = LINTER_CONFIG_PACKAGES[current.linter];
1147
+ const newLinterPkg = LINTER_CONFIG_PACKAGES[toLinter];
1148
+ if (oldLinterPkg && oldLinterPkg !== newLinterPkg && devDeps[oldLinterPkg]) {
1149
+ remove.push(oldLinterPkg);
1150
+ }
1151
+ if (newLinterPkg && newLinterPkg !== oldLinterPkg && oldLinterPkg && devDeps[oldLinterPkg]) {
1152
+ add.push(newLinterPkg);
1153
+ }
1154
+ if (current.formatter !== current.linter) {
1155
+ const oldFormatterPkg = FORMATTER_CONFIG_PACKAGES[current.formatter];
1156
+ const newFormatterPkg = FORMATTER_CONFIG_PACKAGES[toFormatter];
1157
+ if (oldFormatterPkg && oldFormatterPkg !== newFormatterPkg && devDeps[oldFormatterPkg]) {
1158
+ remove.push(oldFormatterPkg);
1159
+ }
1160
+ if (newFormatterPkg && newFormatterPkg !== oldFormatterPkg && oldFormatterPkg && devDeps[oldFormatterPkg]) {
1161
+ add.push(newFormatterPkg);
1162
+ }
1163
+ }
1164
+ if (remove.length > 0 || add.length > 0) {
1165
+ updates.push({
1166
+ path: join(baseDir, entry.name, "package.json"),
1167
+ remove,
1168
+ add
1169
+ });
1170
+ }
1171
+ } catch {
1172
+ }
1173
+ }
1174
+ } catch {
1175
+ }
1176
+ }
1177
+ return updates;
1178
+ }
1179
+ async function applyMigration(plan, root) {
1180
+ for (const change of plan.changes) {
1181
+ if (change.type === "remove-dir") {
1182
+ const fullPath = join(root, change.path);
1183
+ try {
1184
+ await rm(fullPath, { recursive: true });
1185
+ } catch {
1186
+ }
1187
+ }
1188
+ }
1189
+ for (const change of plan.changes) {
1190
+ if (change.type === "remove-file") {
1191
+ const fullPath = join(root, change.path);
1192
+ try {
1193
+ await rm(fullPath);
1194
+ } catch {
1195
+ }
1196
+ }
1197
+ }
1198
+ for (const change of plan.changes) {
1199
+ if (change.type === "add-file" && change.content) {
1200
+ const fullPath = join(root, change.path);
1201
+ await mkdir(dirname(fullPath), { recursive: true });
1202
+ await writeFile(fullPath, change.content);
1203
+ }
1204
+ }
1205
+ await updateRootPackageJson(root, plan);
1206
+ for (const update of plan.subPackageUpdates) {
1207
+ await updateSubPackageJson(root, update);
1208
+ }
1209
+ }
1210
+ async function updateRootPackageJson(root, plan) {
1211
+ const pkgPath = join(root, "package.json");
1212
+ const content = await readFile(pkgPath, "utf-8");
1213
+ const pkg = JSON.parse(content);
1214
+ const devDeps = pkg.devDependencies ?? {};
1215
+ const oldLinterDep = LINTER_DEPS[plan.fromLinter];
1216
+ delete devDeps[oldLinterDep];
1217
+ if (plan.fromFormatter !== plan.fromLinter) {
1218
+ const oldFormatterDep = FORMATTER_DEPS[plan.fromFormatter];
1219
+ delete devDeps[oldFormatterDep];
1220
+ }
1221
+ const resolvedVersions = await resolveMonorepoRootPackageVersions({
1222
+ linter: plan.toLinter,
1223
+ formatter: plan.toFormatter
1224
+ });
1225
+ const newLinterDep = LINTER_DEPS[plan.toLinter];
1226
+ devDeps[newLinterDep] = formatResolvedPackageVersion(resolvedVersions, newLinterDep);
1227
+ if (plan.toFormatter !== plan.toLinter) {
1228
+ const newFormatterDep = FORMATTER_DEPS[plan.toFormatter];
1229
+ devDeps[newFormatterDep] = formatResolvedPackageVersion(resolvedVersions, newFormatterDep);
1230
+ }
1231
+ pkg.devDependencies = Object.fromEntries(
1232
+ Object.entries(devDeps).sort(([a], [b]) => a.localeCompare(b))
1233
+ );
1234
+ const scripts = pkg.scripts ?? {};
1235
+ if (plan.toLinter === "oxlint") {
1236
+ scripts.lint = "oxlint .";
1237
+ } else if (plan.toLinter === "eslint") {
1238
+ scripts.lint = "eslint .";
1239
+ } else if (plan.toLinter === "biome") {
1240
+ scripts.lint = "biome check .";
1241
+ }
1242
+ if (plan.toFormatter === "oxfmt") {
1243
+ scripts.format = "oxfmt .";
1244
+ } else if (plan.toFormatter === "prettier") {
1245
+ scripts.format = "prettier --write .";
1246
+ } else if (plan.toFormatter === "biome") {
1247
+ scripts.format = "biome format . --write";
1248
+ }
1249
+ pkg.scripts = scripts;
1250
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
1251
+ }
1252
+ async function updateSubPackageJson(root, update) {
1253
+ const pkgPath = join(root, update.path);
1254
+ const content = await readFile(pkgPath, "utf-8");
1255
+ const pkg = JSON.parse(content);
1256
+ const devDeps = pkg.devDependencies ?? {};
1257
+ for (const dep of update.remove) {
1258
+ delete devDeps[dep];
1259
+ }
1260
+ for (const dep of update.add) {
1261
+ devDeps[dep] = "workspace:*";
1262
+ }
1263
+ pkg.devDependencies = Object.fromEntries(
1264
+ Object.entries(devDeps).sort(([a], [b]) => a.localeCompare(b))
1265
+ );
1266
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
1267
+ }
1268
+ function formatMigrationChange(change) {
1269
+ const icon = change.type === "remove-dir" || change.type === "remove-file" ? "-" : change.type === "add-file" ? "+" : "~";
1270
+ return ` ${icon} ${change.description}`;
1271
+ }
1272
+
1273
+ async function checkAnyExists(paths) {
1274
+ for (const path of paths) {
1275
+ try {
1276
+ await access(path, constants$1.F_OK);
1277
+ return true;
1278
+ } catch {
1279
+ }
1280
+ }
1281
+ return false;
1282
+ }
1283
+ async function validateWorkspace(monorepoRoot) {
1284
+ const errors = [];
1285
+ const tsConfigPath = join(monorepoRoot, ".config/typescript/package.json");
1286
+ try {
1287
+ await access(tsConfigPath, constants$1.F_OK);
1288
+ } catch {
1289
+ errors.push("Missing .config/typescript package");
1290
+ }
1291
+ const linterPaths = [
1292
+ join(monorepoRoot, ".config/oxlint/package.json"),
1293
+ join(monorepoRoot, ".config/eslint/package.json"),
1294
+ join(monorepoRoot, "eslint.config.js"),
1295
+ join(monorepoRoot, "biome.json")
1296
+ ];
1297
+ const hasLinter = await checkAnyExists(linterPaths);
1298
+ if (!hasLinter) {
1299
+ errors.push(
1300
+ "Missing linter config (.config/oxlint, .config/eslint, eslint.config.js, or biome.json)"
1301
+ );
1302
+ }
1303
+ const formatterPaths = [
1304
+ join(monorepoRoot, ".config/oxfmt/package.json"),
1305
+ join(monorepoRoot, ".config/prettier/package.json"),
1306
+ join(monorepoRoot, ".prettierrc.json"),
1307
+ join(monorepoRoot, "biome.json")
1308
+ ];
1309
+ const hasFormatter = await checkAnyExists(formatterPaths);
1310
+ if (!hasFormatter) {
1311
+ errors.push(
1312
+ "Missing formatter config (.config/oxfmt, .config/prettier, .prettierrc.json, or biome.json)"
1313
+ );
1314
+ }
1315
+ return { valid: errors.length === 0, errors };
1316
+ }
1317
+
1318
+ const require$1 = createRequire(import.meta.url);
1319
+ const pkg = require$1("../package.json");
1320
+ const META_OPTIONS = [
1321
+ "clearConfig",
1322
+ "configPath",
1323
+ "check",
1324
+ "fix",
1325
+ "update",
1326
+ "yes",
1327
+ "workspace",
1328
+ "path",
1329
+ "dir"
1330
+ ];
1331
+ function hasConfigOptions(options) {
1332
+ return Object.keys(options).some(
1333
+ (key) => !META_OPTIONS.includes(key)
1334
+ );
1335
+ }
1336
+ async function fileExists(path) {
1337
+ try {
1338
+ await access$1(path, constants$2.F_OK);
1339
+ return true;
1340
+ } catch {
1341
+ return false;
1342
+ }
1343
+ }
1344
+ async function promptForAiPlatforms(isNonInteractive) {
1345
+ const savedPlatforms = getAiPlatforms();
1346
+ if (isNonInteractive) {
1347
+ return savedPlatforms ?? ALL_AI_PLATFORMS;
1348
+ }
1349
+ if (savedPlatforms && savedPlatforms.length > 0) {
1350
+ const savedLabels = savedPlatforms.map((plat) => AI_PLATFORM_LABELS[plat]).join(", ");
1351
+ const useDefault = await p.confirm({
1352
+ message: `Add AI rules? ${color.dim(`(${savedLabels})`)}`,
1353
+ initialValue: true
1354
+ });
1355
+ if (p.isCancel(useDefault)) {
1356
+ return [];
1357
+ }
1358
+ if (useDefault) {
1359
+ return savedPlatforms;
1360
+ }
1361
+ }
1362
+ const selected = await p.multiselect({
1363
+ message: "Add AI rules?",
1364
+ options: ALL_AI_PLATFORMS.map((platform) => ({
1365
+ value: platform,
1366
+ label: AI_PLATFORM_LABELS[platform],
1367
+ hint: AI_PLATFORM_HINTS[platform]
1368
+ })),
1369
+ initialValues: ["agents"],
1370
+ required: false
1371
+ });
1372
+ if (p.isCancel(selected)) {
1373
+ return [];
1374
+ }
1375
+ const platforms = selected;
1376
+ if (platforms.length === 0) {
1377
+ return [];
1378
+ }
1379
+ return platforms;
1380
+ }
1381
+ async function writeGeneratedFiles(basePath, files) {
1382
+ const filePaths = Object.keys(files).sort();
1383
+ for (const filePath of filePaths) {
1384
+ const fullFilePath = join$1(basePath, filePath);
1385
+ await mkdir$1(dirname$1(fullFilePath), { recursive: true });
1386
+ const file = files[filePath];
1387
+ if (file.type === "text") {
1388
+ await writeFile$1(fullFilePath, file.content);
1389
+ } else {
1390
+ const response = await fetch(file.url);
1391
+ await writeFile$1(fullFilePath, response.body);
1392
+ }
1393
+ }
1394
+ }
1395
+ function calculateWorkspaceRoot(packagePath) {
1396
+ const segments = packagePath.split(/[/\\]/).filter(Boolean);
1397
+ return segments.map(() => "..").join("/");
1398
+ }
1399
+ async function detectMonorepoRoot() {
1400
+ let currentDir = cwd();
1401
+ const root = resolve("/");
1402
+ while (currentDir !== root) {
1403
+ const workspaceFile = join$1(currentDir, "pnpm-workspace.yaml");
1404
+ try {
1405
+ await access$1(workspaceFile, constants$2.F_OK);
1406
+ const content = await readFile$1(workspaceFile, "utf-8");
1407
+ if (content.includes("packages:")) {
1408
+ return currentDir;
1409
+ }
1410
+ } catch {
1411
+ }
1412
+ currentDir = dirname$1(currentDir);
1413
+ }
1414
+ return null;
1415
+ }
1416
+ async function detectPackageRoot() {
1417
+ let currentDir = cwd();
1418
+ const root = resolve("/");
1419
+ while (currentDir !== root) {
1420
+ if (await fileExists(join$1(currentDir, "package.json"))) {
1421
+ return currentDir;
1422
+ }
1423
+ currentDir = dirname$1(currentDir);
1424
+ }
1425
+ return await fileExists(join$1(root, "package.json")) ? root : null;
1426
+ }
1427
+ async function parseWorkspaceDirectories(monorepoRoot) {
1428
+ try {
1429
+ const workspaceFile = join$1(monorepoRoot, "pnpm-workspace.yaml");
1430
+ const content = await readFile$1(workspaceFile, "utf-8");
1431
+ return parseWorkspaceYamlContent(content);
1432
+ } catch {
1433
+ return [];
1434
+ }
1435
+ }
1436
+ async function detectWorkspaceSettings(monorepoRoot) {
1437
+ try {
1438
+ const tooling = await detectTooling(monorepoRoot);
1439
+ const pkgPath = join$1(monorepoRoot, "package.json");
1440
+ const content = await readFile$1(pkgPath, "utf-8");
1441
+ const pkgJson = JSON.parse(content);
1442
+ const packageManager = parsePackageManager(pkgJson.packageManager);
1443
+ const engine = parseEngine(pkgJson.engines);
1444
+ let pnpmManageVersions;
1445
+ try {
1446
+ const workspaceFile = join$1(monorepoRoot, "pnpm-workspace.yaml");
1447
+ const workspaceContent = await readFile$1(workspaceFile, "utf-8");
1448
+ pnpmManageVersions = workspaceContent.includes("manage-package-manager-versions: true");
1449
+ } catch {
1450
+ }
1451
+ return {
1452
+ linter: tooling.linter,
1453
+ formatter: tooling.formatter,
1454
+ packageManager,
1455
+ engine,
1456
+ pnpmManageVersions
1457
+ };
1458
+ } catch {
1459
+ return {};
1460
+ }
1461
+ }
1462
+ async function detectExistingConfigs(monorepoRoot) {
1463
+ const configs = {};
1464
+ const eslintPath = join$1(monorepoRoot, "eslint.config.js");
1465
+ if (await fileExists(eslintPath)) {
1466
+ configs.linter = "eslint";
1467
+ configs.eslintConfigPath = eslintPath;
1468
+ }
1469
+ const prettierPath = join$1(monorepoRoot, ".prettierrc.json");
1470
+ if (await fileExists(prettierPath)) {
1471
+ configs.formatter = "prettier";
1472
+ configs.prettierConfigPath = prettierPath;
1473
+ }
1474
+ const biomePath = join$1(monorepoRoot, "biome.json");
1475
+ if (await fileExists(biomePath)) {
1476
+ configs.biomeConfigPath = biomePath;
1477
+ if (!configs.linter) configs.linter = "biome";
1478
+ if (!configs.formatter) configs.formatter = "biome";
1479
+ }
1480
+ return configs;
1481
+ }
1482
+ async function getMonorepoScope(monorepoRoot) {
1483
+ try {
1484
+ const pkgPath = join$1(monorepoRoot, "package.json");
1485
+ const content = await readFile$1(pkgPath, "utf-8");
1486
+ const pkgJson = JSON.parse(content);
1487
+ if (pkgJson.name) {
1488
+ return pkgJson.name.replace(/^@/, "").replace(/\/.*$/, "");
1489
+ }
1490
+ } catch {
1491
+ }
1492
+ return monorepoRoot.split(/[/\\]/).pop() ?? "workspace";
1493
+ }
1494
+ async function getWorkspacePackages(monorepoRoot) {
1495
+ const packagesDir = join$1(monorepoRoot, "packages");
1496
+ try {
1497
+ const { readdir } = await import('fs/promises');
1498
+ const entries = await readdir(packagesDir, { withFileTypes: true });
1499
+ const names = [];
1500
+ for (const entry of entries) {
1501
+ if (!entry.isDirectory()) continue;
1502
+ try {
1503
+ const content = await readFile$1(
1504
+ join$1(packagesDir, entry.name, "package.json"),
1505
+ "utf-8"
1506
+ );
1507
+ const pkg2 = JSON.parse(content);
1508
+ if (pkg2.name) names.push(pkg2.name);
1509
+ } catch {
1510
+ }
1511
+ }
1512
+ return names;
1513
+ } catch {
1514
+ return [];
1515
+ }
1516
+ }
1517
+ async function ensureConfigInWorkspace(monorepoRoot) {
1518
+ const workspacePath = join$1(monorepoRoot, "pnpm-workspace.yaml");
1519
+ let content;
1520
+ try {
1521
+ content = await readFile$1(workspacePath, "utf-8");
1522
+ } catch {
1523
+ content = `packages:
1524
+ - ".config/*"
1525
+ - "packages/*"
1526
+ `;
1527
+ await writeFile$1(workspacePath, content);
1528
+ return;
1529
+ }
1530
+ if (content.includes(".config/*") || content.includes('".config/*"')) {
1531
+ return;
1532
+ }
1533
+ const lines = content.split("\n");
1534
+ const packagesIndex = lines.findIndex((line) => line.trim().startsWith("packages:"));
1535
+ if (packagesIndex === -1) {
1536
+ content = `packages:
1537
+ - ".config/*"
1538
+ ${content}`;
1539
+ } else {
1540
+ lines.splice(packagesIndex + 1, 0, ' - ".config/*"');
1541
+ content = lines.join("\n");
1542
+ }
1543
+ await writeFile$1(workspacePath, content);
1544
+ }
1545
+ async function migrateEslintConfig(monorepoRoot, files) {
1546
+ const configBasePath = ".config/eslint";
1547
+ const existingConfigPath = join$1(monorepoRoot, "eslint.config.js");
1548
+ let existingContent;
1549
+ try {
1550
+ existingContent = await readFile$1(existingConfigPath, "utf-8");
1551
+ } catch {
1552
+ generateEslintConfigPackage(files);
1553
+ return;
1554
+ }
1555
+ files[`${configBasePath}/package.json`] = {
1556
+ type: "text",
1557
+ content: JSON.stringify(
1558
+ {
1559
+ name: "@config/eslint",
1560
+ version: "0.1.0",
1561
+ private: true,
1562
+ type: "module",
1563
+ exports: {
1564
+ "./base": "./base.js",
1565
+ "./react": "./react.js"
1566
+ }
1567
+ },
1568
+ null,
1569
+ 2
1570
+ )
1571
+ };
1572
+ files[`${configBasePath}/README.md`] = {
1573
+ type: "text",
1574
+ content: `# \`@config/eslint\`
1575
+
1576
+ Shared ESLint configurations.
1577
+
1578
+ ## Usage
1579
+
1580
+ In your package's \`eslint.config.js\`:
1581
+
1582
+ \`\`\`js
1583
+ import base from "@config/eslint/base";
1584
+
1585
+ export default [...base];
1586
+ \`\`\`
1587
+
1588
+ ## Available Configs
1589
+
1590
+ - \`base\` - Base ESLint rules (migrated from root)
1591
+ - \`react\` - React-specific rules
1592
+ `
1593
+ };
1594
+ files[`${configBasePath}/base.js`] = {
1595
+ type: "text",
1596
+ content: existingContent
1597
+ };
1598
+ files[`${configBasePath}/react.js`] = {
1599
+ type: "text",
1600
+ content: `import react from "eslint-plugin-react";
1601
+ import reactHooks from "eslint-plugin-react-hooks";
1602
+
1603
+ export default [
1604
+ {
1605
+ plugins: {
1606
+ react,
1607
+ "react-hooks": reactHooks,
1608
+ },
1609
+ rules: {
1610
+ ...react.configs.recommended.rules,
1611
+ ...reactHooks.configs.recommended.rules,
1612
+ "react/react-in-jsx-scope": "off",
1613
+ },
1614
+ settings: {
1615
+ react: {
1616
+ version: "detect",
1617
+ },
1618
+ },
1619
+ },
1620
+ ];
1621
+ `
1622
+ };
1623
+ }
1624
+ async function migratePrettierConfig(monorepoRoot, files) {
1625
+ const configBasePath = ".config/prettier";
1626
+ const existingConfigPath = join$1(monorepoRoot, ".prettierrc.json");
1627
+ let existingContent;
1628
+ try {
1629
+ existingContent = await readFile$1(existingConfigPath, "utf-8");
1630
+ } catch {
1631
+ generatePrettierConfigPackage(files);
1632
+ return;
1633
+ }
1634
+ files[`${configBasePath}/package.json`] = {
1635
+ type: "text",
1636
+ content: JSON.stringify(
1637
+ {
1638
+ name: "@config/prettier",
1639
+ version: "0.1.0",
1640
+ private: true,
1641
+ exports: {
1642
+ "./base": "./base.json"
1643
+ }
1644
+ },
1645
+ null,
1646
+ 2
1647
+ )
1648
+ };
1649
+ files[`${configBasePath}/README.md`] = {
1650
+ type: "text",
1651
+ content: `# \`@config/prettier\`
1652
+
1653
+ Shared Prettier configurations.
1654
+
1655
+ ## Usage
1656
+
1657
+ In your package's \`.prettierrc\`:
1658
+
1659
+ \`\`\`json
1660
+ "@config/prettier/base"
1661
+ \`\`\`
1662
+
1663
+ Or in \`package.json\`:
1664
+
1665
+ \`\`\`json
1666
+ {
1667
+ "prettier": "@config/prettier/base"
1668
+ }
1669
+ \`\`\`
1670
+
1671
+ ## Available Configs
1672
+
1673
+ - \`base\` - Base Prettier rules (migrated from root)
1674
+ `
1675
+ };
1676
+ files[`${configBasePath}/base.json`] = {
1677
+ type: "text",
1678
+ content: existingContent
1679
+ };
1680
+ }
1681
+ async function createPackageInWorkspace(monorepoRoot, packageManager, inheritedSettings, scope) {
1682
+ const workspaceDirectories = await parseWorkspaceDirectories(monorepoRoot);
1683
+ const defaultDirectories = ["apps", "packages"];
1684
+ const hasCustomDirectories = workspaceDirectories.length > 0 && !workspaceDirectories.every((dir) => defaultDirectories.includes(dir));
1685
+ const packageType = await promptForInitialPackage();
1686
+ if (packageType === "skip") {
1687
+ return false;
1688
+ }
1689
+ const defaultDir = packageType === "app" ? "apps" : "packages";
1690
+ const packageNameInput = await p.text({
1691
+ message: "Package name?",
1692
+ initialValue: `@${scope}/`,
1693
+ validate: (value) => {
1694
+ const validationError = validatePackageName(value);
1695
+ if (validationError) return validationError;
1696
+ const dirName = value.includes("/") ? value.split("/").pop() : value;
1697
+ if (!dirName) return "Package name is required";
1698
+ if (!hasCustomDirectories) {
1699
+ const targetPath = join$1(monorepoRoot, defaultDir, dirName);
1700
+ try {
1701
+ const { statSync } = require$1("fs");
1702
+ statSync(targetPath);
1703
+ return `Directory ${defaultDir}/${dirName} already exists`;
1704
+ } catch {
1705
+ }
1706
+ }
1707
+ }
1708
+ });
1709
+ if (p.isCancel(packageNameInput)) {
1710
+ return false;
1711
+ }
1712
+ const scopedName = packageNameInput;
1713
+ const shortName = scopedName.includes("/") ? scopedName.split("/").pop() : scopedName;
1714
+ const packageOptions = await promptForPackageOptions(scopedName, packageType, inheritedSettings);
1715
+ let targetDir = defaultDir;
1716
+ if (hasCustomDirectories && workspaceDirectories.length > 0) {
1717
+ const dirChoice = await p.select({
1718
+ message: "Target directory",
1719
+ options: workspaceDirectories.map((dir) => ({
1720
+ value: dir,
1721
+ label: dir
1722
+ })),
1723
+ initialValue: workspaceDirectories.includes(defaultDir) ? defaultDir : workspaceDirectories[0]
1724
+ });
1725
+ if (p.isCancel(dirChoice)) {
1726
+ return false;
1727
+ }
1728
+ targetDir = dirChoice;
1729
+ const targetPath = join$1(monorepoRoot, targetDir, shortName);
1730
+ try {
1731
+ const { statSync } = require$1("fs");
1732
+ statSync(targetPath);
1733
+ p.log.error(`Directory ${targetDir}/${shortName} already exists`);
1734
+ return false;
1735
+ } catch {
1736
+ }
1737
+ }
1738
+ const relativePkgPath = join$1(targetDir, shortName);
1739
+ const workspaceRoot = calculateWorkspaceRoot(relativePkgPath);
1740
+ packageOptions.workspaceRoot = workspaceRoot;
1741
+ packageOptions.name = scopedName;
1742
+ packageOptions.packageManager = await resolvePackageManager(packageOptions);
1743
+ packageOptions.engine = await resolveEngine(packageOptions);
1744
+ packageOptions.versions = await resolveProjectPackageVersions(packageOptions);
1745
+ const workspacePackages = packageType === "app" ? await getWorkspacePackages(monorepoRoot) : [];
1746
+ if (workspacePackages.length > 0) {
1747
+ const selectedDeps = await p.multiselect({
1748
+ message: "Add workspace dependencies?",
1749
+ options: workspacePackages.map((name) => ({ value: name, label: name })),
1750
+ required: false
1751
+ });
1752
+ if (!p.isCancel(selectedDeps) && selectedDeps.length > 0) {
1753
+ packageOptions.workspaceDependencies = selectedDeps;
1754
+ }
1755
+ }
1756
+ const outputPath = join$1(monorepoRoot, relativePkgPath);
1757
+ const spinner = p.spinner();
1758
+ spinner.start("Creating package...");
1759
+ try {
1760
+ const files = generate(packageOptions);
1761
+ await writeGeneratedFiles(outputPath, files);
1762
+ spinner.stop(color.green.inverse(` \u2713 Package created at ${relativePkgPath}! `));
1763
+ const addAnother = await p.select({
1764
+ message: "Add another package?",
1765
+ options: [
1766
+ { value: "no", label: "No, I'm done" },
1767
+ { value: "yes", label: "Yes, add another" }
1768
+ ],
1769
+ initialValue: "no"
1770
+ });
1771
+ return !p.isCancel(addAnother) && addAnother === "yes";
1772
+ } catch (error) {
1773
+ spinner.stop("Failed to create package");
1774
+ p.log.error(String(error));
1775
+ return false;
1776
+ }
1777
+ }
1778
+ async function handleCheckCommand() {
1779
+ const monorepoRoot = await detectMonorepoRoot();
1780
+ if (!monorepoRoot) {
1781
+ console.log(color.red("\u2717") + " Not a monorepo workspace");
1782
+ process.exit(1);
1783
+ }
1784
+ const { valid, errors } = await validateWorkspace(monorepoRoot);
1785
+ if (valid) {
1786
+ console.log(color.green("\u2713") + " Valid monorepo workspace");
1787
+ console.log(color.dim(` ${monorepoRoot}`));
1788
+ } else {
1789
+ console.log(color.red("\u2717") + " Invalid monorepo workspace");
1790
+ console.log(color.dim(` ${monorepoRoot}`));
1791
+ for (const error of errors) {
1792
+ console.log(color.red(` \u2022 ${error}`));
1793
+ }
1794
+ }
1795
+ process.exit(valid ? 0 : 1);
1796
+ }
1797
+ async function handleFixCommand(options) {
1798
+ const monorepoRoot = await detectMonorepoRoot();
1799
+ if (!monorepoRoot) {
1800
+ console.log(color.red("\u2717") + " Not a monorepo workspace");
1801
+ console.log(color.dim(" Run this command from within a monorepo"));
1802
+ process.exit(1);
1803
+ }
1804
+ const { valid, errors } = await validateWorkspace(monorepoRoot);
1805
+ if (valid) {
1806
+ console.log(color.green("\u2713") + " Workspace is already valid");
1807
+ console.log(color.dim(` ${monorepoRoot}`));
1808
+ process.exit(0);
1809
+ }
1810
+ console.log(color.yellow("!") + " Invalid monorepo workspace");
1811
+ for (const error of errors) {
1812
+ console.log(color.dim(` \u2022 ${error}`));
1813
+ }
1814
+ console.log();
1815
+ const tooling = await detectWorkspaceSettings(monorepoRoot);
1816
+ const existingConfigs = await detectExistingConfigs(monorepoRoot);
1817
+ const detectedLinter = tooling.linter ?? existingConfigs.linter ?? "oxlint";
1818
+ const detectedFormatter = tooling.formatter ?? existingConfigs.formatter ?? "prettier";
1819
+ const isNonInteractive = Boolean(options.linter && options.formatter);
1820
+ let linter;
1821
+ let formatter;
1822
+ if (isNonInteractive) {
1823
+ linter = options.linter;
1824
+ formatter = options.formatter;
1825
+ } else {
1826
+ const linterChoice = await p.select({
1827
+ message: "Linter",
1828
+ options: [
1829
+ {
1830
+ value: "oxlint",
1831
+ label: "oxlint" + (tooling.linter === "oxlint" ? color.dim(" (installed)") : "")
1832
+ },
1833
+ {
1834
+ value: "eslint",
1835
+ label: "eslint" + (tooling.linter === "eslint" || existingConfigs.linter === "eslint" ? color.dim(" (installed)") : "")
1836
+ },
1837
+ {
1838
+ value: "biome",
1839
+ label: "biome" + (tooling.linter === "biome" ? color.dim(" (installed)") : "")
1840
+ }
1841
+ ],
1842
+ initialValue: detectedLinter
1843
+ });
1844
+ if (p.isCancel(linterChoice)) {
1845
+ p.cancel("Operation cancelled.");
1846
+ process.exit(0);
1847
+ }
1848
+ const formatterChoice = await p.select({
1849
+ message: "Formatter",
1850
+ options: [
1851
+ {
1852
+ value: "oxfmt",
1853
+ label: "oxfmt" + (tooling.formatter === "oxfmt" ? color.dim(" (installed)") : "")
1854
+ },
1855
+ {
1856
+ value: "prettier",
1857
+ label: "prettier" + (tooling.formatter === "prettier" || existingConfigs.formatter === "prettier" ? color.dim(" (installed)") : "")
1858
+ },
1859
+ {
1860
+ value: "biome",
1861
+ label: "biome" + (tooling.formatter === "biome" ? color.dim(" (installed)") : "")
1862
+ }
1863
+ ],
1864
+ initialValue: detectedFormatter
1865
+ });
1866
+ if (p.isCancel(formatterChoice)) {
1867
+ p.cancel("Operation cancelled.");
1868
+ process.exit(0);
1869
+ }
1870
+ linter = linterChoice;
1871
+ formatter = formatterChoice;
1872
+ }
1873
+ console.log();
1874
+ const spinner = p.spinner();
1875
+ spinner.start("Fixing workspace...");
1876
+ try {
1877
+ const files = {};
1878
+ const tsConfigExists = await fileExists(
1879
+ join$1(monorepoRoot, ".config/typescript/package.json")
1880
+ );
1881
+ if (!tsConfigExists) {
1882
+ generateTypescriptConfigPackage(files);
1883
+ }
1884
+ if (linter === "oxlint") {
1885
+ const oxlintExists = await fileExists(join$1(monorepoRoot, ".config/oxlint/package.json"));
1886
+ if (!oxlintExists) generateOxlintConfigPackage(files);
1887
+ } else if (linter === "eslint") {
1888
+ const eslintPkgExists = await fileExists(
1889
+ join$1(monorepoRoot, ".config/eslint/package.json")
1890
+ );
1891
+ if (!eslintPkgExists) {
1892
+ if (existingConfigs.eslintConfigPath) {
1893
+ await migrateEslintConfig(monorepoRoot, files);
1894
+ } else {
1895
+ generateEslintConfigPackage(files);
1896
+ }
1897
+ }
1898
+ }
1899
+ if (formatter === "oxfmt") {
1900
+ const oxfmtExists = await fileExists(join$1(monorepoRoot, ".config/oxfmt/package.json"));
1901
+ if (!oxfmtExists) generateOxfmtConfigPackage(files);
1902
+ } else if (formatter === "prettier") {
1903
+ const prettierPkgExists = await fileExists(
1904
+ join$1(monorepoRoot, ".config/prettier/package.json")
1905
+ );
1906
+ if (!prettierPkgExists) {
1907
+ if (existingConfigs.prettierConfigPath) {
1908
+ await migratePrettierConfig(monorepoRoot, files);
1909
+ } else {
1910
+ generatePrettierConfigPackage(files);
1911
+ }
1912
+ }
1913
+ }
1914
+ if ((linter === "biome" || formatter === "biome") && !existingConfigs.biomeConfigPath) {
1915
+ const versions = await resolveMonorepoRootPackageVersions({
1916
+ linter,
1917
+ formatter
1918
+ });
1919
+ const biomeVersion = getResolvedPackageVersion(versions, "@biomejs/biome");
1920
+ const biomeConfig = {
1921
+ $schema: `https://biomejs.dev/schemas/${biomeVersion}/schema.json`,
1922
+ vcs: {
1923
+ enabled: true,
1924
+ clientKind: "git",
1925
+ useIgnoreFile: true
1926
+ },
1927
+ linter: {
1928
+ enabled: linter === "biome",
1929
+ rules: {
1930
+ recommended: true
1931
+ }
1932
+ },
1933
+ formatter: {
1934
+ enabled: formatter === "biome"
1935
+ }
1936
+ };
1937
+ files["biome.json"] = {
1938
+ type: "text",
1939
+ content: JSON.stringify(biomeConfig, null, 2)
1940
+ };
1941
+ }
1942
+ for (const [filePath, file] of Object.entries(files)) {
1943
+ const fullPath = join$1(monorepoRoot, filePath);
1944
+ await mkdir$1(dirname$1(fullPath), { recursive: true });
1945
+ await writeFile$1(fullPath, file.content);
1946
+ }
1947
+ await ensureConfigInWorkspace(monorepoRoot);
1948
+ if (existingConfigs.eslintConfigPath && linter === "eslint") {
1949
+ try {
1950
+ await unlink(existingConfigs.eslintConfigPath);
1951
+ } catch {
1952
+ }
1953
+ }
1954
+ if (existingConfigs.prettierConfigPath && formatter === "prettier") {
1955
+ try {
1956
+ await unlink(existingConfigs.prettierConfigPath);
1957
+ } catch {
1958
+ }
1959
+ }
1960
+ spinner.stop(color.green("\u2713") + " Workspace fixed!");
1961
+ const generated = Object.keys(files).filter((f) => f.endsWith("package.json"));
1962
+ for (const pkgFile of generated) {
1963
+ const pkgName = pkgFile.replace("/package.json", "");
1964
+ console.log(color.dim(` Generated ${pkgName}`));
1965
+ }
1966
+ const vscodeSettingsExists = await fileExists(join$1(monorepoRoot, ".vscode/settings.json"));
1967
+ const vscodeExtensionsExists = await fileExists(
1968
+ join$1(monorepoRoot, ".vscode/extensions.json")
1969
+ );
1970
+ const vscodeExists = vscodeSettingsExists && vscodeExtensionsExists;
1971
+ if (!vscodeExists) {
1972
+ let addVscode = false;
1973
+ if (isNonInteractive) {
1974
+ addVscode = true;
1975
+ } else {
1976
+ const vscodeChoice = await p.confirm({
1977
+ message: "Generate VS Code settings?",
1978
+ initialValue: true
1979
+ });
1980
+ addVscode = !p.isCancel(vscodeChoice) && vscodeChoice;
1981
+ }
1982
+ if (addVscode) {
1983
+ const vscodeFiles = {};
1984
+ generateVscodeFiles(vscodeFiles, linter, formatter);
1985
+ for (const [filePath, file] of Object.entries(vscodeFiles)) {
1986
+ const fullPath = join$1(monorepoRoot, filePath);
1987
+ await mkdir$1(dirname$1(fullPath), { recursive: true });
1988
+ await writeFile$1(fullPath, file.content);
1989
+ }
1990
+ console.log(color.dim(" Generated .vscode/settings.json"));
1991
+ console.log(color.dim(" Generated .vscode/extensions.json"));
1992
+ }
1993
+ }
1994
+ const aiRulesExist = await fileExists(join$1(monorepoRoot, ".ai/workspace.md"));
1995
+ if (!aiRulesExist) {
1996
+ const platforms = await promptForAiPlatforms(isNonInteractive);
1997
+ if (platforms.length > 0) {
1998
+ const scope = await getMonorepoScope(monorepoRoot);
1999
+ const aiFilesOutput = {};
2000
+ generateAiFiles(aiFilesOutput, {
2001
+ name: scope,
2002
+ packageManager: "pnpm",
2003
+ linter,
2004
+ formatter,
2005
+ isMonorepo: true,
2006
+ platforms
2007
+ });
2008
+ for (const [filePath, file] of Object.entries(aiFilesOutput)) {
2009
+ const fullPath = join$1(monorepoRoot, filePath);
2010
+ await mkdir$1(dirname$1(fullPath), { recursive: true });
2011
+ await writeFile$1(fullPath, file.content);
2012
+ console.log(color.dim(` Generated ${filePath}`));
2013
+ }
2014
+ }
2015
+ }
2016
+ process.exit(0);
2017
+ } catch (error) {
2018
+ spinner.stop(color.red("\u2717") + " Failed to fix workspace");
2019
+ console.error(error);
2020
+ process.exit(1);
2021
+ }
2022
+ }
2023
+ async function handleMigration(config, target, root, options) {
2024
+ const plan = await getMigrationPlan(config, target, root);
2025
+ console.log(color.cyan("Migration:"));
2026
+ if (plan.fromLinter !== plan.toLinter) {
2027
+ console.log(` Linter: ${color.dim(plan.fromLinter)} \u2192 ${color.green(plan.toLinter)}`);
2028
+ }
2029
+ if (plan.fromFormatter !== plan.toFormatter) {
2030
+ console.log(
2031
+ ` Formatter: ${color.dim(plan.fromFormatter)} \u2192 ${color.green(plan.toFormatter)}`
2032
+ );
2033
+ }
2034
+ console.log();
2035
+ console.log(color.cyan("Changes:"));
2036
+ for (const change of plan.changes) {
2037
+ console.log(formatMigrationChange(change));
2038
+ }
2039
+ if (plan.subPackageUpdates.length > 0) {
2040
+ console.log();
2041
+ console.log(color.cyan(`Sub-packages (${plan.subPackageUpdates.length}):`));
2042
+ for (const update of plan.subPackageUpdates) {
2043
+ const changes = [
2044
+ ...update.remove.map((d) => `-${d}`),
2045
+ ...update.add.map((d) => `+${d}`)
2046
+ ].join(", ");
2047
+ console.log(` ~ ${update.path} (${changes})`);
2048
+ }
2049
+ }
2050
+ console.log();
2051
+ if (!options.yes) {
2052
+ const confirm = await p.confirm({
2053
+ message: "Apply migration?",
2054
+ initialValue: true
2055
+ });
2056
+ if (p.isCancel(confirm) || !confirm) {
2057
+ console.log(color.dim(" Migration cancelled"));
2058
+ process.exit(0);
2059
+ }
2060
+ }
2061
+ await applyMigration(plan, root);
2062
+ const aiWorkspacePath = join$1(root, ".ai/workspace.md");
2063
+ const aiRulesExist = await fileExists(aiWorkspacePath);
2064
+ if (aiRulesExist) {
2065
+ console.log();
2066
+ console.log(color.cyan("Updating AI rules..."));
2067
+ const scope = await getMonorepoScope(root);
2068
+ const existingPlatforms = [];
2069
+ if (await fileExists(join$1(root, "AGENTS.md"))) {
2070
+ existingPlatforms.push("agents");
2071
+ }
2072
+ if (await fileExists(join$1(root, "CLAUDE.md"))) {
2073
+ existingPlatforms.push("claude");
2074
+ }
2075
+ const aiFilesOutput = {};
2076
+ generateAiFiles(aiFilesOutput, {
2077
+ name: scope,
2078
+ packageManager: "pnpm",
2079
+ linter: plan.toLinter,
2080
+ formatter: plan.toFormatter,
2081
+ isMonorepo: true,
2082
+ platforms: existingPlatforms.length > 0 ? existingPlatforms : ["agents"]
2083
+ });
2084
+ for (const [filePath, file] of Object.entries(aiFilesOutput)) {
2085
+ const fullPath = join$1(root, filePath);
2086
+ await mkdir$1(dirname$1(fullPath), { recursive: true });
2087
+ await writeFile$1(fullPath, file.content);
2088
+ console.log(color.dim(` ${filePath}`));
2089
+ }
2090
+ }
2091
+ console.log();
2092
+ console.log(color.green("\u2713") + ` Migrated to ${plan.toLinter}/${plan.toFormatter}`);
2093
+ console.log(color.dim(" Run `pnpm install` to update dependencies"));
2094
+ process.exit(0);
2095
+ }
2096
+ async function handleUpdateCommand(options) {
2097
+ const monorepoRoot = await detectMonorepoRoot();
2098
+ const projectRoot = monorepoRoot ?? await detectPackageRoot();
2099
+ if (!projectRoot) {
2100
+ console.log(color.red("\u2717") + " Could not find a project root");
2101
+ console.log(color.dim(" Run this command from inside a generated project"));
2102
+ process.exit(1);
2103
+ }
2104
+ const isMonorepo = monorepoRoot != null;
2105
+ if (isMonorepo) {
2106
+ const { valid, errors } = await validateWorkspace(projectRoot);
2107
+ if (!valid) {
2108
+ console.log(color.yellow("!") + " Workspace has issues:");
2109
+ for (const error of errors) {
2110
+ console.log(color.dim(` \u2022 ${error}`));
2111
+ }
2112
+ console.log();
2113
+ const shouldFix = options.yes || await p.confirm({
2114
+ message: "Run fix first to resolve these issues?",
2115
+ initialValue: true
2116
+ });
2117
+ if (p.isCancel(shouldFix) || !shouldFix) {
2118
+ console.log(color.dim(" Run `pnpm create krispya --fix` to fix manually"));
2119
+ process.exit(1);
2120
+ }
2121
+ const preFixConfig = await detectCurrentConfig(projectRoot);
2122
+ const fixOptions = {
2123
+ ...options,
2124
+ linter: options.linter ?? preFixConfig.linter,
2125
+ formatter: options.formatter ?? preFixConfig.formatter
2126
+ };
2127
+ await handleFixCommand(fixOptions);
2128
+ }
2129
+ } else if (options.linter || options.formatter) {
2130
+ console.log(
2131
+ color.yellow("!") + " Linter/formatter migrations in --update are currently monorepo-only"
2132
+ );
2133
+ console.log(color.dim(" Continuing with standalone shared config updates"));
2134
+ console.log();
2135
+ }
2136
+ const config = await detectCurrentConfig(projectRoot, isMonorepo);
2137
+ const targetLinter = options.linter;
2138
+ const targetFormatter = options.formatter;
2139
+ const migrationTarget = { linter: targetLinter, formatter: targetFormatter };
2140
+ if (isMonorepo && needsMigration(config, migrationTarget)) {
2141
+ await handleMigration(config, migrationTarget, projectRoot, options);
2142
+ return;
2143
+ }
2144
+ console.log(
2145
+ color.cyan("Checking for updates...") + color.dim(` (${config.linter}/${config.formatter})`)
2146
+ );
2147
+ console.log();
2148
+ const expected = await generateExpectedFiles(config);
2149
+ const categories = await compareWithDisk(expected, projectRoot);
2150
+ const allCategories = categories.filter((c) => c.category !== "workspace-config");
2151
+ if (isMonorepo) {
2152
+ const workspaceConfigChanges = await getWorkspaceConfigUpdates(projectRoot);
2153
+ const workspaceCategory = {
2154
+ category: "workspace-config",
2155
+ label: "Workspace Config",
2156
+ changes: workspaceConfigChanges,
2157
+ hasUserModifications: workspaceConfigChanges.some((c) => c.status === "modified")
2158
+ };
2159
+ if (workspaceConfigChanges.length > 0) {
2160
+ const configPkgIndex = allCategories.findIndex((c) => c.category === "config-packages");
2161
+ if (configPkgIndex !== -1) {
2162
+ allCategories.splice(configPkgIndex + 1, 0, workspaceCategory);
2163
+ } else {
2164
+ allCategories.push(workspaceCategory);
2165
+ }
2166
+ }
2167
+ }
2168
+ let updatedCount = 0;
2169
+ let skippedCount = 0;
2170
+ for (const category of allCategories) {
2171
+ const newChanges = category.changes.filter((c) => c.status === "added");
2172
+ const modifiedChanges = category.changes.filter((c) => c.status === "modified");
2173
+ const hasNew = newChanges.length > 0;
2174
+ const hasModified = modifiedChanges.length > 0;
2175
+ const hasChanges = hasNew || hasModified;
2176
+ if (!hasChanges) {
2177
+ console.log(color.green("\u2713") + ` ${category.label}: Up to date`);
2178
+ continue;
2179
+ }
2180
+ if (category.category === "ai-files") {
2181
+ if (hasNew) {
2182
+ console.log(color.cyan(category.label + ":"));
2183
+ console.log(color.dim(` ${newChanges.length} AI file(s) can be added`));
2184
+ console.log();
2185
+ const applyAi = options.yes ? true : await p.confirm({
2186
+ message: "Add AI rules?",
2187
+ initialValue: true
2188
+ });
2189
+ if (!p.isCancel(applyAi) && applyAi) {
2190
+ await applyUpdates(newChanges, projectRoot);
2191
+ console.log(color.green("\u2713") + ` Added ${newChanges.length} AI file(s)`);
2192
+ updatedCount++;
2193
+ } else {
2194
+ console.log(color.dim(` Skipped ${category.label}`));
2195
+ skippedCount++;
2196
+ }
2197
+ }
2198
+ if (hasModified) {
2199
+ console.log(color.cyan("AI Files (existing):"));
2200
+ for (const change of modifiedChanges) {
2201
+ console.log(formatFileChange(change));
2202
+ }
2203
+ console.log();
2204
+ if (options.yes) {
2205
+ console.log(color.dim(" (--yes mode: keeping existing AI files)"));
2206
+ } else {
2207
+ const updateExisting = await p.confirm({
2208
+ message: "Update existing AI files to latest template?",
2209
+ initialValue: false
2210
+ });
2211
+ if (!p.isCancel(updateExisting) && updateExisting) {
2212
+ await applyUpdates(modifiedChanges, projectRoot);
2213
+ console.log(color.green("\u2713") + " Updated existing AI files");
2214
+ }
2215
+ }
2216
+ }
2217
+ console.log();
2218
+ continue;
2219
+ }
2220
+ let changesToApply = [];
2221
+ if (options.yes) {
2222
+ console.log(color.cyan(category.label + ":"));
2223
+ for (const change of [...newChanges, ...modifiedChanges]) {
2224
+ console.log(formatFileChange(change));
2225
+ }
2226
+ console.log();
2227
+ if (category.category === "workspace-config") {
2228
+ changesToApply = [...newChanges, ...modifiedChanges];
2229
+ if (changesToApply.length > 0) {
2230
+ console.log(color.dim(" (--yes mode: applying merge updates)"));
2231
+ }
2232
+ } else {
2233
+ changesToApply = newChanges;
2234
+ if (newChanges.length > 0) {
2235
+ console.log(color.dim(" (--yes mode: adding new files only)"));
2236
+ }
2237
+ }
2238
+ } else if (hasNew && hasModified) {
2239
+ const allChanges = [...newChanges, ...modifiedChanges];
2240
+ const selectedFiles = await p.multiselect({
2241
+ message: `${category.label} (+ new, ~ changed)`,
2242
+ options: allChanges.map((change) => ({
2243
+ value: change.path,
2244
+ label: change.status === "added" ? `+ ${change.path}` : `~ ${change.path}`
2245
+ })),
2246
+ initialValues: newChanges.map((c) => c.path),
2247
+ // Pre-select new files
2248
+ required: false
2249
+ });
2250
+ if (p.isCancel(selectedFiles)) {
2251
+ p.cancel("Operation cancelled.");
2252
+ process.exit(0);
2253
+ }
2254
+ if (selectedFiles.length > 0) {
2255
+ changesToApply = allChanges.filter((c) => selectedFiles.includes(c.path));
2256
+ }
2257
+ } else if (hasNew) {
2258
+ console.log(color.cyan(category.label + ":"));
2259
+ for (const change of newChanges) {
2260
+ console.log(formatFileChange(change));
2261
+ }
2262
+ console.log();
2263
+ const shouldAdd = await p.confirm({
2264
+ message: `Add ${newChanges.length} new file(s)?`,
2265
+ initialValue: true
2266
+ });
2267
+ if (p.isCancel(shouldAdd)) {
2268
+ p.cancel("Operation cancelled.");
2269
+ process.exit(0);
2270
+ }
2271
+ if (shouldAdd) {
2272
+ changesToApply = newChanges;
2273
+ }
2274
+ } else if (hasModified) {
2275
+ console.log(color.cyan(category.label + ":"));
2276
+ for (const change of modifiedChanges) {
2277
+ console.log(formatFileChange(change));
2278
+ }
2279
+ console.log();
2280
+ const shouldUpdate = await p.confirm({
2281
+ message: `Update ${modifiedChanges.length} file(s)? (will overwrite)`,
2282
+ initialValue: false
2283
+ });
2284
+ if (p.isCancel(shouldUpdate)) {
2285
+ p.cancel("Operation cancelled.");
2286
+ process.exit(0);
2287
+ }
2288
+ if (shouldUpdate) {
2289
+ changesToApply = modifiedChanges;
2290
+ }
2291
+ }
2292
+ if (changesToApply.length > 0) {
2293
+ await applyUpdates(changesToApply, projectRoot);
2294
+ const addedCount = changesToApply.filter((c) => c.status === "added").length;
2295
+ const updatedFilesCount = changesToApply.filter((c) => c.status === "modified").length;
2296
+ const parts = [];
2297
+ if (addedCount > 0) parts.push(`added ${addedCount}`);
2298
+ if (updatedFilesCount > 0) parts.push(`updated ${updatedFilesCount}`);
2299
+ console.log(color.green("\u2713") + ` ${category.label}: ${parts.join(", ")}`);
2300
+ updatedCount++;
2301
+ } else {
2302
+ console.log(color.dim(` Skipped ${category.label}`));
2303
+ skippedCount++;
2304
+ }
2305
+ console.log();
2306
+ }
2307
+ if (updatedCount === 0 && skippedCount === 0) {
2308
+ console.log(color.green("\u2713") + " Everything is up to date!");
2309
+ } else if (updatedCount > 0) {
2310
+ console.log(
2311
+ color.green("\u2713") + ` Updated ${updatedCount} ${updatedCount === 1 ? "category" : "categories"}`
2312
+ );
2313
+ if (skippedCount > 0) {
2314
+ console.log(color.dim(` Skipped ${skippedCount}`));
2315
+ }
2316
+ }
2317
+ process.exit(0);
2318
+ }
2319
+ async function handleWorkspaceCommand(name, options) {
2320
+ const monorepoRoot = await detectMonorepoRoot();
2321
+ if (!monorepoRoot) {
2322
+ console.error(color.red("Error:") + " --workspace flag requires being inside a monorepo");
2323
+ process.exit(1);
2324
+ }
2325
+ if (!name) {
2326
+ console.error(color.red("Error:") + " Package name is required with --workspace flag");
2327
+ console.log(color.dim(" Example: pnpm create krispya my-lib --workspace --type library"));
2328
+ process.exit(1);
2329
+ }
2330
+ const scope = await getMonorepoScope(monorepoRoot);
2331
+ const inheritedSettings = await detectWorkspaceSettings(monorepoRoot);
2332
+ const projectType = options.type ?? "app";
2333
+ const defaultDir = projectType === "library" ? "packages" : "apps";
2334
+ const targetDir = options.dir ?? defaultDir;
2335
+ const template = options.template ?? "vanilla";
2336
+ const baseTemplate = getBaseTemplate(template);
2337
+ const scopedName = name.startsWith("@") ? name : `@${scope}/${name}`;
2338
+ const fullPackagePath = join$1(monorepoRoot, targetDir, name);
2339
+ try {
2340
+ await access$1(fullPackagePath, constants$2.F_OK);
2341
+ console.error(color.red("Error:") + ` Directory ${targetDir}/${name} already exists`);
2342
+ process.exit(1);
2343
+ } catch {
2344
+ }
2345
+ const linter = inheritedSettings.linter ?? options.linter ?? "oxlint";
2346
+ const formatter = inheritedSettings.formatter ?? options.formatter ?? "prettier";
2347
+ const packageManager = inheritedSettings.packageManager?.name ?? "pnpm";
2348
+ const engine = inheritedSettings.engine ?? {
2349
+ name: "node",
2350
+ version: "latest"
2351
+ };
2352
+ const pnpmManageVersions = inheritedSettings.pnpmManageVersions ?? true;
2353
+ const isLibrary = projectType === "library";
2354
+ const relativePkgPath = join$1(targetDir, name);
2355
+ const workspaceRoot = calculateWorkspaceRoot(relativePkgPath);
2356
+ const generateOptions = {
2357
+ name: scopedName,
2358
+ projectType,
2359
+ libraryBundler: isLibrary ? options.bundler ?? "unbuild" : void 0,
2360
+ template,
2361
+ linter,
2362
+ formatter,
2363
+ packageManager: { name: packageManager },
2364
+ engine,
2365
+ pnpmManageVersions,
2366
+ workspaceRoot,
2367
+ ...baseTemplate === "r3f" && {
2368
+ drei: options.drei ? {} : void 0,
2369
+ handle: options.handle ? {} : void 0,
2370
+ leva: options.leva ? {} : void 0,
2371
+ postprocessing: options.postprocessing ? {} : void 0,
2372
+ rapier: options.rapier ? {} : void 0,
2373
+ xr: options.xr ? {} : void 0,
2374
+ uikit: options.uikit ? {} : void 0,
2375
+ offscreen: options.offscreen ? {} : void 0,
2376
+ zustand: options.zustand ? {} : void 0,
2377
+ koota: options.koota ? {} : void 0,
2378
+ viverse: options.viverse ? {} : void 0,
2379
+ triplex: options.triplex ? {} : void 0
2380
+ }
2381
+ };
2382
+ generateOptions.packageManager = await resolvePackageManager(generateOptions);
2383
+ generateOptions.engine = await resolveEngine(generateOptions);
2384
+ generateOptions.versions = await resolveProjectPackageVersions(generateOptions);
2385
+ console.log(color.cyan("Creating") + ` ${scopedName} in ${targetDir}/${name}...`);
2386
+ try {
2387
+ const files = generate(generateOptions);
2388
+ await writeGeneratedFiles(fullPackagePath, files);
2389
+ console.log(color.green("\u2713") + ` Created ${scopedName} at ${targetDir}/${name}`);
2390
+ process.exit(0);
2391
+ } catch (error) {
2392
+ console.error(color.red("Error:") + " Failed to create package");
2393
+ console.error(String(error));
2394
+ process.exit(1);
2395
+ }
2396
+ }
2397
+ async function handleMonorepoCreation(generateOptions, isNonInteractive) {
2398
+ const { generateMonorepo } = await import('./chunks/index.mjs').then(function (n) { return n.J; });
2399
+ const packageManager = getPackageManagerName(generateOptions.packageManager);
2400
+ generateOptions.packageManager = await resolvePackageManager(generateOptions);
2401
+ generateOptions.engine = await resolveEngine(generateOptions);
2402
+ generateOptions.versions = await resolveMonorepoRootPackageVersions({
2403
+ linter: generateOptions.linter ?? "oxlint",
2404
+ formatter: generateOptions.formatter ?? "prettier",
2405
+ engine: generateOptions.engine,
2406
+ versions: generateOptions.versions
2407
+ });
2408
+ const aiPlatforms = await promptForAiPlatforms(isNonInteractive);
2409
+ const projectPath = join$1(cwd(), generateOptions.name);
2410
+ const spinner = p.spinner();
2411
+ spinner.start("Creating monorepo workspace...");
2412
+ try {
2413
+ const { files } = generateMonorepo({
2414
+ name: generateOptions.name,
2415
+ linter: generateOptions.linter ?? "oxlint",
2416
+ formatter: generateOptions.formatter ?? "prettier",
2417
+ packageManager: generateOptions.packageManager ?? {
2418
+ name: packageManager
2419
+ },
2420
+ pnpmManageVersions: generateOptions.pnpmManageVersions,
2421
+ engine: generateOptions.engine,
2422
+ versions: generateOptions.versions,
2423
+ aiPlatforms: aiPlatforms.length > 0 ? aiPlatforms : void 0
2424
+ });
2425
+ const filePaths = Object.keys(files).sort();
2426
+ for (const filePath of filePaths) {
2427
+ const fullFilePath = join$1(projectPath, filePath);
2428
+ await mkdir$1(dirname$1(fullFilePath), { recursive: true });
2429
+ const file = files[filePath];
2430
+ if (file.type === "text") {
2431
+ await writeFile$1(fullFilePath, file.content);
2432
+ }
2433
+ }
2434
+ spinner.stop(color.green.inverse(" \u2713 Monorepo workspace created! "));
2435
+ if (isNonInteractive) {
2436
+ process.exit(0);
2437
+ }
2438
+ const newWorkspaceSettings = {
2439
+ linter: generateOptions.linter,
2440
+ formatter: generateOptions.formatter,
2441
+ packageManager: generateOptions.packageManager ?? {
2442
+ name: packageManager
2443
+ },
2444
+ engine: generateOptions.engine,
2445
+ pnpmManageVersions: generateOptions.pnpmManageVersions
2446
+ };
2447
+ const scope = generateOptions.name;
2448
+ let addMore = true;
2449
+ while (addMore) {
2450
+ addMore = await createPackageInWorkspace(
2451
+ projectPath,
2452
+ packageManager,
2453
+ newWorkspaceSettings,
2454
+ scope
2455
+ );
2456
+ }
2457
+ const nextSteps = [
2458
+ `cd ${generateOptions.name}`,
2459
+ `${packageManager} install`,
2460
+ `${packageManager} run dev`
2461
+ ].join("\n");
2462
+ p.note(nextSteps, "Next steps");
2463
+ p.outro(color.green("Happy coding! \u2728"));
2464
+ process.exit(0);
2465
+ } catch (error) {
2466
+ spinner.stop("Failed to create monorepo workspace");
2467
+ p.log.error(String(error));
2468
+ process.exit(1);
2469
+ }
2470
+ }
2471
+ async function handleStandaloneProjectCreation(generateOptions, isNonInteractive) {
2472
+ const base = generateOptions.template ? getBaseTemplate(generateOptions.template) : "vanilla";
2473
+ const defaultFallbackName = base === "vanilla" ? "vanilla-app" : base === "react" ? "react-app" : "react-three-app";
2474
+ generateOptions.name ??= defaultFallbackName;
2475
+ const aiPlatforms = await promptForAiPlatforms(isNonInteractive);
2476
+ if (aiPlatforms.length > 0) {
2477
+ generateOptions.aiPlatforms = aiPlatforms;
2478
+ }
2479
+ const packageManager = getPackageManagerName(generateOptions.packageManager);
2480
+ const isLibrary = generateOptions.projectType === "library";
2481
+ generateOptions.packageManager = await resolvePackageManager(generateOptions);
2482
+ generateOptions.engine = await resolveEngine(generateOptions);
2483
+ generateOptions.versions = await resolveProjectPackageVersions(generateOptions);
2484
+ const projectPath = join$1(cwd(), generateOptions.name);
2485
+ const spinner = p.spinner();
2486
+ spinner.start("Creating project...");
2487
+ try {
2488
+ const files = generate(generateOptions);
2489
+ await writeGeneratedFiles(projectPath, files);
2490
+ spinner.stop(color.green.inverse(" \u2713 Project created! "));
2491
+ if (isNonInteractive) process.exit(0);
2492
+ const nextSteps = isLibrary ? [
2493
+ `cd ${generateOptions.name}`,
2494
+ `${packageManager} install`,
2495
+ `${packageManager} run build`
2496
+ ].join("\n") : [
2497
+ `cd ${generateOptions.name}`,
2498
+ `${packageManager} install`,
2499
+ `${packageManager} run dev`
2500
+ ].join("\n");
2501
+ p.note(nextSteps, "Next steps");
2502
+ p.outro(color.green("Happy coding! \u2728"));
2503
+ } catch (error) {
2504
+ spinner.stop("Failed to create project");
2505
+ p.log.error(String(error));
2506
+ process.exit(1);
2507
+ }
2508
+ }
2509
+ async function handleInteractiveMonorepoMode(monorepoRoot) {
2510
+ const choice = await p.select({
2511
+ message: "Detected monorepo workspace",
2512
+ options: [
2513
+ { value: "add", label: "Add new package to this workspace" },
2514
+ { value: "standalone", label: "Create standalone project" }
2515
+ ],
2516
+ initialValue: "add"
2517
+ });
2518
+ if (p.isCancel(choice)) {
2519
+ p.cancel("Operation cancelled.");
2520
+ process.exit(0);
2521
+ }
2522
+ if (choice === "add") {
2523
+ const inheritedSettings = await detectWorkspaceSettings(monorepoRoot);
2524
+ const hasSettings = Object.values(inheritedSettings).some(Boolean);
2525
+ if (hasSettings) {
2526
+ const settingsInfo = [
2527
+ inheritedSettings.linter && `linter: ${inheritedSettings.linter}`,
2528
+ inheritedSettings.formatter && `formatter: ${inheritedSettings.formatter}`,
2529
+ inheritedSettings.packageManager && `pm: ${inheritedSettings.packageManager.name}`
2530
+ ].filter(Boolean).join(", ");
2531
+ p.log.info(`Using workspace settings (${settingsInfo})`);
2532
+ }
2533
+ const scope = await getMonorepoScope(monorepoRoot);
2534
+ let addMore = true;
2535
+ while (addMore) {
2536
+ addMore = await createPackageInWorkspace(
2537
+ monorepoRoot,
2538
+ inheritedSettings.packageManager?.name ?? "pnpm",
2539
+ inheritedSettings,
2540
+ scope
2541
+ );
2542
+ }
2543
+ p.note([`cd ${monorepoRoot}`, "pnpm install", "pnpm run dev"].join("\n"), "Next steps");
2544
+ p.outro(color.green("Happy coding! \u2728"));
2545
+ process.exit(0);
2546
+ }
2547
+ }
2548
+ async function main() {
2549
+ const program = new Command().name("create-krispya").description("CLI for creating Vanilla, React, and React Three Fiber projects").argument("[name]", "name for the project").option("--type <type>", "project type: app or library (default: app)").option(
2550
+ "--bundler <bundler>",
2551
+ "library bundler: unbuild or tsdown (default: unbuild, only for libraries)"
2552
+ ).option(
2553
+ "--template <type>",
2554
+ "project template: vanilla, vanilla-js, react, react-js, r3f, r3f-js (default: vanilla)"
2555
+ ).option("--linter <type>", "linter: eslint, oxlint, or biome (default: oxlint)").option("--formatter <type>", "formatter: prettier, oxfmt, or biome (default: prettier)").option("--drei", "add @react-three/drei (r3f only)").option("--handle", "add @react-three/handle (r3f only)").option("--leva", "add leva (r3f only)").option("--postprocessing", "add @react-three/postprocessing (r3f only)").option("--rapier", "add @react-three/rapier (r3f only)").option("--xr", "add @react-three/xr (r3f only)").option("--uikit", "add @react-three/uikit (r3f only)").option("--offscreen", "add @react-three/offscreen (r3f only)").option("--zustand", "add zustand (r3f only)").option("--koota", "add koota (r3f only)").option("--triplex", "set up triplex development environment (r3f only)").option("--viverse", "set up viverse deployment (r3f only)").option("--package-manager <manager>", "specify package manager (e.g. npm, yarn, pnpm)").option(
2556
+ "--pnpm-manage-versions",
2557
+ "enable manage-package-manager-versions in pnpm-workspace.yaml (default: true)"
2558
+ ).option(
2559
+ "--no-pnpm-manage-versions",
2560
+ "disable manage-package-manager-versions in pnpm-workspace.yaml"
2561
+ ).option(
2562
+ "--node-version <version>",
2563
+ 'set Node.js version for engines.node field (default: "latest")'
2564
+ ).option("--workspace", "Add package to current monorepo workspace (non-interactive)").option("--dir <directory>", "Target directory for --workspace (default: apps/ or packages/)").option("--clear-config", "Clear saved preferences").option("--config-path", "Print the path to the config file").option("--check", "Check if current directory is in a valid monorepo workspace").option("--fix", "Fix monorepo by generating missing .config packages").option("--update", "Update monorepo workspace to latest configuration").option("-y, --yes", "Non-interactive mode - accept all prompts").option(
2565
+ "--path <directory>",
2566
+ "Run in specified directory instead of current working directory"
2567
+ ).action(async (name, options) => {
2568
+ if (options.path) {
2569
+ process.chdir(options.path);
2570
+ }
2571
+ if (options.clearConfig) {
2572
+ clearConfig();
2573
+ console.log("Configuration cleared.");
2574
+ process.exit(0);
2575
+ }
2576
+ if (options.configPath) {
2577
+ console.log(getConfigPath());
2578
+ process.exit(0);
2579
+ }
2580
+ if (name?.startsWith("-")) {
2581
+ switch (name) {
2582
+ case "--version":
2583
+ case "-V":
2584
+ console.log(pkg.version);
2585
+ process.exit(0);
2586
+ case "--help":
2587
+ case "-h":
2588
+ program.help();
2589
+ break;
2590
+ case "--clear-config":
2591
+ clearConfig();
2592
+ console.log("Configuration cleared.");
2593
+ process.exit(0);
2594
+ case "--config-path":
2595
+ console.log(getConfigPath());
2596
+ process.exit(0);
2597
+ case "--check":
2598
+ await handleCheckCommand();
2599
+ break;
2600
+ case "--fix":
2601
+ options.fix = true;
2602
+ break;
2603
+ case "--update":
2604
+ options.update = true;
2605
+ break;
2606
+ case "--yes":
2607
+ options.yes = true;
2608
+ break;
2609
+ default:
2610
+ console.error(color.red(`Unknown option: ${name}`));
2611
+ process.exit(1);
2612
+ }
2613
+ }
2614
+ if (options.check) {
2615
+ await handleCheckCommand();
2616
+ }
2617
+ if (options.fix) {
2618
+ await handleFixCommand(options);
2619
+ }
2620
+ if (options.update) {
2621
+ await handleUpdateCommand(options);
2622
+ }
2623
+ if (options.dir && !options.workspace) {
2624
+ console.error(color.red("Error:") + " --dir requires --workspace flag");
2625
+ console.log(
2626
+ color.dim(" Example: pnpm create krispya my-lib --workspace --dir examples")
2627
+ );
2628
+ process.exit(1);
2629
+ }
2630
+ if (options.workspace) {
2631
+ await handleWorkspaceCommand(name, options);
2632
+ }
2633
+ console.clear();
2634
+ p.intro(color.bgCyan(color.black(` create-krispya v${pkg.version} `)));
2635
+ const monorepoRoot = await detectMonorepoRoot();
2636
+ if (monorepoRoot && !hasConfigOptions(options)) {
2637
+ await handleInteractiveMonorepoMode(monorepoRoot);
2638
+ }
2639
+ let generateOptions;
2640
+ if (options.yes) {
2641
+ const template = options.template ?? "vanilla";
2642
+ const baseTemplate = getBaseTemplate(template);
2643
+ const defaultName = getDefaultProjectName(template);
2644
+ const projectType = options.type ?? "app";
2645
+ generateOptions = {
2646
+ name: name || defaultName,
2647
+ projectType,
2648
+ libraryBundler: projectType === "library" ? options.bundler ?? "unbuild" : void 0,
2649
+ template,
2650
+ linter: options.linter ?? "oxlint",
2651
+ formatter: options.formatter ?? "prettier",
2652
+ ...baseTemplate === "r3f" && {
2653
+ drei: options.drei ? {} : void 0,
2654
+ handle: options.handle ? {} : void 0,
2655
+ leva: options.leva ? {} : void 0,
2656
+ postprocessing: options.postprocessing ? {} : void 0,
2657
+ rapier: options.rapier ? {} : void 0,
2658
+ xr: options.xr ? {} : void 0,
2659
+ uikit: options.uikit ? {} : void 0,
2660
+ offscreen: options.offscreen ? {} : void 0,
2661
+ zustand: options.zustand ? {} : void 0,
2662
+ koota: options.koota ? {} : void 0,
2663
+ viverse: options.viverse ? {} : void 0,
2664
+ triplex: options.triplex ? {} : void 0
2665
+ },
2666
+ packageManager: options.packageManager ? { name: options.packageManager } : void 0,
2667
+ pnpmManageVersions: options.pnpmManageVersions,
2668
+ engine: { name: "node", version: options.nodeVersion ?? "latest" }
2669
+ };
2670
+ } else {
2671
+ const presets = hasConfigOptions(options) ? {
2672
+ type: options.type,
2673
+ template: options.template,
2674
+ bundler: options.bundler,
2675
+ linter: options.linter,
2676
+ formatter: options.formatter,
2677
+ packageManager: options.packageManager,
2678
+ engine: options.nodeVersion ? { name: "node", version: options.nodeVersion } : void 0,
2679
+ pnpmManageVersions: options.pnpmManageVersions,
2680
+ drei: options.drei,
2681
+ handle: options.handle,
2682
+ leva: options.leva,
2683
+ postprocessing: options.postprocessing,
2684
+ rapier: options.rapier,
2685
+ xr: options.xr,
2686
+ uikit: options.uikit,
2687
+ offscreen: options.offscreen,
2688
+ zustand: options.zustand,
2689
+ koota: options.koota,
2690
+ triplex: options.triplex,
2691
+ viverse: options.viverse
2692
+ } : void 0;
2693
+ generateOptions = await promptForOptions(name, presets);
2694
+ }
2695
+ const isNonInteractive = options.yes ?? false;
2696
+ if (generateOptions.projectType === "monorepo") {
2697
+ await handleMonorepoCreation(generateOptions, isNonInteractive);
2698
+ } else {
2699
+ await handleStandaloneProjectCreation(generateOptions, isNonInteractive);
2700
+ }
2701
+ });
2702
+ await program.parseAsync();
2703
+ }
2704
+ main().catch(console.error);