### Create a Basic Logging Plugin Source: https://github.com/kubb-labs/fabric/blob/main/docs/guide/creating-plugins.md This example demonstrates creating a simple plugin that logs a message when the Fabric lifecycle starts. It uses `fabric.on` to subscribe to the `lifecycle:start` event. ```typescript import { createFabric } from '@kubb/fabric-core' import { definePlugin } from '@kubb/fabric-core/plugins' const helloPlugin = definePlugin({ name: 'helloPlugin', install(fabric) { fabric.on('lifecycle:start', () => { console.log('Hello from plugin!') }) }, }) const fabric = createFabric() fabric.use(helloPlugin) ``` -------------------------------- ### Usage Example Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/fsx-plugin.md Create and render FSX components with the fsx plugin. This example demonstrates creating a simple component and rendering it to a string. ```APIDOC ## Usage Create and render FSX components with the fsx plugin. **Example:** Create a simple component and render it. ```tsx twoslash [run.ts] import { createFabric } from '@kubb/fabric-core' import { fsxPlugin } from '@kubb/fabric-core/plugins' import { createComponent } from '@kubb/fabric-core' const fabric = createFabric() fabric.use(fsxPlugin) const App = createComponent('App', () => { return 'Hello from Fabric!' }) const output = await fabric.render(App()) ``` ```ts [output] "Hello from Fabric!" ``` ``` -------------------------------- ### Example: Plain Text File Generation Source: https://github.com/kubb-labs/fabric/blob/main/docs/parsers/default-parser.md A complete example demonstrating the generation of a plain text README.txt file using the defaultParser, showcasing source concatenation. ```tsx import { createFabric } from '@kubb/fabric-core' import { fsPlugin } from '@kubb/fabric-core/plugins' const fabric = createFabric() fabric.use(fsPlugin) await fabric.addFile({ baseName: 'README.txt', path: './output/README.txt', sources: [ { value: 'Project Name', isExportable: false }, { value: '', isExportable: false }, { value: 'Description of the project.', isExportable: false }, ], imports: [], exports: [], }) await fabric.write() ``` ```css Project Name Description of the project. ``` -------------------------------- ### Usage Example Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/react-plugin.md Create and render React components with the react plugin. This example shows how to import the necessary functions, initialize Fabric, use the reactPlugin, define a simple React component, and render it. ```APIDOC ## Usage Example Create and render React components with the react plugin. **Example:** Create a React component and render it. ```tsx import { createFabric } from '@kubb/fabric-core' import { reactPlugin } from '@kubb/react-fabric/plugins' const fabric = createFabric() fabric.use(reactPlugin) const App = () => { return
Hello from React!
} await fabric.render(App) ``` ``` -------------------------------- ### Repository Setup Details Source: https://github.com/kubb-labs/fabric/blob/main/AGENTS.md Outlines the core technologies and conventions used for setting up the monorepo. ```bash - **Monorepo** - Uses pnpm workspaces and Turborepo - **Module system** - ESM-only (`type: "module"`) - **Node version** - 20 - **Versioning** - Changesets - **CI/CD** - GitHub Actions ``` -------------------------------- ### Install @kubb/fabric-core Source: https://github.com/kubb-labs/fabric/blob/main/docs/core.md Install @kubb/fabric-core as a dev dependency using your preferred package manager. ```bash bun add -d @kubb/fabric-core ``` ```bash pnpm add -D @kubb/fabric-core ``` ```bash npm install --save-dev @kubb/fabric-core ``` ```bash yarn add -D @kubb/fabric-core ``` -------------------------------- ### Define a Basic Plugin Source: https://github.com/kubb-labs/fabric/blob/main/docs/guide/creating-plugins.md Use the `definePlugin` factory from `@kubb/fabric-core/plugins` to create a new plugin. The `install` function is called when the plugin is registered and is used for subscribing to events and performing setup. ```typescript import { definePlugin } from '@kubb/fabric-core/plugins' const myPlugin = definePlugin({ name: 'myPlugin', install(fabric, options) { // Subscribe to events, transform files } }) ``` -------------------------------- ### Example: Basic File Writing Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/fs-plugin.md Demonstrates basic file writing using `fsPlugin` and `typescriptParser`. ```APIDOC ## Examples ### Basic File Writing ```ts twoslash import { createFabric } from '@kubb/fabric-core' import { fsPlugin } from '@kubb/fabric-core/plugins' import { typescriptParser } from '@kubb/fabric-core/parsers' const fabric = createFabric() fabric.use(fsPlugin) fabric.use(typescriptParser) await fabric.addFile({ baseName: 'types.ts', path: './output/types.ts', sources: [ { value: 'export type User = { id: number; name: string }', isExportable: true }, ], imports: [], exports: [] }) await fabric.write() ``` ``` -------------------------------- ### Comprehensive Fabric Generation Example Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/events.md A complete example demonstrating multiple event listeners for lifecycle tracking, file addition, progress updates, writing status, and final reporting. It also includes configuration and running the generation process. ```typescript import { createFabric } from '@kubb/fabric-core' import { fsPlugin } from '@kubb/fabric-core/plugins' import { typescriptParser } from '@kubb/fabric-core/parsers' const fabric = createFabric() // Lifecycle tracking let stats = { startTime: 0, filesAdded: 0, filesProcessed: 0, filesWritten: 0, } fabric.context.on('lifecycle:start', () => { stats.startTime = Date.now() console.log('šŸš€ Generation started') }) fabric.context.on('files:added', (files) => { stats.filesAdded += files.length console.log(`šŸ“ Added ${files.length} files (total: ${stats.filesAdded})`) }) fabric.context.on('file:processing:update', ({ processed, total, percentage }) => { const bar = 'ā–ˆ'.repeat(Math.floor(percentage / 5)) + 'ā–‘'.repeat(20 - Math.floor(percentage / 5)) process.stdout.write(`\r${bar} ${percentage.toFixed(1)}% (${processed}/${total})`) }) fabric.context.on('files:writing:start', (files) => { stats.filesWritten = files.length console.log(`\nšŸ“ Writing ${files.length} files...`) }) fabric.context.on('files:writing:end', (files) => { console.log(`āœ“ Wrote ${files.length} files`) }) fabric.context.on('lifecycle:end', () => { const elapsed = Date.now() - stats.startTime console.log('\n✨ Generation complete!') console.log(` Time: ${elapsed}ms`) console.log(` Files: ${stats.filesWritten}`) }) // Configure and run fabric.use(fsPlugin, { clean: { path: './generated' } }) fabric.use(typescriptParser) await fabric.addFile({ baseName: 'user.ts', path: './generated/user.ts', sources: [{ value: 'export type User = {}', isExportable: true }], imports: [], exports: [] }) await fabric.write({ extension: { '.ts': '.ts' } }) ``` ```bash šŸ“ Added 1 files (total: 1) šŸ“ Writing 1 files... ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆ 100.0% (1/1) āœ“ Wrote 1 files ✨ Generation complete! Time: 150ms Files: 1 ``` -------------------------------- ### Basic Barrel Generation Example Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/barrel-plugin.md This example demonstrates how to set up the barrel and fs plugins, add files with exportable types, and then write the generated index file. The output is a consolidated `index.ts` file re-exporting defined types. ```typescript import { createFabric } from '@kubb/fabric-core' import { barrelPlugin, fsPlugin } from '@kubb/fabric-core/plugins' import { typescriptParser } from '@kubb/fabric-core/parsers' const fabric = createFabric() fabric.use(barrelPlugin, { root: './generated', mode: 'named', }) fabric.use(fsPlugin, { clean: { path: './generated' }, }) fabric.use(typescriptParser) await fabric.addFile({ baseName: 'user.ts', path: './generated/models/user.ts', sources: [ { value: 'export type User = { id: number; name: string }', isExportable: true }, ], imports: [], exports: [], }) await fabric.addFile({ baseName: 'post.ts', path: './generated/models/post.ts', sources: [ { value: 'export type Post = { id: number; title: string }', isExportable: true }, ], imports: [], exports: [], }) await fabric.write() ``` ```typescript export { User } from './user' export { Post } from './post' ``` -------------------------------- ### Complete File Generation Example Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/components/file.md A comprehensive example demonstrating the creation of a TypeScript file with type imports, type definitions, and function implementations. This showcases the full capability of the File component. ```tsx import { createFabric } from '@kubb/fabric-core' import { fsxPlugin } from '@kubb/fabric-core/plugins' import { File, Br } from '@kubb/fabric-core' const fabric = createFabric() fabric.use(fsxPlugin) const component = File({ baseName: 'user.ts', path: './generated/types/user.ts', }).children([ File.Import({ name: 'BaseEntity', path: './base', isTypeOnly: true }), Br(), File.Source({ name: 'User', isExportable: true }).children([ `export type User = BaseEntity & { name: string email: string }` ]), Br(), File.Source({ name: 'createUser', isExportable: true }).children([ `export function createUser(data: User): User { return { ...data, id: Math.random() } }` ]) ]) const output = await fabric.render(component) ``` ```ts import type BaseEntity from "./base"; export type User = BaseEntity & { name: string email: string } export function createUser(data: User): User { return { ...data, id: Math.random() } } ``` -------------------------------- ### Define Parser with Options and Install Logic Source: https://github.com/kubb-labs/fabric/blob/main/docs/guide/creating-parsers.md Create a parser that accepts custom options like `indent` and `semicolons`. The `install` function can be used to log these options when the parser is registered. ```typescript type MyParserOptions = { indent?: number semicolons?: boolean } const myParser = defineParser({ name: 'myParser', extNames: ['.ext'], install(fabric, options) { const indent = options?.indent ?? 2 const semicolons = options?.semicolons ?? true console.log(`Using indent: ${indent}, semicolons: ${semicolons}`) }, parse(file) { return '...' }, }) ``` -------------------------------- ### Install React Fabric Source: https://github.com/kubb-labs/fabric/blob/main/docs/react.md Install React Fabric as a development dependency using your preferred package manager. ```bash bun add -d @kubb/react-fabric ``` ```bash pnpm add -D @kubb/react-fabric ``` ```bash npm install --save-dev @kubb/react-fabric ``` ```bash yarn add -D @kubb/react-fabric ``` -------------------------------- ### lifecycle:start Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/events.md Emitted when Fabric begins execution. Use for initializing resources or starting timers. ```APIDOC ## lifecycle:start Emitted when Fabric begins execution. Use for initializing resources or starting timers. **Payload:** None **Example:** ```ts fabric.context.on('lifecycle:start', async () => { console.log('Starting Fabric...') }) ``` ``` -------------------------------- ### Examples: CLI Progress UI Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/react-plugin.md Build interactive command-line interfaces that show a progress bar with React components. ```APIDOC ## Examples: CLI Progress UI Build interactive command-line interfaces that shows a progressbar with React components: ```tsx twoslash import { createFabric, useEffect, useState } from '@kubb/react-fabric' import { reactPlugin } from '@kubb/react-fabric/plugins' const fabric = createFabric() fabric.use(reactPlugin, { stdout: process.stdout }) // show the output in the terminal const Progress = () => { const [progress, setProgress] = useState(0) useEffect(() => { const interval = setInterval(() => { setProgress((prev: number) => Math.min(prev + 10, 100)) }, 100) return () => clearInterval(interval) }, []) return <>Progress: {progress}% } await fabric.render() await fabric.waitUntilExit() ``` ``` -------------------------------- ### Listen to Fabric Lifecycle Events Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/quick-start.md This example shows how to hook into Fabric's event system to monitor generation progress and log messages during the process. It logs the start of file writing, processing progress, and completion. ```typescript import { createFabric } from '@kubb/fabric-core' import { fsPlugin } from '@kubb/fabric-core/plugins' import { typescriptParser } from '@kubb/fabric-core/parsers' const fabric = createFabric() // Listen to events fabric.context.on('files:writing:start', () => { console.log('Writing files ...') }) fabric.context.on('file:processing:update', ({ processed, total, percentage }) => { console.log(`Progress: ${percentage.toFixed(1)}% (${processed}/${total})`) }) fabric.context.on('lifecycle:end', () => { console.log('Generation completed!') }) fabric.use(fsPlugin) fabric.use(typescriptParser) await fabric.addFile({ baseName: 'output.ts', path: './generated/output.ts', sources: [ { value: 'export const message = "Hello, Fabric!"', isExportable: true }, ], imports: [], exports: [], }) await fabric.write() ``` -------------------------------- ### Example: Clean Before Writing Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/fs-plugin.md Illustrates how to use the `clean` option to remove a directory before writing files. ```APIDOC ### Clean Before Writing ```ts twoslash import { createFabric } from '@kubb/fabric-core' import { fsPlugin } from '@kubb/fabric-core/plugins' import { typescriptParser } from '@kubb/fabric-core/parsers' const fabric = createFabric() fabric.use(fsPlugin, { clean: { path: './output' }, // Remove ./output directory first }) fabric.use(typescriptParser) await fabric.addFile({ baseName: 'api.ts', path: './output/api.ts', sources: [ { value: 'export const API_URL = "https://api.example.com"', isExportable: true }, ], imports: [], exports: [] }) await fabric.write() ``` ``` -------------------------------- ### Install Fabric Core with Bun Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Use this command to add the core Fabric package as a development dependency using Bun. ```bash bun add -d @kubb/fabric-core ``` -------------------------------- ### Examples: Template Generation Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/react-plugin.md Generate code templates using React components. ```APIDOC ## Examples: Template Generation Generate code templates using React components: ```tsx twoslash import { createFabric} from '@kubb/react-fabric' import { reactPlugin } from '@kubb/react-fabric/plugins' const fabric = createFabric() fabric.use(reactPlugin, { stdout: process.stdout }) // show the output in the terminal const TypeTemplate = ({ name, fields }: { name: string; fields: string[] }) => { return ( <> export interface {name} {'{'} {fields.map(f => ( <> {f}: string; ))} {'}'} ) } await fabric.render() await fabric.waitUntilExit() ``` ``` -------------------------------- ### Create and Render a React Component Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/react-plugin.md Demonstrates the basic setup for using the reactPlugin by creating a Fabric instance, using the plugin, defining a simple React component, and rendering it. ```tsx import { createFabric } from '@kubb/fabric-core' import { reactPlugin } from '@kubb/react-fabric/plugins' const fabric = createFabric() fabric.use(reactPlugin) const App = () => { return
Hello from React!
} await fabric.render(App) ``` -------------------------------- ### Install React Fabric with Bun Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Use this command to add the React integration package as a development dependency using Bun. ```bash bun add -d @kubb/react-fabric ``` -------------------------------- ### Usage Source: https://github.com/kubb-labs/fabric/blob/main/docs/react/components/fabric.md Example of how to use the Fabric component for file generation with metadata. ```APIDOC ## Fabric Component Usage This example demonstrates how to use the `Fabric` component from `@kubb/react-fabric` to generate files with metadata. ### Component Signature ```tsx {/* File generation components */} ``` ### Props #### meta - **Type**: `TMeta` - **Required**: `false` - **Default**: `{}` - **Description**: Metadata attached to the Fabric context. #### children - **Type**: `KubbNode` - **Required**: `false` - **Description**: Child React components, typically `File` components for defining file content. ### Example ```tsx import { createReactFabric, Fabric, File } from '@kubb/react-fabric' const fabric = createReactFabric() export function Generator() { return ( export type User = {'{'} id: number {'}'} ) } const output = await fabric.renderToString() ``` ### Output Example ```ts export type User = { id: number }; ``` ``` -------------------------------- ### Generated Index File Example Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/barrel-plugin.md Example of an index.ts file generated by the barrel plugin when using 'named' mode. ```typescript export * from './types' export * from './api' ``` -------------------------------- ### Verify Fabric Installation Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Create a TypeScript file to test the Fabric initialization. This script imports `createFabric` from `@kubb/fabric-core` and logs a success message. ```ts import { createFabric } from '@kubb/fabric-core' const fabric = createFabric() console.log('Fabric initialized successfully!') ``` -------------------------------- ### Example: Dry Run for Testing Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/fs-plugin.md Shows how to use `dryRun: true` to test file generation without actually writing files to disk, combined with `onBeforeWrite` for logging. ```APIDOC ### Dry Run for Testing ```ts twoslash import { createFabric } from '@kubb/fabric-core' import { fsPlugin } from '@kubb/fabric-core/plugins' const fabric = createFabric() fabric.use(fsPlugin, { dryRun: true, // Test without writing files onBeforeWrite: (path, data) => { console.log(`Would write: ${path}`) }, }) await fabric.addFile({ baseName: 'test.ts', path: './output/test.ts', sources: [ { value: 'export const x = 1', isExportable: true }, ], imports: [], exports: [], }) await fabric.write() // No files written to disk ``` ``` -------------------------------- ### React Component Generation Example Source: https://github.com/kubb-labs/fabric/blob/main/docs/parsers/tsx-parser.md Generate React components with proper TSX syntax using the tsxParser. This example creates a UserCard component. ```typescript import { createFabric } from '@kubb/fabric-core' import { fsPlugin } from '@kubb/fabric-core/plugins' import { tsxParser } from '@kubb/fabric-core/parsers' const fabric = createFabric() fabric.use(fsPlugin, { clean: { path: './components' }, }) fabric.use(tsxParser) await fabric.addFile({ baseName: 'UserCard.tsx', path: './components/UserCard.tsx', sources: [ { value: 'interface Props { name: string }', isExportable: false }, { value: 'export const UserCard = ({ name }: Props) =>
{name}
', isExportable: true, }, ], imports: [], exports: [], }) await fabric.write() ``` -------------------------------- ### Install Fabric Core with Yarn Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Use this command to add the core Fabric package as a development dependency using Yarn. ```bash yarn add -D @kubb/fabric-core ``` -------------------------------- ### Basic TypeScript File Generation Source: https://github.com/kubb-labs/fabric/blob/main/docs/parsers/typescript-parser.md This example demonstrates creating a basic TypeScript file with exported types and constants using the typescriptParser. ```typescript import { createFabric } from '@kubb/fabric-core' import { fsPlugin } from '@kubb/fabric-core/plugins' import { typescriptParser } from '@kubb/fabric-core/parsers' const fabric = createFabric() fabric.use(fsPlugin) fabric.use(typescriptParser) await fabric.addFile({ baseName: 'user.ts', path: './output/user.ts', sources: [ { value: 'export type User = { id: number; name: string }', isExportable: true }, { value: 'export const defaultUser: User = { id: 0, name: "Guest" }', isExportable: true }, ], imports: [], exports: [], }) await fabric.write({ extension: { '.ts': '.ts' } }) ``` -------------------------------- ### Reinstall Dependencies Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md If facing installation issues, remove `node_modules` and `package-lock.json` (or equivalent) and reinstall all dependencies. ```bash rm -rf node_modules package-lock.json npm install ``` -------------------------------- ### Install React Fabric with Yarn Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Use this command to add the React integration package as a development dependency using Yarn. ```bash yarn add -D @kubb/react-fabric ``` -------------------------------- ### Configure Fabric Instance with Multiple Plugins Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins.md Plugins are configured during the creation of your Fabric instance. This example demonstrates using loggerPlugin, fsxPlugin, and fsPlugin together. ```typescript import { createFabric } from '@kubb/fabric-core' import { fsPlugin, fsxPlugin, loggerPlugin } from '@kubb/fabric-core/plugins' const fabric = createFabric() fabric.use(loggerPlugin) fabric.use(fsxPlugin) fabric.use(fsPlugin, { dryRun: false, clean: { path: './generated' }, }) ``` -------------------------------- ### Register and Use a Plugin Source: https://github.com/kubb-labs/fabric/blob/main/docs/guide/creating-plugins.md Create a plugin using `definePlugin` and then register it with the Fabric instance using the `fabric.use()` method. The `install` function within the plugin will be executed upon registration. ```typescript import { createFabric } from '@kubb/fabric-core' import { definePlugin } from '@kubb/fabric-core/plugins' const myPlugin = definePlugin({ name: 'myPlugin', install(fabric) { // Plugin logic here }, }) const fabric = createFabric() fabric.use(myPlugin) ``` -------------------------------- ### Install React Fabric with npm Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Use this command to add the React integration package as a development dependency using npm. ```bash npm install --save-dev @kubb/react-fabric ``` -------------------------------- ### Install Fabric Core with pnpm Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Use this command to add the core Fabric package as a development dependency using pnpm. ```bash pnpm add -D @kubb/fabric-core ``` -------------------------------- ### Install React Fabric with pnpm Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Use this command to add the React integration package as a development dependency using pnpm. ```bash pnpm add -D @kubb/react-fabric ``` -------------------------------- ### Check Node.js Version Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Verify that your installed Node.js version meets the minimum requirement of v20.0.0. ```bash node --version # Should show v20.0.0 or higher ``` -------------------------------- ### File Import Examples Source: https://github.com/kubb-labs/fabric/blob/main/docs/react/components/file.md Demonstrates different ways to use the File.Import component to generate import statements. Supports default, named, aliased, and type-only imports. ```tsx ``` ```tsx ``` ```tsx ``` ```tsx ``` ```tsx ``` ```tsx ``` -------------------------------- ### Code Generation Example Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/fsx-plugin.md Generate TypeScript code using component composition with the fsxPlugin, demonstrating how to create models and constants. ```APIDOC ## Examples ### Code Generation from Templates Generate TypeScript code using component composition: ```tsx twoslash [run.ts] import { createFabric, Type, Const, File, createComponent, Br } from '@kubb/fabric-core' import { fsxPlugin } from '@kubb/fabric-core/plugins' const ModelGenerator = createComponent('ModelGenerator', ({ name, fields }: { name: string fields: Array<{ name: string; type: string }> }) => { return File({ baseName: `${name.toLowerCase()}.ts`, path: `./${name.toLowerCase()}.ts`, children: [ Type({ name, export: true, children: `{ ${fields.map(f => `${f.name}: ${f.type}`).join('; ')} }`, }), Br(), Const({ name: `default${name}`, export: true, type: name, children: `{ ${fields.map(f => `${f.name}: undefined`).join(', ')} }`, }), Br() ], }) }) const fabric = createFabric() fabric.use(fsxPlugin) const output = await fabric.render( ModelGenerator({ name: 'User', fields: [ { name: 'id', type: 'number' }, { name: 'name', type: 'string' }, { name: 'email', type: 'string' }, ], }) ) ``` ```ts [output] export type User = { id: number; name: string; email: string } export const defaultUser: User = { id: undefined, name: undefined, email: undefined } ``` ``` -------------------------------- ### Install Fabric Core with npm Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Use this command to add the core Fabric package as a development dependency using npm. ```bash npm install --save-dev @kubb/fabric-core ``` -------------------------------- ### Internal Usage Example Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/components/root.md Demonstrates how the Fabric runtime internally uses the Root component. Users typically do not create it directly. ```APIDOC ## Internal Usage The Root component is automatically used by the fsxPlugin runtime. You typically won't create it directly. ```ts // The runtime creates Root internally await fabric.render(component) // Root is automatically wrapped around your component ``` ``` -------------------------------- ### Generated Index File for 'all' Mode Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/barrel-plugin.md Example of an index.ts file generated by the barrel plugin when using 'all' mode. ```typescript export * from "./models/api/client"; export * from "./models/types/user"; ``` -------------------------------- ### Create and Render a Simple FSX Component Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/fsx-plugin.md Use this snippet to create a basic FSX component and render its output using the fsxPlugin. Ensure `@kubb/fabric-core` and its plugins are installed. ```tsx import { createFabric } from '@kubb/fabric-core' import { fsxPlugin } from '@kubb/fabric-core/plugins' import { createComponent } from '@kubb/fabric-core' const fabric = createFabric() fabric.use(fsxPlugin) const App = createComponent('App', () => { return 'Hello from Fabric!' }) const output = await fabric.render(App()) ``` ```ts "Hello from Fabric!" ``` -------------------------------- ### Create Fabric Instance and Add Files Source: https://github.com/kubb-labs/fabric/blob/main/examples/core/README.md Demonstrates how to create a Fabric instance, register plugins and parsers, add files with content, and write them to disk. Use this to set up the file generation process. ```typescript import { createFabric } from '@kubb/fabric-core' import { fsPlugin } from '@kubb/fabric-core/plugins' import { typescriptParser } from '@kubb/fabric-core/parsers' const fabric = createFabric() fabric.use(fsPlugin, { dryRun: false, onBeforeWrite: (path, data) => { console.log('About to write:', path) }, clean: { path: './generated' }, }) fabric.use(typescriptParser) await fabric.addFile({ baseName: 'index.ts', path: './generated/index.ts', sources: [ { value: 'export const x = 1', isExportable: true }, ], imports: [], exports: [], }) await fabric.write() ``` -------------------------------- ### Listen to lifecycle events Source: https://github.com/kubb-labs/fabric/blob/main/docs/core.md Register event listeners on the Fabric instance's context to hook into the generation lifecycle. This example logs a message when generation starts. ```typescript fabric.context.on('lifecycle:start', () => { console.log('Generation started') }) ``` -------------------------------- ### Inspect Generated Files Before Writing Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/troubleshooting.md Hook into the 'files:writing:start' event to examine file contents, sources, and imports before they are written to disk. ```typescript fabric.context.on('files:writing:start', (files) => { for (const file of files) { console.log(` File: ${file.path}`) console.log('Sources:', file.sources?.length || 0) console.log('Imports:', file.imports?.length || 0) // Print first source if (file.sources?.[0]) { console.log('Content preview:', file.sources[0].value.slice(0, 100)) } } }) ``` -------------------------------- ### Listen to Files Writing Start Event Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/events.md This event is emitted before any files are written to disk. It provides the count of files about to be written, useful for logging or pre-write operations. ```typescript fabric.context.on('files:writing:start', async (files) => { console.log(`Preparing to write ${files.length} files`) }) ``` -------------------------------- ### Create Fabric Instance and Add Files Source: https://github.com/kubb-labs/fabric/blob/main/packages/react-fabric/README.md Demonstrates creating a Fabric instance, registering plugins like fsPlugin and typescriptParser, and adding a file to be generated. Use this to set up the file generation process. ```typescript import { createFabric } from '@kubb/fabric-core' import { fsPlugin } from '@kubb/fabric-core/plugins' import { typescriptParser } from '@kubb/fabric-core/parsers' const fabric = createFabric() fabric.use(fsPlugin, { dryRun: false, onBeforeWrite: (path, data) => { console.log('About to write:', path) }, clean: { path: './generated' }, }) fabric.use(typescriptParser) await fabric.addFile({ baseName: 'index.ts', path: './generated/index.ts', sources: [ { value: 'export const x = 1', isExportable: true }, ], imports: [], exports: [], }) await fabric.write() ``` -------------------------------- ### Check npm package installation Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Verify if `@kubb/fabric-core` is listed in your project's installed dependencies. ```bash npm list @kubb/fabric-core ``` -------------------------------- ### Listen to Lifecycle Start Event Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/events.md Emitted when Fabric begins execution. Use for initializing resources or starting timers. ```typescript fabric.context.on('lifecycle:start', async () => { console.log('Starting Fabric...') }) ``` -------------------------------- ### Basic Fabric Configuration with Plugins and Parsers Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/configure.md Initialize Fabric and register core plugins and parsers. Ensure necessary imports are included. ```typescript import { createFabric } from '@kubb/fabric-core' import { fsPlugin, loggerPlugin } from '@kubb/fabric-core/plugins' import { typescriptParser } from '@kubb/fabric-core/parsers' const fabric = createFabric() // Configure plugins fabric.use(loggerPlugin, { progress: true }) fabric.use(fsPlugin, { clean: { path: './output' } }) fabric.use(typescriptParser) ``` -------------------------------- ### Set Up Event Listeners Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/configure.md React to Fabric lifecycle events to log progress or trigger custom actions. Common events include 'lifecycle:start', 'file:processing:update', 'files:writing:start', and 'lifecycle:end'. ```typescript import { createFabric } from '@kubb/fabric-core' const fabric = createFabric() fabric.context.on('lifecycle:start', async () => { console.log('Starting generation...') }) fabric.context.on('file:processing:update', async ({ processed, total, percentage }) => { console.log(`Progress: ${percentage.toFixed(1)}%`) }) fabric.context.on('files:writing:start', async (files) => { console.log(`Writing ${files.length} files...`) }) fabric.context.on('lifecycle:end', async () => { console.log('Generation complete!') }) ``` -------------------------------- ### Common Development Commands Source: https://github.com/kubb-labs/fabric/blob/main/AGENTS.md Lists essential commands for managing dependencies, building, testing, and linting the project. ```bash pnpm install # Install dependencies pnpm clean # Clean build artifacts pnpm build # Build all packages pnpm test # Run tests pnpm typecheck # Type check packages pnpm lint # Lint code pnpm lint:fix # Lint and fix issues pnpm changeset # Create changelog entry pnpm run upgrade && pnpm i # Upgrade dependencies ``` -------------------------------- ### lifecycle:render Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/events.md Emitted when rendering starts (requires `reactPlugin` or `fsxPlugin`). ```APIDOC ## lifecycle:render Emitted when rendering starts (requires `reactPlugin` or `fsxPlugin`). ```ts fabric.context.on('lifecycle:render', async ({ fabric }) => { console.log('Rendering started') }) ``` **Payload:** | | | | |-------:|:---------|:-------------------------| | fabric | `Fabric` | The Fabric instance | ``` -------------------------------- ### Listen to lifecycle events Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/events.md Example of how to listen to various lifecycle events in Fabric. ```APIDOC ## Listen to lifecycle events Access the event emitter through `fabric.context.on()` or `fabric.context.events.on()`. ### Example: ```ts import { createFabric } from '@kubb/fabric-core' const fabric = createFabric() fabric.context.on('lifecycle:start', async () => { console.log('Fabric execution started') }) fabric.context.on('file:processing:update', async ({ processed, total, percentage }) => { console.log(`Progress: ${percentage.toFixed(1)}% (${processed}/${total})`) }) fabric.context.on('lifecycle:end', async () => { console.log('Fabric execution completed') }) ``` **Event handlers can be async:** ```ts fabric.context.on('lifecycle:start', async () => { await initializeDatabase() console.log('Database ready') }) ``` ``` -------------------------------- ### Listen to Lifecycle Render Event Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/events.md Emitted when rendering starts. Requires `reactPlugin` or `fsxPlugin`. ```typescript fabric.context.on('lifecycle:render', async ({ fabric }) => { console.log('Rendering started') }) ``` -------------------------------- ### Run Verification Script with Bun Source: https://github.com/kubb-labs/fabric/blob/main/docs/getting-started/installation.md Execute the verification script using Bun. ```bash bun test-fabric.ts ``` -------------------------------- ### Create a Fabric Instance with Core Plugins Source: https://context7.com/kubb-labs/fabric/llms.txt Use `createFabric` to initialize the core Fabric runtime. Register essential plugins like `loggerPlugin` and `fsPlugin`, along with parsers like `typescriptParser`. Files can then be added imperatively using `addFile` and written to disk with `write`. ```typescript import { createFabric } from '@kubb/fabric-core' import { typescriptParser } from '@kubb/fabric-core/parsers' import { fsPlugin, loggerPlugin } from '@kubb/fabric-core/plugins' const fabric = createFabric({ mode: 'sequential' }) // 'sequential' | 'parallel' // Register plugins and parsers fabric.use(loggerPlugin, { progress: true }) fabric.use(fsPlugin, { clean: { path: './generated' } }) fabric.use(typescriptParser) // handles .ts and .js files // Add files imperatively await fabric.addFile({ baseName: 'user.ts', path: './generated/user.ts', sources: [ { value: 'export type User = { id: number; name: string }', isExportable: true, isIndexable: true }, ], imports: [{ name: ['BaseModel'], path: './base', isTypeOnly: true }], exports: [], }) // Write all files to disk; triggers files:writing:start → file:processing:update → files:writing:end await fabric.write({ extension: { '.ts': '.ts' } }) // Output: ./generated/user.ts ``` -------------------------------- ### Import defineParser Factory Source: https://github.com/kubb-labs/fabric/blob/main/docs/guide/creating-parsers.md Import the `defineParser` factory from `@kubb/fabric-core/parsers` to start creating custom parsers. ```typescript import { defineParser } from '@kubb/fabric-core/parsers' ``` -------------------------------- ### Create a Plugin with Options Source: https://github.com/kubb-labs/fabric/blob/main/docs/guide/creating-plugins.md Define a plugin that accepts configuration options. Use these options to customize plugin behavior, such as setting a prefix for logs or enabling verbose output. ```typescript import { createFabric } from '@kubb/fabric-core' import { definePlugin } from '@kubb/fabric-core/plugins' type LoggerOptions = { prefix?: string verbose?: boolean } const loggerPlugin = definePlugin({ name: 'loggerPlugin', install(fabric, options) { const prefix = options?.prefix ?? '[LOG]' const verbose = options?.verbose ?? false fabric.on('lifecycle:start', () => { console.log(`${prefix} Starting...`) }) if (verbose) { fabric.on('file:processing:update', ({ processed, total }) => { console.log(`${prefix} Progress: ${processed}/${total}`) }) } fabric.on('lifecycle:end', () => { console.log(`${prefix} Completed!`) }) }, }) const fabric = createFabric() fabric.use(loggerPlugin, { prefix: '[GEN]', verbose: true, }) ``` -------------------------------- ### Injected Methods: render Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/react-plugin.md Renders a React component tree to the terminal and emits the `lifecycle:start` event. ```APIDOC ## Injected Methods: render(Fabric) Renders a React component tree to the terminal and emits the `lifecycle:start` event. **Example:** ```tsx [app.tsx] const App = () =>
Building files...
await fabric.render(App) ``` ``` -------------------------------- ### File Import Formats Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/components/file.md Demonstrates different ways to import modules using the File.Import utility. Supports simple strings, arrays of strings, aliased named imports, and namespace imports. ```ts // Simple string File.Import({ name: 'React', path: 'react' }) // -> import React from 'react' ``` ```ts // Array of strings File.Import({ name: ['useState', 'useEffect'], path: 'react' }) // -> import { useState, useEffect } from 'react' ``` ```ts // Named imports with aliases File.Import({ name: [{ propertyName: 'default', name: 'React' }], path: 'react' }) // -> import { default as React } from 'react' ``` ```ts // Namespace import File.Import({ name: 'React', path: 'react', isNameSpace: true }) // -> import * as React from 'react' ``` -------------------------------- ### createComponent Helper Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/fsx-plugin.md The `createComponent` helper allows you to build reusable components for code generation, as demonstrated in these examples. ```APIDOC ## `createComponent` The `createComponent` helper allows you to build reusable components for code generation: ```tsx twoslash [component-example.ts] import { createComponent, Const } from '@kubb/fabric-core' const MyConst = createComponent('MyConst', ({ name }: { name: string }) => { return Const({ name, children: '"hello"' }) }) const output = MyConst({ name: 'greeting' })() ``` ```ts twoslash [component-with-children.ts] import { createComponent, Const } from '@kubb/fabric-core' const MyConst = createComponent('MyConst', ({ name }: { name: string }) => { return Const({ name }).children('"hello"') }) const output = MyConst({ name: 'greeting' })() ``` ```ts [output] const greeting = "hello" ``` ``` -------------------------------- ### Run Test Suite Source: https://github.com/kubb-labs/fabric/blob/main/CONTRIBUTING.md Execute this command to run the project's test suite. This verifies that the code functions as expected and catches regressions. ```bash pnpm run test ``` -------------------------------- ### Import definePlugin Factory Source: https://github.com/kubb-labs/fabric/blob/main/docs/guide/creating-plugins.md The `definePlugin` factory is available in the `@kubb/fabric-core/plugins` package. Import it to start defining your custom plugins. ```typescript import { definePlugin } from '@kubb/fabric-core/plugins' ``` -------------------------------- ### Generated File Content Source: https://github.com/kubb-labs/fabric/blob/main/packages/react-fabric/README.md This is the content of the file generated by the preceding TypeScript example. It shows a simple export statement. ```typescript export const x = 1 ``` -------------------------------- ### Install Plugin and Parser with fabric.use Source: https://context7.com/kubb-labs/fabric/llms.txt Registers custom parsers and plugins into the Fabric instance. Parsers handle file extensions, while plugins hook into lifecycle events and can extend the fabric object. ```typescript import { createFabric } from '@kubb/fabric-core' import { definePlugin } from '@kubb/fabric-core/plugins' import { defineParser } from '@kubb/fabric-core/parsers' // Custom parser for .json files const jsonParser = defineParser({ name: 'json-parser', extNames: ['.json'], install() {}, async parse(file) { const src = file.sources.map((s) => s.value).join('\n') return src // return raw JSON string as-is }, }) // Custom plugin that logs every written file const auditPlugin = definePlugin({ name: 'audit', install(ctx) { const written: string[] = [] ctx.on('file:processing:update', ({ file }) => { written.push(file.path) }) ctx.on('lifecycle:end', () => { console.log('Wrote', written.length, 'files:', written) }) }, }) const fabric = createFabric() await fabric.use(jsonParser) await fabric.use(auditPlugin) await fabric.addFile({ baseName: 'config.json', path: './out/config.json', sources: [{ value: '{"version":1}' }], imports: [], exports: [], }) ``` -------------------------------- ### createFabric Source: https://github.com/kubb-labs/fabric/blob/main/packages/react-fabric/README.md Initializes a new Fabric instance. This is the entry point for using the fabric toolkit. ```APIDOC ## createFabric(options?): Fabric Returns a Fabric instance with: - `fabric.use(pluginOrParser, ...options) => Fabric` — register plugins and parsers. - `fabric.addFile(...files)` — queue in-memory files to generate. - `fabric.files` — getter with all queued files. - `fabric.context` — internal context holding events, options, FileManager, installed plugins/parsers. ``` -------------------------------- ### definePlugin Source: https://github.com/kubb-labs/fabric/blob/main/packages/react-fabric/README.md Factory to declare a plugin that can be registered via `fabric.use`. It allows defining installation logic and runtime method injections. ```APIDOC ## definePlugin Factory to declare a plugin that can be registered via `fabric.use`. ### Parameters - **name** (string) - Required - String identifier of your plugin. - **install(fabric, options)** (function) - Required - Called when the plugin is registered. You can subscribe to core events and perform side effects here. - **inject?(fabric, options)** (function) - Optional - Return synchronously the runtime methods/properties to merge into `fabric` (e.g. `write`, `render`). This must not be async. ### Example ```ts import { createFabric } from '@kubb/fabric-core' import { definePlugin } from '@kubb/fabric-core/plugins' const helloPlugin = definePlugin<{ name?: string }, { sayHello: (msg?: string) => void }>({ name: 'helloPlugin', install(fabric, options) { fabric.context.events.on('lifecycle:start', () => { console.log('Fabric started') }) }, inject(fabric, options) { return { sayHello(msg = options?.name ?? 'world') { console.log(`Hello ${msg}!`) }, } }, }) const fabric = createFabric() await fabric.use(helloPlugin, { name: 'Fabric' }) f fabric.sayHello() // -> Hello Fabric! ``` ``` -------------------------------- ### Create App Container with File Generation Source: https://github.com/kubb-labs/fabric/blob/main/docs/core/components/fabric.md Use Fabric to create an app container and generate a file with specific content. This example demonstrates setting up Fabric, adding a plugin, defining a File component with its source, and rendering the output. ```typescript import { createFabric } from '@kubb/fabric-core' import { fsxPlugin } from '@kubb/fabric-core/plugins' import { Fabric, File } from '@kubb/fabric-core' const fabric = createFabric() fabric.use(fsxPlugin) const Component = Fabric().children([ File({ baseName: 'user.ts', path: './generated/user.ts' }) .children( File.Source().children(['export type User = { id: number }']) ) ]) const output = await fabric.render(Component) ``` ```typescript export type User = { id: number }; ``` -------------------------------- ### Plugin Options: stdout Source: https://github.com/kubb-labs/fabric/blob/main/docs/plugins/react-plugin.md Configure the output stream for rendered content. If set, output is written progressively. ```APIDOC ## Plugin Options: stdout Output stream for rendered content. If set, output is written progressively. | | | |:----|:--------------------------------| | Type: | ` NodeJS.WriteStream` | | Required: | `false` | ```ts [example.ts] import { createWriteStream } from 'fs' fabric.use(reactPlugin, { stdout: createWriteStream('./output.txt'), }) ``` ``` -------------------------------- ### Create React Fabric Generator Source: https://github.com/kubb-labs/fabric/blob/main/docs/react/components/root.md This example demonstrates how to set up a basic React Fabric generator using the Root component. It includes necessary imports and the basic structure for a generator function. ```tsx import { createReactFabric, Root, Fabric, TreeNode, FileManager } from '@kubb/react-fabric' import type { ComponentNode } from '@kubb/react-fabric/types' const fabric = createReactFabric() const treeNode = new TreeNode({ type: 'Root', props: {} }) const fileManager = new FileManager() export function Generator() { return ( process.exit(error ? 1 : 0)} onError={(error: Error) => console.error(error)} treeNode={treeNode} fileManager={fileManager} > {/* Your components */} ) } ```