Skip to content

creatium - Examples

Simple Example

Instance file

Set de configuration and build the [creatiium] instance.

ts
import {
	dirname,
	join,
} from 'node:path'
import { fileURLToPath } from 'node:url'

import { version }  from '../../package.json'
import { Creatium } from '../../src/main' // change for `import { Creatium } from 'creatium'`

const currentDir   = join( dirname( fileURLToPath( import.meta.url ) ) )
const templatesDir = join( currentDir, 'templates' )
const name         = 'Simple test'

export const creatium = new Creatium( {
	name,
	version,
	templates : {
		js : {
			input : join( templatesDir, 'js-project' ),
			name  : 'JavaScript project',
		},
		ts : {
			input : join( templatesDir, 'ts-project' ),
			name  : 'TypeScript project',
		},
	},
} )

Bin file

Create binary and then call cli method of [creatium] instance

ts
#!/usr/bin/env node

import { creatium } from './main'

await creatium.cli()

Library file

Create Function for use it as a library

ts
import { creatium } from './main'

type CreateParams = Parameters<typeof creatium.build>[0]

export const create = async ( params: CreateParams ): Promise<CreateParams> => {

	return await creatium.build( params )

}

Simple Example (custom)

Instance file

Set de configuration and build the [creatiium] instance.

ts
import {
	dirname,
	join,
} from 'node:path'
import { fileURLToPath } from 'node:url'

import { version }  from '../../package.json'
import { Creatium } from '../../src/main' // change for `import { Creatium } from 'creatium'`

const currentDir   = join( dirname( fileURLToPath( import.meta.url ) ) )
const templatesDir = join( currentDir, 'templates' )
const name         = 'Simple Custom test'

export const creatium = new Creatium( {
	name,
	version,
	updater   : true,
	cache     : true,
	templates : {
		js : {
			input : join( templatesDir, 'js-project' ),
			name  : 'JavaScript project',
		},
		ts : {
			input : join( templatesDir, 'ts-project' ),
			name  : 'TypeScript project',
		},
	},
	opts : {
		// use only this options for install
		install : [
			'pnpm',
			'npm',
			'deno',
		],
		// Delecte onpenEditor option
		openEditor : false,
		// Delecte name option. The name will be taken from output basename.
		name       : false,
	},
	// Add custom constants for replace in templates
	consts : { header: `Template generated by ${name}. A project from PigeonPosse` },
} )

Bin file

Create binary and then call cli method of [creatium] instance

ts
#!/usr/bin/env node

import { creatium } from './main'

await creatium.cli()

Library file

Create Function for use it as a library

ts
import { creatium } from './main'

type CreateParams = Partial<Parameters<typeof creatium.build>[0]>

export const create = async ( params?: CreateParams ) => {

	return await creatium.build( {
		input  : 'js', // Default input. it is the key of one template
		output : './build', // Default output
		...( params ?? {} ),
	} )

}

Advanced Example

Instance file

Set de configuration and build the [creatiium] instance.

ts
import {
	dirname,
	join,
} from 'node:path'
import process           from 'node:process'
import { fileURLToPath } from 'node:url'

import {
	version,
	author,
} from '../../package.json'
import {
	CreatiumCore,
	prompt,
	sys,
	style,
} from '../../src/main' // change for `import { Creatium } from 'creatium'`

const { copyDir }  = sys
const { color }    = style
const currentDir   = join( dirname( fileURLToPath( import.meta.url ) ) )
const templatesDir = join( currentDir, 'templates' )
const name         = 'Advanced test'
const cancelFn     = ( ) => {

	prompt.cancel( color.red( 'Chaooo 💔' ) )
	process.exit( 0 )

}

/** Instance of your create-project */
export const creatium = new CreatiumCore( {
	name,
	version,
	updater  : true,
	cache    : true,
	onCancel : cancelFn,
	prompt   : {
		// Add a box information first of all
		intro : {
			// The option void will not appear in cli options
			type : 'void',
			desc : 'Hello world',
			fn   : ( ) => {

				const value = `Package version: ${color.green( version )}\nAuthor: ${color.green( author.name )}`
				prompt.box( {
					value : value,
					opts  : {
						padding   : 1,
						dimBorder : true,
					},
				} )

			},
		},
		output : {
			type         : 'output',
			alias        : [ 'o' ],
			desc         : 'Where do you want create a new project?',
			initialValue : 'my project',
		},
		name : {
			type  : 'name',
			alias : [ 'n' ],
		},
		wsFiles : {
			type      : 'boolean',
			desc      : 'Include workspace files',
			promptMsg : 'Do you want add a workspace files like LICENSE, .npmrc and .gitignore?',
		},
		desc : {
			type : 'text',
			desc : 'Add a description of your project',
		},
		input : {
			type    : 'template',
			desc    : 'Select template',
			options : {
				js : {
					input : join( templatesDir, 'js-project' ),
					name  : 'JavaScript project',
				},
				ts : {
					input : join( templatesDir, 'ts-project' ),
					name  : 'TypeScript project',
				},
			},
		},
		install : {
			type        : 'install',
			desc        : 'Select package manager',
			onlyOptions : [
				'pnpm',
				'npm',
				'deno',
			],
		},
		openEditor : { type: 'openEditor' },
	},
} )

/**
 * Function for create a new project template.
 * @param {Awaited<ReturnType<typeof creatium.cli>>} params - The values to create the template.
 * @returns {Promise<void>} - A promise that resolves when the template is created.
 */
export const createTemplate = async ( params: Awaited<ReturnType<typeof creatium.cli>> ) => {

	try {

		const {
			output,
			input,
			install,
			openEditor,
			name,
			wsFiles,
			// extract constants for used in createTemplate
			...consts
		} = params
		const partialsDir = join( currentDir, 'partials' )

		const getGPL3License = async () => {

			try {

				const response = await fetch( 'https://www.gnu.org/licenses/gpl-3.0.txt' )

				if ( !response.ok )
					throw new Error( `Failed to fetch GPL-3 license: ${response.status} ${response.statusText}` )

				return await response.text()

			}
			catch ( error ) {

				console.error( 'Error fetching the GPL-3 license:', error )
				throw error

			}

		}

		if ( !output )  throw new Error( 'Output is required' )

		// Copy the workspace files if wsFiles is true.
		// this must be first than the creatium.createTemplate because creatium.createTemplate ends the line process
		// and wsFiles must be override in the creatium.createTemplate function.
		if ( wsFiles ) {

			await copyDir( {
				input : join( partialsDir, 'workspace' ),
				output,
			} )
			prompt.log.success( 'Added workspace files!' )

		}

		await creatium.createTemplate( {
			output,
			input,
			install,
			openEditor,
			name,
			consts : {
				...consts,
				pkg : JSON.stringify( {
					name        : name,
					description : consts.desc,
					version     : '0.0.1',
				}, null, 2 ),
				license : await getGPL3License(),
			},
		} )

	}
	catch ( error ) {

		prompt.log.step( '' )

		if ( error instanceof Error )
			prompt.log.error( color.red( error.message ) )
		else
			console.error( 'Unexpected error:', error )

		prompt.log.step( '' )
		cancelFn()

	}

}

Bin file

Create binary and then call cli method of [creatium] instance

ts
#!/usr/bin/env node

import {
	creatium,
	createTemplate,
} from './main'

// Run the CLI and obtain the prompt values
const res = await creatium.cli()

// Call to the create function for create the template
await createTemplate( res )

Library file

Create Function for use it as a library

ts
import {
	creatium,
	createTemplate,
} from './main'

type CreateParams = Parameters<typeof creatium.build>[0]

export const create = async ( params: CreateParams ) => {

	// Run the build function without running the CLI.
	// The user will can not use the cli flags to configure the template.
	const res = await creatium.build( params, { activeCli: false } )

	// call to the create function for create the template
	await createTemplate( res )

}