Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add cli #42

Merged
merged 6 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Copyright 2023 https://fal.ai
Copyright 2024 https://fal.ai

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

Expand Down
18 changes: 18 additions & 0 deletions libs/cli/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions libs/cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## Fal.ai App Generator

Generate a new full stack app configured with Fal.ai proxy and models.

```sh
npx @fal-ai/create
```
11 changes: 11 additions & 0 deletions libs/cli/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* eslint-disable */
export default {
displayName: 'cli',
preset: '../../jest.preset.js',
testEnvironment: 'node',
transform: {
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/libs/cli',
};
21 changes: 21 additions & 0 deletions libs/cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "@fal-ai/create",
"version": "0.0.1",
"description": "The fal serverless app generator.",
"main": "index.js",
"keywords": [
"fal",
"next",
"nextjs",
"express"
],
"repository": {
"type": "git",
"url": "https://github.com/fal-ai/serverless-js.git",
"directory": "libs/cli"
},
"type": "module",
"author": "",
"license": "MIT",
"dependencies": {}
}
41 changes: 41 additions & 0 deletions libs/cli/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "cli",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/cli/src",
"projectType": "library",
"targets": {
"build": {
"executor": "@nx/js:tsc",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/libs/cli",
"tsConfig": "libs/cli/tsconfig.lib.json",
"packageJson": "libs/cli/package.json",
"main": "libs/cli/src/index.ts",
"assets": ["LICENSE", "CODE_OF_CONDUCT.md", "libs/cli/README.md"]
}
},
"lint": {
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["libs/cli/**/*.ts"]
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "libs/cli/jest.config.ts",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
}
},
"tags": []
}
148 changes: 148 additions & 0 deletions libs/cli/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
#!/usr/bin/env node

import chalk from 'chalk';
import path from 'path';
import fs from 'fs';
import childProcess from 'child_process';
import ora from 'ora';
import select from '@inquirer/select';
import { input } from '@inquirer/prompts';
import { Command } from 'commander';
import { execa, execaCommand } from 'execa';
import open from 'open';

const program = new Command();
const log = console.log;
const repoUrl = 'https://github.com/fal-ai/fal-nextjs-template.git';
const green = chalk.green;
const purple = chalk.hex('#6e40c9');

async function main() {
const spinner = ora({
text: 'Creating codebase',
});
try {
const kebabRegez = /^([a-z]+)(-[a-z0-9]+)*$/;

program
.name('Fal.ai App Generator')
.description('Generate full stack AI apps integrated with Fal.ai.');

program.parse(process.argv);

const args = program.args;
let appName = args[0];

if (!appName || !kebabRegez.test(args[0])) {
appName = await input({
message: 'Enter your app name',
default: 'model-playground',
validate: (d) => {
if (!kebabRegez.test(d)) {
return 'please enter your app name in the format of my-app-name';
}
return true;
},
});
}

const hasFalEnv = await select({
message: 'Do you have a Fal.ai API key?',
choices: [
{
name: 'Yes',
value: true,
},
{
name: 'No',
value: false,
},
],
});

if (!hasFalEnv) {
await open('https://www.fal.ai/dashboard');
}

const fal_api_key = await input({ message: 'Fal AI API Key' });

let envs = `
# environment, either PRODUCTION or DEVELOPMENT
ENVIRONMENT="PRODUCTION"

# FAL AI API Key
FAL_KEY="${fal_api_key}"
`;

log(`\nInitializing project. \n`);

spinner.start();
await execa('git', ['clone', repoUrl, appName]);

let packageJson = fs.readFileSync(`${appName}/package.json`, 'utf8');
const packageObj = JSON.parse(packageJson);
packageObj.name = appName;
packageJson = JSON.stringify(packageObj, null, 2);
fs.writeFileSync(`${appName}/package.json`, packageJson);
fs.writeFileSync(`${appName}/.env.local`, envs);

process.chdir(path.join(process.cwd(), appName));
spinner.text = '';
let startCommand = '';

if (isBunInstalled()) {
spinner.text = 'Installing dependencies';
await execaCommand('bun install').pipeStdout(process.stdout);
spinner.text = '';
startCommand = 'bun dev';
console.log('\n');
} else if (isYarnInstalled()) {
await execaCommand('yarn').pipeStdout(process.stdout);
startCommand = 'yarn dev';
} else {
spinner.text = 'Installing dependencies';
await execa('npm', ['install', '--verbose']).pipeStdout(process.stdout);
spinner.text = '';
startCommand = 'npm run dev';
}

spinner.stop();
process.chdir('../');
log(
`${green.bold('Success!')} Created ${purple.bold(
appName
)} at ${process.cwd()} \n`
);
log(
`To get started, change into the new directory and run ${chalk.cyan(
startCommand
)}\n`
);
} catch (err) {
log('\n');
if (err.exitCode == 128) {
log('Error: directory already exists.');
}
spinner.stop();
}
}

main();

function isYarnInstalled() {
try {
childProcess.execSync('yarn --version');
return true;
} catch {
return false;
}
}

function isBunInstalled() {
try {
childProcess.execSync('bun --version');
return true;
} catch (err) {
return false;
}
}
13 changes: 13 additions & 0 deletions libs/cli/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
22 changes: 22 additions & 0 deletions libs/cli/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "ESNext",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*",
"src/types/*"
]
}
},
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"],
"include": ["src/**/*.ts"]
}
14 changes: 14 additions & 0 deletions libs/cli/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
4 changes: 4 additions & 0 deletions libs/cli/yarn.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1


4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,21 @@
]
},
"dependencies": {
"@inquirer/prompts": "^3.3.0",
"@inquirer/select": "^1.3.1",
"@msgpack/msgpack": "^3.0.0-beta2",
"@oclif/core": "^2.3.0",
"@oclif/plugin-help": "^5.2.5",
"axios": "^1.0.0",
"chalk": "^5.3.0",
"change-case": "^4.1.2",
"chokidar": "^3.5.3",
"core-js": "^3.6.5",
"cors": "^2.8.5",
"cross-fetch": "^3.1.5",
"dotenv": "^16.3.1",
"encoding": "^0.1.13",
"execa": "^8.0.1",
"express": "^4.18.2",
"fast-glob": "^3.2.12",
"http-proxy": "^1.18.1",
Expand Down
1 change: 1 addition & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"skipDefaultLibCheck": true,
"baseUrl": ".",
"paths": {
"@fal-ai/cli": ["libs/cli/src/index.ts"],
"@fal-ai/serverless-client": ["libs/client/src/index.ts"],
"@fal-ai/serverless-proxy": ["libs/proxy/src/index.ts"],
"@fal-ai/serverless-proxy/express": ["libs/proxy/src/express.ts"],
Expand Down
Loading