-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.ts
More file actions
272 lines (239 loc) · 9.55 KB
/
deploy.ts
File metadata and controls
272 lines (239 loc) · 9.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import { fileURLToPath } from "node:url";
import { dirname, join, relative } from "node:path";
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync, unlinkSync } from "node:fs";
import { execFileSync } from "node:child_process";
const API_BASE = "https://api.run402.com";
const rootDir = dirname(fileURLToPath(import.meta.url));
const siteDir = join(rootDir, "site");
const customDir = join(siteDir, "custom");
function loadBrand(): Record<string, unknown> {
const brandPath = join(customDir, "brand.json");
const defaults = {
name: "Krello",
tagline: "Trello-style collaboration — forkable, no seat fees.",
logo: "custom/logo.svg",
favicon: "favicon.svg",
fonts: {
display: { family: "Fraunces", weights: [600, 700] },
body: { family: "Space Grotesk", weights: [400, 500, 700] },
source: "google",
},
languages: ["en"],
defaultLanguage: "en",
defaultTheme: "sunrise",
defaultAccent: "ember",
};
if (!existsSync(brandPath)) return defaults;
try {
const brand = JSON.parse(readFileSync(brandPath, "utf-8"));
return { ...defaults, ...brand };
} catch {
return defaults;
}
}
function loadTemplates(): Array<Record<string, unknown>> {
const templatesDir = join(customDir, "templates");
if (!existsSync(templatesDir)) return [];
const files = readdirSync(templatesDir).filter((f: string) => f.endsWith(".json")).sort();
return files.map((file: string) => {
const id = file.replace(/\.json$/, "");
const data = JSON.parse(readFileSync(join(templatesDir, file), "utf-8"));
return { id, ...data };
});
}
function buildFontsLink(fonts: Record<string, unknown>): string {
if (!fonts || (fonts as Record<string, unknown>).source !== "google") return "";
const display = fonts.display as { family: string; weights: number[] } | undefined;
const body = fonts.body as { family: string; weights: number[] } | undefined;
const families: string[] = [];
if (display?.family) {
const weights = (display.weights || [400, 700]).join(";");
families.push(`family=${display.family.replace(/\s/g, "+")}:wght@${weights}`);
}
if (body?.family) {
const weights = (body.weights || [400, 500, 700]).join(";");
families.push(`family=${body.family.replace(/\s/g, "+")}:wght@${weights}`);
}
if (!families.length) return "";
return `<link href="https://fonts.googleapis.com/css2?${families.join("&")}&display=swap" rel="stylesheet" />`;
}
function loadBootString(): string {
const enPath = join(customDir, "strings", "en.json");
if (!existsSync(enPath)) return "Preparing your boards.";
try {
const strings = JSON.parse(readFileSync(enPath, "utf-8"));
return strings["boot.preparing"] || "Preparing your boards.";
} catch {
return "Preparing your boards.";
}
}
function compileHtml(html: string, brand: Record<string, unknown>, templates: Array<Record<string, unknown>>, anonKey: string): string {
const fonts = brand.fonts as Record<string, unknown> | undefined;
const fontsLink = buildFontsLink(fonts || {});
const bootString = loadBootString();
let compiled = html;
compiled = compiled.replace(/\{\{html_lang\}\}/g, String(brand.defaultLanguage || "en"));
compiled = compiled.replace(/\{\{brand\.name\}\}/g, String(brand.name || "Krello"));
compiled = compiled.replace(/\{\{brand\.tagline\}\}/g, String(brand.tagline || ""));
compiled = compiled.replace(/\{\{brand\.favicon\}\}/g, String(brand.favicon || "favicon.svg"));
compiled = compiled.replace(/\{\{fonts_link\}\}/g, fontsLink);
compiled = compiled.replace(/\{\{brand_json\}\}/g, JSON.stringify(brand));
compiled = compiled.replace(/\{\{templates_json\}\}/g, JSON.stringify(templates));
compiled = compiled.replace(/\{\{boot\.preparing\}\}/g, bootString);
compiled = compiled.replace('apikey: "",', `apikey: "${anonKey}",`);
return compiled;
}
const SUBDOMAIN = process.env.KRELLO_SUBDOMAIN || "krello";
const APP_URL = `https://${SUBDOMAIN}.run402.com`;
const EXISTING_PROJECT = process.env.KRELLO_PROJECT_ID || "";
const EXISTING_ANON_KEY = process.env.KRELLO_ANON_KEY || "";
const ADMIN_EMAIL = process.env.KRELLO_ADMIN_EMAIL || "";
const PUBLIC_SIGNUP = process.env.KRELLO_PUBLIC_SIGNUP === "true";
function cli(...args: string[]): string {
return execFileSync("run402", args, { encoding: "utf-8" }).trim();
}
function cliJson(...args: string[]) {
return JSON.parse(cli(...args));
}
function withTempFile<T>(name: string, data: string, fn: (path: string) => T): T {
const path = join(rootDir, name);
writeFileSync(path, data);
try {
return fn(path);
} finally {
try { unlinkSync(path); } catch {}
}
}
function generateSecret(): string {
const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
let result = "kbs-";
for (let i = 0; i < 24; i++) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
function buildManifest(projectId: string, anonKey: string, bootstrapSecret: string, subdomain?: string) {
const manifest: Record<string, unknown> = {
project_id: projectId,
name: "krello",
migrations_file: "schema.sql",
functions: [{
name: "krello",
code: readFileSync(join(rootDir, "function.js"), "utf-8"),
config: { timeout: 30, memory: 256 },
}],
secrets: [
{ key: "KRELLO_APP_URL", value: APP_URL },
{ key: "KRELLO_BOOTSTRAP_SECRET", value: bootstrapSecret },
],
files: loadSiteFiles(anonKey),
};
if (subdomain) manifest.subdomain = subdomain;
return manifest;
}
async function invokeFunction(anonKey: string, body: Record<string, unknown>) {
const res = await fetch(`${API_BASE}/functions/v1/krello/admin-bootstrap`, {
method: "POST",
headers: {
"Content-Type": "application/json",
apikey: anonKey,
},
body: JSON.stringify(body),
});
return res.json();
}
async function main() {
console.log("=== Krello Deploy ===\n");
let projectId = EXISTING_PROJECT;
let anonKey = EXISTING_ANON_KEY;
if (!projectId || !anonKey) {
console.log("1) Provisioning project...");
const result = cliJson("projects", "provision");
projectId = result.project_id;
anonKey = result.anon_key;
console.log(` Project: ${projectId}`);
console.log(` Anon Key: ${anonKey}`);
} else {
console.log(`1) Using existing project: ${projectId}`);
}
const bootstrapSecret = generateSecret();
console.log("\n2) Deploying (schema + function + site + subdomain)...");
const manifest = buildManifest(projectId, anonKey, bootstrapSecret, SUBDOMAIN);
const deployResult = withTempFile(".deploy-manifest.json", JSON.stringify(manifest), (path) => {
return cliJson("deploy", "--manifest", path);
});
console.log(` Site: ${deployResult.site_url || deployResult.subdomain_url || APP_URL}`);
console.log("\n3) Provisioning mailbox...");
try {
const mailboxResult = cliJson("email", "create", SUBDOMAIN, "--project", projectId);
const mailboxId = mailboxResult.mailbox_id;
cli("secrets", "set", projectId, "KRELLO_MAILBOX_ID", mailboxId);
console.log(` Mailbox: ${SUBDOMAIN}@mail.run402.com (${mailboxId})`);
} catch {
// Mailbox may already exist — get its ID via status
try {
const statusResult = cliJson("email", "status", "--project", projectId);
const existingId = statusResult.mailbox_id;
if (existingId) {
cli("secrets", "set", projectId, "KRELLO_MAILBOX_ID", existingId);
console.log(` Mailbox already exists (${existingId}), secret updated.`);
} else {
console.log(" Mailbox exists but could not read ID.");
}
} catch {
console.log(" Mailbox creation skipped.");
}
}
if (ADMIN_EMAIL) {
console.log("\n4) Setting bootstrap secret...");
cli("secrets", "set", projectId, "KRELLO_BOOTSTRAP_SECRET", bootstrapSecret);
console.log(" Bootstrapping admin account...\n");
const bootstrapBody: Record<string, unknown> = {
secret: bootstrapSecret,
admin_email: ADMIN_EMAIL,
};
if (PUBLIC_SIGNUP) bootstrapBody.public_signup = true;
const bootstrapResult = await invokeFunction(anonKey, bootstrapBody);
if (bootstrapResult.admin_email) {
console.log(` Admin: ${bootstrapResult.admin_email}`);
console.log(` Password: ${bootstrapResult.admin_password}`);
} else {
console.log(` Bootstrap: ${bootstrapResult.error || "skipped (already bootstrapped)"}`);
}
}
console.log("\n5) Publishing forkable version...");
cli("apps", "publish", projectId,
"--description", "Beautiful Trello-style collaboration app for run402 with multi-user boards, invite links, rich cards, and export/duplicate flows.",
"--tags", "kanban,boards,collaboration,auth,starter,trello,run402",
"--visibility", "public",
"--fork-allowed");
console.log(" Published");
console.log("\n=== Krello Live ===");
console.log(`Site: ${APP_URL}`);
console.log(`Project: ${projectId}`);
console.log(`Anon Key: ${anonKey}`);
}
function loadSiteFiles(anonKey: string) {
const brand = loadBrand();
const templates = loadTemplates();
const files: Array<{ file: string; data: string }> = [];
function walk(currentDir: string) {
for (const entry of readdirSync(currentDir)) {
const absolute = join(currentDir, entry);
const stats = statSync(absolute);
if (stats.isDirectory()) {
walk(absolute);
continue;
}
let data = readFileSync(absolute, "utf-8");
if (entry === "index.html") {
data = compileHtml(data, brand, templates, anonKey);
}
files.push({
file: relative(siteDir, absolute).replace(/\\/g, "/"),
data,
});
}
}
walk(siteDir);
return files;
}
main();