-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.ts
More file actions
285 lines (257 loc) · 10.6 KB
/
deploy.ts
File metadata and controls
285 lines (257 loc) · 10.6 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
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
* SkMeld deploy script — one-click deploy to Run402.
*
* Usage:
* npx tsx deploy.ts # deploy
* npx tsx deploy.ts --publish # deploy + publish to marketplace
*
* Requires BUYER_PRIVATE_KEY in .env (two levels up from apps/skmeld/).
*/
import { config } from "dotenv";
config({ path: "../../.env" }); // monorepo layout (apps/skmeld/)
config({ path: ".env" }); // standalone repo
import { readFileSync, writeFileSync, readdirSync, existsSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { execSync } from "node:child_process";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import { toClientEvmSigner } from "@x402/evm";
import { createSIWxPayload, encodeSIWxHeader } from "@x402/extensions/sign-in-with-x";
import type { CompleteSIWxInfo } from "@x402/extensions/sign-in-with-x";
import { privateKeyToAccount } from "viem/accounts";
import { createPublicClient, http } from "viem";
import { baseSepolia } from "viem/chains";
const BASE_URL = process.env.RUN402_API_BASE || "https://api.run402.com";
const BUYER_KEY = process.env.BUYER_PRIVATE_KEY as `0x${string}`;
const SUBDOMAIN = process.env.SKMELD_SUBDOMAIN || "skmeld-dev";
const PUBLISH = process.argv.includes("--publish");
if (!BUYER_KEY) {
console.error("Missing BUYER_PRIVATE_KEY in .env");
process.exit(1);
}
// x402 + SIWx setup
const account = privateKeyToAccount(BUYER_KEY);
const publicClient = createPublicClient({ chain: baseSepolia, transport: http() });
const signer = toClientEvmSigner(account, publicClient);
const client = new x402Client();
client.register("eip155:84532", new ExactEvmScheme(signer));
const fetchPaid = wrapFetchWithPayment(fetch, client);
async function siwxHeaders(path: string): Promise<Record<string, string>> {
const baseUrl = new URL(BASE_URL);
const uri = `${baseUrl.protocol}//${baseUrl.host}${path}`;
const now = new Date();
const info: CompleteSIWxInfo = {
domain: baseUrl.hostname,
uri,
statement: "Sign in to Run402",
version: "1",
nonce: Math.random().toString(36).slice(2),
issuedAt: now.toISOString(),
expirationTime: new Date(now.getTime() + 5 * 60 * 1000).toISOString(),
chainId: "eip155:84532",
type: "eip191",
};
const payload = await createSIWxPayload(info, account);
return { "SIGN-IN-WITH-X": encodeSIWxHeader(payload) };
}
function readSQL(...files: string[]): string {
return files.map(f => readFileSync(join(__dirname, "sql", f), "utf-8")).join("\n");
}
function readFunction(name: string): string {
return readFileSync(join(__dirname, "functions", name), "utf-8");
}
function readSiteFiles(dir: string): Array<{ file: string; data: string }> {
const files: Array<{ file: string; data: string }> = [];
function walk(base: string, prefix = "") {
for (const entry of readdirSync(join(base, prefix), { withFileTypes: true })) {
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
walk(base, rel);
} else {
files.push({ file: rel, data: readFileSync(join(base, rel), "utf-8") });
}
}
}
walk(dir);
return files;
}
async function main() {
console.log("\n=== SkMeld Deploy ===\n");
console.log(`Target: ${BASE_URL}`);
console.log(`Wallet: ${account.address}`);
console.log(`Publish: ${PUBLISH}\n`);
// 1. Subscribe to tier (if needed)
console.log("1) Subscribing to tier...");
const tierRes = await fetchPaid(`${BASE_URL}/tiers/v1/prototype`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
});
console.log(` Tier: ${tierRes.status}`);
// 2. Provision project (once) or reuse from app.json
console.log("\n2) Project...");
const appJsonPath = join(__dirname, "app.json");
let project: { project_id: string; anon_key: string; service_key: string };
if (existsSync(appJsonPath)) {
project = JSON.parse(readFileSync(appJsonPath, "utf-8"));
console.log(` Reusing: ${project.project_id} (from app.json)`);
} else {
const headers = await siwxHeaders("/projects/v1");
const projRes = await fetch(`${BASE_URL}/projects/v1`, {
method: "POST",
headers: { "Content-Type": "application/json", ...headers },
body: JSON.stringify({ name: "skmeld" }),
});
project = await projRes.json();
writeFileSync(appJsonPath, JSON.stringify(project, null, 2));
console.log(` Created: ${project.project_id} (saved to app.json)`);
}
console.log(` Anon key: ${project.anon_key?.slice(0, 20)}...`);
// 3. Build frontend (always rebuild to avoid stale bundles)
console.log("\n3) Building frontend...");
const siteDir = join(__dirname, "site");
execSync("npm run build", { cwd: __dirname, stdio: "inherit" });
// 3b. Inject brand config into index.html
console.log(" Injecting brand config...");
const brandPath = join(__dirname, "src", "custom", "brand.json");
if (existsSync(brandPath)) {
const brand = JSON.parse(readFileSync(brandPath, "utf-8"));
const indexPath = join(siteDir, "index.html");
let html = readFileSync(indexPath, "utf-8");
// Inject title
html = html.replace(
/<!-- BRAND:TITLE -->\s*<title>[^<]*<\/title>/,
`<title>${brand.name}</title>`,
);
// Inject Google Fonts
if (brand.fonts?.source === "google") {
const families: string[] = [];
if (brand.fonts.display?.family) {
families.push(
`family=${brand.fonts.display.family.replace(/ /g, "+")}:wght@${(brand.fonts.display.weights || [600, 700]).join(";")}`,
);
}
if (brand.fonts.body?.family && brand.fonts.body.family !== brand.fonts.display?.family) {
families.push(
`family=${brand.fonts.body.family.replace(/ /g, "+")}:wght@${(brand.fonts.body.weights || [400, 500, 700]).join(";")}`,
);
}
if (families.length > 0) {
const fontsLink = `<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?${families.join("&")}&display=swap" rel="stylesheet">`;
html = html.replace("<!-- BRAND:FONTS -->", fontsLink);
}
}
html = html.replace("<!-- BRAND:FONTS -->", "");
// Inject brand script
const brandScript = `<script>window.__SKMELD_BRAND__=${JSON.stringify(brand)};</script>`;
html = html.replace("<!-- BRAND:SCRIPT -->", brandScript);
writeFileSync(indexPath, html);
console.log(` Brand: ${brand.name}`);
}
// 3c. Inject runtime config (anon key, API base) into index.html
{
const indexPath = join(siteDir, "index.html");
let html = readFileSync(indexPath, "utf-8");
const configScript = `<script>window.__SKMELD_CONFIG__=${JSON.stringify({
apiBase: BASE_URL,
anonKey: project.anon_key,
})};</script>`;
// Insert before the closing </head> tag
html = html.replace("</head>", `${configScript}\n</head>`);
writeFileSync(indexPath, html);
console.log(` Config injected (anon key: ${project.anon_key?.slice(0, 20)}...)`);
}
// 4. Read all SQL
const migrations = readSQL("schema.sql", "seed-base.sql");
const rlsSQL = readSQL("rls.sql");
const viewsSQL = readSQL("views.sql");
// 5. Read functions (all in the bundle, including scheduled)
const functionFiles = [
"bootstrap.ts", "submit-request.ts", "update-request.ts",
"transition-request.ts", "add-comment.ts",
"create-invites.ts", "redeem-invite.ts",
"on-signup.ts", "scheduled-tasks.ts",
];
const schedules: Record<string, string> = {
"scheduled-tasks": "0 */4 * * *",
};
const functions = functionFiles.map(f => {
const name = f.replace(".ts", "");
return {
name,
code: readFunction(f),
...(schedules[name] ? { schedule: schedules[name] } : {}),
};
});
// 6. Read site files
const siteFiles = readSiteFiles(siteDir);
console.log(` Site files: ${siteFiles.length}`);
// 7. Bundle deploy
console.log("\n4) Deploying bundle...");
const deployHeaders = await siwxHeaders("/deploy/v1");
const deployRes = await fetch(`${BASE_URL}/deploy/v1`, {
method: "POST",
headers: { "Content-Type": "application/json", ...deployHeaders },
body: JSON.stringify({
project_id: project.project_id,
migrations: migrations + "\n" + rlsSQL + "\n" + viewsSQL,
functions,
files: siteFiles,
subdomain: SUBDOMAIN,
bootstrap: {
admin_email: "admin@skmeld.example",
app_name: "SkMeld Demo",
seed_demo_data: true,
},
}),
});
const deployBody = await deployRes.json();
console.log(` Deploy status: ${deployRes.status}`);
if (deployRes.status >= 400) {
console.log(` Deploy error: ${JSON.stringify(deployBody)}`);
}
if (deployBody.bootstrap_result) {
console.log(` Bootstrap: ${JSON.stringify(deployBody.bootstrap_result)}`);
}
if (deployBody.bootstrap_error) {
console.log(` Bootstrap error: ${deployBody.bootstrap_error}`);
}
// 8. Publish (optional)
if (PUBLISH) {
console.log("\n5) Publishing to marketplace...");
const pubRes = await fetch(`${BASE_URL}/projects/v1/admin/${project.project_id}/publish`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${project.service_key}`,
},
body: JSON.stringify({
visibility: "public",
fork_allowed: true,
description: "Property maintenance request tracker for landlords, HOAs, and office managers. Open source, MIT.",
tags: ["maintenance", "property", "skmeld", "board", "tracker"],
bootstrap_variables: [
{ name: "admin_email", type: "string", required: true, description: "Email for the first admin user" },
{ name: "app_name", type: "string", required: false, description: "Business name" },
{ name: "seed_demo_data", type: "boolean", required: false, default: false, description: "Populate with sample data" },
],
}),
});
const pubBody = await pubRes.json();
console.log(` Published: ${pubBody.id} (${pubRes.status})`);
}
// Summary
console.log("\n=== Deploy Complete ===");
console.log(`URL: https://${SUBDOMAIN}.run402.com`);
console.log(`Project ID: ${project.project_id}`);
console.log(`Anon Key: ${project.anon_key}`);
console.log(`Service Key: ${project.service_key?.slice(0, 20)}...`);
console.log("");
}
main().catch((err) => {
console.error("\nDeploy failed:", err);
process.exit(1);
});