App Store Templates (#5289)
* Start by moving what we have to _templates * WIP * WIP * Add create/edit/delete template commands * Type fixes cli Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: zomars <[email protected]>
This commit is contained in:
185 files changed
+2272
-1317
No files matched your search
@@ -0,0 +1,49 @@
|
||||
import React, { FC } from "react";
|
||||
import { SupportedCommands } from "src/types";
|
||||
|
||||
import Create from "./commandViews/Create";
|
||||
import CreateTemplate from "./commandViews/Create";
|
||||
import Delete from "./commandViews/Delete";
|
||||
import DeleteTemplate from "./commandViews/DeleteTemplate";
|
||||
import Edit from "./commandViews/Edit";
|
||||
import EditTemplate from "./commandViews/EditTemplate";
|
||||
|
||||
export const App: FC<{
|
||||
template: string;
|
||||
command: SupportedCommands;
|
||||
slug?: string;
|
||||
}> = ({ command, template, slug }) => {
|
||||
if (command === "create") {
|
||||
return <Create template={template} />;
|
||||
}
|
||||
|
||||
if (command === "edit") {
|
||||
return <Edit slug={slug} />;
|
||||
}
|
||||
|
||||
if (command === "edit-template") {
|
||||
return <EditTemplate slug={slug} />;
|
||||
}
|
||||
|
||||
if (command === "delete") {
|
||||
if (!slug) {
|
||||
throw new Error('Slug is required for "delete" command');
|
||||
}
|
||||
return <Delete slug={slug} />;
|
||||
}
|
||||
|
||||
if (command === "create-template") {
|
||||
return <CreateTemplate template={template} />;
|
||||
}
|
||||
|
||||
if (command === "delete-template") {
|
||||
if (!slug) {
|
||||
throw new Error('Slug is required for "delete-template" command');
|
||||
}
|
||||
return <DeleteTemplate slug={slug} />;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export default App;
|
||||
@@ -1,463 +0,0 @@
|
||||
import fs from "fs";
|
||||
import { Box, Text } from "ink";
|
||||
import SelectInput from "ink-select-input";
|
||||
import TextInput from "ink-text-input";
|
||||
import path from "path";
|
||||
import React, { FC, useEffect, useState } from "react";
|
||||
|
||||
import execSync from "./execSync";
|
||||
|
||||
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, "..", "..", "..");
|
||||
|
||||
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,
|
||||
subCategory,
|
||||
editMode = false,
|
||||
appDescription,
|
||||
appName,
|
||||
slug,
|
||||
publisherName,
|
||||
publisherEmail,
|
||||
extendsFeature,
|
||||
}) {
|
||||
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 });
|
||||
|
||||
const categoryToVariantMap = {
|
||||
video: "conferencing",
|
||||
};
|
||||
|
||||
const dataFromCategory =
|
||||
category === "video"
|
||||
? {
|
||||
appData: {
|
||||
location: {
|
||||
type: `integrations:${slug}_video`,
|
||||
label: `${appName}`,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {};
|
||||
const dataFromSubCategory =
|
||||
category === "video" && subCategory === "static"
|
||||
? {
|
||||
appData: {
|
||||
...dataFromCategory.appData,
|
||||
location: {
|
||||
...dataFromCategory.appData.location,
|
||||
linkType: "static",
|
||||
organizerInputPlaceholder: "https://anything.anything",
|
||||
urlRegExp: "",
|
||||
},
|
||||
},
|
||||
}
|
||||
: {};
|
||||
let config = {
|
||||
"/*": "Don't modify slug - If required, do it using cli edit command",
|
||||
name: appName,
|
||||
// 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: categoryToVariantMap[category] || category,
|
||||
categories: [category],
|
||||
publisher: publisherName,
|
||||
email: publisherEmail,
|
||||
description: appDescription,
|
||||
extendsFeature: extendsFeature,
|
||||
// TODO: Use this to avoid edit and delete on the apps created outside of cli
|
||||
__createdUsingCli: true,
|
||||
...dataFromCategory,
|
||||
...dataFromSubCategory,
|
||||
};
|
||||
const currentConfig = JSON.parse(fs.readFileSync(`${appDirPath}/config.json`).toString());
|
||||
config = {
|
||||
...currentConfig,
|
||||
...config,
|
||||
};
|
||||
fs.writeFileSync(`${appDirPath}/config.json`, JSON.stringify(config, null, 2));
|
||||
fs.writeFileSync(
|
||||
`${appDirPath}/DESCRIPTION.md`,
|
||||
fs
|
||||
.readFileSync(`${appDirPath}/DESCRIPTION.md`)
|
||||
.toString()
|
||||
.replace(/_DESCRIPTION_/g, appDescription)
|
||||
.replace(/_APP_DIR_/g, slug)
|
||||
);
|
||||
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 }) {
|
||||
let configContent = "[]";
|
||||
try {
|
||||
if (fs.statSync(this.seedConfigPath)) {
|
||||
configContent = fs.readFileSync(this.seedConfigPath).toString();
|
||||
}
|
||||
} catch (e) {}
|
||||
const seedConfig = JSON.parse(configContent);
|
||||
|
||||
if (!seedConfig.find((app) => app.slug === slug)) {
|
||||
seedConfig.push({
|
||||
dirName: slug,
|
||||
categories: [category],
|
||||
slug: slug,
|
||||
type: `${slug}_${category}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Add the message as a property to first item so that it stays always at the top
|
||||
seedConfig[0]["/*"] =
|
||||
"This file is auto-generated and updated by `yarn app-store create/edit`. Don't edit it manually";
|
||||
|
||||
// Add the message as a property to first item so that it stays always at the top
|
||||
seedConfig[0]["/*"] =
|
||||
"This file is auto-generated and updated by `yarn app-store create/edit`. Don't edit it manually";
|
||||
|
||||
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 Title", name: "appName", type: "text", explainer: "Keep it very short" },
|
||||
{
|
||||
label: "App Description",
|
||||
name: "appDescription",
|
||||
type: "text",
|
||||
explainer:
|
||||
"A detailed description of your app. You can later modify DESCRIPTION.md to add slider and other components",
|
||||
},
|
||||
{
|
||||
label: "Category of App",
|
||||
name: "appCategory",
|
||||
type: "select",
|
||||
options: [
|
||||
{ label: "Calendar", value: "calendar" },
|
||||
{
|
||||
label:
|
||||
"Static Link - Video(Apps like Ping.gg/Riverside/Whereby which require you to provide a link to join your room)",
|
||||
value: "video_static",
|
||||
},
|
||||
{ label: "Other - Video", value: "video_other" },
|
||||
{ label: "Payment", value: "payment" },
|
||||
{ label: "Messaging", value: "messaging" },
|
||||
{ label: "Web3", value: "web3" },
|
||||
{ label: "Automation", value: "automation" },
|
||||
{ label: "Analytics", value: "analytics" },
|
||||
{ label: "Other", value: "other" },
|
||||
],
|
||||
explainer: "This is how apps are categorized in App Store.",
|
||||
},
|
||||
{
|
||||
label: "What kind of app would you consider it?",
|
||||
name: "extendsFeature",
|
||||
options: [
|
||||
{ label: "User", value: "User" },
|
||||
{
|
||||
label: "Event Type(Available for configuration in Apps tab for all Event Types)",
|
||||
value: "EventType",
|
||||
},
|
||||
],
|
||||
},
|
||||
{ label: "Publisher Name", name: "publisherName", type: "text", explainer: "Let users know who you are" },
|
||||
{
|
||||
label: "Publisher Email",
|
||||
name: "publisherEmail",
|
||||
type: "text",
|
||||
explainer: "Let users know how they can contact you.",
|
||||
},
|
||||
];
|
||||
const field = fields[inputIndex];
|
||||
const fieldLabel = field?.label || "";
|
||||
const fieldName = field?.name || "";
|
||||
const fieldValue = appInputData[fieldName] || "";
|
||||
const appName = appInputData["appName"];
|
||||
const rawCategory = appInputData["appCategory"] || "";
|
||||
const appDescription = appInputData["appDescription"];
|
||||
const publisherName = appInputData["publisherName"];
|
||||
const publisherEmail = appInputData["publisherEmail"];
|
||||
let extendsFeature = appInputData["extendsFeature"] || [];
|
||||
if (rawCategory === "analytics") {
|
||||
// Analytics only means EventType Analytics as of now
|
||||
extendsFeature = "EventType";
|
||||
}
|
||||
const [status, setStatus] = useState<"inProgress" | "done">("inProgress");
|
||||
const allFieldsFilled = inputIndex === fields.length;
|
||||
const [progressUpdate, setProgressUpdate] = useState("");
|
||||
const category = rawCategory.split("_")[0];
|
||||
const subCategory = rawCategory.split("_")[1];
|
||||
if (!editMode) {
|
||||
slug = getSlugFromAppName(appName);
|
||||
}
|
||||
useEffect(() => {
|
||||
// When all fields have been filled
|
||||
if (allFieldsFilled) {
|
||||
const it = BaseAppFork.create({
|
||||
category,
|
||||
subCategory,
|
||||
appDescription,
|
||||
appName,
|
||||
slug,
|
||||
publisherName,
|
||||
publisherEmail,
|
||||
extendsFeature,
|
||||
});
|
||||
for (const item of it) {
|
||||
setProgressUpdate(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
|
||||
setStatus("done");
|
||||
}
|
||||
});
|
||||
|
||||
if (!slug && editMode) {
|
||||
return <Text>--slug is required</Text>;
|
||||
}
|
||||
|
||||
if (allFieldsFilled) {
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text>
|
||||
{editMode
|
||||
? `Editing app with slug ${slug}`
|
||||
: `Creating app with name '${appName}' of type '${category}'`}
|
||||
</Text>
|
||||
<Text>{progressUpdate}</Text>
|
||||
{status === "done" ? (
|
||||
<Box flexDirection="column" paddingTop={2} paddingBottom={2}>
|
||||
<Text bold italic>
|
||||
Just wait for a few seconds for process to exit and then you are good to go. Your App code
|
||||
exists at ${getAppDirPath(slug)}
|
||||
Tip : Go and change the logo of your app by replacing {getAppDirPath(slug) + "/static/icon.svg"}
|
||||
</Text>
|
||||
<Text bold italic>
|
||||
App Summary:
|
||||
</Text>
|
||||
<Box flexDirection="column">
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Slug: </Text>
|
||||
<Text>{slug}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">App URL: </Text>
|
||||
<Text>{`http://localhost:3000/apps/${slug}`}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Name: </Text>
|
||||
<Text>{appName}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Description: </Text>
|
||||
<Text>{appDescription}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Category: </Text>
|
||||
<Text>{category}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Publisher Name: </Text>
|
||||
<Text>{publisherName}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Publisher Email: </Text>
|
||||
<Text>{publisherEmail}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
) : (
|
||||
<Text>Please wait...</Text>
|
||||
)}
|
||||
<Text italic color="gray">
|
||||
Note: You should not rename app directory manually. Use cli only to do that as it needs to be
|
||||
updated in DB as well
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// 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 flexDirection="column">
|
||||
<Box flexDirection="column">
|
||||
<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;
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Box>
|
||||
<Text color="gray" italic>
|
||||
{field.explainer}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const DeleteApp = ({ noDbUpdate, slug }) => {
|
||||
const [confirmedAppSlug, setConfirmedAppSlug] = useState("");
|
||||
const [allowDeletion, setAllowDeletion] = useState(false);
|
||||
const [state, setState] = useState({ done: null, description: null });
|
||||
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);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<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;
|
||||
@@ -1,278 +0,0 @@
|
||||
import chokidar from "chokidar";
|
||||
import fs from "fs";
|
||||
import { debounce } from "lodash";
|
||||
import path from "path";
|
||||
import prettier from "prettier";
|
||||
|
||||
import { AppMeta } from "@calcom/types/App";
|
||||
|
||||
import prettierConfig from "../../config/prettier-preset";
|
||||
import execSync from "./execSync";
|
||||
|
||||
function isFileThere(path) {
|
||||
try {
|
||||
fs.statSync(path);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let isInWatchMode = false;
|
||||
if (process.argv[2] === "--watch") {
|
||||
isInWatchMode = true;
|
||||
}
|
||||
|
||||
const formatOutput = (source: string) => prettier.format(source, prettierConfig);
|
||||
|
||||
const getVariableName = function (appName: string) {
|
||||
return appName.replace("-", "_");
|
||||
};
|
||||
|
||||
const getAppId = function (app: { name: string }) {
|
||||
// Handle stripe separately as it's an old app with different dirName than slug/appId
|
||||
return app.name === "stripepayment" ? "stripe" : app.name;
|
||||
};
|
||||
|
||||
const APP_STORE_PATH = path.join(__dirname, "..", "..", "app-store");
|
||||
type App = Partial<AppMeta> & {
|
||||
name: string;
|
||||
path: string;
|
||||
};
|
||||
function getAppName(candidatePath) {
|
||||
function isValidAppName(candidatePath) {
|
||||
if (
|
||||
!candidatePath.startsWith("_") &&
|
||||
candidatePath !== "ee" &&
|
||||
!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 metadataOutput = [];
|
||||
const schemasOutput = [];
|
||||
const appKeysSchemasOutput = [];
|
||||
const serverOutput = [];
|
||||
const appDirs: { name: string; path: string }[] = [];
|
||||
|
||||
fs.readdirSync(`${APP_STORE_PATH}`).forEach(function (dir) {
|
||||
if (dir === "ee") {
|
||||
fs.readdirSync(path.join(APP_STORE_PATH, dir)).forEach(function (eeDir) {
|
||||
if (fs.statSync(path.join(APP_STORE_PATH, dir, eeDir)).isDirectory()) {
|
||||
if (!getAppName(path.resolve(eeDir))) {
|
||||
appDirs.push({
|
||||
name: eeDir,
|
||||
path: path.join(dir, eeDir),
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
if (fs.statSync(path.join(APP_STORE_PATH, dir)).isDirectory()) {
|
||||
if (!getAppName(dir)) {
|
||||
return;
|
||||
}
|
||||
appDirs.push({
|
||||
name: dir,
|
||||
path: dir,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function forEachAppDir(callback: (arg: App) => void) {
|
||||
for (let i = 0; i < appDirs.length; i++) {
|
||||
const configPath = path.join(APP_STORE_PATH, appDirs[i].path, "config.json");
|
||||
let app;
|
||||
|
||||
if (fs.existsSync(configPath)) {
|
||||
app = JSON.parse(fs.readFileSync(configPath).toString());
|
||||
} else {
|
||||
app = {};
|
||||
}
|
||||
|
||||
callback({
|
||||
...app,
|
||||
name: appDirs[i].name,
|
||||
path: appDirs[i].path,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
forEachAppDir((app) => {
|
||||
const templateDestinationDir = path.join(APP_STORE_PATH, app.path, "extensions");
|
||||
const templateDestinationFilePath = path.join(templateDestinationDir, "EventTypeAppCard.tsx");
|
||||
const zodDestinationFilePath = path.join(APP_STORE_PATH, app.path, "zod.ts");
|
||||
|
||||
if (app.extendsFeature === "EventType" && !isFileThere(templateDestinationFilePath)) {
|
||||
execSync(`mkdir -p ${templateDestinationDir}`);
|
||||
execSync(`cp ../app-store/_templates/extensions/EventTypeAppCard.tsx ${templateDestinationFilePath}`);
|
||||
execSync(`cp ../app-store/_templates/zod.ts ${zodDestinationFilePath}`);
|
||||
}
|
||||
});
|
||||
|
||||
function getObjectExporter(
|
||||
objectName,
|
||||
{
|
||||
fileToBeImported,
|
||||
importBuilder,
|
||||
entryBuilder,
|
||||
}: {
|
||||
fileToBeImported: string;
|
||||
importBuilder?: (arg: App) => string;
|
||||
entryBuilder: (arg: App) => string;
|
||||
}
|
||||
) {
|
||||
const output = [];
|
||||
forEachAppDir((app) => {
|
||||
if (
|
||||
fs.existsSync(path.join(APP_STORE_PATH, app.path, fileToBeImported)) &&
|
||||
typeof importBuilder === "function"
|
||||
) {
|
||||
output.push(importBuilder(app));
|
||||
}
|
||||
});
|
||||
|
||||
output.push(`export const ${objectName} = {`);
|
||||
|
||||
forEachAppDir((app) => {
|
||||
if (fs.existsSync(path.join(APP_STORE_PATH, app.path, fileToBeImported))) {
|
||||
output.push(entryBuilder(app));
|
||||
}
|
||||
});
|
||||
|
||||
output.push(`};`);
|
||||
return output;
|
||||
}
|
||||
|
||||
serverOutput.push(
|
||||
...getObjectExporter("apiHandlers", {
|
||||
fileToBeImported: "api/index.ts",
|
||||
// Import path must have / even for windows and not \
|
||||
entryBuilder: (app) => ` "${app.name}": import("./${app.path.replace(/\\/g, "/")}/api"),`,
|
||||
})
|
||||
);
|
||||
|
||||
metadataOutput.push(
|
||||
...getObjectExporter("appStoreMetadata", {
|
||||
fileToBeImported: "_metadata.ts",
|
||||
// Import path must have / even for windows and not \
|
||||
importBuilder: (app) =>
|
||||
`import { metadata as ${getVariableName(app.name)}_meta } from "./${app.path.replace(
|
||||
/\\/g,
|
||||
"/"
|
||||
)}/_metadata";`,
|
||||
entryBuilder: (app) => ` "${app.name}":${getVariableName(app.name)}_meta,`,
|
||||
})
|
||||
);
|
||||
|
||||
schemasOutput.push(
|
||||
...getObjectExporter("appDataSchemas", {
|
||||
fileToBeImported: "zod.ts",
|
||||
// Import path must have / even for windows and not \
|
||||
importBuilder: (app) =>
|
||||
`import { appDataSchema as ${getVariableName(app.name)}_schema } from "./${app.path.replace(
|
||||
/\\/g,
|
||||
"/"
|
||||
)}/zod";`,
|
||||
// Key must be appId as this is used by eventType metadata and lookup is by appId
|
||||
entryBuilder: (app) => ` "${getAppId(app)}":${getVariableName(app.name)}_schema ,`,
|
||||
})
|
||||
);
|
||||
|
||||
appKeysSchemasOutput.push(
|
||||
...getObjectExporter("appKeysSchemas", {
|
||||
fileToBeImported: "zod.ts",
|
||||
// Import path must have / even for windows and not \
|
||||
importBuilder: (app) =>
|
||||
`import { appKeysSchema as ${getVariableName(app.name)}_keys_schema } from "./${app.path.replace(
|
||||
/\\/g,
|
||||
"/"
|
||||
)}/zod";`,
|
||||
// Key must be appId as this is used by eventType metadata and lookup is by appId
|
||||
entryBuilder: (app) => ` "${getAppId(app)}":${getVariableName(app.name)}_keys_schema ,`,
|
||||
})
|
||||
);
|
||||
|
||||
browserOutput.push(
|
||||
...getObjectExporter("InstallAppButtonMap", {
|
||||
fileToBeImported: "components/InstallAppButton.tsx",
|
||||
entryBuilder: (app) =>
|
||||
` ${app.name}: dynamic(() =>import("./${app.path}/components/InstallAppButton")),`,
|
||||
})
|
||||
);
|
||||
|
||||
// TODO: Make a component map creator that accepts ComponentName and does the rest.
|
||||
// TODO: dailyvideo has a slug of daily-video, so that mapping needs to be taken care of. But it is an old app, so it doesn't need AppSettings
|
||||
browserOutput.push(
|
||||
...getObjectExporter("AppSettingsComponentsMap", {
|
||||
fileToBeImported: "components/AppSettings.tsx",
|
||||
entryBuilder: (app) => ` ${app.name}: dynamic(() =>import("./${app.path}/components/AppSettings")),`,
|
||||
})
|
||||
);
|
||||
|
||||
browserOutput.push(
|
||||
...getObjectExporter("EventTypeAddonMap", {
|
||||
fileToBeImported: path.join("extensions", "EventTypeAppCard.tsx"),
|
||||
entryBuilder: (app) =>
|
||||
` ${app.name}: dynamic(() =>import("./${app.path}/extensions/EventTypeAppCard")),`,
|
||||
})
|
||||
);
|
||||
|
||||
const banner = `/**
|
||||
This file is autogenerated using the command \`yarn app-store:build --watch\`.
|
||||
Don't modify this file manually.
|
||||
**/
|
||||
`;
|
||||
const filesToGenerate: [string, string[]][] = [
|
||||
["apps.metadata.generated.ts", metadataOutput],
|
||||
["apps.server.generated.ts", serverOutput],
|
||||
["apps.browser.generated.tsx", browserOutput],
|
||||
["apps.schemas.generated.ts", schemasOutput],
|
||||
["apps.keys-schemas.generated.ts", appKeysSchemasOutput],
|
||||
];
|
||||
filesToGenerate.forEach(([fileName, output]) => {
|
||||
fs.writeFileSync(`${APP_STORE_PATH}/${fileName}`, formatOutput(`${banner}${output.join("\n")}`));
|
||||
});
|
||||
console.log(`Generated ${filesToGenerate.map(([fileName]) => fileName).join(", ")}`);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
import chokidar from "chokidar";
|
||||
import fs from "fs";
|
||||
import { debounce } from "lodash";
|
||||
import path from "path";
|
||||
import prettier from "prettier";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
//@ts-ignore
|
||||
import prettierConfig from "@calcom/config/prettier-preset";
|
||||
import { AppMeta } from "@calcom/types/App";
|
||||
|
||||
import { APP_STORE_PATH } from "./constants";
|
||||
import { getAppName } from "./utils/getAppName";
|
||||
|
||||
let isInWatchMode = false;
|
||||
if (process.argv[2] === "--watch") {
|
||||
isInWatchMode = true;
|
||||
}
|
||||
|
||||
const formatOutput = (source: string) =>
|
||||
prettier.format(source, {
|
||||
parser: "babel",
|
||||
...prettierConfig,
|
||||
});
|
||||
|
||||
const getVariableName = function (appName: string) {
|
||||
return appName.replace(/[-.]/g, "_");
|
||||
};
|
||||
|
||||
const getAppId = function (app: { name: string }) {
|
||||
// Handle stripe separately as it's an old app with different dirName than slug/appId
|
||||
return app.name === "stripepayment" ? "stripe" : app.name;
|
||||
};
|
||||
|
||||
type App = Partial<AppMeta> & {
|
||||
name: string;
|
||||
path: string;
|
||||
};
|
||||
function generateFiles() {
|
||||
const browserOutput = [`import dynamic from "next/dynamic"`];
|
||||
const metadataOutput = [];
|
||||
const schemasOutput = [];
|
||||
const appKeysSchemasOutput = [];
|
||||
const serverOutput = [];
|
||||
const appDirs: { name: string; path: string }[] = [];
|
||||
|
||||
fs.readdirSync(`${APP_STORE_PATH}`).forEach(function (dir) {
|
||||
if (dir === "ee" || dir === "templates") {
|
||||
fs.readdirSync(path.join(APP_STORE_PATH, dir)).forEach(function (subDir) {
|
||||
if (fs.statSync(path.join(APP_STORE_PATH, dir, subDir)).isDirectory()) {
|
||||
if (getAppName(subDir)) {
|
||||
appDirs.push({
|
||||
name: subDir,
|
||||
path: path.join(dir, subDir),
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
if (fs.statSync(path.join(APP_STORE_PATH, dir)).isDirectory()) {
|
||||
if (!getAppName(dir)) {
|
||||
return;
|
||||
}
|
||||
appDirs.push({
|
||||
name: dir,
|
||||
path: dir,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function forEachAppDir(callback: (arg: App) => void) {
|
||||
for (let i = 0; i < appDirs.length; i++) {
|
||||
const configPath = path.join(APP_STORE_PATH, appDirs[i].path, "config.json");
|
||||
let app;
|
||||
|
||||
if (fs.existsSync(configPath)) {
|
||||
app = JSON.parse(fs.readFileSync(configPath).toString());
|
||||
} else {
|
||||
app = {};
|
||||
}
|
||||
|
||||
callback({
|
||||
...app,
|
||||
name: appDirs[i].name,
|
||||
path: appDirs[i].path,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows has paths with backslashes, so we need to replace them with forward slashes
|
||||
* .ts and .tsx files are imported without extensions
|
||||
* If a file has index.ts or index.tsx, it can be imported after removing the index.ts* part
|
||||
*/
|
||||
function getModulePath(path: string, moduleName: string) {
|
||||
return (
|
||||
`./${path.replace(/\\/g, "/")}/` +
|
||||
moduleName.replace(/\/index\.ts|\/index\.tsx/, "").replace(/\.tsx$|\.ts$/, "")
|
||||
);
|
||||
}
|
||||
|
||||
type ImportConfig =
|
||||
| {
|
||||
fileToBeImported: string;
|
||||
importName?: string;
|
||||
}
|
||||
| [
|
||||
{
|
||||
fileToBeImported: string;
|
||||
importName?: string;
|
||||
},
|
||||
{
|
||||
fileToBeImported: string;
|
||||
importName: string;
|
||||
}
|
||||
];
|
||||
|
||||
/**
|
||||
* If importConfig is an array, only 2 items are allowed. First one is the main one and second one is the fallback
|
||||
*/
|
||||
function getExportedObject(
|
||||
objectName: string,
|
||||
{
|
||||
lazyImport = false,
|
||||
importConfig,
|
||||
entryObjectKeyGetter = (app) => app.name,
|
||||
}: {
|
||||
lazyImport?: boolean;
|
||||
importConfig: ImportConfig;
|
||||
entryObjectKeyGetter?: (arg: App, importName?: string) => string;
|
||||
}
|
||||
) {
|
||||
const output: string[] = [];
|
||||
|
||||
const getLocalImportName = (
|
||||
app: { name: string },
|
||||
chosenConfig: ReturnType<typeof getChosenImportConfig>
|
||||
) => `${getVariableName(app.name)}_${getVariableName(chosenConfig.fileToBeImported)}`;
|
||||
|
||||
const fileToBeImportedExists = (
|
||||
app: { path: string },
|
||||
chosenConfig: ReturnType<typeof getChosenImportConfig>
|
||||
) => fs.existsSync(path.join(APP_STORE_PATH, app.path, chosenConfig.fileToBeImported));
|
||||
|
||||
addImportStatements();
|
||||
createExportObject();
|
||||
|
||||
return output;
|
||||
|
||||
function addImportStatements() {
|
||||
forEachAppDir((app) => {
|
||||
const chosenConfig = getChosenImportConfig(importConfig, app);
|
||||
if (fileToBeImportedExists(app, chosenConfig) && chosenConfig.importName) {
|
||||
const importName = chosenConfig.importName;
|
||||
if (!lazyImport) {
|
||||
if (importName !== "default") {
|
||||
// Import with local alias that will be used by createExportObject
|
||||
output.push(
|
||||
`import { ${importName} as ${getLocalImportName(app, chosenConfig)} } from "${getModulePath(
|
||||
app.path,
|
||||
chosenConfig.fileToBeImported
|
||||
)}"`
|
||||
);
|
||||
} else {
|
||||
// Default Import
|
||||
output.push(
|
||||
`import ${getLocalImportName(app, chosenConfig)} from "${getModulePath(
|
||||
app.path,
|
||||
chosenConfig.fileToBeImported
|
||||
)}"`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function createExportObject() {
|
||||
output.push(`export const ${objectName} = {`);
|
||||
|
||||
forEachAppDir((app) => {
|
||||
const chosenConfig = getChosenImportConfig(importConfig, app);
|
||||
|
||||
if (fileToBeImportedExists(app, chosenConfig)) {
|
||||
if (!lazyImport) {
|
||||
const key = entryObjectKeyGetter(app);
|
||||
output.push(`"${key}": ${getLocalImportName(app, chosenConfig)},`);
|
||||
} else {
|
||||
const key = entryObjectKeyGetter(app);
|
||||
if (chosenConfig.fileToBeImported.endsWith(".tsx")) {
|
||||
output.push(
|
||||
`"${key}": dynamic(() => import("${getModulePath(
|
||||
app.path,
|
||||
chosenConfig.fileToBeImported
|
||||
)}")),`
|
||||
);
|
||||
} else {
|
||||
output.push(`"${key}": import("${getModulePath(app.path, chosenConfig.fileToBeImported)}"),`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
output.push(`};`);
|
||||
}
|
||||
|
||||
function getChosenImportConfig(importConfig: ImportConfig, app: { path: string }) {
|
||||
let chosenConfig;
|
||||
|
||||
if (!(importConfig instanceof Array)) {
|
||||
chosenConfig = importConfig;
|
||||
} else {
|
||||
if (fs.existsSync(path.join(APP_STORE_PATH, app.path, importConfig[0].fileToBeImported))) {
|
||||
chosenConfig = importConfig[0];
|
||||
} else {
|
||||
chosenConfig = importConfig[1];
|
||||
}
|
||||
}
|
||||
return chosenConfig;
|
||||
}
|
||||
}
|
||||
|
||||
serverOutput.push(
|
||||
...getExportedObject("apiHandlers", {
|
||||
importConfig: {
|
||||
fileToBeImported: "api/index.ts",
|
||||
},
|
||||
lazyImport: true,
|
||||
})
|
||||
);
|
||||
|
||||
metadataOutput.push(
|
||||
...getExportedObject("appStoreMetadata", {
|
||||
// Try looking for config.json and if it's not found use _metadata.ts to generate appStoreMetadata
|
||||
importConfig: [
|
||||
{
|
||||
fileToBeImported: "config.json",
|
||||
importName: "default",
|
||||
},
|
||||
{
|
||||
fileToBeImported: "_metadata.ts",
|
||||
importName: "metadata",
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
schemasOutput.push(
|
||||
...getExportedObject("appDataSchemas", {
|
||||
// Import path must have / even for windows and not \
|
||||
importConfig: {
|
||||
fileToBeImported: "zod.ts",
|
||||
importName: "appDataSchema",
|
||||
},
|
||||
// HACK: Key must be appId as this is used by eventType metadata and lookup is by appId
|
||||
// This can be removed once we rename the ids of apps like stripe to that of their app folder name
|
||||
entryObjectKeyGetter: (app) => getAppId(app),
|
||||
})
|
||||
);
|
||||
|
||||
appKeysSchemasOutput.push(
|
||||
...getExportedObject("appKeysSchemas", {
|
||||
importConfig: {
|
||||
fileToBeImported: "zod.ts",
|
||||
importName: "appKeysSchema",
|
||||
},
|
||||
// HACK: Key must be appId as this is used by eventType metadata and lookup is by appId
|
||||
// This can be removed once we rename the ids of apps like stripe to that of their app folder name
|
||||
entryObjectKeyGetter: (app) => getAppId(app),
|
||||
})
|
||||
);
|
||||
|
||||
browserOutput.push(
|
||||
...getExportedObject("InstallAppButtonMap", {
|
||||
importConfig: {
|
||||
fileToBeImported: "components/InstallAppButton.tsx",
|
||||
},
|
||||
lazyImport: true,
|
||||
})
|
||||
);
|
||||
|
||||
// TODO: Make a component map creator that accepts ComponentName and does the rest.
|
||||
// TODO: dailyvideo has a slug of daily-video, so that mapping needs to be taken care of. But it is an old app, so it doesn't need AppSettings
|
||||
browserOutput.push(
|
||||
...getExportedObject("AppSettingsComponentsMap", {
|
||||
importConfig: {
|
||||
fileToBeImported: "components/AppSettingsInterface.tsx",
|
||||
},
|
||||
lazyImport: true,
|
||||
})
|
||||
);
|
||||
|
||||
browserOutput.push(
|
||||
...getExportedObject("EventTypeAddonMap", {
|
||||
importConfig: {
|
||||
fileToBeImported: path.join("components", "EventTypeAppCardInterface.tsx"),
|
||||
},
|
||||
lazyImport: true,
|
||||
})
|
||||
);
|
||||
|
||||
const banner = `/**
|
||||
This file is autogenerated using the command \`yarn app-store:build --watch\`.
|
||||
Don't modify this file manually.
|
||||
**/
|
||||
`;
|
||||
const filesToGenerate: [string, string[]][] = [
|
||||
["apps.metadata.generated.ts", metadataOutput],
|
||||
["apps.server.generated.ts", serverOutput],
|
||||
["apps.browser.generated.tsx", browserOutput],
|
||||
["apps.schemas.generated.ts", schemasOutput],
|
||||
["apps.keys-schemas.generated.ts", appKeysSchemasOutput],
|
||||
];
|
||||
filesToGenerate.forEach(([fileName, output]) => {
|
||||
fs.writeFileSync(`${APP_STORE_PATH}/${fileName}`, formatOutput(`${banner}${output.join("\n")}`));
|
||||
});
|
||||
console.log(`Generated ${filesToGenerate.map(([fileName]) => fileName).join(", ")}`);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -3,23 +3,35 @@ import { render } from "ink";
|
||||
import meow from "meow";
|
||||
import React from "react";
|
||||
|
||||
import App from "./CliApp";
|
||||
import App from "./App";
|
||||
import { SupportedCommands } from "./types";
|
||||
|
||||
const cli = meow(
|
||||
`
|
||||
Usage
|
||||
$ app-store create/delete/edit - Edit and Delete commands must be used on apps created using cli
|
||||
$ 'app-store create' or 'app-store create-template' - Creates a new app or template
|
||||
Options
|
||||
[--template -t] Template to use.
|
||||
|
||||
|
||||
Options
|
||||
[--slug] Slug. This is the name of app dir for apps created with cli.
|
||||
$ 'app-store edit' or 'app-store edit-template' - Edit the App or Template identified by slug
|
||||
Options
|
||||
[--slug -s] Slug. This is the name of app dir for apps created with cli.
|
||||
|
||||
|
||||
$ 'app-store delete' or 'app-store delete-template' - Deletes the app or template identified by slug
|
||||
Options
|
||||
[--slug -s] Slug. This is the name of app dir for apps created with cli.
|
||||
`,
|
||||
{
|
||||
flags: {
|
||||
noDbUpdate: {
|
||||
type: "boolean",
|
||||
},
|
||||
slug: {
|
||||
type: "string",
|
||||
alias: "s",
|
||||
},
|
||||
template: {
|
||||
type: "string",
|
||||
alias: "t",
|
||||
},
|
||||
},
|
||||
allowUnknownFlags: false,
|
||||
@@ -30,20 +42,32 @@ if (cli.input.length !== 1) {
|
||||
cli.showHelp();
|
||||
}
|
||||
|
||||
const command = cli.input[0] as "create" | "delete" | "edit";
|
||||
const supportedCommands = ["create", "delete", "edit"];
|
||||
const command = cli.input[0] as SupportedCommands;
|
||||
const supportedCommands = [
|
||||
"create",
|
||||
"delete",
|
||||
"edit",
|
||||
"create-template",
|
||||
"delete-template",
|
||||
"edit-template",
|
||||
] as const;
|
||||
|
||||
if (!supportedCommands.includes(command)) {
|
||||
cli.showHelp();
|
||||
}
|
||||
let slug;
|
||||
|
||||
let slug = null;
|
||||
|
||||
if (command === "delete" || command === "edit") {
|
||||
if (
|
||||
command === "delete" ||
|
||||
command === "edit" ||
|
||||
command === "delete-template" ||
|
||||
command === "edit-template"
|
||||
) {
|
||||
slug = cli.flags.slug;
|
||||
if (!slug) {
|
||||
console.log("--slug is required");
|
||||
cli.showHelp();
|
||||
cli.showHelp(0);
|
||||
}
|
||||
}
|
||||
render(<App slug={slug} command={command} noDbUpdate={cli.flags.noDbUpdate} />);
|
||||
|
||||
render(<App slug={slug} template={cli.flags.template || ""} command={command} />);
|
||||
@@ -0,0 +1,7 @@
|
||||
import React from "react";
|
||||
|
||||
import { AppForm } from "../components/AppCreateUpdateForm";
|
||||
|
||||
export default function Create(props: Omit<React.ComponentProps<typeof AppForm>, "action">) {
|
||||
return <AppForm action="create-template" {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import React from "react";
|
||||
|
||||
import { AppForm } from "../components/AppCreateUpdateForm";
|
||||
|
||||
export default function CreateTemplate(props: Omit<React.ComponentProps<typeof AppForm>, "action">) {
|
||||
return <AppForm action="create-template" {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import React from "react";
|
||||
|
||||
import DeleteForm from "../components/DeleteForm";
|
||||
|
||||
export default function Delete({ slug }: { slug: string }) {
|
||||
return <DeleteForm slug={slug} action="delete" />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import React from "react";
|
||||
|
||||
import DeleteForm from "../components/DeleteForm";
|
||||
|
||||
export default function Delete({ slug }: { slug: string }) {
|
||||
return <DeleteForm slug={slug} action="delete-template" />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import React from "react";
|
||||
|
||||
import { AppForm } from "../components/AppCreateUpdateForm";
|
||||
|
||||
export default function Edit(props: Omit<React.ComponentProps<typeof AppForm>, "action">) {
|
||||
return <AppForm action="edit" {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import React from "react";
|
||||
|
||||
import { AppForm } from "../components/AppCreateUpdateForm";
|
||||
|
||||
export default function Edit(props: Omit<React.ComponentProps<typeof AppForm>, "action">) {
|
||||
return <AppForm action="edit-template" {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
import fs from "fs";
|
||||
import { Box, Newline, Text, useApp } from "ink";
|
||||
import SelectInput from "ink-select-input";
|
||||
import TextInput from "ink-text-input";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
import { AppMeta } from "@calcom/types/App";
|
||||
|
||||
import { getSlugFromAppName, BaseAppFork, Seed, generateAppFiles, getAppDirPath } from "../core";
|
||||
import { getApp } from "../utils/getApp";
|
||||
import Templates from "../utils/templates";
|
||||
import Label from "./Label";
|
||||
import { Message } from "./Message";
|
||||
|
||||
export const AppForm = ({
|
||||
template: cliTemplate = "",
|
||||
slug: givenSlug = "",
|
||||
action,
|
||||
}: {
|
||||
template?: string;
|
||||
slug?: string;
|
||||
action: "create" | "edit" | "create-template" | "edit-template";
|
||||
}) => {
|
||||
cliTemplate = Templates.find((t) => t.value === cliTemplate)?.value || "";
|
||||
const { exit } = useApp();
|
||||
const isTemplate = action === "create-template" || action === "edit-template";
|
||||
const isEditAction = action === "edit" || action === "edit-template";
|
||||
let initialConfig = {
|
||||
template: cliTemplate,
|
||||
name: "",
|
||||
description: "",
|
||||
category: "",
|
||||
publisher: "",
|
||||
email: "",
|
||||
};
|
||||
|
||||
const [app] = useState(() => getApp(givenSlug, isTemplate));
|
||||
|
||||
if ((givenSlug && action === "edit-template") || action === "edit")
|
||||
try {
|
||||
const config = JSON.parse(
|
||||
fs.readFileSync(`${getAppDirPath(givenSlug, isTemplate)}/config.json`).toString()
|
||||
) as AppMeta;
|
||||
initialConfig = {
|
||||
...config,
|
||||
category: config.categories[0],
|
||||
template: config.__template,
|
||||
};
|
||||
} catch (e) {}
|
||||
|
||||
const fields = [
|
||||
{
|
||||
label: "App Title",
|
||||
name: "name",
|
||||
type: "text",
|
||||
explainer: "Keep it short and sweet like 'Google Meet'",
|
||||
optional: false,
|
||||
defaultValue: "",
|
||||
},
|
||||
{
|
||||
label: "App Description",
|
||||
name: "description",
|
||||
type: "text",
|
||||
explainer:
|
||||
"A detailed description of your app. You can later modify DESCRIPTION.mdx to add markdown as well",
|
||||
optional: false,
|
||||
defaultValue: "",
|
||||
},
|
||||
// You can't edit the base template of an App or Template - You need to start fresh for that.
|
||||
cliTemplate || isEditAction
|
||||
? null
|
||||
: {
|
||||
label: "Choose a base Template",
|
||||
name: "template",
|
||||
type: "select",
|
||||
options: Templates,
|
||||
optional: false,
|
||||
defaultValue: "",
|
||||
},
|
||||
{
|
||||
optional: false,
|
||||
label: "Category of App",
|
||||
name: "category",
|
||||
type: "select",
|
||||
options: [
|
||||
{ label: "Calendar", value: "calendar" },
|
||||
{ label: "Video", value: "video" },
|
||||
{ label: "Payment", value: "payment" },
|
||||
{ label: "Messaging", value: "messaging" },
|
||||
{ label: "Web3", value: "web3" },
|
||||
{ label: "Automation", value: "automation" },
|
||||
{ label: "Analytics", value: "analytics" },
|
||||
{ label: "Other", value: "other" },
|
||||
],
|
||||
defaultValue: "",
|
||||
explainer: "This is how apps are categorized in App Store.",
|
||||
},
|
||||
{
|
||||
optional: true,
|
||||
label: "Publisher Name",
|
||||
name: "publisher",
|
||||
type: "text",
|
||||
explainer: "Let users know who you are",
|
||||
defaultValue: "Your Name",
|
||||
},
|
||||
{
|
||||
optional: true,
|
||||
label: "Publisher Email",
|
||||
name: "email",
|
||||
type: "text",
|
||||
explainer: "Let users know how they can contact you.",
|
||||
defaultValue: "[email protected]",
|
||||
},
|
||||
].filter((f) => f);
|
||||
const [appInputData, setAppInputData] = useState(initialConfig);
|
||||
const [inputIndex, setInputIndex] = useState(0);
|
||||
const [slugFinalized, setSlugFinalized] = useState(false);
|
||||
|
||||
const field = fields[inputIndex];
|
||||
const fieldLabel = field?.label || "";
|
||||
const fieldName = field?.name || "";
|
||||
let fieldValue = appInputData[fieldName as keyof typeof appInputData] || "";
|
||||
let validationResult: Parameters<typeof Message>[0]["message"] | null = null;
|
||||
const { name, category, description, publisher, email, template } = appInputData;
|
||||
|
||||
const [status, setStatus] = useState<"inProgress" | "done">("inProgress");
|
||||
const formCompleted = inputIndex === fields.length;
|
||||
if (field?.name === "appCategory") {
|
||||
// Use template category as the default category
|
||||
fieldValue = Templates.find((t) => t.value === appInputData["template"])?.category || "";
|
||||
}
|
||||
const slug = getSlugFromAppName(name) || givenSlug;
|
||||
|
||||
useEffect(() => {
|
||||
// When all fields have been filled
|
||||
(async () => {
|
||||
if (formCompleted) {
|
||||
await BaseAppFork.create({
|
||||
category,
|
||||
description,
|
||||
name,
|
||||
slug,
|
||||
publisher,
|
||||
email,
|
||||
template,
|
||||
editMode: isEditAction,
|
||||
isTemplate,
|
||||
oldSlug: givenSlug,
|
||||
});
|
||||
|
||||
await Seed.update({ slug, category: category, oldSlug: givenSlug, isTemplate });
|
||||
|
||||
await 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
|
||||
setStatus("done");
|
||||
}
|
||||
})();
|
||||
}, [formCompleted]);
|
||||
|
||||
if (action === "edit" || action === "edit-template") {
|
||||
if (!slug) {
|
||||
return <Text>--slug is required</Text>;
|
||||
}
|
||||
if (!app) {
|
||||
return (
|
||||
<Message
|
||||
message={{
|
||||
text: `App with slug ${givenSlug} not found`,
|
||||
type: "error",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (status === "done") {
|
||||
// HACK: This is a hack to exit the process manually because due to some reason cli isn't automatically exiting
|
||||
setTimeout(() => {
|
||||
exit();
|
||||
}, 500);
|
||||
}
|
||||
|
||||
if (formCompleted) {
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{status !== "done" && (
|
||||
<Message
|
||||
key="progressHeading"
|
||||
message={{
|
||||
text: isEditAction
|
||||
? `Editing app with slug ${slug}`
|
||||
: `Creating ${
|
||||
action === "create-template" ? "template" : "app"
|
||||
} with name '${name}' categorized in '${category}' using template '${template}'`,
|
||||
type: "info",
|
||||
showInProgressIndicator: true,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{status === "done" && (
|
||||
<Box flexDirection="column" paddingTop={2} paddingBottom={2}>
|
||||
<Text bold>
|
||||
Just wait for a few seconds for process to exit and then you are good to go. Your{" "}
|
||||
{isTemplate ? "Template" : "App"} code exists at {getAppDirPath(slug, isTemplate)}
|
||||
</Text>
|
||||
<Text>
|
||||
Tip : Go and change the logo of your {isTemplate ? "template" : "app"} by replacing{" "}
|
||||
{getAppDirPath(slug, isTemplate) + "/static/icon.svg"}
|
||||
</Text>
|
||||
<Newline />
|
||||
<Text bold underline color="blue">
|
||||
App Summary:
|
||||
</Text>
|
||||
<Box flexDirection="column">
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Slug: </Text>
|
||||
<Text>{slug}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">{isTemplate ? "Template" : "App"} URL: </Text>
|
||||
<Text>{`http://localhost:3000/apps/${slug}`}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Name: </Text>
|
||||
<Text>{name}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Description: </Text>
|
||||
<Text>{description}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Category: </Text>
|
||||
<Text>{category}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Publisher Name: </Text>
|
||||
<Text>{publisher}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color="green">Publisher Email: </Text>
|
||||
<Text>{email}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
<Text italic color="gray">
|
||||
Note: You should not rename app directory manually. Use cli only to do that as it needs to be
|
||||
updated in DB as well
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
if (slug && slug !== givenSlug && fs.existsSync(getAppDirPath(slug, isTemplate))) {
|
||||
validationResult = {
|
||||
text: `${
|
||||
action === "create" ? "App" : "Template"
|
||||
} with slug ${slug} already exists. If you want to edit it, use edit command`,
|
||||
type: "error",
|
||||
};
|
||||
|
||||
if (slugFinalized) {
|
||||
return <Message message={validationResult} />;
|
||||
}
|
||||
}
|
||||
const selectedOptionIndex =
|
||||
field?.type === "select" ? field?.options?.findIndex((o) => o.value === fieldValue) : 0;
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box flexDirection="column">
|
||||
{isEditAction ? (
|
||||
<Message
|
||||
message={{
|
||||
text: `\nLet's edit your ${isTemplate ? "Template" : "App"}! We have prefilled the details.\n`,
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<Message
|
||||
message={{
|
||||
text: `\nLet's create your ${
|
||||
isTemplate ? "Template" : "App"
|
||||
}! Start by providing the information that's asked\n`,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Box>
|
||||
<Label>{`${fieldLabel}`}</Label>
|
||||
{field?.type == "text" ? (
|
||||
<TextInput
|
||||
value={fieldValue}
|
||||
placeholder={field?.defaultValue}
|
||||
onSubmit={(value) => {
|
||||
if (!value && !field.optional) {
|
||||
return;
|
||||
}
|
||||
setSlugFinalized(true);
|
||||
setInputIndex((index) => {
|
||||
return index + 1;
|
||||
});
|
||||
}}
|
||||
onChange={(value) => {
|
||||
setAppInputData((appInputData) => {
|
||||
return {
|
||||
...appInputData,
|
||||
[fieldName]: value,
|
||||
};
|
||||
});
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<SelectInput<string>
|
||||
items={field?.options}
|
||||
itemComponent={(item) => {
|
||||
const myItem = item as { value: string; label: string };
|
||||
return (
|
||||
<Box justifyContent="space-between">
|
||||
<Box flexShrink={0} flexGrow={1}>
|
||||
<Text color="blue">{myItem.value}: </Text>
|
||||
</Box>
|
||||
<Text>{item.label}</Text>
|
||||
</Box>
|
||||
);
|
||||
}}
|
||||
key={fieldName}
|
||||
initialIndex={selectedOptionIndex === -1 ? 0 : selectedOptionIndex}
|
||||
onSelect={(item) => {
|
||||
setAppInputData((appInputData) => {
|
||||
return {
|
||||
...appInputData,
|
||||
[fieldName]: item.value,
|
||||
};
|
||||
});
|
||||
setInputIndex((index) => {
|
||||
return index + 1;
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Box>
|
||||
{validationResult ? (
|
||||
<Message message={validationResult} />
|
||||
) : (
|
||||
<Text color="gray" italic>
|
||||
{field?.explainer}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,109 @@
|
||||
import { Text } from "ink";
|
||||
import TextInput from "ink-text-input";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
import { ImportantText } from "../components/ImportantText";
|
||||
import { Message } from "../components/Message";
|
||||
import { BaseAppFork, Seed, generateAppFiles } from "../core";
|
||||
import { getApp } from "../utils/getApp";
|
||||
|
||||
export default function DeleteForm({ slug, action }: { slug: string; action: "delete" | "delete-template" }) {
|
||||
const [confirmedAppSlug, setConfirmedAppSlug] = useState("");
|
||||
const [state, setState] = useState<
|
||||
| "INITIALIZED"
|
||||
| "DELETION_CONFIRMATION_FAILED"
|
||||
| "DELETION_CONFIRMATION_SUCCESSFUL"
|
||||
| "DELETION_COMPLETED"
|
||||
| "APP_NOT_EXISTS"
|
||||
>("INITIALIZED");
|
||||
const isTemplate = action === "delete-template";
|
||||
const app = getApp(slug, isTemplate);
|
||||
useEffect(() => {
|
||||
if (!app) {
|
||||
setState("APP_NOT_EXISTS");
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (state === "DELETION_CONFIRMATION_SUCCESSFUL") {
|
||||
(async () => {
|
||||
await BaseAppFork.delete({ slug, isTemplate });
|
||||
Seed.revert({ slug });
|
||||
await generateAppFiles();
|
||||
// successMsg({ text: `App with slug ${slug} has been deleted`, done: true });
|
||||
setState("DELETION_COMPLETED");
|
||||
})();
|
||||
}
|
||||
}, [slug, state]);
|
||||
|
||||
if (state === "INITIALIZED") {
|
||||
return (
|
||||
<>
|
||||
<ImportantText>
|
||||
Type below the slug of the {isTemplate ? "Template" : "App"} that you want to delete.
|
||||
</ImportantText>
|
||||
<Text color="gray" italic>
|
||||
It would cleanup the app directory and App table and Credential table.
|
||||
</Text>
|
||||
<TextInput
|
||||
value={confirmedAppSlug}
|
||||
onSubmit={(value) => {
|
||||
if (value === slug) {
|
||||
setState("DELETION_CONFIRMATION_SUCCESSFUL");
|
||||
} else {
|
||||
setState("DELETION_CONFIRMATION_FAILED");
|
||||
}
|
||||
}}
|
||||
onChange={(val) => {
|
||||
setConfirmedAppSlug(val);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (state === "APP_NOT_EXISTS") {
|
||||
return (
|
||||
<Message
|
||||
message={{
|
||||
text: `${isTemplate ? "Template" : "App"} with slug ${slug} doesn't exist`,
|
||||
type: "error",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (state === "DELETION_CONFIRMATION_SUCCESSFUL") {
|
||||
return (
|
||||
<Message
|
||||
message={{
|
||||
text: `Deleting ${isTemplate ? "Template" : "App"}`,
|
||||
type: "info",
|
||||
showInProgressIndicator: true,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (state === "DELETION_COMPLETED") {
|
||||
return (
|
||||
<Message
|
||||
message={{
|
||||
text: `${
|
||||
isTemplate ? "Template" : "App"
|
||||
} with slug "${slug}" has been deleted. You might need to restart your dev environment`,
|
||||
type: "success",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (state === "DELETION_CONFIRMATION_FAILED") {
|
||||
return (
|
||||
<Message
|
||||
message={{
|
||||
text: `Slug doesn't match - Should have been ${slug}`,
|
||||
type: "error",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { Text } from "ink";
|
||||
import React from "react";
|
||||
|
||||
export function ImportantText({ children }: { children: React.ReactNode }) {
|
||||
return <Text color="red">{children}</Text>;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
|
||||
export default function Label({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<Box>
|
||||
<Text underline>{children}</Text>
|
||||
<Text>: </Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Text } from "ink";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
export function Message({
|
||||
message,
|
||||
}: {
|
||||
message: { text: string; type?: "info" | "error" | "success"; showInProgressIndicator?: boolean };
|
||||
}) {
|
||||
const color = message.type === "success" ? "green" : message.type === "error" ? "red" : "white";
|
||||
const [progressText, setProgressText] = useState("...");
|
||||
useEffect(() => {
|
||||
if (message.showInProgressIndicator) {
|
||||
const interval = setInterval(() => {
|
||||
setProgressText((progressText) => {
|
||||
return progressText.length > 3 ? "" : progressText + ".";
|
||||
});
|
||||
}, 1000);
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
};
|
||||
}
|
||||
}, [message.showInProgressIndicator]);
|
||||
return (
|
||||
<Text color={color}>
|
||||
{message.text}
|
||||
{message.showInProgressIndicator && progressText}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import path from "path";
|
||||
|
||||
export const APP_STORE_PATH = path.join(__dirname, "..", "..", "app-store");
|
||||
export const TEMPLATES_PATH = path.join(APP_STORE_PATH, "templates");
|
||||
@@ -0,0 +1,192 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
import seedAppStoreConfig from "@calcom/prisma/seed-app-store.config.json";
|
||||
|
||||
import { APP_STORE_PATH, TEMPLATES_PATH } from "./constants";
|
||||
import execSync from "./utils/execSync";
|
||||
|
||||
const slugify = (str: string) => {
|
||||
// A valid dir name
|
||||
// A valid URL path
|
||||
// It is okay to not be a valid variable name. This is so that we can use hyphens which look better then underscores in URL and as directory name
|
||||
return str.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase();
|
||||
};
|
||||
|
||||
export function getSlugFromAppName(appName: string): string {
|
||||
if (!appName) {
|
||||
return appName;
|
||||
}
|
||||
return slugify(appName);
|
||||
}
|
||||
|
||||
export function getAppDirPath(slug: string, isTemplate: boolean) {
|
||||
if (!isTemplate) {
|
||||
return path.join(APP_STORE_PATH, `${slug}`);
|
||||
}
|
||||
return path.join(TEMPLATES_PATH, `${slug}`);
|
||||
}
|
||||
|
||||
function absolutePath(appRelativePath: string) {
|
||||
return path.join(APP_STORE_PATH, appRelativePath);
|
||||
}
|
||||
|
||||
const updatePackageJson = ({
|
||||
slug,
|
||||
appDescription,
|
||||
appDirPath,
|
||||
}: {
|
||||
slug: string;
|
||||
appDescription: string;
|
||||
appDirPath: string;
|
||||
}) => {
|
||||
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 workspaceDir = path.resolve(__dirname, "..", "..", "..");
|
||||
|
||||
export const BaseAppFork = {
|
||||
create: async function ({
|
||||
category,
|
||||
editMode = false,
|
||||
description,
|
||||
name,
|
||||
slug,
|
||||
publisher,
|
||||
email,
|
||||
template,
|
||||
isTemplate,
|
||||
oldSlug,
|
||||
}: {
|
||||
category: string;
|
||||
editMode?: boolean;
|
||||
description: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
publisher: string;
|
||||
email: string;
|
||||
template: string;
|
||||
isTemplate: boolean;
|
||||
oldSlug?: string;
|
||||
}) {
|
||||
const appDirPath = getAppDirPath(slug, isTemplate);
|
||||
if (!editMode) {
|
||||
await execSync(`mkdir -p ${appDirPath}`);
|
||||
await execSync(`cp -r ${TEMPLATES_PATH}/${template}/* ${appDirPath}`);
|
||||
} else {
|
||||
if (!oldSlug) {
|
||||
throw new Error("oldSlug is required when editMode is true");
|
||||
}
|
||||
if (oldSlug !== slug) {
|
||||
// We need to rename only if they are different
|
||||
const oldAppDirPath = getAppDirPath(oldSlug, isTemplate);
|
||||
|
||||
await execSync(`mv ${oldAppDirPath} ${appDirPath}`);
|
||||
}
|
||||
}
|
||||
updatePackageJson({ slug, appDirPath, appDescription: description });
|
||||
|
||||
const categoryToVariantMap = {
|
||||
video: "conferencing",
|
||||
};
|
||||
|
||||
let config = {
|
||||
name: name,
|
||||
// Plan to remove it. DB already has it and name of dir is also the same.
|
||||
slug: slug,
|
||||
type: `${slug}_${category}`,
|
||||
// TODO: Remove usage of imageSrc, it is being used in ConnectCalendars.tsx. After that delete imageSrc in all configs and from here
|
||||
imageSrc: `icon.svg`,
|
||||
logo: `icon.svg`,
|
||||
variant: categoryToVariantMap[category as keyof typeof categoryToVariantMap] || category,
|
||||
categories: [category],
|
||||
publisher: publisher,
|
||||
email: email,
|
||||
description: description,
|
||||
// TODO: Use this to avoid edit and delete on the apps created outside of cli
|
||||
__createdUsingCli: true,
|
||||
isTemplate,
|
||||
// Store the template used to create an app
|
||||
__template: template,
|
||||
};
|
||||
const currentConfig = JSON.parse(fs.readFileSync(`${appDirPath}/config.json`).toString());
|
||||
config = {
|
||||
...currentConfig,
|
||||
...config,
|
||||
};
|
||||
fs.writeFileSync(`${appDirPath}/config.json`, JSON.stringify(config, null, 2));
|
||||
fs.writeFileSync(
|
||||
`${appDirPath}/DESCRIPTION.md`,
|
||||
fs
|
||||
.readFileSync(`${appDirPath}/DESCRIPTION.md`)
|
||||
.toString()
|
||||
.replace(/_DESCRIPTION_/g, description)
|
||||
.replace(/_APP_DIR_/g, slug)
|
||||
);
|
||||
},
|
||||
|
||||
delete: async function ({ slug, isTemplate }: { slug: string; isTemplate: boolean }) {
|
||||
const appDirPath = getAppDirPath(slug, isTemplate);
|
||||
await execSync(`rm -rf ${appDirPath}`);
|
||||
},
|
||||
};
|
||||
|
||||
export const Seed = {
|
||||
seedConfigPath: absolutePath("../prisma/seed-app-store.config.json"),
|
||||
update: async function ({
|
||||
slug,
|
||||
category,
|
||||
oldSlug,
|
||||
isTemplate,
|
||||
}: {
|
||||
slug: string;
|
||||
category: string;
|
||||
oldSlug: string;
|
||||
isTemplate: boolean;
|
||||
}) {
|
||||
let configContent = "[]";
|
||||
try {
|
||||
if (fs.statSync(this.seedConfigPath)) {
|
||||
configContent = fs.readFileSync(this.seedConfigPath).toString();
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
let seedConfig: typeof seedAppStoreConfig = JSON.parse(configContent);
|
||||
seedConfig = seedConfig.filter((app) => app.slug !== oldSlug);
|
||||
|
||||
if (!seedConfig.find((app) => app.slug === slug)) {
|
||||
seedConfig.push({
|
||||
dirName: slug,
|
||||
categories: [category],
|
||||
slug: slug,
|
||||
type: `${slug}_${category}`,
|
||||
isTemplate: isTemplate,
|
||||
});
|
||||
}
|
||||
|
||||
// Add the message as a property to first item so that it stays always at the top
|
||||
seedConfig[0]["/*"] =
|
||||
"This file is auto-generated and updated by `yarn app-store create/edit`. Don't edit it manually";
|
||||
|
||||
// Add the message as a property to first item so that it stays always at the top
|
||||
seedConfig[0]["/*"] =
|
||||
"This file is auto-generated and updated by `yarn app-store create/edit`. Don't edit it manually";
|
||||
|
||||
fs.writeFileSync(this.seedConfigPath, JSON.stringify(seedConfig, null, 2));
|
||||
await execSync(`cd ${workspaceDir}/packages/prisma && yarn seed-app-store seed-templates`);
|
||||
},
|
||||
revert: async function ({ slug }: { slug: string }) {
|
||||
let seedConfig: typeof seedAppStoreConfig = JSON.parse(fs.readFileSync(this.seedConfigPath).toString());
|
||||
seedConfig = seedConfig.filter((app) => app.slug !== slug);
|
||||
fs.writeFileSync(this.seedConfigPath, JSON.stringify(seedConfig, null, 2));
|
||||
await execSync(`yarn workspace @calcom/prisma delete-app ${slug}`);
|
||||
},
|
||||
};
|
||||
|
||||
export const generateAppFiles = async () => {
|
||||
await execSync(`yarn ts-node --transpile-only src/build.ts`);
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
import child_process from "child_process";
|
||||
|
||||
const execSync = (cmd: string) => {
|
||||
if (process.env.DEBUG === "1") {
|
||||
console.log(`${process.cwd()}$: ${cmd}`);
|
||||
}
|
||||
const result = child_process.execSync(cmd).toString();
|
||||
if (process.env.DEBUG === "1") {
|
||||
console.log(result);
|
||||
}
|
||||
return cmd;
|
||||
};
|
||||
export default execSync;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
export type SupportedCommands =
|
||||
| "create"
|
||||
| "edit"
|
||||
| "delete"
|
||||
| "create-template"
|
||||
| "delete-template"
|
||||
| "edit-template";
|
||||
@@ -0,0 +1,26 @@
|
||||
import child_process from "child_process";
|
||||
|
||||
const execSync = async (cmd: string) => {
|
||||
const silent = process.env.DEBUG === "1" ? false : true;
|
||||
if (!silent) {
|
||||
console.log(`${process.cwd()}$: ${cmd}`);
|
||||
}
|
||||
const result: string = await new Promise((resolve, reject) => {
|
||||
child_process.exec(cmd, (err, stdout, stderr) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
console.log(err);
|
||||
}
|
||||
if (stderr && !silent) {
|
||||
console.log(stderr);
|
||||
}
|
||||
resolve(stdout);
|
||||
});
|
||||
});
|
||||
|
||||
if (!silent) {
|
||||
console.log(result.toString());
|
||||
}
|
||||
return cmd;
|
||||
};
|
||||
export default execSync;
|
||||
@@ -0,0 +1,26 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
import { APP_STORE_PATH, TEMPLATES_PATH } from "../constants";
|
||||
import { getAppName } from "./getAppName";
|
||||
|
||||
export const getApp = (slug: string, isTemplate: boolean) => {
|
||||
const base = isTemplate ? TEMPLATES_PATH : APP_STORE_PATH;
|
||||
const foundApp = fs
|
||||
.readdirSync(base)
|
||||
.filter((dir) => {
|
||||
if (fs.statSync(path.join(base, dir)).isDirectory() && getAppName(dir)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.find((appName) => appName === slug);
|
||||
if (foundApp) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(path.join(base, foundApp, "config.json")).toString());
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import path from "path";
|
||||
|
||||
import { APP_STORE_PATH } from "../constants";
|
||||
|
||||
export function getAppName(candidatePath) {
|
||||
function isValidAppName(candidatePath) {
|
||||
if (
|
||||
!candidatePath.startsWith("_") &&
|
||||
candidatePath !== "ee" &&
|
||||
!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;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
import { TEMPLATES_PATH } from "../constants";
|
||||
import { getAppName } from "./getAppName";
|
||||
|
||||
const Templates = fs
|
||||
.readdirSync(TEMPLATES_PATH)
|
||||
.filter((dir) => {
|
||||
if (fs.statSync(path.join(TEMPLATES_PATH, dir)).isDirectory() && getAppName(dir)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.map((dir) => {
|
||||
try {
|
||||
const config = JSON.parse(fs.readFileSync(path.join(TEMPLATES_PATH, dir, "config.json")).toString());
|
||||
return {
|
||||
label: `${config.description}`,
|
||||
value: dir,
|
||||
category: config.categories[0],
|
||||
};
|
||||
} catch (e) {
|
||||
// config.json might not exist
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter((item) => !!item) as { label: string; value: string; category: string }[];
|
||||
export default Templates;
|
||||
Reference in new issue
Block a user