create-krispya 0.7.0 → 0.8.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/index.cjs CHANGED
@@ -1,2971 +1,23 @@
1
1
  'use strict';
2
2
 
3
- const chalk = require('chalk');
4
- const promises = require('fs/promises');
5
- const fs = require('fs');
6
- const path = require('path');
7
-
8
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
9
-
10
- const chalk__default = /*#__PURE__*/_interopDefaultCompat(chalk);
11
-
12
- const HtmlContent = `<!DOCTYPE html>
13
- <html lang="en">
14
- <head>
15
- <meta charset="UTF-8">
16
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
17
- <title>$title</title>
18
- </head>
19
- <body style="margin: 0; overscroll-behavior: none; user-select: none; touch-action: none;">
20
- <script type="module" src="$indexPath"><\/script>
21
- <div style="width: 100dvw; height: 100dvh; overflow: hidden;" id="root"></div>
22
- </body>
23
- </html>`;
24
- const ViteHtmlContent = `<!DOCTYPE html>
25
- <html lang="en">
26
- <head>
27
- <meta charset="UTF-8">
28
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
29
- <title>$title</title>
30
- </head>
31
- <body>
32
- <div id="app"></div>
33
- <script type="module" src="$indexPath"><\/script>
34
- </body>
35
- </html>`;
36
- const IndexContent = `import { StrictMode } from 'react'
37
- import { createRoot } from 'react-dom/client'
38
- import { App } from './app.js'
39
-
40
- createRoot(document.getElementById('root')!).render(
41
- <StrictMode>
42
- <App />
43
- </StrictMode>,
44
- )`;
45
- const ViteIndexContent = `import './style.css'
46
-
47
- document.querySelector('#app')!.innerHTML = \`
48
- <h1>Hello Vite!</h1>
49
- <p>Edit src/main.ts and save to see HMR in action.</p>
50
- \``;
51
- const ViteStyleContent = `body {
52
- font-family: system-ui, -apple-system, sans-serif;
53
- margin: 0;
54
- padding: 2rem;
55
- min-height: 100vh;
56
- background: #1a1a1a;
57
- color: #fff;
58
- }
59
-
60
- h1 {
61
- color: #646cff;
62
- }
63
-
64
- a {
65
- color: #646cff;
66
- }`;
67
- const GitAttributes = [
68
- "* text eol=lf",
69
- "*.png binary",
70
- "*.jpg binary",
71
- "*.jpeg binary",
72
- "*.gif binary",
73
- "*.ico binary",
74
- "*.mov binary",
75
- "*.mp4 binary",
76
- "*.mp3 binary",
77
- "*.flv binary",
78
- "*.fla binary",
79
- "*.wav binary",
80
- "*.swf binary",
81
- "*.gz binary",
82
- "*.zip binary",
83
- "*.7z binary",
84
- "*.ttf binary",
85
- "*.eot binary",
86
- "*.woff binary",
87
- "*.pyc binary",
88
- "*.pdf binary",
89
- "*.glb binary",
90
- "*.gltf binary"
91
- ].join("\n");
92
- const defaultFormatterConfig = {
93
- printWidth: 102,
94
- tabWidth: 2,
95
- useTabs: false,
96
- semi: true,
97
- singleQuote: true,
98
- trailingComma: "es5",
99
- bracketSpacing: true,
100
- arrowParens: "always"
101
- };
102
- const defaultPrettierConfig = {
103
- $schema: "https://json.schemastore.org/prettierrc",
104
- ...defaultFormatterConfig,
105
- overrides: [
106
- {
107
- files: ["*.md", "**/*.md"],
108
- options: { semi: false }
109
- },
110
- {
111
- files: ["*.yml", "*.yaml", "**/*.yml", "**/*.yaml"],
112
- options: { semi: false }
113
- }
114
- ]
115
- };
116
- const defaultOxfmtConfig = {
117
- printWidth: defaultFormatterConfig.printWidth,
118
- tabWidth: defaultFormatterConfig.tabWidth,
119
- useTabs: defaultFormatterConfig.useTabs,
120
- semi: defaultFormatterConfig.semi,
121
- singleQuote: defaultFormatterConfig.singleQuote,
122
- trailingComma: defaultFormatterConfig.trailingComma,
123
- bracketSpacing: defaultFormatterConfig.bracketSpacing,
124
- arrowParens: defaultFormatterConfig.arrowParens
125
- };
126
- const defaultLinterConfig = {
127
- ignorePatterns: ["dist"],
128
- rules: {
129
- noUnusedVars: {
130
- level: "warn",
131
- argsIgnorePattern: "^_",
132
- varsIgnorePattern: "^_",
133
- caughtErrorsIgnorePattern: "^_"
134
- },
135
- noUnusedExpressions: {
136
- level: "warn",
137
- allowShortCircuit: true
138
- }
139
- }
140
- };
141
-
142
- function generateAiFiles(files, params) {
143
- const { platforms, isMonorepo, configStrategy, ...rest } = params;
144
- if (platforms.length === 0) return;
145
- files[".ai/workspace.md"] = {
146
- type: "text",
147
- content: generateWorkspace({
148
- ...rest,
149
- isMonorepo: !!isMonorepo,
150
- configStrategy: configStrategy ?? "stealth"
151
- })
152
- };
153
- const pointer = "See `.ai/` for project rules.\n";
154
- for (const platform of platforms) {
155
- const path = platform === "agents" ? "AGENTS.md" : "CLAUDE.md";
156
- files[path] = { type: "text", content: pointer };
157
- }
158
- }
159
- function generateWorkspace(ctx) {
160
- const { name, packageManager, linter, formatter, isMonorepo, configStrategy } = ctx;
161
- const sections = [
162
- `# ${name}`,
163
- "",
164
- `- **Type:** ${isMonorepo ? "pnpm monorepo" : "standalone project"}`,
165
- `- **Package Manager:** ${packageManager}`,
166
- `- **Linter:** ${linter}`,
167
- `- **Formatter:** ${formatter}`,
168
- "",
169
- "## Commands",
170
- "",
171
- `- \`${packageManager} test\` \u2014 run tests`,
172
- `- \`${packageManager} build\` \u2014 build`,
173
- `- \`${packageManager} lint\` and \`${packageManager} format\` \u2014 run before committing`
174
- ];
175
- if (isMonorepo) {
176
- sections.push(
177
- "",
178
- "## Structure",
179
- "",
180
- "- `apps/` \u2014 applications",
181
- "- `packages/` \u2014 shared libraries",
182
- "- `.config/` \u2014 shared config packages",
183
- "",
184
- "## Monorepo",
185
- "",
186
- "- Use `workspace:*` for internal dependencies",
187
- `- New packages: \`${packageManager} create krispya <name> --workspace\``
188
- );
189
- } else if (configStrategy === "root") {
190
- sections.push(
191
- "",
192
- "## Structure",
193
- "",
194
- "- `src/` \u2014 source code",
195
- "- `dist/` \u2014 generated, don't edit",
196
- "- Config files (`tsconfig.json`, etc.) are at project root"
197
- );
198
- } else {
199
- sections.push(
200
- "",
201
- "## Structure",
202
- "",
203
- "- `src/` \u2014 source code",
204
- "- `.config/` \u2014 configs, don't move",
205
- "- `dist/` \u2014 generated, don't edit"
206
- );
207
- }
208
- sections.push("");
209
- return sections.join("\n");
210
- }
211
-
212
- function generateTypescriptConfig(baseTemplateOrParams) {
213
- const params = typeof baseTemplateOrParams === "string" ? { baseTemplate: baseTemplateOrParams } : baseTemplateOrParams;
214
- const { baseTemplate, useConfigPackage, configStrategy = "stealth", nodeVersion } = params;
215
- const isReact = baseTemplate === "react";
216
- const isR3f = baseTemplate === "r3f";
217
- const files = {};
218
- const devDependencies = {};
219
- if (nodeVersion) {
220
- const majorVersion = nodeVersion.split(".")[0];
221
- devDependencies["@types/node"] = `^${majorVersion}.0.0`;
222
- } else {
223
- devDependencies["@types/node"] = "^22.0.0";
224
- }
225
- if (isReact || isR3f) {
226
- devDependencies["@types/react"] = "^19.0.0";
227
- devDependencies["@types/react-dom"] = "^19.0.0";
228
- }
229
- if (isR3f) {
230
- devDependencies["@types/three"] = "~0.175.0";
231
- }
232
- if (useConfigPackage) {
233
- devDependencies["@config/typescript"] = "workspace:*";
234
- const baseConfig = isReact || isR3f ? "@config/typescript/react.json" : "@config/typescript/app.json";
235
- files["tsconfig.json"] = {
236
- type: "text",
237
- content: JSON.stringify(
238
- {
239
- $schema: "https://json.schemastore.org/tsconfig",
240
- extends: baseConfig,
241
- include: ["src/**/*", "tests/**/*"]
242
- },
243
- null,
244
- 2
245
- )
246
- };
247
- return { files, devDependencies };
248
- }
249
- if (configStrategy === "stealth") {
250
- const tsConfig = {
251
- $schema: "https://json.schemastore.org/tsconfig",
252
- files: [],
253
- references: [{ path: "./.config/tsconfig.app.json" }, { path: "./.config/tsconfig.node.json" }]
254
- };
255
- files["tsconfig.json"] = {
256
- type: "text",
257
- content: JSON.stringify(tsConfig, null, 2)
258
- };
259
- const tsConfigApp = {
260
- $schema: "https://json.schemastore.org/tsconfig",
261
- compilerOptions: {
262
- target: "ESNext",
263
- module: "ESNext",
264
- moduleResolution: "bundler",
265
- lib: ["DOM", "DOM.Iterable", "ESNext"],
266
- esModuleInterop: true,
267
- allowSyntheticDefaultImports: true,
268
- strict: true,
269
- skipLibCheck: true,
270
- composite: true,
271
- rewriteRelativeImportExtensions: true,
272
- erasableSyntaxOnly: true,
273
- ...isReact || isR3f ? { jsx: "react-jsx" } : {}
274
- },
275
- include: ["../src", "../tests"]
276
- };
277
- files[".config/tsconfig.app.json"] = {
278
- type: "text",
279
- content: JSON.stringify(tsConfigApp, null, 2)
280
- };
281
- const tsConfigNode = {
282
- $schema: "https://json.schemastore.org/tsconfig",
283
- compilerOptions: {
284
- target: "ESNext",
285
- module: "ESNext",
286
- moduleResolution: "bundler",
287
- lib: ["ESNext"],
288
- esModuleInterop: true,
289
- allowSyntheticDefaultImports: true,
290
- strict: true,
291
- skipLibCheck: true,
292
- composite: true,
293
- rewriteRelativeImportExtensions: true,
294
- erasableSyntaxOnly: true
295
- },
296
- include: ["../*.config.ts", "./*.ts"]
297
- };
298
- files[".config/tsconfig.node.json"] = {
299
- type: "text",
300
- content: JSON.stringify(tsConfigNode, null, 2)
301
- };
302
- } else {
303
- const tsConfig = {
304
- $schema: "https://json.schemastore.org/tsconfig",
305
- files: [],
306
- references: [{ path: "./tsconfig.app.json" }, { path: "./tsconfig.node.json" }]
307
- };
308
- files["tsconfig.json"] = {
309
- type: "text",
310
- content: JSON.stringify(tsConfig, null, 2)
311
- };
312
- const tsConfigApp = {
313
- $schema: "https://json.schemastore.org/tsconfig",
314
- compilerOptions: {
315
- target: "ESNext",
316
- module: "ESNext",
317
- moduleResolution: "bundler",
318
- lib: ["DOM", "DOM.Iterable", "ESNext"],
319
- esModuleInterop: true,
320
- allowSyntheticDefaultImports: true,
321
- strict: true,
322
- skipLibCheck: true,
323
- composite: true,
324
- rewriteRelativeImportExtensions: true,
325
- erasableSyntaxOnly: true,
326
- ...isReact || isR3f ? { jsx: "react-jsx" } : {}
327
- },
328
- include: ["src", "tests"]
329
- };
330
- files["tsconfig.app.json"] = {
331
- type: "text",
332
- content: JSON.stringify(tsConfigApp, null, 2)
333
- };
334
- const tsConfigNode = {
335
- $schema: "https://json.schemastore.org/tsconfig",
336
- compilerOptions: {
337
- target: "ESNext",
338
- module: "ESNext",
339
- moduleResolution: "bundler",
340
- lib: ["ESNext"],
341
- esModuleInterop: true,
342
- allowSyntheticDefaultImports: true,
343
- strict: true,
344
- skipLibCheck: true,
345
- composite: true,
346
- rewriteRelativeImportExtensions: true,
347
- erasableSyntaxOnly: true
348
- },
349
- include: ["*.config.ts"]
350
- };
351
- files["tsconfig.node.json"] = {
352
- type: "text",
353
- content: JSON.stringify(tsConfigNode, null, 2)
354
- };
355
- }
356
- return { files, devDependencies };
357
- }
358
-
359
- const DEFAULT_LIBRARY_VERSION = "0.1.0";
360
- function generatePackageJson(params) {
361
- const {
362
- name,
363
- language,
364
- isLibrary,
365
- dependencies,
366
- devDependencies,
367
- peerDependencies,
368
- scripts,
369
- options,
370
- workspaceDependencies
371
- } = params;
372
- const files = {};
373
- const packageManager = options.packageManager ?? "pnpm";
374
- const isPnpm = packageManager === "pnpm";
375
- const packageJson = {
376
- name,
377
- description: "Built with \u{1F339} create-krispya",
378
- type: "module"
379
- };
380
- if (isLibrary) {
381
- packageJson.version = DEFAULT_LIBRARY_VERSION;
382
- packageJson.main = "./dist/index.mjs";
383
- packageJson.module = "./dist/index.mjs";
384
- if (language === "typescript") {
385
- packageJson.types = "./dist/index.d.ts";
386
- }
387
- packageJson.exports = {
388
- ".": {
389
- ...language === "typescript" && { types: "./dist/index.d.ts" },
390
- import: "./dist/index.mjs",
391
- require: "./dist/index.cjs"
392
- }
393
- };
394
- packageJson.files = ["dist"];
395
- }
396
- const sortKeys = (obj) => Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
397
- const allDependencies = { ...dependencies };
398
- if (workspaceDependencies && workspaceDependencies.length > 0) {
399
- for (const pkgName of workspaceDependencies) {
400
- allDependencies[pkgName] = "workspace:*";
401
- }
402
- }
403
- const allDevDependencies = { ...devDependencies };
404
- if (options.nodeVersion) {
405
- const majorVersion = options.nodeVersion.split(".")[0];
406
- allDevDependencies["@types/node"] ??= `^${majorVersion}.0.0`;
407
- }
408
- packageJson.scripts = scripts;
409
- packageJson.dependencies = sortKeys(allDependencies);
410
- if (Object.keys(allDevDependencies).length > 0) {
411
- packageJson.devDependencies = sortKeys(allDevDependencies);
412
- }
413
- if (isLibrary && Object.keys(peerDependencies).length > 0) {
414
- packageJson.peerDependencies = sortKeys(peerDependencies);
415
- }
416
- const isMonorepoPackage = options.workspaceRoot != null;
417
- if (!isMonorepoPackage) {
418
- const engines = {};
419
- if (isPnpm) {
420
- const pnpmVersion = options.pnpmVersion ?? "10.11.0";
421
- const majorVersion = pnpmVersion.split(".")[0];
422
- engines.pnpm = `>=${majorVersion}.0.0`;
423
- packageJson.packageManager = `pnpm@${pnpmVersion}`;
424
- } else if (packageManager === "yarn") {
425
- const yarnVersion = options.yarnVersion ?? "4.6.0";
426
- const majorVersion = yarnVersion.split(".")[0];
427
- engines.yarn = `>=${majorVersion}.0.0`;
428
- packageJson.packageManager = `yarn@${yarnVersion}`;
429
- } else if (packageManager === "npm") {
430
- const npmVersion = options.npmVersion ?? "11.0.0";
431
- const majorVersion = npmVersion.split(".")[0];
432
- engines.npm = `>=${majorVersion}.0.0`;
433
- packageJson.packageManager = `npm@${npmVersion}`;
434
- }
435
- if (options.nodeVersion) {
436
- const majorVersion = options.nodeVersion.split(".")[0];
437
- engines.node = `>=${majorVersion}.0.0`;
438
- }
439
- if (Object.keys(engines).length > 0) {
440
- packageJson.engines = engines;
441
- }
442
- }
443
- files["package.json"] = {
444
- type: "text",
445
- content: JSON.stringify(packageJson, null, 2)
446
- };
447
- if (isPnpm && !options.workspaceRoot) {
448
- const manageVersions = options.pnpmManageVersions ?? true;
449
- const workspaceLines = [];
450
- if (manageVersions) {
451
- workspaceLines.push("manage-package-manager-versions: true", "");
452
- }
453
- workspaceLines.push("onlyBuiltDependencies:", " - esbuild");
454
- files["pnpm-workspace.yaml"] = {
455
- type: "text",
456
- content: workspaceLines.join("\n")
457
- };
458
- }
459
- return { files };
460
- }
461
-
462
- function generateReadme(params) {
463
- const { name, baseTemplate, isLibrary, libraryBundler, packageManager, codeSnippets } = params;
464
- const isVanilla = baseTemplate === "vanilla";
465
- const isReact = baseTemplate === "react";
466
- const isR3f = baseTemplate === "r3f";
467
- const ext = "ts";
468
- const jsxExt = "tsx";
469
- codeSnippets["readme-libraries"] ??= [];
470
- codeSnippets["readme-commands"] ??= [];
471
- if (isLibrary) ; else if (isVanilla) {
472
- codeSnippets["readme-libraries"].unshift(
473
- `[Vite](https://vitejs.dev/) - Next generation frontend tooling`
474
- );
475
- } else if (isReact) {
476
- codeSnippets["readme-libraries"].unshift(
477
- `[React](https://react.dev/) - A JavaScript library for building user interfaces`,
478
- `[Vite](https://vitejs.dev/) - Next generation frontend tooling`
479
- );
480
- } else {
481
- codeSnippets["readme-libraries"].unshift(
482
- `[React](https://react.dev/) - A JavaScript library for building user interfaces`,
483
- `[Three.js](https://threejs.org/) - JavaScript 3D library`,
484
- `[@react-three/fiber](https://docs.pmnd.rs/react-three-fiber) - lets you create Three.js scenes using React components`
485
- );
486
- }
487
- if (isLibrary) {
488
- codeSnippets["readme-commands"].unshift(
489
- `\`${packageManager} install\` to install the dependencies`,
490
- `\`${packageManager} run build\` to build the library into the \`dist\` folder`,
491
- `\`${packageManager} run test\` to run the tests`,
492
- `\`${packageManager} run release\` to build and publish to npm`
493
- );
494
- } else {
495
- codeSnippets["readme-commands"].unshift(
496
- `\`${packageManager} install\` to install the dependencies`,
497
- `\`${packageManager} run dev\` to run the development server and preview the app with live updates`,
498
- `\`${packageManager} run build\` to build the app into the \`dist\` folder`,
499
- `\`${packageManager} run test\` to run the tests`
500
- );
501
- }
502
- let architectureDesc;
503
- if (isLibrary) {
504
- architectureDesc = [
505
- `- \`src/index.${isReact || isR3f ? jsxExt : ext}\` is the main entry point for your library exports`,
506
- `- Add your library code in the \`src\` folder`,
507
- `- \`tests/\` contains your test files`
508
- ];
509
- } else if (isVanilla) {
510
- architectureDesc = [
511
- `- \`src/main.${ext}\` is the entry point for your application`,
512
- `- \`tests/\` contains your test files`,
513
- `- Static assets can be placed in the \`public\` folder`
514
- ];
515
- } else if (isReact) {
516
- architectureDesc = [
517
- `- \`src/app.${jsxExt}\` defines the main application component`,
518
- `- \`src/index.${jsxExt}\` renders the React app into the DOM`,
519
- `- \`tests/\` contains your test files`,
520
- `- Static assets can be placed in the \`public\` folder`
521
- ];
522
- } else {
523
- architectureDesc = [
524
- `- \`app.${jsxExt}\` defines the main application component containing your 3D content`,
525
- `- Modify the content inside the \`<Canvas>\` component to change what is visible on screen`,
526
- `- \`tests/\` contains your test files`,
527
- `- Static assets can be placed in the \`public\` folder`
528
- ];
529
- }
530
- const bundlerDescription = isLibrary ? libraryBundler === "unbuild" ? `This library uses [unbuild](https://github.com/unjs/unbuild) for building.` : `This library uses [tsdown](https://github.com/nicepkg/tsdown) for building.` : `This project uses [Vite](https://vitejs.dev/) as the bundler for fast development and optimized production builds.`;
531
- const content = [
532
- `# ${name}`,
533
- `This ${isLibrary ? "library" : "project"} was generated with create-krispya`,
534
- ...codeSnippets["readme-start"] ?? [],
535
- "\n",
536
- `## Project Architecture`,
537
- bundlerDescription,
538
- ...architectureDesc,
539
- "\n",
540
- `## Libraries`,
541
- `The following libraries are used - checkout the linked docs to learn more`,
542
- ...(codeSnippets["readme-libraries"] ?? []).map((library) => `- ${library}`),
543
- "\n",
544
- codeSnippets["readme-tools"] && `## Tools`,
545
- ...(codeSnippets["readme-tools"] ?? []).map((tool) => `- ${tool}`),
546
- codeSnippets["readme-tools"] && `
547
- `,
548
- `## Development Commands`,
549
- ...(codeSnippets["readme-commands"] ?? []).map((command) => `- ${command}`),
550
- ...codeSnippets["readme-end"] ?? []
551
- ].filter(Boolean).join("\n");
552
- return { type: "text", content };
553
- }
554
-
555
- function generateSourceFiles(params) {
556
- const { name, baseTemplate, language, isLibrary, codeSnippets, replacements } = params;
557
- const files = {};
558
- const ext = language === "typescript" ? "ts" : "js";
559
- const jsxExt = language === "typescript" ? "tsx" : "jsx";
560
- const isVanilla = baseTemplate === "vanilla";
561
- const isReact = baseTemplate === "react";
562
- const isR3f = baseTemplate === "r3f";
563
- if (isLibrary) {
564
- const libExt = isReact || isR3f ? jsxExt : ext;
565
- let libContent;
566
- if (isVanilla) {
567
- libContent = [
568
- `// Library entry point`,
569
- `export function hello(name: string = "world"): string {`,
570
- ` return \`Hello, \${name}!\``,
571
- `}`
572
- ].join("\n");
573
- } else if (isReact) {
574
- libContent = [
575
- `// Library entry point`,
576
- `export function MyComponent({ message = "Hello from library!" }: { message?: string }) {`,
577
- ` return <div>{message}</div>`,
578
- `}`
579
- ].join("\n");
580
- } else {
581
- libContent = [
582
- `// Library entry point`,
583
- `export function MyMesh({ color = "orange" }: { color?: string }) {`,
584
- ` return (`,
585
- ` <mesh>`,
586
- ` <boxGeometry />`,
587
- ` <meshStandardMaterial color={color} />`,
588
- ` </mesh>`,
589
- ` )`,
590
- `}`
591
- ].join("\n");
592
- }
593
- files[`src/index.${libExt}`] = { type: "text", content: libContent };
594
- } else if (isVanilla) {
595
- files[`src/main.${ext}`] = { type: "text", content: ViteIndexContent };
596
- files["src/style.css"] = { type: "text", content: ViteStyleContent };
597
- const indexHtml = ViteHtmlContent.replace("$indexPath", `./src/main.${ext}`).replace(
598
- "$title",
599
- name
600
- );
601
- files["index.html"] = { type: "text", content: indexHtml };
602
- } else {
603
- files[`src/index.tsx`] = { type: "text", content: IndexContent };
604
- const indexHtml = HtmlContent.replace(
605
- "$indexPath",
606
- language === "javascript" ? "./src/index.jsx" : "./src/index.tsx"
607
- ).replace("$title", name);
608
- files["index.html"] = { type: "text", content: indexHtml };
609
- codeSnippets["dom-end"]?.reverse();
610
- codeSnippets["global-end"]?.reverse();
611
- codeSnippets["scene-end"]?.reverse();
612
- let appCode;
613
- if (isReact) {
614
- appCode = [
615
- ...codeSnippets["import"] ?? [],
616
- ...codeSnippets["global-start"] ?? [],
617
- `export function App() {`,
618
- " return (",
619
- ' <div style={{ padding: "2rem" }}>',
620
- " <h1>Hello React!</h1>",
621
- " <p>Edit src/app.tsx and save to see changes.</p>",
622
- " </div>",
623
- " )",
624
- "}",
625
- ...codeSnippets["global-end"] ?? []
626
- ].join("\n");
627
- } else {
628
- appCode = [
629
- ...codeSnippets["import"] ?? [],
630
- ...codeSnippets["global-start"] ?? [],
631
- `export function App() {`,
632
- " return <>",
633
- ...codeSnippets["dom-start"] ?? [],
634
- ...codeSnippets["dom"] ?? [],
635
- " <Canvas>",
636
- ...codeSnippets["scene-start"] ?? [],
637
- ...codeSnippets["scene"] ?? [],
638
- ...codeSnippets["scene-end"] ?? [],
639
- " </Canvas>",
640
- ...codeSnippets["dom-end"] ?? [],
641
- " </>",
642
- "}",
643
- ...codeSnippets["global-end"] ?? []
644
- ].join("\n");
645
- }
646
- for (const { search, replace } of replacements) {
647
- appCode = appCode.replace(search, replace);
648
- }
649
- files[`src/app.tsx`] = { type: "text", content: appCode };
650
- }
651
- return files;
652
- }
653
-
654
- function generateTestFiles(params) {
655
- const { baseTemplate, language, isLibrary } = params;
656
- const files = {};
657
- const ext = language === "typescript" ? "ts" : "js";
658
- const jsxExt = language === "typescript" ? "tsx" : "jsx";
659
- const isVanilla = baseTemplate === "vanilla";
660
- const isReact = baseTemplate === "react";
661
- const isR3f = baseTemplate === "r3f";
662
- if (isLibrary) {
663
- const testExt = isReact || isR3f ? jsxExt : ext;
664
- let testContent;
665
- if (isVanilla) {
666
- testContent = [
667
- `import { describe, it, expect } from "vitest"`,
668
- `import { hello } from "../src/index.js"`,
669
- ``,
670
- `describe("hello", () => {`,
671
- ` it("returns greeting with default name", () => {`,
672
- ` expect(hello()).toBe("Hello, world!")`,
673
- ` })`,
674
- ``,
675
- ` it("returns greeting with custom name", () => {`,
676
- ` expect(hello("vitest")).toBe("Hello, vitest!")`,
677
- ` })`,
678
- `})`
679
- ].join("\n");
680
- } else if (isReact) {
681
- testContent = [
682
- `import { describe, it, expect } from "vitest"`,
683
- `import { render, screen } from "@testing-library/react"`,
684
- `import { MyComponent } from "../src/index.js"`,
685
- ``,
686
- `describe("MyComponent", () => {`,
687
- ` it("renders with default message", () => {`,
688
- ` render(<MyComponent />)`,
689
- ` expect(screen.getByText("Hello from library!")).toBeDefined()`,
690
- ` })`,
691
- ``,
692
- ` it("renders with custom message", () => {`,
693
- ` render(<MyComponent message="Custom message" />)`,
694
- ` expect(screen.getByText("Custom message")).toBeDefined()`,
695
- ` })`,
696
- `})`
697
- ].join("\n");
698
- } else {
699
- testContent = [
700
- `import { describe, it, expect } from "vitest"`,
701
- `import { MyMesh } from "../src/index.js"`,
702
- ``,
703
- `describe("MyMesh", () => {`,
704
- ` it("is defined", () => {`,
705
- ` expect(MyMesh).toBeDefined()`,
706
- ` })`,
707
- `})`
708
- ].join("\n");
709
- }
710
- files[`tests/index.test.${testExt}`] = {
711
- type: "text",
712
- content: testContent
713
- };
714
- } else if (isVanilla) {
715
- const testContent = [
716
- `import { describe, it, expect } from "vitest"`,
717
- ``,
718
- `describe("example", () => {`,
719
- ` it("works", () => {`,
720
- ` expect(1 + 1).toBe(2)`,
721
- ` })`,
722
- `})`
723
- ].join("\n");
724
- files[`tests/main.test.${ext}`] = { type: "text", content: testContent };
725
- } else if (isReact) {
726
- const testContent = [
727
- `import { describe, it, expect } from "vitest"`,
728
- `import { render, screen } from "@testing-library/react"`,
729
- `import { App } from "../src/app.js"`,
730
- ``,
731
- `describe("App", () => {`,
732
- ` it("renders heading", () => {`,
733
- ` render(<App />)`,
734
- ` expect(screen.getByText("Hello React!")).toBeDefined()`,
735
- ` })`,
736
- `})`
737
- ].join("\n");
738
- files[`tests/app.test.${jsxExt}`] = { type: "text", content: testContent };
739
- } else {
740
- const testContent = [
741
- `import { describe, it, expect } from "vitest"`,
742
- `import { App } from "../src/app.js"`,
743
- ``,
744
- `describe("App", () => {`,
745
- ` it("is defined", () => {`,
746
- ` expect(App).toBeDefined()`,
747
- ` })`,
748
- `})`
749
- ].join("\n");
750
- files[`tests/app.test.${jsxExt}`] = { type: "text", content: testContent };
751
- }
752
- return files;
753
- }
754
-
755
- const COMMON_GITIGNORE_LINES = ["node_modules", "dist", "*.tsbuildinfo", ".env", ".env.*", "!.env.example"];
756
- function generateGitignore(variant) {
757
- const lines = variant === "workspace-root" ? [...COMMON_GITIGNORE_LINES, ".DS_Store"] : COMMON_GITIGNORE_LINES;
758
- return {
759
- type: "text",
760
- content: lines.join("\n")
761
- };
762
- }
763
-
764
- function generateVscodeFiles$1(params) {
765
- const { codeSnippets, vscodeSettings } = params;
766
- const files = {};
767
- if (codeSnippets["vscode-extension-suggestion"]?.length) {
768
- const uniqueRecommendations = [...new Set(codeSnippets["vscode-extension-suggestion"])];
769
- files[".vscode/extensions.json"] = {
770
- type: "text",
771
- content: JSON.stringify(
772
- {
773
- recommendations: uniqueRecommendations
774
- },
775
- null,
776
- 2
777
- )
778
- };
779
- }
780
- if (Object.keys(vscodeSettings).length > 0) {
781
- const sortedSettings = Object.fromEntries(
782
- Object.entries(vscodeSettings).sort(([a], [b]) => a.localeCompare(b))
783
- );
784
- files[".vscode/settings.json"] = {
785
- type: "text",
786
- content: JSON.stringify(sortedSettings, null, 2)
787
- };
788
- }
789
- return files;
790
- }
791
-
792
- function formatValue(value, indent) {
793
- const spaces = " ".repeat(indent);
794
- const innerSpaces = " ".repeat(indent + 1);
795
- if (typeof value === "string") {
796
- if (value.startsWith("$raw:")) {
797
- return value.slice(5);
798
- }
799
- return JSON.stringify(value);
800
- }
801
- if (typeof value === "number" || typeof value === "boolean") {
802
- return String(value);
803
- }
804
- if (value === null) {
805
- return "null";
806
- }
807
- if (Array.isArray(value)) {
808
- if (value.length === 0) return "[]";
809
- const items = value.map((v) => `${innerSpaces}${formatValue(v, indent + 1)}`);
810
- return `[
811
- ${items.join(",\n")}
812
- ${spaces}]`;
813
- }
814
- if (typeof value === "object") {
815
- const entries = Object.entries(value);
816
- if (entries.length === 0) return "{}";
817
- const props = entries.map(
818
- ([key, val]) => `${innerSpaces}${key}: ${formatValue(val, indent + 1)}`
819
- );
820
- return `{
821
- ${props.join(",\n")}
822
- ${spaces}}`;
823
- }
824
- return String(value);
825
- }
826
- function generateViteConfig(params) {
827
- const { viteConfig, codeSnippets } = params;
828
- const configBody = formatValue(viteConfig, 0);
829
- const viteConfigContent = [
830
- `import { defineConfig } from "vite"`,
831
- ...codeSnippets["vite-config-import"] ?? [],
832
- ``,
833
- `export default defineConfig(${configBody})`,
834
- ``
835
- ].join("\n");
836
- return { type: "text", content: viteConfigContent };
837
- }
838
-
839
- function generateTypescriptConfigPackage(files) {
840
- const basePath = ".config/typescript";
841
- files[`${basePath}/package.json`] = {
842
- type: "text",
843
- content: JSON.stringify(
844
- {
845
- name: "@config/typescript",
846
- version: "0.1.0",
847
- private: true,
848
- files: ["base.json", "app.json", "node.json", "react.json"]
849
- },
850
- null,
851
- 2
852
- )
853
- };
854
- files[`${basePath}/README.md`] = {
855
- type: "text",
856
- content: `# \`@config/typescript\`
857
-
858
- These are base shared \`tsconfig.json\`s from which all other \`tsconfig.json\`s inherit.
859
-
860
- ## Usage
861
-
862
- In your package's \`tsconfig.json\`:
863
-
864
- \`\`\`json
865
- {
866
- "extends": "@config/typescript/app.json",
867
- "include": ["src/**/*", "tests"]
868
- }
869
- \`\`\`
870
-
871
- ## Available Configs
872
-
873
- - \`base.json\` - Common TypeScript compiler options
874
- - \`app.json\` - For browser/DOM code (extends base)
875
- - \`node.json\` - For Node.js code (extends base)
876
- - \`react.json\` - For React projects with JSX (extends app)
877
- `
878
- };
879
- files[`${basePath}/base.json`] = {
880
- type: "text",
881
- content: JSON.stringify(
882
- {
883
- $schema: "https://json.schemastore.org/tsconfig",
884
- compilerOptions: {
885
- target: "ESNext",
886
- module: "ESNext",
887
- moduleResolution: "bundler",
888
- esModuleInterop: true,
889
- allowSyntheticDefaultImports: true,
890
- strict: true,
891
- skipLibCheck: true,
892
- composite: true,
893
- rewriteRelativeImportExtensions: true,
894
- erasableSyntaxOnly: true
895
- }
896
- },
897
- null,
898
- 2
899
- )
900
- };
901
- files[`${basePath}/app.json`] = {
902
- type: "text",
903
- content: JSON.stringify(
904
- {
905
- $schema: "https://json.schemastore.org/tsconfig",
906
- extends: "./base.json",
907
- compilerOptions: {
908
- lib: ["DOM", "DOM.Iterable", "ESNext"]
909
- }
910
- },
911
- null,
912
- 2
913
- )
914
- };
915
- files[`${basePath}/node.json`] = {
916
- type: "text",
917
- content: JSON.stringify(
918
- {
919
- $schema: "https://json.schemastore.org/tsconfig",
920
- extends: "./base.json",
921
- compilerOptions: {
922
- lib: ["ESNext"]
923
- }
924
- },
925
- null,
926
- 2
927
- )
928
- };
929
- files[`${basePath}/react.json`] = {
930
- type: "text",
931
- content: JSON.stringify(
932
- {
933
- $schema: "https://json.schemastore.org/tsconfig",
934
- extends: "./app.json",
935
- compilerOptions: {
936
- jsx: "react-jsx"
937
- }
938
- },
939
- null,
940
- 2
941
- )
942
- };
943
- }
944
- function generateOxlintConfigPackage(files) {
945
- const basePath = ".config/oxlint";
946
- const { rules } = defaultLinterConfig;
947
- files[`${basePath}/package.json`] = {
948
- type: "text",
949
- content: JSON.stringify(
950
- {
951
- name: "@config/oxlint",
952
- version: "0.1.0",
953
- private: true,
954
- files: ["base.json", "react.json"]
955
- },
956
- null,
957
- 2
958
- )
959
- };
960
- files[`${basePath}/README.md`] = {
961
- type: "text",
962
- content: `# \`@config/oxlint\`
963
-
964
- Shared oxlint configurations for the monorepo.
965
-
966
- ## Usage
967
-
968
- Run oxlint with a config:
969
-
970
- \`\`\`bash
971
- oxlint -c node_modules/@config/oxlint/base.json
972
- \`\`\`
973
-
974
- ## Available Configs
975
-
976
- - \`base.json\` - Base linting rules for TypeScript projects
977
- - \`react.json\` - Extends base with React-specific rules
978
- `
979
- };
980
- files[`${basePath}/base.json`] = {
981
- type: "text",
982
- content: JSON.stringify(
983
- {
984
- $schema: "./node_modules/oxlint/configuration_schema.json",
985
- plugins: ["unicorn", "typescript", "oxc"],
986
- rules: {
987
- "no-unused-vars": [
988
- rules.noUnusedVars.level,
989
- {
990
- argsIgnorePattern: rules.noUnusedVars.argsIgnorePattern,
991
- varsIgnorePattern: rules.noUnusedVars.varsIgnorePattern,
992
- caughtErrorsIgnorePattern: rules.noUnusedVars.caughtErrorsIgnorePattern
993
- }
994
- ],
995
- "no-useless-escape": "off",
996
- "no-unused-expressions": [
997
- rules.noUnusedExpressions.level,
998
- { allowShortCircuit: rules.noUnusedExpressions.allowShortCircuit }
999
- ]
1000
- },
1001
- ignorePatterns: defaultLinterConfig.ignorePatterns
1002
- },
1003
- null,
1004
- 2
1005
- )
1006
- };
1007
- files[`${basePath}/react.json`] = {
1008
- type: "text",
1009
- content: JSON.stringify(
1010
- {
1011
- $schema: "./node_modules/oxlint/configuration_schema.json",
1012
- plugins: ["unicorn", "typescript", "oxc", "react"],
1013
- rules: {
1014
- "no-unused-vars": [
1015
- rules.noUnusedVars.level,
1016
- {
1017
- argsIgnorePattern: rules.noUnusedVars.argsIgnorePattern,
1018
- varsIgnorePattern: rules.noUnusedVars.varsIgnorePattern,
1019
- caughtErrorsIgnorePattern: rules.noUnusedVars.caughtErrorsIgnorePattern
1020
- }
1021
- ],
1022
- "no-useless-escape": "off",
1023
- "no-unused-expressions": [
1024
- rules.noUnusedExpressions.level,
1025
- { allowShortCircuit: rules.noUnusedExpressions.allowShortCircuit }
1026
- ]
1027
- },
1028
- ignorePatterns: defaultLinterConfig.ignorePatterns
1029
- },
1030
- null,
1031
- 2
1032
- )
1033
- };
1034
- }
1035
- function generateEslintConfigPackage(files) {
1036
- const basePath = ".config/eslint";
1037
- files[`${basePath}/package.json`] = {
1038
- type: "text",
1039
- content: JSON.stringify(
1040
- {
1041
- name: "@config/eslint",
1042
- version: "0.1.0",
1043
- private: true,
1044
- type: "module",
1045
- exports: {
1046
- "./base": "./base.js",
1047
- "./react": "./react.js"
1048
- },
1049
- files: ["base.js", "react.js"],
1050
- devDependencies: {
1051
- "@eslint/js": "^9.17.0",
1052
- "typescript-eslint": "^8.18.0"
1053
- }
1054
- },
1055
- null,
1056
- 2
1057
- )
1058
- };
1059
- files[`${basePath}/README.md`] = {
1060
- type: "text",
1061
- content: `# \`@config/eslint\`
1062
-
1063
- Shared ESLint configurations for the monorepo.
1064
-
1065
- ## Usage
1066
-
1067
- In your package's \`eslint.config.js\`:
1068
-
1069
- \`\`\`js
1070
- import base from "@config/eslint/base";
1071
-
1072
- export default [...base];
1073
- \`\`\`
1074
-
1075
- Or for React projects:
1076
-
1077
- \`\`\`js
1078
- import react from "@config/eslint/react";
1079
-
1080
- export default [...react];
1081
- \`\`\`
1082
-
1083
- ## Available Configs
1084
-
1085
- - \`base\` - Base linting rules for TypeScript projects
1086
- - \`react\` - Extends base with React-specific rules
1087
- `
1088
- };
1089
- files[`${basePath}/base.js`] = {
1090
- type: "text",
1091
- content: `import js from "@eslint/js";
1092
- import tseslint from "typescript-eslint";
1093
-
1094
- export default tseslint.config(
1095
- js.configs.recommended,
1096
- ...tseslint.configs.recommended,
1097
- {
1098
- rules: {
1099
- "@typescript-eslint/no-unused-vars": [
1100
- "error",
1101
- {
1102
- argsIgnorePattern: "^_",
1103
- varsIgnorePattern: "^_",
1104
- caughtErrorsIgnorePattern: "^_",
1105
- },
1106
- ],
1107
- },
1108
- },
1109
- {
1110
- ignores: ["dist/**", "node_modules/**"],
1111
- }
1112
- );
1113
- `
1114
- };
1115
- files[`${basePath}/react.js`] = {
1116
- type: "text",
1117
- content: `import js from "@eslint/js";
1118
- import tseslint from "typescript-eslint";
1119
-
1120
- export default tseslint.config(
1121
- js.configs.recommended,
1122
- ...tseslint.configs.recommended,
1123
- {
1124
- rules: {
1125
- "@typescript-eslint/no-unused-vars": [
1126
- "error",
1127
- {
1128
- argsIgnorePattern: "^_",
1129
- varsIgnorePattern: "^_",
1130
- caughtErrorsIgnorePattern: "^_",
1131
- },
1132
- ],
1133
- },
1134
- },
1135
- {
1136
- ignores: ["dist/**", "node_modules/**"],
1137
- }
1138
- );
1139
- `
1140
- };
1141
- }
1142
- function generatePrettierConfigPackage(files) {
1143
- const basePath = ".config/prettier";
1144
- files[`${basePath}/package.json`] = {
1145
- type: "text",
1146
- content: JSON.stringify(
1147
- {
1148
- name: "@config/prettier",
1149
- version: "0.1.0",
1150
- private: true,
1151
- type: "module",
1152
- exports: {
1153
- ".": "./base.json"
1154
- },
1155
- files: ["base.json"]
1156
- },
1157
- null,
1158
- 2
1159
- )
1160
- };
1161
- files[`${basePath}/README.md`] = {
1162
- type: "text",
1163
- content: `# \`@config/prettier\`
1164
-
1165
- Shared Prettier configuration for the monorepo.
1166
-
1167
- ## Usage
1168
-
1169
- In your package's \`package.json\`:
1170
-
1171
- \`\`\`json
1172
- {
1173
- "prettier": "@config/prettier"
1174
- }
1175
- \`\`\`
1176
-
1177
- Or in \`.prettierrc.json\`:
1178
-
1179
- \`\`\`json
1180
- "@config/prettier"
1181
- \`\`\`
1182
-
1183
- ## Available Configs
1184
-
1185
- - Default export - Base formatter settings
1186
- `
1187
- };
1188
- files[`${basePath}/base.json`] = {
1189
- type: "text",
1190
- content: JSON.stringify(defaultPrettierConfig, null, 2)
1191
- };
1192
- }
1193
- function generateOxfmtConfigPackage(files) {
1194
- const basePath = ".config/oxfmt";
1195
- files[`${basePath}/package.json`] = {
1196
- type: "text",
1197
- content: JSON.stringify(
1198
- {
1199
- name: "@config/oxfmt",
1200
- version: "0.1.0",
1201
- private: true,
1202
- files: ["base.json"]
1203
- },
1204
- null,
1205
- 2
1206
- )
1207
- };
1208
- files[`${basePath}/README.md`] = {
1209
- type: "text",
1210
- content: `# \`@config/oxfmt\`
1211
-
1212
- Shared oxfmt (formatter) configuration for the monorepo.
1213
-
1214
- ## Usage
1215
-
1216
- Run oxfmt with the config:
1217
-
1218
- \`\`\`bash
1219
- oxfmt -c node_modules/@config/oxfmt/base.json --write .
1220
- \`\`\`
1221
-
1222
- ## Available Configs
1223
-
1224
- - \`base.json\` - Base formatter settings (Prettier-compatible)
1225
- `
1226
- };
1227
- files[`${basePath}/base.json`] = {
1228
- type: "text",
1229
- content: JSON.stringify(defaultOxfmtConfig, null, 2)
1230
- };
1231
- }
1232
-
1233
- function generateMonorepo(params) {
1234
- const {
1235
- name,
1236
- linter,
1237
- formatter,
1238
- packageManager,
1239
- pnpmVersion,
1240
- pnpmManageVersions,
1241
- nodeVersion,
1242
- aiPlatforms
1243
- } = params;
1244
- const files = {};
1245
- const isPnpm = packageManager === "pnpm";
1246
- const devDependencies = {};
1247
- if (nodeVersion) {
1248
- const majorVersion = nodeVersion.split(".")[0];
1249
- devDependencies["@types/node"] = `^${majorVersion}.0.0`;
1250
- } else {
1251
- devDependencies["@types/node"] = "^22.0.0";
1252
- }
1253
- if (linter === "oxlint") {
1254
- devDependencies["oxlint"] = "^1.36.0";
1255
- } else if (linter === "eslint") {
1256
- devDependencies["eslint"] = "^9.17.0";
1257
- } else if (linter === "biome") {
1258
- devDependencies["@biomejs/biome"] = "^1.9.4";
1259
- }
1260
- if (formatter === "oxfmt") {
1261
- devDependencies["oxfmt"] = "^0.21.0";
1262
- } else if (formatter === "prettier") {
1263
- devDependencies["prettier"] = "^3.4.2";
1264
- }
1265
- const rootPackageJson = {
1266
- name: "root",
1267
- version: "0.0.0",
1268
- private: true,
1269
- type: "module",
1270
- scripts: {
1271
- dev: "pnpm --filter './apps/*' run dev",
1272
- build: "pnpm --filter './packages/*' run build && pnpm --filter './apps/*' run build",
1273
- test: "pnpm -r run test",
1274
- lint: linter === "oxlint" ? "oxlint ." : linter === "biome" ? "biome check ." : "eslint .",
1275
- format: formatter === "oxfmt" ? "oxfmt -c .config/oxfmt/base.json ." : formatter === "biome" ? "biome format . --write" : "prettier --config .config/prettier/base.json --write ."
1276
- },
1277
- devDependencies
1278
- };
1279
- const engines = {};
1280
- if (isPnpm && pnpmVersion) {
1281
- const majorVersion = pnpmVersion.split(".")[0];
1282
- engines.pnpm = `>=${majorVersion}.0.0`;
1283
- rootPackageJson.packageManager = `pnpm@${pnpmVersion}`;
1284
- }
1285
- if (nodeVersion) {
1286
- const majorVersion = nodeVersion.split(".")[0];
1287
- engines.node = `>=${majorVersion}.0.0`;
1288
- }
1289
- if (Object.keys(engines).length > 0) {
1290
- rootPackageJson.engines = engines;
1291
- }
1292
- files["package.json"] = {
1293
- type: "text",
1294
- content: JSON.stringify(rootPackageJson, null, 2)
1295
- };
1296
- if (isPnpm) {
1297
- const workspaceLines = [];
1298
- if (pnpmManageVersions) {
1299
- workspaceLines.push("manage-package-manager-versions: true", "");
1300
- }
1301
- workspaceLines.push(
1302
- "packages:",
1303
- ' - ".config/*"',
1304
- ' - "apps/*"',
1305
- ' - "packages/*"',
1306
- ""
1307
- );
1308
- workspaceLines.push("onlyBuiltDependencies:", " - esbuild");
1309
- files["pnpm-workspace.yaml"] = {
1310
- type: "text",
1311
- content: workspaceLines.join("\n")
1312
- };
1313
- }
1314
- files["tsconfig.json"] = {
1315
- type: "text",
1316
- content: JSON.stringify(
1317
- {
1318
- extends: "@config/typescript/base.json",
1319
- compilerOptions: {
1320
- noEmit: true
1321
- },
1322
- references: []
1323
- },
1324
- null,
1325
- 2
1326
- )
1327
- };
1328
- generateTypescriptConfigPackage(files);
1329
- if (linter === "oxlint") {
1330
- generateOxlintConfigPackage(files);
1331
- files["oxlint.json"] = {
1332
- type: "text",
1333
- content: JSON.stringify(
1334
- {
1335
- $schema: "./node_modules/oxlint/configuration_schema.json",
1336
- extends: ["@config/oxlint/base.json"]
1337
- },
1338
- null,
1339
- 2
1340
- )
1341
- };
1342
- } else if (linter === "eslint") {
1343
- generateEslintConfigPackage(files);
1344
- files["eslint.config.js"] = {
1345
- type: "text",
1346
- content: `import base from "@config/eslint/base";
1347
-
1348
- export default [...base];
1349
- `
1350
- };
1351
- } else if (linter === "biome") {
1352
- const biomeConfig = {
1353
- $schema: "https://biomejs.dev/schemas/1.9.4/schema.json",
1354
- vcs: {
1355
- enabled: true,
1356
- clientKind: "git",
1357
- useIgnoreFile: true
1358
- },
1359
- linter: {
1360
- enabled: true,
1361
- rules: {
1362
- recommended: true
1363
- }
1364
- },
1365
- formatter: {
1366
- enabled: formatter === "biome"
1367
- }
1368
- };
1369
- files["biome.json"] = {
1370
- type: "text",
1371
- content: JSON.stringify(biomeConfig, null, 2)
1372
- };
1373
- }
1374
- if (formatter === "oxfmt") {
1375
- generateOxfmtConfigPackage(files);
1376
- } else if (formatter === "prettier") {
1377
- generatePrettierConfigPackage(files);
1378
- }
1379
- files[".gitignore"] = generateGitignore("workspace-root");
1380
- files[".gitattributes"] = {
1381
- type: "text",
1382
- content: `* text=auto eol=lf
1383
- *.{cmd,[cC][mM][dD]} text eol=crlf
1384
- *.{bat,[bB][aA][tT]} text eol=crlf
1385
- `
1386
- };
1387
- generateVscodeFiles(files, linter, formatter);
1388
- files["README.md"] = {
1389
- type: "text",
1390
- content: `# ${name}
1391
-
1392
- This monorepo workspace was generated with create-krispya.
1393
-
1394
- ## Structure
1395
-
1396
- - \`apps/\` - Applications
1397
- - \`packages/\` - Shared packages and libraries
1398
- - \`.config/\` - Shared configuration packages
1399
-
1400
- ## Development Commands
1401
-
1402
- - \`${packageManager} install\` to install all dependencies
1403
- - \`${packageManager} run dev\` to run all applications in development mode
1404
- - \`${packageManager} run build\` to build all packages and applications
1405
- - \`${packageManager} run test\` to run tests across the workspace
1406
- - \`${packageManager} run lint\` to lint all code
1407
- - \`${packageManager} run format\` to format all code
1408
-
1409
- ## Adding Packages
1410
-
1411
- To add a new package to this workspace, run create-krispya from this directory and it will detect the monorepo.
1412
- `
1413
- };
1414
- if (aiPlatforms && aiPlatforms.length > 0) {
1415
- generateAiFiles(files, {
1416
- name,
1417
- packageManager,
1418
- linter,
1419
- formatter,
1420
- isMonorepo: true,
1421
- platforms: aiPlatforms
1422
- });
1423
- }
1424
- return { files };
1425
- }
1426
- function generateVscodeFiles(files, linter, formatter) {
1427
- const recommendations = [];
1428
- const settings = {};
1429
- if (linter === "oxlint") {
1430
- recommendations.push("oxc.oxc-vscode");
1431
- settings["oxc.enable"] = true;
1432
- settings["eslint.enable"] = false;
1433
- settings["biome.enabled"] = false;
1434
- } else if (linter === "eslint") {
1435
- recommendations.push("dbaeumer.vscode-eslint");
1436
- settings["eslint.enable"] = true;
1437
- settings["oxc.enable"] = false;
1438
- settings["biome.enabled"] = false;
1439
- } else if (linter === "biome") {
1440
- recommendations.push("biomejs.biome");
1441
- settings["biome.enabled"] = true;
1442
- settings["eslint.enable"] = false;
1443
- settings["oxc.enable"] = false;
1444
- }
1445
- if (formatter === "oxfmt") {
1446
- if (!recommendations.includes("oxc.oxc-vscode")) {
1447
- recommendations.push("oxc.oxc-vscode");
1448
- }
1449
- settings["editor.defaultFormatter"] = "oxc.oxc-vscode";
1450
- settings["[json]"] = {
1451
- "editor.defaultFormatter": "vscode.json-language-features"
1452
- };
1453
- settings["[jsonc]"] = {
1454
- "editor.defaultFormatter": "vscode.json-language-features"
1455
- };
1456
- } else if (formatter === "prettier") {
1457
- recommendations.push("esbenp.prettier-vscode");
1458
- settings["editor.defaultFormatter"] = "esbenp.prettier-vscode";
1459
- } else if (formatter === "biome") {
1460
- if (!recommendations.includes("biomejs.biome")) {
1461
- recommendations.push("biomejs.biome");
1462
- }
1463
- settings["editor.defaultFormatter"] = "biomejs.biome";
1464
- }
1465
- files[".vscode/extensions.json"] = {
1466
- type: "text",
1467
- content: JSON.stringify({ recommendations }, null, 2)
1468
- };
1469
- const codeSnippets = {};
1470
- if (recommendations.length > 0) {
1471
- codeSnippets["vscode-extension-suggestion"] = recommendations;
1472
- }
1473
- Object.assign(
1474
- files,
1475
- generateVscodeFiles$1({
1476
- codeSnippets,
1477
- vscodeSettings: settings
1478
- })
1479
- );
1480
- }
1481
-
1482
- function toBiomeLevel(level) {
1483
- return level;
1484
- }
1485
- function generateBiome(generator, options) {
1486
- if (options == null || !options.linter && !options.formatter) {
1487
- return;
1488
- }
1489
- const version = generator.versions.biome ?? "2.0.0";
1490
- generator.addDevDependency("@biomejs/biome", `^${version}`);
1491
- const { rules } = defaultLinterConfig;
1492
- const biomeConfig = {
1493
- $schema: `https://biomejs.dev/schemas/${version}/schema.json`
1494
- };
1495
- if (options.linter) {
1496
- biomeConfig.linter = {
1497
- enabled: true,
1498
- rules: {
1499
- recommended: true,
1500
- correctness: {
1501
- noUnusedVariables: toBiomeLevel(rules.noUnusedVars.level)
1502
- }
1503
- }
1504
- };
1505
- } else {
1506
- biomeConfig.linter = {
1507
- enabled: false
1508
- };
1509
- }
1510
- if (options.formatter) {
1511
- biomeConfig.formatter = {
1512
- enabled: true,
1513
- lineWidth: defaultFormatterConfig.printWidth,
1514
- indentWidth: defaultFormatterConfig.tabWidth,
1515
- indentStyle: "space"
1516
- };
1517
- biomeConfig.javascript = {
1518
- formatter: {
1519
- semicolons: "always" ,
1520
- quoteStyle: "single" ,
1521
- trailingCommas: defaultFormatterConfig.trailingComma,
1522
- bracketSpacing: defaultFormatterConfig.bracketSpacing,
1523
- arrowParentheses: "always"
1524
- }
1525
- };
1526
- biomeConfig.json = {
1527
- formatter: {
1528
- indentWidth: 2
1529
- }
1530
- };
1531
- } else {
1532
- biomeConfig.formatter = {
1533
- enabled: false
1534
- };
1535
- }
1536
- const isStealth = generator.isStealthConfig();
1537
- if (isStealth) {
1538
- generator.addFile(".config/biome.json", {
1539
- type: "text",
1540
- content: JSON.stringify(biomeConfig, null, 2)
1541
- });
1542
- if (options.linter) {
1543
- generator.addScript("lint", "biome lint --config-path .config .");
1544
- }
1545
- if (options.formatter) {
1546
- generator.addScript(
1547
- "format",
1548
- "biome format --config-path .config --write ."
1549
- );
1550
- }
1551
- generator.addVscodeSetting("biome.linter.configPath", ".config/biome.json");
1552
- } else {
1553
- generator.addFile("biome.json", {
1554
- type: "text",
1555
- content: JSON.stringify(biomeConfig, null, 2)
1556
- });
1557
- if (options.linter) {
1558
- generator.addScript("lint", "biome lint .");
1559
- }
1560
- if (options.formatter) {
1561
- generator.addScript("format", "biome format --write .");
1562
- }
1563
- }
1564
- const roles = [];
1565
- if (options.linter) roles.push("linter");
1566
- if (options.formatter) roles.push("formatter");
1567
- generator.inject(
1568
- "readme-tools",
1569
- `[Biome](https://biomejs.dev/) - Fast ${roles.join(
1570
- " and "
1571
- )} for JavaScript and TypeScript`
1572
- );
1573
- generator.inject("vscode-extension-suggestion", "biomejs.biome");
1574
- generator.addVscodeSetting("biome.enabled", true);
1575
- if (options.formatter) {
1576
- generator.addVscodeSetting("editor.defaultFormatter", "biomejs.biome");
1577
- }
1578
- }
1579
-
1580
- function generateDrei(generator, options) {
1581
- if (options == null) {
1582
- return;
1583
- }
1584
- generator.addDependency("@react-three/drei", "^10.0.0");
1585
- generator.inject("import", `import { Environment } from "@react-three/drei"`);
1586
- generator.inject("scene", '<Environment background preset="city" />');
1587
- generator.inject(
1588
- "readme-libraries",
1589
- `[@react-three/drei](https://drei.docs.pmnd.rs/) - Useful helpers for @react-three/fiber`
1590
- );
1591
- }
1592
-
1593
- function getLanguageFromTemplate(template) {
1594
- return template.endsWith("-js") ? "javascript" : "typescript";
1595
- }
1596
- function getBaseTemplate(template) {
1597
- return template.replace("-js", "");
1598
- }
1599
-
1600
- function toEslintLevel(level) {
1601
- return level;
1602
- }
1603
- function generateEslint(generator, options) {
1604
- const version = generator.versions.eslint ?? "9.17.0";
1605
- generator.addDevDependency("eslint", `^${version}`);
1606
- const template = generator.options.template ?? "vanilla";
1607
- const baseTemplate = getBaseTemplate(template);
1608
- const isTypescript = getLanguageFromTemplate(template) === "typescript";
1609
- const isReact = baseTemplate === "react" || baseTemplate === "r3f";
1610
- const { rules } = defaultLinterConfig;
1611
- const imports = ['import js from "@eslint/js"'];
1612
- const configs = ["js.configs.recommended"];
1613
- if (isTypescript) {
1614
- generator.addDevDependency("typescript-eslint", "^8.18.0");
1615
- imports.push('import tseslint from "typescript-eslint"');
1616
- configs.push("...tseslint.configs.recommended");
1617
- }
1618
- if (isReact) {
1619
- generator.addDevDependency("eslint-plugin-react-hooks", "^5.1.0");
1620
- imports.push('import reactHooks from "eslint-plugin-react-hooks"');
1621
- }
1622
- const ignoresArray = JSON.stringify(defaultLinterConfig.ignorePatterns);
1623
- const unusedVarsRule = isTypescript ? "@typescript-eslint/no-unused-vars" : "no-unused-vars";
1624
- const rulesConfig = {
1625
- [unusedVarsRule]: [
1626
- toEslintLevel(rules.noUnusedVars.level),
1627
- {
1628
- argsIgnorePattern: rules.noUnusedVars.argsIgnorePattern,
1629
- varsIgnorePattern: rules.noUnusedVars.varsIgnorePattern,
1630
- caughtErrorsIgnorePattern: rules.noUnusedVars.caughtErrorsIgnorePattern
1631
- }
1632
- ],
1633
- "no-unused-expressions": [
1634
- toEslintLevel(rules.noUnusedExpressions.level),
1635
- { allowShortCircuit: rules.noUnusedExpressions.allowShortCircuit }
1636
- ]
1637
- };
1638
- const rulesString = JSON.stringify(rulesConfig, null, 4).replace(/\n/g, "\n ");
1639
- const configContent = [
1640
- ...imports,
1641
- "",
1642
- "export default [",
1643
- ` { ignores: ${ignoresArray} },`,
1644
- ` ${configs.join(",\n ")},`,
1645
- isReact ? ` {
1646
- plugins: {
1647
- "react-hooks": reactHooks,
1648
- },
1649
- rules: reactHooks.configs.recommended.rules,
1650
- },` : "",
1651
- ` {
1652
- rules: ${rulesString},
1653
- },`,
1654
- "]"
1655
- ].filter(Boolean).join("\n");
1656
- const isStealth = generator.isStealthConfig();
1657
- if (isStealth) {
1658
- generator.addFile(".config/eslint.config.js", {
1659
- type: "text",
1660
- content: configContent
1661
- });
1662
- generator.addScript("lint", "eslint --config .config/eslint.config.js .");
1663
- generator.addVscodeSetting("eslint.options", {
1664
- overrideConfigFile: ".config/eslint.config.js"
1665
- });
1666
- } else {
1667
- generator.addFile("eslint.config.js", {
1668
- type: "text",
1669
- content: configContent
1670
- });
1671
- generator.addScript("lint", "eslint .");
1672
- }
1673
- generator.inject(
1674
- "readme-tools",
1675
- "[ESLint](https://eslint.org/) - Linter for JavaScript and TypeScript"
1676
- );
1677
- generator.inject("vscode-extension-suggestion", "dbaeumer.vscode-eslint");
1678
- generator.addVscodeSetting("eslint.enable", true);
1679
- }
1680
-
1681
- function generateFiber(generator, _options) {
1682
- generator.inject("import", `import { Box } from "./box.js"`);
1683
- generator.inject(
1684
- "scene",
1685
- [
1686
- `<ambientLight intensity={Math.PI / 2} />`,
1687
- `<spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} decay={0} intensity={Math.PI} />`,
1688
- `<pointLight position={[-10, -10, -10]} decay={0} intensity={Math.PI} />`,
1689
- `<Box position={[-1.2, 0, 0]} />`,
1690
- `<Box position={[1.2, 0, 0]} />`
1691
- ].join("\n")
1692
- );
1693
- generator.addFile("src/box.tsx", {
1694
- type: "text",
1695
- content: `import type { Mesh } from 'three'
1696
- import { useRef, useState } from 'react'
1697
- import { useFrame, ThreeElements } from '@react-three/fiber'
1698
-
1699
- export function Box(props: ThreeElements['mesh']) {
1700
- const meshRef = useRef<Mesh>(null!)
1701
- const [hovered, setHover] = useState(false)
1702
- const [active, setActive] = useState(false)
1703
- useFrame((state, delta) => (meshRef.current.rotation.x += delta))
1704
- return (
1705
- <mesh
1706
- {...props}
1707
- ref={meshRef}
1708
- scale={active ? 1.5 : 1}
1709
- onClick={(event) => setActive(!active)}
1710
- onPointerOver={(event) => setHover(true)}
1711
- onPointerOut={(event) => setHover(false)}>
1712
- <boxGeometry args={[1, 1, 1]} />
1713
- <meshStandardMaterial color={hovered ? 'hotpink' : '#2f74c0'} />
1714
- </mesh>
1715
- )
1716
- }`
1717
- });
1718
- }
1719
-
1720
- function generateGithubPages(generator, options) {
1721
- if (options === false || (generator.options.packageManager ?? "npm") != "npm") {
1722
- return;
1723
- }
1724
- generator.addFile(".github/workflows/gh-pages.yml", {
1725
- type: "text",
1726
- content: `name: Deploy to Github Pages
1727
-
1728
- on:
1729
- push:
1730
- branches:
1731
- - main
1732
-
1733
- jobs:
1734
- build-and-deploy:
1735
- runs-on: ubuntu-latest
1736
- permissions:
1737
- pages: write
1738
- contents: read
1739
- id-token: write
1740
-
1741
- environment:
1742
- name: github-pages
1743
- url: \${{ steps.deployment.outputs.page_url }}
1744
-
1745
- steps:
1746
- - name: Checkout code
1747
- uses: actions/checkout@v3
1748
-
1749
- - name: Setup Node
1750
- uses: actions/setup-node@v3
1751
- with:
1752
- node-version: 20
1753
-
1754
- - name: Install dependencies
1755
- run: npm install
1756
-
1757
- - name: Build project
1758
- run: npm run build
1759
-
1760
- - name: Upload artifact
1761
- uses: actions/upload-pages-artifact@v3
1762
- with:
1763
- path: './dist'
1764
-
1765
- - name: Deploy to GitHub Pages
1766
- id: deployment
1767
- uses: actions/deploy-pages@v4
1768
- `
1769
- });
1770
- generator.inject("readme-start", `A github pages deployment action is configurd.`);
1771
- if (generator.options.githubUserName != null && generator.options.githubRepoName != null) {
1772
- const address = `${generator.options.githubUserName}.github.io/${generator.options.githubRepoName}`;
1773
- generator.inject(
1774
- "readme-start",
1775
- `Your app will be publish at [${address}](https://${address}) once the github action is finished.
1776
- `
1777
- );
1778
- }
1779
- }
1780
-
1781
- function generateHandle(generator, options) {
1782
- if (options == null) {
1783
- return;
1784
- }
1785
- generator.addDependency("@react-three/handle", "^6.6.16");
1786
- generator.inject(
1787
- "readme-libraries",
1788
- `[@react-three/handle](https://pmndrs.github.io/xr/docs/handles/introduction) - interactive controls and handles for your 3D objects`
1789
- );
1790
- }
1791
-
1792
- function generateKoota(generator, options) {
1793
- if (options == null) {
1794
- return;
1795
- }
1796
- generator.addDependency("koota", "^0.4.0");
1797
- generator.inject(
1798
- "readme-libraries",
1799
- `[koota](https://github.com/pmndrs/koota) - ECS-based state management library optimized for real-time apps, games, and XR experiences`
1800
- );
1801
- }
1802
-
1803
- function generateLeva(generator, options) {
1804
- if (options == null) {
1805
- return;
1806
- }
1807
- generator.addDependency("leva", "^0.10.0");
1808
- generator.inject(
1809
- "readme-libraries",
1810
- `[leva](https://github.com/pmndrs/leva) - HTML GUI panel for React with lightweight, beautiful and extensible controls`
1811
- );
1812
- }
1813
-
1814
- function generateOffscreen(generator, options) {
1815
- if (options == null) {
1816
- return;
1817
- }
1818
- if (generator.options.xr != null) {
1819
- console.info(
1820
- chalk__default.blue("Info:"),
1821
- "@react-three/offscreen is disabled because it is not supported with XR"
1822
- );
1823
- return;
1824
- }
1825
- generator.addDependency("@react-three/offscreen", "^0.0.8");
1826
- generator.inject(
1827
- "readme-libraries",
1828
- `[@react-three/offscreen](https://github.com/pmndrs/offscreen) - Offload your scene to a worker thread for better performance`
1829
- );
1830
- }
1831
-
1832
- function generateOxfmt(generator, options) {
1833
- const isMonorepo = generator.options.workspaceRoot != null;
1834
- if (isMonorepo) {
1835
- generator.addDevDependency("@config/oxfmt", "workspace:*");
1836
- const configPath = "node_modules/@config/oxfmt/base.json";
1837
- generator.addScript("format", `oxfmt -c ${configPath} --write .`);
1838
- generator.addVscodeSetting("oxc.fmt.configPath", configPath);
1839
- } else {
1840
- const version = generator.versions.oxfmt ?? "0.1.0";
1841
- generator.addDevDependency("oxfmt", `^${version}`);
1842
- const isStealth = generator.isStealthConfig();
1843
- if (isStealth) {
1844
- generator.addFile(".config/oxfmt.json", {
1845
- type: "text",
1846
- content: JSON.stringify(defaultOxfmtConfig, null, 2)
1847
- });
1848
- generator.addScript("format", "oxfmt -c .config/oxfmt.json --write .");
1849
- generator.addVscodeSetting("oxc.fmt.configPath", ".config/oxfmt.json");
1850
- } else {
1851
- generator.addFile("oxfmt.json", {
1852
- type: "text",
1853
- content: JSON.stringify(defaultOxfmtConfig, null, 2)
1854
- });
1855
- generator.addScript("format", "oxfmt -c oxfmt.json --write .");
1856
- }
1857
- }
1858
- generator.inject(
1859
- "readme-tools",
1860
- "[Oxfmt](https://oxc.rs/docs/guide/usage/formatter) - Fast Prettier-compatible code formatter"
1861
- );
1862
- generator.inject("vscode-extension-suggestion", "oxc.oxc-vscode");
1863
- generator.addVscodeSetting("editor.defaultFormatter", "oxc.oxc-vscode");
1864
- generator.addVscodeSetting("[json]", {
1865
- "editor.defaultFormatter": "vscode.json-language-features"
1866
- });
1867
- generator.addVscodeSetting("[jsonc]", {
1868
- "editor.defaultFormatter": "vscode.json-language-features"
1869
- });
1870
- generator.addVscodeSetting("[markdown]", {
1871
- "editor.defaultFormatter": "vscode.markdown-language-features"
1872
- });
1873
- generator.addVscodeSetting("[yaml]", {
1874
- "editor.defaultFormatter": "redhat.vscode-yaml"
1875
- });
1876
- }
1877
-
1878
- function toOxlintLevel(level) {
1879
- return level;
1880
- }
1881
- function generateOxlint(generator, options) {
1882
- const template = generator.options.template ?? "vanilla";
1883
- const baseTemplate = getBaseTemplate(template);
1884
- const isReact = baseTemplate === "react" || baseTemplate === "r3f";
1885
- const isMonorepo = generator.options.workspaceRoot != null;
1886
- if (isMonorepo) {
1887
- generator.addDevDependency("@config/oxlint", "workspace:*");
1888
- const configPath = isReact ? "node_modules/@config/oxlint/react.json" : "node_modules/@config/oxlint/base.json";
1889
- generator.addScript("lint", `oxlint -c ${configPath}`);
1890
- generator.addVscodeSetting("oxc.configPath", configPath);
1891
- } else {
1892
- const version = generator.versions.oxlint ?? "0.16.0";
1893
- generator.addDevDependency("oxlint", `^${version}`);
1894
- const isStealth = generator.isStealthConfig();
1895
- const { rules } = defaultLinterConfig;
1896
- const plugins = ["unicorn", "typescript", "oxc"];
1897
- if (isReact) {
1898
- plugins.push("react");
1899
- }
1900
- const oxlintConfig = {
1901
- $schema: isStealth ? "../node_modules/oxlint/configuration_schema.json" : "./node_modules/oxlint/configuration_schema.json",
1902
- plugins,
1903
- rules: {
1904
- "no-unused-vars": [
1905
- toOxlintLevel(rules.noUnusedVars.level),
1906
- {
1907
- argsIgnorePattern: rules.noUnusedVars.argsIgnorePattern,
1908
- varsIgnorePattern: rules.noUnusedVars.varsIgnorePattern,
1909
- caughtErrorsIgnorePattern: rules.noUnusedVars.caughtErrorsIgnorePattern
1910
- }
1911
- ],
1912
- "no-useless-escape": "off",
1913
- "no-unused-expressions": [
1914
- toOxlintLevel(rules.noUnusedExpressions.level),
1915
- { allowShortCircuit: rules.noUnusedExpressions.allowShortCircuit }
1916
- ]
1917
- },
1918
- ignorePatterns: defaultLinterConfig.ignorePatterns
1919
- };
1920
- if (isStealth) {
1921
- generator.addFile(".config/oxlint.json", {
1922
- type: "text",
1923
- content: JSON.stringify(oxlintConfig, null, 2)
1924
- });
1925
- generator.addScript("lint", "oxlint -c .config/oxlint.json");
1926
- generator.addVscodeSetting("oxc.configPath", ".config/oxlint.json");
1927
- } else {
1928
- generator.addFile("oxlint.json", {
1929
- type: "text",
1930
- content: JSON.stringify(oxlintConfig, null, 2)
1931
- });
1932
- generator.addScript("lint", "oxlint");
1933
- }
1934
- }
1935
- generator.inject(
1936
- "readme-tools",
1937
- "[Oxlint](https://oxc.rs/docs/guide/usage/linter) - A fast linter for JavaScript and TypeScript"
1938
- );
1939
- generator.inject("vscode-extension-suggestion", "oxc.oxc-vscode");
1940
- generator.addVscodeSetting("oxc.enable", true);
1941
- }
1942
-
1943
- function generatePostprocessing(generator, options) {
1944
- if (options == null) {
1945
- return;
1946
- }
1947
- if (generator.options.xr != null) {
1948
- console.info(
1949
- chalk__default.blue("Info:"),
1950
- "@react-three/postprocessing is disabled because it is not supported with XR"
1951
- );
1952
- return;
1953
- }
1954
- generator.addDependency("@react-three/postprocessing", "^3.0.4");
1955
- generator.inject(
1956
- "readme-libraries",
1957
- `[@react-three/postprocessing](https://react-postprocessing.docs.pmnd.rs/) - Post-processing effects for @react-three/fiber`
1958
- );
1959
- }
1960
-
1961
- function generatePrettier(generator, options) {
1962
- const version = generator.versions.prettier ?? "3.4.2";
1963
- generator.addDevDependency("prettier", `^${version}`);
1964
- const isStealth = generator.isStealthConfig();
1965
- if (isStealth) {
1966
- generator.addFile(".config/prettier.json", {
1967
- type: "text",
1968
- content: JSON.stringify(defaultPrettierConfig, null, 2)
1969
- });
1970
- generator.addScript(
1971
- "format",
1972
- "prettier --config .config/prettier.json --write ."
1973
- );
1974
- generator.addVscodeSetting("prettier.configPath", ".config/prettier.json");
1975
- } else {
1976
- generator.addFile(".prettierrc", {
1977
- type: "text",
1978
- content: JSON.stringify(defaultPrettierConfig, null, 2)
1979
- });
1980
- generator.addScript("format", "prettier --write .");
1981
- }
1982
- generator.inject(
1983
- "readme-tools",
1984
- "[Prettier](https://prettier.io/) - Opinionated code formatter"
1985
- );
1986
- generator.inject("vscode-extension-suggestion", "esbenp.prettier-vscode");
1987
- generator.addVscodeSetting(
1988
- "editor.defaultFormatter",
1989
- "esbenp.prettier-vscode"
1990
- );
1991
- }
1992
-
1993
- function generateRapier(generator, options) {
1994
- if (options == null) {
1995
- return;
1996
- }
1997
- generator.addDependency("@react-three/rapier", "^2.1.0");
1998
- generator.inject(
1999
- "readme-libraries",
2000
- `[@react-three/rapier](https://github.com/pmndrs/react-three-rapier) - Physics based on Rapier for your @react-three/fiber scene`
2001
- );
2002
- }
2003
-
2004
- function unique(...array) {
2005
- const set = /* @__PURE__ */ new Set();
2006
- for (const arr of array) {
2007
- for (const item of arr) {
2008
- set.add(item);
2009
- }
2010
- }
2011
- return Array.from(set);
2012
- }
2013
-
2014
- function generateProvidersModule(generator) {
2015
- const canvasProviders = [];
2016
- const globalProviders = [];
2017
- const providerDefs = {
2018
- uikit: {
2019
- type: "layout-effect",
2020
- props: [
2021
- {
2022
- declaredPropDefaultValue: '"light"',
2023
- declaredPropName: "colorMode",
2024
- propName: "colorMode",
2025
- propValue: "colorMode",
2026
- declaredPropType: '"light" | "dark"'
2027
- }
2028
- ],
2029
- code: `
2030
- setPreferredColorScheme(colorMode);
2031
- `,
2032
- import: 'import { setPreferredColorScheme } from "@react-three/uikit"'
2033
- },
2034
- rapier: {
2035
- component: "Physics",
2036
- type: "wrapped-jsx",
2037
- import: 'import { Physics } from "@react-three/rapier";',
2038
- props: [
2039
- {
2040
- declaredPropDefaultValue: false,
2041
- declaredPropName: "physicsEnabled",
2042
- propName: "paused",
2043
- propValue: "!physicsEnabled",
2044
- declaredPropType: "boolean"
2045
- },
2046
- {
2047
- declaredPropDefaultValue: true,
2048
- declaredPropName: "debugPhysics",
2049
- propName: "debug",
2050
- propValue: "debugPhysics",
2051
- declaredPropType: "boolean"
2052
- }
2053
- ]
2054
- },
2055
- postprocessing: {
2056
- type: "inline-jsx",
2057
- code: `
2058
- <EffectComposer enabled={postProcessingEnabled}>
2059
- <DepthOfField
2060
- focusDistance={0}
2061
- focalLength={0.02}
2062
- bokehScale={2}
2063
- height={480}
2064
- />
2065
- <Bloom luminanceThreshold={0} luminanceSmoothing={0.9} height={300} />
2066
- </EffectComposer>
2067
- `,
2068
- import: 'import { Bloom, DepthOfField, EffectComposer } from "@react-three/postprocessing";',
2069
- props: [
2070
- {
2071
- declaredPropDefaultValue: true,
2072
- declaredPropName: "postProcessingEnabled",
2073
- propName: "enabled",
2074
- propValue: "postProcessingEnabled",
2075
- declaredPropType: "boolean"
2076
- }
2077
- ]
2078
- }
2079
- };
2080
- if (generator.options.rapier) {
2081
- canvasProviders.push("rapier");
2082
- }
2083
- if (!!generator.options.postprocessing && !generator.options.xr) {
2084
- canvasProviders.push("postprocessing");
2085
- }
2086
- if (generator.options.uikit) {
2087
- globalProviders.push("uikit");
2088
- }
2089
- function generateProviderFunction(name, { jsdoc, providers }) {
2090
- const resolvedProviders = providers.map((provider) => providerDefs[provider]);
2091
- const providerProps = resolvedProviders.flatMap((provider) => provider.props || []);
2092
- const providerImports = resolvedProviders.flatMap((provider) => provider.import);
2093
- const wrappedComponents = resolvedProviders.filter(
2094
- (provider) => provider.type === "wrapped-jsx"
2095
- );
2096
- const inlineComponents = resolvedProviders.filter((provider) => provider.type === "inline-jsx");
2097
- const layoutEffects = resolvedProviders.filter((provider) => provider.type === "layout-effect");
2098
- const declaredProps = providerProps.map((prop) => `${prop.declaredPropName} = ${prop.declaredPropDefaultValue}`).join(", ");
2099
- const declaredTypes = providerProps.map((prop) => `${prop.declaredPropName}?: ${prop.declaredPropType}`).join("; ");
2100
- const reactImports = ["type ReactNode"];
2101
- if (layoutEffects.length) {
2102
- reactImports.push("useLayoutEffect");
2103
- }
2104
- return {
2105
- reactImports,
2106
- imports: providerImports,
2107
- code: `
2108
- /**
2109
- ${jsdoc.split("\n").map((line) => ` * ${line}`).join("\n")}
2110
- */
2111
- export function ${name}({ children, ${declaredProps} }: { children: ReactNode; ${declaredTypes} }) {
2112
- ${layoutEffects.length ? `
2113
- useLayoutEffect(() => {
2114
- ${layoutEffects.map((effect) => effect.code).join("\n")}
2115
- }, [${layoutEffects.map((effect) => effect.props?.[0]?.propValue)}]);
2116
- ` : ""}
2117
- return (
2118
- <>
2119
- ${inlineComponents.map((provider) => provider.code)}
2120
- ${wrappedComponents.reduce((acc, provider) => {
2121
- const props = provider.props?.map((prop) => `${prop.propName}={${prop.propValue}}`).join(" ");
2122
- return `<${provider.component} ${props}>${acc}</${provider.component}>`;
2123
- }, "{children}")}
2124
- </>
2125
- );
2126
- }`
2127
- };
2128
- }
2129
- const global = generateProviderFunction("GlobalProvider", {
2130
- jsdoc: "The global provider is rendered at the root of your application,\nuse it to set up global configuration like themes.\nProps defined on this component appear as controls inside Triplex.\n\nSee: https://triplex.dev/docs/building-your-scene/providers#global-provider",
2131
- providers: globalProviders
2132
- });
2133
- const canvas = generateProviderFunction("CanvasProvider", {
2134
- jsdoc: "The canvas provider is rendered as a child inside the React Three Fiber canvas,\nuse it to set up canvas specific configuration like post-processing and physics.\nProps defined on this component appear as controls inside Triplex.\n\nSee: https://triplex.dev/docs/building-your-scene/providers#canvas-provider",
2135
- providers: canvasProviders
2136
- });
2137
- return `
2138
- import { ${unique(global.reactImports, canvas.reactImports).sort().join(", ")} } from "react";
2139
- ${unique(global.imports, canvas.imports).sort().join("\n")}
2140
-
2141
- ${global.code}
2142
- ${canvas.code}
2143
- `;
2144
- }
2145
- function generateTriplex(generator, options) {
2146
- if (options == null) {
2147
- return;
2148
- }
2149
- generator.inject("vscode-extension-suggestion", "trytriplex.triplex-vsce");
2150
- generator.inject(
2151
- "readme-tools",
2152
- `[Triplex](https://triplex.dev) - Your visual workspace for React / Three Fiber. Get started by installing [Triplex for VS Code](https://triplex.dev/docs/get-started/vscode). Don't use Visual Studio Code? Download [Triplex Standalone](https://triplex.dev/docs/get-started/standalone).`
2153
- );
2154
- generator.addFile(".triplex/providers.tsx", {
2155
- content: generateProvidersModule(generator),
2156
- type: "text"
2157
- });
2158
- generator.addFile(".triplex/config.json", {
2159
- content: JSON.stringify(
2160
- {
2161
- $schema: "https://triplex.dev/config.schema.json",
2162
- provider: "./providers.tsx"
2163
- },
2164
- null,
2165
- 2
2166
- ),
2167
- type: "text"
2168
- });
2169
- }
2170
-
2171
- function generateTsdown(generator) {
2172
- generator.addDevDependency("tsdown", "^0.12.0");
2173
- const template = generator.options.template ?? "vanilla";
2174
- const baseTemplate = getBaseTemplate(template);
2175
- const language = getLanguageFromTemplate(template);
2176
- const isReact = baseTemplate === "react" || baseTemplate === "r3f";
2177
- const ext = language === "typescript" ? "ts" : "js";
2178
- const configLines = [
2179
- `import { defineConfig } from "tsdown"`,
2180
- ``,
2181
- `export default defineConfig({`,
2182
- ` entry: ["./src/index.${ext}${isReact ? "x" : ""}"],`,
2183
- ` format: ["esm", "cjs"],`,
2184
- ` dts: ${language === "typescript"},`,
2185
- ` clean: true,`
2186
- ];
2187
- if (isReact) {
2188
- configLines.push(` esbuild: {`);
2189
- configLines.push(` jsx: "automatic",`);
2190
- configLines.push(` },`);
2191
- }
2192
- configLines.push(`})`);
2193
- generator.addFile(`tsdown.config.${ext}`, {
2194
- type: "text",
2195
- content: configLines.join("\n")
2196
- });
2197
- generator.addScript("build", "tsdown");
2198
- generator.inject(
2199
- "readme-libraries",
2200
- "[tsdown](https://github.com/nicepkg/tsdown) - Fast TypeScript bundler powered by esbuild"
2201
- );
2202
- }
2203
-
2204
- function generateUikit(generator, options) {
2205
- if (options == null) {
2206
- return;
2207
- }
2208
- generator.addDependency("@react-three/uikit", "^0.8.15");
2209
- generator.inject(
2210
- "readme-libraries",
2211
- `[@react-three/uikit](https://pmndrs.github.io/uikit/docs/) - UI primitives for React Three Fiber`
2212
- );
2213
- }
2214
-
2215
- function generateUnbuild(generator) {
2216
- generator.addDevDependency("unbuild", "^3.5.0");
2217
- const template = generator.options.template ?? "vanilla";
2218
- const baseTemplate = getBaseTemplate(template);
2219
- const language = getLanguageFromTemplate(template);
2220
- const isReact = baseTemplate === "react" || baseTemplate === "r3f";
2221
- const ext = language === "typescript" ? "ts" : "js";
2222
- const isMonorepo = generator.options.workspaceRoot != null;
2223
- const buildConfigLines = [
2224
- `import { defineBuildConfig } from "unbuild"`,
2225
- ``,
2226
- `export default defineBuildConfig({`,
2227
- ` entries: ["./src/index"],`,
2228
- ` declaration: ${language === "typescript"},`,
2229
- ` clean: true,`,
2230
- ` rollup: {`,
2231
- ` emitCJS: true,`
2232
- ];
2233
- if (isReact) {
2234
- buildConfigLines.push(` esbuild: {`);
2235
- buildConfigLines.push(` jsx: "automatic",`);
2236
- buildConfigLines.push(` },`);
2237
- }
2238
- buildConfigLines.push(` },`);
2239
- buildConfigLines.push(`})`);
2240
- const isStealth = generator.isStealthConfig() && !isMonorepo;
2241
- if (isStealth) {
2242
- generator.addFile(`.config/build.config.${ext}`, {
2243
- type: "text",
2244
- content: buildConfigLines.join("\n")
2245
- });
2246
- generator.addScript("build", `unbuild --config .config/build.config.${ext}`);
2247
- } else {
2248
- generator.addFile(`build.config.${ext}`, {
2249
- type: "text",
2250
- content: buildConfigLines.join("\n")
2251
- });
2252
- generator.addScript("build", "unbuild");
2253
- }
2254
- generator.inject(
2255
- "readme-libraries",
2256
- "[unbuild](https://github.com/unjs/unbuild) - Unified JavaScript build system"
2257
- );
2258
- }
2259
-
2260
- function generateVitest(generator) {
2261
- const version = generator.versions.vitest ?? "4.0.0";
2262
- generator.addDevDependency("vitest", `^${version}`);
2263
- const template = generator.options.template ?? "vanilla";
2264
- const baseTemplate = getBaseTemplate(template);
2265
- const isReact = baseTemplate === "react" || baseTemplate === "r3f";
2266
- if (isReact) {
2267
- generator.addDevDependency("@testing-library/react", "^16.2.0");
2268
- generator.addDevDependency("@testing-library/dom", "^10.4.0");
2269
- generator.addDevDependency("jsdom", "^26.0.0");
2270
- }
2271
- if (isReact) {
2272
- generator.configureVite({ test: { environment: "jsdom" } });
2273
- }
2274
- generator.addScript("test", "vitest");
2275
- generator.inject(
2276
- "readme-tools",
2277
- "[Vitest](https://vitest.dev/) - Fast unit test framework powered by Vite"
2278
- );
2279
- }
2280
-
2281
- function generateViverse(generator, options) {
2282
- if (options == null || (generator.options.packageManager ?? "npm") != "npm") {
2283
- return;
2284
- }
2285
- generator.addFile(".github/workflows/viverse.yml", {
2286
- type: "text",
2287
- content: `name: Deploy to Viverse
2288
-
2289
- on:
2290
- push:
2291
- branches:
2292
- - main
2293
- workflow_dispatch:
2294
-
2295
- jobs:
2296
- check-secrets:
2297
- runs-on: ubuntu-latest
2298
- outputs:
2299
- secrets-available: \${{ steps.check.outputs.secrets-available }}
2300
- steps:
2301
- - id: check
2302
- run: |
2303
- if [[ -n "\${{ secrets.VIVERSE_EMAIL }}" && -n "\${{ secrets.VIVERSE_PASSWORD }}" ]]; then
2304
- echo "secrets-available=true" >> $GITHUB_OUTPUT
2305
- else
2306
- echo "secrets-available=false" >> $GITHUB_OUTPUT
2307
- fi
2308
-
2309
- build-and-deploy:
2310
- runs-on: ubuntu-latest
2311
- needs: check-secrets
2312
- # Only run if secrets are present
2313
- if: needs.check-secrets.outputs.secrets-available == 'true'
2314
- permissions:
2315
- contents: read
2316
-
2317
- steps:
2318
- - name: Checkout code
2319
- uses: actions/checkout@v3
2320
-
2321
- - name: Setup Node
2322
- uses: actions/setup-node@v3
2323
- with:
2324
- node-version: 22
2325
-
2326
- - name: Install dependencies
2327
- run: npm install
2328
-
2329
- - name: Build project
2330
- run: npm run build
2331
-
2332
- - name: Viverse Login
2333
- run: npx viverse-cli auth login -e \${{ secrets.VIVERSE_EMAIL }} -p \${{ secrets.VIVERSE_PASSWORD }}
2334
-
2335
- - name: Deploy to Viverse
2336
- run: npx viverse-cli app publish ./dist --auto-create-app --name ${generator.options.name}
2337
-
2338
- `
2339
- });
2340
- generator.addDependency("@viverse/cli", "^0.9.5-beta.8");
2341
- generator.inject(
2342
- "readme-start",
2343
- `A GitHub CI/CD workflow for publishing to Viverse is configured.
2344
-
2345
- To use publish to viverse via the CI/CD workflow:
2346
- 1. Set \`VIVERSE_EMAIL\` and \`VIVERSE_PASSWORD\` secrets in your repository settings under \`Secrets and Variables\` > \`Actions\` > \`New repository secret\`
2347
- 2. Manually trigger the "Deploy to Viverse" workflow or push to the main branch
2348
-
2349
- **Manual CLI Upload:**
2350
- You can also upload your project manually using the Viverse CLI:
2351
- \`\`\`bash
2352
- viverse-cli auth login -e <email> -p <password>
2353
- npm run build
2354
- viverse-cli app publish ./dist --auto-create-app --name ${generator.options.name}
2355
- \`\`\`
2356
- `
2357
- );
2358
- }
2359
-
2360
- function generateXr(generator, options) {
2361
- if (options == null || options === false) {
2362
- return;
2363
- }
2364
- if (options === true) {
2365
- options = {};
2366
- }
2367
- generator.addDependency("@react-three/xr", "^6.6.16");
2368
- generator.addDependency("@vitejs/plugin-basic-ssl", "^2.0.0");
2369
- generator.inject("import", "import { XR, createXRStore } from '@react-three/xr'");
2370
- generator.inject(
2371
- `global-start`,
2372
- `const store = createXRStore(${JSON.stringify(options.storeOptions ?? {})})`
2373
- );
2374
- generator.inject("scene-start", "<XR store={store}>");
2375
- generator.inject("scene-end", "</XR>");
2376
- generator.inject("vite-config-import", "import basicSsl from '@vitejs/plugin-basic-ssl'");
2377
- generator.configureVite({
2378
- server: {
2379
- host: true
2380
- },
2381
- plugins: ["$raw:basicSsl()"]
2382
- });
2383
- generator.inject(
2384
- "dom-start",
2385
- `<div style={{
2386
- display: "flex",
2387
- flexDirection: "row",
2388
- gap: "1rem",
2389
- position: 'absolute',
2390
- zIndex: 10000,
2391
- background: 'black',
2392
- borderRadius: '0.5rem',
2393
- border: 'none',
2394
- fontWeight: 'bold',
2395
- color: 'white',
2396
- cursor: 'pointer',
2397
- fontSize: '1.5rem',
2398
- bottom: '1rem',
2399
- left: '50%',
2400
- boxShadow: '0px 0px 20px rgba(0,0,0,1)',
2401
- transform: 'translate(-50%, 0)',
2402
- }}><button
2403
- style={{ cursor: "pointer", padding: '1rem 2rem', fontSize: "1rem", background: "none", color: "white", border: "none" }}
2404
- onClick={() => store.enterAR()}
2405
- >
2406
- Enter AR
2407
- </button>
2408
- <button
2409
- style={{ cursor: "pointer", padding: '1rem 2rem', fontSize: "1rem", background: "none", color: "white", border: "none" }}
2410
- onClick={() => store.enterVR()}
2411
- >
2412
- Enter VR
2413
- </button></div>`
2414
- );
2415
- generator.inject(
2416
- "readme-libraries",
2417
- `[@react-three/xr](https://pmndrs.github.io/xr/docs/) - VR/AR support for @react-three/fiber`
2418
- );
2419
- }
2420
-
2421
- function generateZustand(generator, options) {
2422
- if (options == null) {
2423
- return;
2424
- }
2425
- generator.addDependency("zustand", "^5.0.3");
2426
- generator.inject(
2427
- "readme-libraries",
2428
- `[zustand](https://zustand.docs.pmnd.rs/) - small, fast and scalable state-management solution`
2429
- );
2430
- }
2431
-
2432
- function merge(target, modification) {
2433
- if (modification == null) {
2434
- throw new Error(`Cannot merge "${modification}" modification into target "${target}"`);
2435
- }
2436
- if (target == null) {
2437
- return modification;
2438
- }
2439
- if (Array.isArray(target)) {
2440
- if (!Array.isArray(modification)) {
2441
- throw new Error(
2442
- `Cannot merge non-array modification "${modification}" into array target "${target}"`
2443
- );
2444
- }
2445
- return [...target, ...modification];
2446
- }
2447
- if (typeof target === "object") {
2448
- if (typeof modification != "object") {
2449
- throw new Error(
2450
- `Cannot merge non-object modification "${modification}" into object target "${target}"`
2451
- );
2452
- }
2453
- const result = { ...target };
2454
- for (const modificationKey in modification) {
2455
- result[modificationKey] = merge(target[modificationKey], modification[modificationKey]);
2456
- }
2457
- return result;
2458
- }
2459
- console.warn(`target "${target}" is overwritten with modification "${modification}"`);
2460
- return modification;
2461
- }
2462
-
2463
- async function getLatestNpmVersion(packageName, fallback) {
2464
- try {
2465
- const response = await fetch(
2466
- `https://registry.npmjs.org/${packageName}/latest`
2467
- );
2468
- const data = await response.json();
2469
- return data.version;
2470
- } catch {
2471
- return fallback;
2472
- }
2473
- }
2474
- async function getLatestPnpmVersion() {
2475
- return getLatestNpmVersion("pnpm", "10.11.0");
2476
- }
2477
- async function getLatestYarnVersion() {
2478
- return getLatestNpmVersion("yarn", "4.6.0");
2479
- }
2480
- async function getLatestNpmCliVersion() {
2481
- return getLatestNpmVersion("npm", "11.0.0");
2482
- }
2483
- async function getLatestNodeVersion() {
2484
- try {
2485
- const response = await fetch("https://nodejs.org/dist/index.json");
2486
- const data = await response.json();
2487
- const latestVersion = data[0];
2488
- if (latestVersion) {
2489
- return latestVersion.version.replace(/^v/, "");
2490
- }
2491
- return "25.0.0";
2492
- } catch {
2493
- return "25.0.0";
2494
- }
2495
- }
2496
- function validateNameSegment(segment, label) {
2497
- if (!segment.length) {
2498
- return `${label} is required`;
2499
- }
2500
- if (!/^[a-z0-9-]+$/.test(segment)) {
2501
- return `${label} must be lowercase and contain only letters, numbers, and hyphens`;
2502
- }
2503
- if (segment.startsWith("-") || segment.endsWith("-")) {
2504
- return `${label} cannot start or end with a hyphen`;
2505
- }
2506
- if (segment.includes("--")) {
2507
- return `${label} cannot contain consecutive hyphens`;
2508
- }
2509
- return void 0;
2510
- }
2511
- function validatePackageName(name) {
2512
- if (!name.length) {
2513
- return "Package name is required";
2514
- }
2515
- if (name.includes("..") || name.includes("\\")) {
2516
- return "Package name cannot contain path traversal sequences";
2517
- }
2518
- if (name.startsWith("@")) {
2519
- const slashIndex = name.indexOf("/");
2520
- if (slashIndex === -1) {
2521
- return "Scoped package name must include a package name after the scope (e.g., @scope/name)";
2522
- }
2523
- if (name.indexOf("/", slashIndex + 1) !== -1) {
2524
- return "Package name can only have one slash for scoped packages";
2525
- }
2526
- const scope = name.slice(1, slashIndex);
2527
- const packageName = name.slice(slashIndex + 1);
2528
- const scopeError = validateNameSegment(scope, "Scope");
2529
- if (scopeError) return scopeError;
2530
- const nameError = validateNameSegment(packageName, "Package name");
2531
- if (nameError) return nameError;
2532
- return void 0;
2533
- }
2534
- if (name.includes("/")) {
2535
- return "Unscoped package name cannot contain slashes. Use @scope/name format for scoped packages";
2536
- }
2537
- return validateNameSegment(name, "Package name");
2538
- }
2539
- function parseWorkspaceYamlContent(content) {
2540
- const directories = [];
2541
- let inPackagesSection = false;
2542
- for (const line of content.split("\n")) {
2543
- const trimmed = line.trim();
2544
- if (trimmed === "packages:") {
2545
- inPackagesSection = true;
2546
- continue;
2547
- }
2548
- if (inPackagesSection && trimmed && !line.startsWith(" ") && !line.startsWith(" ") && !trimmed.startsWith("-")) {
2549
- break;
2550
- }
2551
- if (inPackagesSection && trimmed.startsWith("-")) {
2552
- const entry = trimmed.slice(1).trim().replace(/^["']|["']$/g, "").replace(/^\.\//, "").replace(/\/\*.*$/, "");
2553
- if (entry && !entry.startsWith(".")) {
2554
- directories.push(entry);
2555
- }
2556
- }
2557
- }
2558
- return directories;
2559
- }
2560
- async function pathExists(path) {
2561
- try {
2562
- await promises.access(path, fs.constants.F_OK);
2563
- return true;
2564
- } catch {
2565
- return false;
2566
- }
2567
- }
2568
- function detectLinterFromScript(script) {
2569
- if (!script) return void 0;
2570
- if (script.includes("oxlint")) return "oxlint";
2571
- if (script.includes("eslint")) return "eslint";
2572
- if (script.includes("biome check") || script.includes("biome lint")) return "biome";
2573
- return void 0;
2574
- }
2575
- function detectFormatterFromScript(script) {
2576
- if (!script) return void 0;
2577
- if (script.includes("prettier")) return "prettier";
2578
- if (script.includes("oxfmt")) return "oxfmt";
2579
- if (script.includes("biome format")) return "biome";
2580
- return void 0;
2581
- }
2582
- async function detectLinterFromConfig(root) {
2583
- if (await pathExists(path.join(root, ".config/oxlint"))) return "oxlint";
2584
- if (await pathExists(path.join(root, ".config/eslint"))) return "eslint";
2585
- if (await pathExists(path.join(root, "biome.json"))) {
2586
- try {
2587
- const content = await promises.readFile(path.join(root, "biome.json"), "utf-8");
2588
- const config = JSON.parse(content);
2589
- if (config.linter?.enabled !== false) return "biome";
2590
- } catch {
2591
- return "biome";
2592
- }
2593
- }
2594
- return void 0;
2595
- }
2596
- async function detectFormatterFromConfig(root) {
2597
- if (await pathExists(path.join(root, ".config/prettier"))) return "prettier";
2598
- if (await pathExists(path.join(root, ".config/oxfmt"))) return "oxfmt";
2599
- if (await pathExists(path.join(root, "biome.json"))) {
2600
- try {
2601
- const content = await promises.readFile(path.join(root, "biome.json"), "utf-8");
2602
- const config = JSON.parse(content);
2603
- if (config.formatter?.enabled !== false) return "biome";
2604
- } catch {
2605
- return "biome";
2606
- }
2607
- }
2608
- return void 0;
2609
- }
2610
- function detectLinterFromDeps(devDeps) {
2611
- if (!devDeps) return void 0;
2612
- if (devDeps["@biomejs/biome"]) return "biome";
2613
- if (devDeps.eslint) return "eslint";
2614
- if (devDeps.oxlint) return "oxlint";
2615
- return void 0;
2616
- }
2617
- function detectFormatterFromDeps(devDeps) {
2618
- if (!devDeps) return void 0;
2619
- if (devDeps["@biomejs/biome"]) return "biome";
2620
- if (devDeps.prettier) return "prettier";
2621
- if (devDeps.oxfmt) return "oxfmt";
2622
- return void 0;
2623
- }
2624
- async function detectTooling(root) {
2625
- try {
2626
- const pkgPath = path.join(root, "package.json");
2627
- const content = await promises.readFile(pkgPath, "utf-8");
2628
- const pkg = JSON.parse(content);
2629
- const linter = detectLinterFromScript(pkg.scripts?.lint) ?? await detectLinterFromConfig(root) ?? detectLinterFromDeps(pkg.devDependencies);
2630
- const formatter = detectFormatterFromScript(pkg.scripts?.format) ?? await detectFormatterFromConfig(root) ?? detectFormatterFromDeps(pkg.devDependencies);
2631
- return { linter, formatter };
2632
- } catch {
2633
- return { linter: void 0, formatter: void 0 };
2634
- }
2635
- }
2636
- function generateRandomName() {
2637
- const adjectives = [
2638
- "red",
2639
- "blue",
2640
- "green",
2641
- "yellow",
2642
- "purple",
2643
- "orange",
2644
- "pink",
2645
- "black",
2646
- "white",
2647
- "tiny",
2648
- "big",
2649
- "small",
2650
- "large",
2651
- "huge",
2652
- "giant",
2653
- "mini",
2654
- "mega",
2655
- "super",
2656
- "happy",
2657
- "sad",
2658
- "angry",
2659
- "calm",
2660
- "quiet",
2661
- "loud",
2662
- "silent",
2663
- "noisy",
2664
- "shiny",
2665
- "dull",
2666
- "bright",
2667
- "dark",
2668
- "fuzzy",
2669
- "smooth",
2670
- "rough",
2671
- "soft"
2672
- ];
2673
- const nouns = [
2674
- "apple",
2675
- "banana",
2676
- "cherry",
2677
- "date",
2678
- "elderberry",
2679
- "fig",
2680
- "grape",
2681
- "honeydew",
2682
- "cat",
2683
- "dog",
2684
- "elephant",
2685
- "fox",
2686
- "giraffe",
2687
- "horse",
2688
- "iguana",
2689
- "jaguar",
2690
- "mountain",
2691
- "river",
2692
- "ocean",
2693
- "desert",
2694
- "forest",
2695
- "jungle",
2696
- "meadow",
2697
- "valley",
2698
- "star",
2699
- "moon",
2700
- "sun",
2701
- "planet",
2702
- "comet",
2703
- "asteroid",
2704
- "galaxy",
2705
- "universe"
2706
- ];
2707
- const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
2708
- const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
2709
- return `${randomAdjective}-${randomNoun}`;
2710
- }
2711
-
2712
- function generate(options) {
2713
- const clonedOptions = structuredClone(options);
2714
- const template = clonedOptions.template ?? "vanilla";
2715
- const baseTemplate = getBaseTemplate(template);
2716
- const language = getLanguageFromTemplate(template);
2717
- const isVanilla = baseTemplate === "vanilla";
2718
- const isReact = baseTemplate === "react";
2719
- const isR3f = baseTemplate === "r3f";
2720
- const isLibrary = clonedOptions.projectType === "library";
2721
- const libraryBundler = clonedOptions.libraryBundler ?? "unbuild";
2722
- const files = {
2723
- ...clonedOptions.files
2724
- };
2725
- const replacements = clonedOptions.replacements ?? [];
2726
- const versions = clonedOptions.versions ?? {};
2727
- const dependencies = {
2728
- ...clonedOptions.dependencies
2729
- };
2730
- const devDependencies = {};
2731
- const peerDependencies = {};
2732
- if (!isLibrary) {
2733
- devDependencies.vite = versions.vite ? `^${versions.vite}` : "^6.3.4";
2734
- }
2735
- if (isReact || isR3f) {
2736
- if (isLibrary) {
2737
- peerDependencies["react"] = "^18.0.0 || ^19.0.0";
2738
- peerDependencies["react-dom"] = "^18.0.0 || ^19.0.0";
2739
- } else {
2740
- dependencies["react"] = "^19.0.0";
2741
- dependencies["react-dom"] = "^19.0.0";
2742
- devDependencies["@vitejs/plugin-react"] = "^4.4.1";
2743
- }
2744
- }
2745
- if (isR3f) {
2746
- if (isLibrary) {
2747
- peerDependencies["three"] = ">=0.150.0";
2748
- peerDependencies["@react-three/fiber"] = "^8.0.0 || ^9.0.0";
2749
- } else {
2750
- dependencies["three"] = "~0.175.0";
2751
- dependencies["@react-three/fiber"] = "^9.0.0";
2752
- }
2753
- }
2754
- if (language === "typescript") {
2755
- const tsResult = generateTypescriptConfig({
2756
- baseTemplate,
2757
- useConfigPackage: clonedOptions.workspaceRoot != null,
2758
- configStrategy: clonedOptions.configStrategy,
2759
- nodeVersion: clonedOptions.nodeVersion
2760
- });
2761
- Object.assign(files, tsResult.files);
2762
- Object.assign(devDependencies, tsResult.devDependencies);
2763
- }
2764
- const codeSnippets = {};
2765
- const vscodeSettings = {};
2766
- const scripts = isLibrary ? {} : {
2767
- dev: "vite",
2768
- build: "vite build"
2769
- };
2770
- if (!isLibrary && (isReact || isR3f)) {
2771
- codeSnippets["vite-config-import"] = [
2772
- "import react from '@vitejs/plugin-react'"
2773
- ];
2774
- }
2775
- if (!isLibrary && isR3f) {
2776
- codeSnippets["import"] = [`import { Canvas } from "@react-three/fiber"`];
2777
- }
2778
- const defaultName = isVanilla ? "vanilla-app" : isReact ? "react-app" : "react-three-app";
2779
- const name = clonedOptions.name ?? defaultName;
2780
- let viteConfig = {
2781
- base: "./"
2782
- };
2783
- if (!isLibrary && (isReact || isR3f)) {
2784
- viteConfig.plugins = ["$raw:react()"];
2785
- }
2786
- if (!isLibrary && isR3f) {
2787
- viteConfig.resolve = { dedupe: ["three"] };
2788
- }
2789
- const isMonorepoPackage = clonedOptions.workspaceRoot != null;
2790
- const generator = {
2791
- options: clonedOptions,
2792
- versions,
2793
- isStealthConfig() {
2794
- return (clonedOptions.configStrategy ?? "stealth") === "stealth";
2795
- },
2796
- addDependency(name2, semver) {
2797
- dependencies[name2];
2798
- dependencies[name2] = semver;
2799
- },
2800
- addDevDependency(name2, semver) {
2801
- devDependencies[name2];
2802
- devDependencies[name2] = semver;
2803
- },
2804
- addFile(path, content) {
2805
- files[path] = content;
2806
- },
2807
- addScript(name2, command) {
2808
- scripts[name2] = command;
2809
- },
2810
- inject(location, code) {
2811
- let entries = codeSnippets[location];
2812
- if (entries == null) {
2813
- codeSnippets[location] = entries = [];
2814
- }
2815
- entries.push(code);
2816
- },
2817
- replace(search, replace) {
2818
- replacements.push({ search, replace });
2819
- },
2820
- configureVite(config) {
2821
- viteConfig = merge(viteConfig, config);
2822
- },
2823
- addVscodeSetting(key, value) {
2824
- vscodeSettings[key] = value;
2825
- }
2826
- };
2827
- if (isR3f) {
2828
- generateDrei(generator, clonedOptions.drei);
2829
- generateHandle(generator, clonedOptions.handle);
2830
- generateKoota(generator, clonedOptions.koota);
2831
- generateLeva(generator, clonedOptions.leva);
2832
- generateOffscreen(generator, clonedOptions.offscreen);
2833
- generatePostprocessing(generator, clonedOptions.postprocessing);
2834
- generateRapier(generator, clonedOptions.rapier);
2835
- generateUikit(generator, clonedOptions.uikit);
2836
- generateXr(generator, clonedOptions.xr);
2837
- generateZustand(generator, clonedOptions.zustand);
2838
- generateFiber(generator, clonedOptions.fiber);
2839
- generateTriplex(generator, clonedOptions.triplex);
2840
- generateViverse(generator, clonedOptions.viverse);
2841
- }
2842
- if (!isLibrary) {
2843
- generateGithubPages(generator, clonedOptions.githubPages);
2844
- }
2845
- if (isLibrary) {
2846
- if (libraryBundler === "unbuild") {
2847
- generateUnbuild(generator);
2848
- } else if (libraryBundler === "tsdown") {
2849
- generateTsdown(generator);
2850
- }
2851
- const packageManager2 = clonedOptions.packageManager ?? "pnpm";
2852
- generator.addScript(
2853
- "release",
2854
- `${packageManager2} run build && ${packageManager2} publish`
2855
- );
2856
- }
2857
- const testing = clonedOptions.testing ?? (isLibrary ? "vitest" : "none");
2858
- if (testing === "vitest") {
2859
- generateVitest(generator);
2860
- }
2861
- const linter = clonedOptions.linter;
2862
- const formatter = clonedOptions.formatter;
2863
- if (linter === "eslint") {
2864
- generateEslint(generator);
2865
- generator.addVscodeSetting("biome.enabled", false);
2866
- generator.addVscodeSetting("oxc.enable", false);
2867
- } else if (linter === "oxlint") {
2868
- generateOxlint(generator);
2869
- generator.addVscodeSetting("eslint.enable", false);
2870
- generator.addVscodeSetting("biome.enabled", false);
2871
- } else if (linter === "biome") {
2872
- generateBiome(generator, {
2873
- linter: true,
2874
- formatter: formatter === "biome"
2875
- });
2876
- generator.addVscodeSetting("eslint.enable", false);
2877
- generator.addVscodeSetting("oxc.enable", false);
2878
- }
2879
- if (formatter === "prettier") {
2880
- generatePrettier(generator);
2881
- } else if (formatter === "oxfmt") {
2882
- generateOxfmt(generator);
2883
- } else if (formatter === "biome" && linter !== "biome") {
2884
- generateBiome(generator, { linter: false, formatter: true });
2885
- generator.addVscodeSetting("eslint.enable", false);
2886
- generator.addVscodeSetting("oxc.enable", false);
2887
- }
2888
- for (const { code, location } of clonedOptions.injections ?? []) {
2889
- generator.inject(location, code);
2890
- }
2891
- if (!isLibrary) {
2892
- files["vite.config.ts"] = generateViteConfig({ viteConfig, codeSnippets });
2893
- }
2894
- const packageManager = options.packageManager ?? "pnpm";
2895
- files["README.md"] = generateReadme({
2896
- name,
2897
- baseTemplate,
2898
- isLibrary,
2899
- libraryBundler,
2900
- packageManager,
2901
- codeSnippets
2902
- });
2903
- Object.assign(
2904
- files,
2905
- generateSourceFiles({
2906
- name,
2907
- baseTemplate,
2908
- language,
2909
- isLibrary,
2910
- codeSnippets,
2911
- replacements
2912
- })
2913
- );
2914
- if (testing === "vitest") {
2915
- Object.assign(
2916
- files,
2917
- generateTestFiles({
2918
- baseTemplate,
2919
- language,
2920
- isLibrary
2921
- })
2922
- );
2923
- }
2924
- Object.assign(
2925
- files,
2926
- generatePackageJson({
2927
- name,
2928
- language,
2929
- isLibrary,
2930
- dependencies,
2931
- devDependencies,
2932
- peerDependencies,
2933
- scripts,
2934
- options: clonedOptions,
2935
- workspaceDependencies: clonedOptions.workspaceDependencies
2936
- }).files
2937
- );
2938
- if (!isMonorepoPackage) {
2939
- Object.assign(files, generateVscodeFiles$1({ codeSnippets, vscodeSettings }));
2940
- }
2941
- if (!isMonorepoPackage) {
2942
- files[".gitignore"] = generateGitignore("standalone");
2943
- files[".gitattributes"] = { type: "text", content: GitAttributes };
2944
- }
2945
- if (!isMonorepoPackage && clonedOptions.aiPlatforms?.length) {
2946
- generateAiFiles(files, {
2947
- name,
2948
- packageManager: clonedOptions.packageManager ?? "pnpm",
2949
- linter: clonedOptions.linter ?? "oxlint",
2950
- formatter: clonedOptions.formatter ?? "prettier",
2951
- isMonorepo: false,
2952
- configStrategy: clonedOptions.configStrategy,
2953
- platforms: clonedOptions.aiPlatforms
2954
- });
2955
- }
2956
- return files;
2957
- }
2958
-
2959
- exports.detectTooling = detectTooling;
2960
- exports.generate = generate;
2961
- exports.generateMonorepo = generateMonorepo;
2962
- exports.generateRandomName = generateRandomName;
2963
- exports.getBaseTemplate = getBaseTemplate;
2964
- exports.getLanguageFromTemplate = getLanguageFromTemplate;
2965
- exports.getLatestNodeVersion = getLatestNodeVersion;
2966
- exports.getLatestNpmCliVersion = getLatestNpmCliVersion;
2967
- exports.getLatestNpmVersion = getLatestNpmVersion;
2968
- exports.getLatestPnpmVersion = getLatestPnpmVersion;
2969
- exports.getLatestYarnVersion = getLatestYarnVersion;
2970
- exports.parseWorkspaceYamlContent = parseWorkspaceYamlContent;
2971
- exports.validatePackageName = validatePackageName;
3
+ const index = require('./chunks/index.cjs');
4
+ require('fs/promises');
5
+ require('fs');
6
+ require('path');
7
+ require('chalk');
8
+
9
+
10
+
11
+ exports.detectTooling = index.detectTooling;
12
+ exports.generate = index.generate;
13
+ exports.generateMonorepo = index.generateMonorepo;
14
+ exports.generateRandomName = index.generateRandomName;
15
+ exports.getBaseTemplate = index.getBaseTemplate;
16
+ exports.getLanguageFromTemplate = index.getLanguageFromTemplate;
17
+ exports.getLatestNodeVersion = index.getLatestNodeVersion;
18
+ exports.getLatestNpmCliVersion = index.getLatestNpmCliVersion;
19
+ exports.getLatestNpmVersion = index.getLatestNpmVersion;
20
+ exports.getLatestPnpmVersion = index.getLatestPnpmVersion;
21
+ exports.getLatestYarnVersion = index.getLatestYarnVersion;
22
+ exports.parseWorkspaceYamlContent = index.parseWorkspaceYamlContent;
23
+ exports.validatePackageName = index.validatePackageName;