[Feature] App Store CLI - Make it super easy to add an app. (#2917)

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
Hariom Balharaandkodiakhq[bot] authored and GitHub committed 2022-06-07 11:43:32 +05:30
1 parent 51b86b1d97
commit 18e0f13605
44 files changed
+1290 -131

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
node_modules
dist
+32
View File
@@ -0,0 +1,32 @@
{
"name": "@calcom/app-store-cli",
"version": "0.0.0",
"bin": "dist/cli.js",
"engines": {
"node": ">=10"
},
"scripts": {
"cli": "ts-node --transpile-only src/cli.tsx",
"watch": "ts-node --transpile-only src/app-store.ts --watch",
"generate": "ts-node --transpile-only src/app-store.ts"
},
"files": [
"dist/cli.js"
],
"dependencies": {
"@calcom/lib": "*",
"ink": "^3.2.0",
"ink-select-input": "^4.2.1",
"ink-text-input": "^4.0.3",
"meow": "^9.0.0",
"react": "^17.0.2"
},
"devDependencies": {
"chokidar": "^3.5.3",
"@types/react": "^18.0.9",
"eslint-plugin-react": "^7.30.0",
"eslint-plugin-react-hooks": "^4.5.0",
"ts-node": "^10.6.0",
"typescript": "^4.6.4"
}
}
+39
View File
@@ -0,0 +1,39 @@
## Steps to create an app
- Create a folder in packages/app-store/{APP_NAME} = {APP}
- Fill it with a sample app
- Modify {APP}/_metadata.ts with the data provided
## Approach
- appType is derived from App Name(a slugify operation that makes a string that can be used as a director name, a variable name for imports and a URL path).
- appType is then used to create the app directory. It becomes `config.type` of config.json. config.type is the value used to create an entry in App table and retrieve any apps or credentials. It also becomes App.dirName
- dirnames that don't start with _ are considered apps in packages/app-store and based on those apps .generated.ts* files are created. This allows pre-cli apps to keep on working.
- app directory is populated with app-store/_baseApp with newly updated config.json and package.json
- `packages/prisma/seed-app-store.config.json` is updated with new app.
NOTE: After app-store-cli is live, Credential.appId and Credential.type would be same for new apps. For old apps they would remain different. Credential.type would be used to identify credentials in integrations call and Credential.appId/App.slug would be used to identify apps.
If we rename all existing apps to their slug names, we can remove type and then use just appId to refer to things everywhere. This can be done later on.
## TODO
- Beta Release
- Show a warning somewhere that app directory must not be renamed manually, edit command must be used.
- edit command should ask for slug and verify if it exists
- Improvements
- Prefill fields in edit command
- Merge app-store:watch and app-store commands, introduce app-store --watch
- Allow inputs in non interactive way as well - That would allow easily copy pasting commands.
- App already exists check. Ask user to run edit/regenerate command
- An app created through CLI should be able to completely skip API validation for testing purposes. Credentials should be created with no API specified specific to the app. It would allow us to test any app end to end not worrying about the corresponding API endpoint.
- Require assets path relative to app dir.
## Roadmap
- Avoid delete and edit on apps created outside of cli
- Someone can add wrong directory name(which doesn't satisfy slug requirements) manually. How to handle it.
- Allow editing and updating app from the cal app itself - including assets uploading when developing locally.
- Improvements in shared code across app
- Use baseApp/api/add.ts for all apps with configuration of credentials creation and redirection URL.
- Delete creation side effects if App creation fails - Might make debugging difficult
- This is so that web app doesn't break because of additional app folders or faulty db-seed
+329
View File
@@ -0,0 +1,329 @@
import child_process from "child_process";
import fs from "fs";
import { Box, Text, useApp, useInput, useStdin } from "ink";
import SelectInput from "ink-select-input";
import TextInput from "ink-text-input";
import path from "path";
import React, { FC, useEffect, useRef, useState } from "react";
const slugify = (str: string) => {
// It is to be a valid dir name, a valid JS variable name and a valid URL path
return str.replace(/[^a-zA-Z0-9]/g, "_").toLowerCase();
};
function getSlugFromAppName(appName: string | null): string | null {
if (!appName) {
return appName;
}
return slugify(appName);
}
function getAppDirPath(slug: any) {
return path.join(appStoreDir, `${slug}`);
}
const appStoreDir = path.resolve(__dirname, "..", "..", "app-store");
const workspaceDir = path.resolve(__dirname, "..", "..", "..");
const execSync = (...args) => {
const result = child_process.execSync(...args).toString();
if (process.env.DEBUG === "1") {
console.log(`$: ${args[0]}`);
console.log(result);
}
return args[0];
};
function absolutePath(appRelativePath) {
return path.join(appStoreDir, appRelativePath);
}
const updatePackageJson = ({ slug, appDescription, appDirPath }) => {
const packageJsonConfig = JSON.parse(fs.readFileSync(`${appDirPath}/package.json`).toString());
packageJsonConfig.name = `@calcom/${slug}`;
packageJsonConfig.description = appDescription;
// packageJsonConfig.description = `@calcom/${appName}`;
fs.writeFileSync(`${appDirPath}/package.json`, JSON.stringify(packageJsonConfig, null, 2));
};
const BaseAppFork = {
create: function* ({
category,
editMode = false,
appDescription,
appName,
slug,
appTitle,
publisherName,
publisherEmail,
}) {
const appDirPath = getAppDirPath(slug);
let message = !editMode ? "Forking base app" : "Updating app";
yield message;
if (!editMode) {
execSync(`mkdir -p ${appDirPath}`);
execSync(`cp -r ${absolutePath("_baseApp/*")} ${appDirPath}`);
}
updatePackageJson({ slug, appDirPath, appDescription });
let config = {
"/*": "Don't modify slug - If required, do it using cli edit command",
name: appName,
title: appTitle,
// Plan to remove it. DB already has it and name of dir is also the same.
slug: slug,
type: `${slug}_${category}`,
imageSrc: `/api/app-store/${slug}/icon.svg`,
logo: `/api/app-store/${slug}/icon.svg`,
url: `https://cal.com/apps/${slug}`,
variant: category,
categories: [category],
publisher: publisherName,
email: publisherEmail,
description: appDescription,
// TODO: Use this to avoid edit and delete on the apps created outside of cli
__createdUsingCli: true,
};
const currentConfig = JSON.parse(fs.readFileSync(`${appDirPath}/config.json`).toString());
config = {
...currentConfig,
...config,
};
fs.writeFileSync(`${appDirPath}/config.json`, JSON.stringify(config, null, 2));
message = !editMode ? "Forked base app" : "Updated app";
yield message;
},
delete: function ({ slug }) {
const appDirPath = getAppDirPath(slug);
execSync(`rm -rf ${appDirPath}`);
},
};
const Seed = {
seedConfigPath: absolutePath("../prisma/seed-app-store.config.json"),
update: function ({ slug, category, noDbUpdate }) {
const seedConfig = JSON.parse(fs.readFileSync(this.seedConfigPath).toString());
if (!seedConfig.find((app) => app.slug === slug)) {
seedConfig.push({
"/*": "This file is auto-generated and managed by `yarn app-store`. Don't edit manually but it is to be committed",
dirName: slug,
categories: [category],
slug: slug,
type: `${slug}_${category}`,
});
}
fs.writeFileSync(this.seedConfigPath, JSON.stringify(seedConfig, null, 2));
if (!noDbUpdate) {
execSync(`cd ${workspaceDir} && yarn db-seed`);
}
},
revert: async function ({ slug, noDbUpdate }) {
let seedConfig = JSON.parse(fs.readFileSync(this.seedConfigPath).toString());
seedConfig = seedConfig.filter((app) => app.slug !== slug);
fs.writeFileSync(this.seedConfigPath, JSON.stringify(seedConfig, null, 2));
if (!noDbUpdate) {
execSync(`yarn workspace @calcom/prisma delete-app ${slug}`);
}
},
};
const generateAppFiles = () => {
execSync(`cd ${__dirname} && yarn ts-node --transpile-only src/app-store.ts`);
};
const CreateApp = ({ noDbUpdate, slug = null, editMode = false }) => {
// AppName
// Type of App - Other, Calendar, Video, Payment, Messaging, Web3
const [appInputData, setAppInputData] = useState({});
const [inputIndex, setInputIndex] = useState(0);
const fields = [
{ label: "App Name", name: "appName", type: "text" },
{ label: "App Title", name: "appTitle", type: "text" },
{ label: "App Description", name: "appDescription", type: "text" },
{
label: "Category of App",
name: "appCategory",
type: "select",
options: [
{ label: "calendar", value: "calendar" },
{ label: "video", value: "video" },
{ label: "payment", value: "payment" },
{ label: "messaging", value: "messaging" },
{ label: "web3", value: "web3" },
{ label: "other", value: "other" },
],
},
{ label: "Publisher Name", name: "publisherName", type: "text" },
{ label: "Publisher Email", name: "publisherEmail", type: "text" },
];
const field = fields[inputIndex];
const fieldLabel = field?.label || "";
const fieldName = field?.name || "";
const fieldValue = appInputData[fieldName] || "";
const appName = appInputData["appName"];
const category = appInputData["appCategory"];
const appTitle = appInputData["appTitle"];
const appDescription = appInputData["appDescription"];
const publisherName = appInputData["publisherName"];
const publisherEmail = appInputData["publisherEmail"];
const [result, setResult] = useState("...");
const allFieldsFilled = inputIndex === fields.length;
useEffect(() => {
// When all fields have been filled
if (allFieldsFilled) {
const it = BaseAppFork.create({
category,
appDescription,
appName,
slug,
appTitle,
publisherName,
publisherEmail,
});
for (const item of it) {
setResult(item);
}
Seed.update({ slug, category, noDbUpdate });
generateAppFiles();
// FIXME: Even after CLI showing this message, it is stuck doing work before exiting
// So we ask the user to wait for some time
setResult(
`App has been given slug: ${slug}. Just wait for a few seconds for the process to complete and start editing ${getAppDirPath(
slug
)} to work on your app.`
);
}
});
if (!slug && editMode) {
return <Text>--slug is required</Text>;
}
if (!editMode) {
slug = getSlugFromAppName(appName);
}
if (allFieldsFilled) {
return (
<>
<Text>
{editMode
? `Editing app with slug ${slug}`
: `Creating app with name '${appName}' of type '${category}'`}
</Text>
<Text>{result}</Text>
<Text>
Please note that you should use cli only to rename an app directory as it needs to be updated in DB
as well
</Text>
</>
);
}
// Hack: using field.name == "appTitle" to identify that app Name has been submitted and not being edited.
if (!editMode && field.name === "appTitle" && slug && fs.existsSync(getAppDirPath(slug))) {
return (
<>
<Text>App with slug {slug} already exists. If you want to edit it, use edit command</Text>
</>
);
}
return (
<Box>
<Text color="green">{`${fieldLabel}:`}</Text>
{field.type == "text" ? (
<TextInput
value={fieldValue}
onSubmit={(value) => {
if (!value) {
return;
}
setInputIndex((index) => {
return index + 1;
});
}}
onChange={(value) => {
setAppInputData((appInputData) => {
return {
...appInputData,
[fieldName]: value,
};
});
}}
/>
) : (
<SelectInput<string>
items={field.options}
onSelect={(item) => {
setAppInputData((appInputData) => {
return {
...appInputData,
[fieldName]: item.value,
};
});
setInputIndex((index) => {
return index + 1;
});
}}></SelectInput>
)}
</Box>
);
};
const DeleteApp = ({ noDbUpdate, slug }) => {
const [confirmedAppSlug, setConfirmedAppSlug] = useState("");
const [allowDeletion, setAllowDeletion] = useState(false);
const [state, setState] = useState({});
useEffect(() => {
if (allowDeletion) {
BaseAppFork.delete({ slug });
Seed.revert({ slug });
generateAppFiles();
setState({ description: `App with slug ${slug} has been deleted`, done: true });
}
}, [allowDeletion, slug]);
return (
<>
<Text>
Confirm the slug of the app that you want to delete. Note, that it would cleanup the app directory,
App table and Credential table
</Text>
{!state.done && (
<TextInput
value={confirmedAppSlug}
onSubmit={(value) => {
if (value === slug) {
setState({ description: `Deletion started`, done: true });
setAllowDeletion(true);
} else {
setState({ description: `Slug doesn't match - Should have been ${slug}`, done: true });
}
}}
onChange={(val) => {
setConfirmedAppSlug(val);
}}></TextInput>
)}
<Text>{state.description}</Text>
</>
);
};
const App: FC<{ noDbUpdate?: boolean; command: "create" | "delete"; slug?: string }> = ({
command,
noDbUpdate,
slug,
}) => {
if (command === "create") {
return <CreateApp noDbUpdate={noDbUpdate} />;
}
if (command === "delete") {
return <DeleteApp slug={slug} noDbUpdate={noDbUpdate} />;
}
if (command === "edit") {
return <CreateApp slug={slug} editMode={true} noDbUpdate={noDbUpdate} />;
}
};
module.exports = App;
export default App;
+127
View File
@@ -0,0 +1,127 @@
const fs = require("fs");
const path = require("path");
let isInWatchMode = false;
if (process.argv[2] === "--watch") {
isInWatchMode = true;
}
const chokidar = require("chokidar");
const { debounce } = require("lodash");
const APP_STORE_PATH = path.join(__dirname, "..", "..", "app-store");
function getAppName(candidatePath) {
function isValidAppName(candidatePath) {
if (!candidatePath.startsWith("_") && !candidatePath.includes("/") && !candidatePath.includes("\\")) {
return candidatePath;
}
}
if (isValidAppName(candidatePath)) {
// Already a dirname of an app
return candidatePath;
}
// Get dirname of app from full path
const dirName = path.relative(APP_STORE_PATH, candidatePath);
return isValidAppName(dirName) ? dirName : null;
}
function generateFiles() {
const browserOutput = [`import dynamic from "next/dynamic"`];
const serverOutput = [];
const appDirs = [];
fs.readdirSync(`${APP_STORE_PATH}`).forEach(function (dir) {
if (fs.statSync(`${APP_STORE_PATH}/${dir}`).isDirectory()) {
if (!getAppName(dir)) {
return;
}
appDirs.push(dir);
}
});
function forEachAppDir(callback) {
for (let i = 0; i < appDirs.length; i++) {
callback(appDirs[i]);
}
}
function getObjectExporter(objectName, { fileToBeImported, importBuilder, entryBuilder }) {
const output = [];
forEachAppDir((appName) => {
if (fs.existsSync(path.join(APP_STORE_PATH, appName, fileToBeImported))) {
output.push(importBuilder(appName));
}
});
output.push(`export const ${objectName} = {`);
forEachAppDir((dirName) => {
if (fs.existsSync(path.join(APP_STORE_PATH, dirName, fileToBeImported))) {
output.push(entryBuilder(dirName));
}
});
output.push(`};`);
return output;
}
serverOutput.push(
...getObjectExporter("apiHandlers", {
fileToBeImported: "api/index.ts",
importBuilder: (appName) => `const ${appName}_api = import("./${appName}/api");`,
entryBuilder: (appName) => `${appName}:${appName}_api,`,
})
);
browserOutput.push(
...getObjectExporter("appStoreMetadata", {
fileToBeImported: "_metadata.ts",
importBuilder: (appName) => `import { metadata as ${appName}_meta } from "./${appName}/_metadata";`,
entryBuilder: (appName) => `${appName}:${appName}_meta,`,
})
);
browserOutput.push(
...getObjectExporter("InstallAppButtonMap", {
fileToBeImported: "components/InstallAppButton.tsx",
importBuilder: (appName) =>
`const ${appName}_installAppButton = dynamic(() =>import("./${appName}/components/InstallAppButton"));`,
entryBuilder: (appName) => `${appName}:${appName}_installAppButton,`,
})
);
const banner = `/**
This file is autogenerated using the command \`yarn app-store --watch\`. It automatically runs when using \`yarn dx\`
Don't modify this file manually.
**/
`;
fs.writeFileSync(`${APP_STORE_PATH}/apps.server.generated.ts`, `${banner}${serverOutput.join("\n")}`);
fs.writeFileSync(`${APP_STORE_PATH}/apps.browser.generated.tsx`, `${banner}${browserOutput.join("\n")}`);
console.log("Generated `apps.server.generated.ts` and `apps.browser.generated.tsx`");
}
const debouncedGenerateFiles = debounce(generateFiles);
if (isInWatchMode) {
chokidar
.watch(APP_STORE_PATH)
.on("addDir", (dirPath) => {
const appName = getAppName(dirPath);
if (appName) {
console.log(`Added ${appName}`);
debouncedGenerateFiles();
}
})
.on("change", (filePath) => {
if (filePath.endsWith("config.json")) {
console.log("Config file changed");
debouncedGenerateFiles();
}
})
.on("unlinkDir", (dirPath) => {
const appName = getAppName(dirPath);
if (appName) {
console.log(`Removed ${appName}`);
debouncedGenerateFiles();
}
});
} else {
generateFiles();
}
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env node
import { render } from "ink";
import meow from "meow";
import React from "react";
import App from "./CliApp";
const cli = meow(
`
Usage
$ app-store create/delete/edit - Edit and Delete commands must be used on apps created using cli
Options
[--slug] Slug. This is the name of app dir for apps created with cli.
`,
{
flags: {
noDbUpdate: {
type: "boolean",
},
slug: {
type: "string",
},
},
allowUnknownFlags: false,
}
);
if (cli.input.length !== 1) {
cli.showHelp();
}
const command = cli.input[0] as "create" | "delete" | "edit";
const supportedCommands = ["create", "delete", "edit"];
if (!supportedCommands.includes(command)) {
cli.showHelp();
}
let slug = null;
if (command === "delete" || command === "edit") {
slug = cli.flags.slug;
if (!slug) {
console.log("--slug is required");
cli.showHelp();
}
}
render(<App slug={slug} command={command} noDbUpdate={cli.flags.noDbUpdate} />);
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"jsx": "react",
"esModuleInterop": true,
"outDir": "dist",
"noEmitOnError": false,
"target": "ES2020",
"baseUrl": "."
},
"include": [
"next-env.d.ts",
"../../packages/types/*.d.ts",
"../../packages/types/next-auth.d.ts",
"./src/**/*.ts",
"./src/**/*.tsx",
"../lib/**/*.ts"
]
}