ownledger 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +93 -0
- package/CHANGELOG.md +20 -0
- package/LICENSE +21 -0
- package/README.md +102 -2
- package/assets/_headers +5 -0
- package/assets/app.css +61 -0
- package/assets/app.js +369 -0
- package/assets/icon.svg +1 -0
- package/assets/index.html +30 -0
- package/assets/manifest.webmanifest +1 -0
- package/dist/cli/check.d.ts +3 -0
- package/dist/cli/check.js +21 -0
- package/dist/cli/deploy.d.ts +1 -0
- package/dist/cli/deploy.js +258 -0
- package/dist/cli/dev.d.ts +3 -0
- package/dist/cli/dev.js +107 -0
- package/dist/cli/import.d.ts +3 -0
- package/dist/cli/import.js +151 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +47 -0
- package/dist/cli/init.d.ts +1 -0
- package/dist/cli/init.js +73 -0
- package/dist/cli/jsonc.d.ts +2 -0
- package/dist/cli/jsonc.js +39 -0
- package/dist/engine/actions.d.ts +53 -0
- package/dist/engine/actions.js +205 -0
- package/dist/engine/balances.d.ts +30 -0
- package/dist/engine/balances.js +75 -0
- package/dist/engine/categories.d.ts +17 -0
- package/dist/engine/categories.js +35 -0
- package/dist/engine/check.d.ts +11 -0
- package/dist/engine/check.js +220 -0
- package/dist/engine/dates.d.ts +15 -0
- package/dist/engine/dates.js +56 -0
- package/dist/engine/defaults.d.ts +2 -0
- package/dist/engine/defaults.js +61 -0
- package/dist/engine/index.d.ts +13 -0
- package/dist/engine/index.js +13 -0
- package/dist/engine/load.d.ts +23 -0
- package/dist/engine/load.js +129 -0
- package/dist/engine/networth.d.ts +12 -0
- package/dist/engine/networth.js +73 -0
- package/dist/engine/registry.d.ts +24 -0
- package/dist/engine/registry.js +41 -0
- package/dist/engine/reports.d.ts +68 -0
- package/dist/engine/reports.js +149 -0
- package/dist/engine/schedules.d.ts +75 -0
- package/dist/engine/schedules.js +208 -0
- package/dist/engine/types.d.ts +122 -0
- package/dist/engine/types.js +2 -0
- package/dist/engine/write.d.ts +30 -0
- package/dist/engine/write.js +105 -0
- package/dist/import/hash.d.ts +1 -0
- package/dist/import/hash.js +17 -0
- package/dist/import/index.d.ts +6 -0
- package/dist/import/index.js +6 -0
- package/dist/import/mapping.d.ts +96 -0
- package/dist/import/mapping.js +54 -0
- package/dist/import/profile.d.ts +39 -0
- package/dist/import/profile.js +125 -0
- package/dist/import/run.d.ts +101 -0
- package/dist/import/run.js +416 -0
- package/dist/import/workbook.d.ts +13 -0
- package/dist/import/workbook.js +168 -0
- package/dist/import/xlsx-write.d.ts +6 -0
- package/dist/import/xlsx-write.js +38 -0
- package/dist/node/files.d.ts +3 -0
- package/dist/node/files.js +26 -0
- package/dist/node/scaffold.d.ts +14 -0
- package/dist/node/scaffold.js +45 -0
- package/dist/worker/api.d.ts +3 -0
- package/dist/worker/api.js +139 -0
- package/dist/worker/auth.d.ts +11 -0
- package/dist/worker/auth.js +176 -0
- package/dist/worker/env.d.ts +25 -0
- package/dist/worker/env.js +6 -0
- package/dist/worker/github.d.ts +29 -0
- package/dist/worker/github.js +154 -0
- package/dist/worker/index.d.ts +5 -0
- package/dist/worker/index.js +64 -0
- package/dist/worker/mcp.d.ts +4 -0
- package/dist/worker/mcp.js +292 -0
- package/dist/worker/store.d.ts +42 -0
- package/dist/worker/store.js +92 -0
- package/dist/worker/tar.d.ts +2 -0
- package/dist/worker/tar.js +62 -0
- package/dist/worker/version.d.ts +1 -0
- package/dist/worker/version.js +2 -0
- package/package.json +68 -4
- package/presets/misa.mapping.yaml +48 -0
- package/templates/repo/.github/dependabot.yml +11 -0
- package/templates/repo/.github/workflows/check.yml +15 -0
- package/templates/repo/.github/workflows/deploy.yml +21 -0
- package/templates/repo/README.md +10 -0
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { createPrivateKey, randomBytes } from "node:crypto";
|
|
3
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { parse as parseJsonc } from "./jsonc.js";
|
|
7
|
+
import { appJwt } from "../worker/github.js";
|
|
8
|
+
function opt(args, name) {
|
|
9
|
+
const i = args.indexOf(name);
|
|
10
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
11
|
+
}
|
|
12
|
+
function run(cmd, args, cwd, input) {
|
|
13
|
+
const r = spawnSync(cmd, args, { cwd, input, encoding: "utf8", stdio: [input === undefined ? "inherit" : "pipe", "pipe", "pipe"], env: { ...process.env, FORCE_COLOR: "0" } });
|
|
14
|
+
if (r.status !== 0)
|
|
15
|
+
throw new Error(`${cmd} ${args.join(" ")} failed:\n${(r.stderr || r.stdout).slice(-1500)}`);
|
|
16
|
+
return r.stdout;
|
|
17
|
+
}
|
|
18
|
+
const wrangler = (c, args, input) => run("npx", ["wrangler", ...args], c.root, input);
|
|
19
|
+
function openBrowser(url) {
|
|
20
|
+
const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
|
|
21
|
+
try {
|
|
22
|
+
spawn(cmd, [url], { stdio: "ignore", detached: true, shell: process.platform === "win32" }).unref();
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
/* printed below anyway */
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const say = (s) => console.log(s);
|
|
29
|
+
/* ------------------------------------------------------------------ steps */
|
|
30
|
+
function cloudflareAccount(c, args) {
|
|
31
|
+
const given = opt(args, "--account-id") ?? process.env.CLOUDFLARE_ACCOUNT_ID;
|
|
32
|
+
let out;
|
|
33
|
+
try {
|
|
34
|
+
out = wrangler(c, ["whoami"]);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
say("Signing in to Cloudflare (browser)…");
|
|
38
|
+
execFileSync("npx", ["wrangler", "login"], { cwd: c.root, stdio: "inherit" });
|
|
39
|
+
out = wrangler(c, ["whoami"]);
|
|
40
|
+
}
|
|
41
|
+
if (/not authenticated/i.test(out)) {
|
|
42
|
+
execFileSync("npx", ["wrangler", "login"], { cwd: c.root, stdio: "inherit" });
|
|
43
|
+
out = wrangler(c, ["whoami"]);
|
|
44
|
+
}
|
|
45
|
+
const ids = [...out.matchAll(/│\s*(.+?)\s*│\s*([0-9a-f]{32})\s*│/g)].map((m) => ({ name: m[1].trim(), id: m[2] }));
|
|
46
|
+
if (given)
|
|
47
|
+
return given;
|
|
48
|
+
if (ids.length === 1)
|
|
49
|
+
return ids[0].id;
|
|
50
|
+
if (!ids.length)
|
|
51
|
+
throw new Error("couldn't read your Cloudflare account id from `wrangler whoami`; pass --account-id");
|
|
52
|
+
throw new Error(`several Cloudflare accounts: pass --account-id <id>\n${ids.map((x) => ` ${x.id} ${x.name}`).join("\n")}`);
|
|
53
|
+
}
|
|
54
|
+
function readConfig(c) {
|
|
55
|
+
const f = join(c.root, "wrangler.jsonc");
|
|
56
|
+
return existsSync(f) ? parseJsonc(readFileSync(f, "utf8")) : {};
|
|
57
|
+
}
|
|
58
|
+
function writeConfig(c, cfg) {
|
|
59
|
+
writeFileSync(join(c.root, "wrangler.jsonc"), `// Written by \`ownledger deploy\`. No secrets here: they are Worker secrets (wrangler secret list).\n${JSON.stringify(cfg, null, 2)}\n`);
|
|
60
|
+
}
|
|
61
|
+
function kvId(c, accountId) {
|
|
62
|
+
const title = `ownledger-${c.name}`;
|
|
63
|
+
const list = JSON.parse(wrangler(c, ["kv", "namespace", "list"]).replace(/^[^[]*/, ""));
|
|
64
|
+
const hit = list.find((n) => n.title === title);
|
|
65
|
+
if (hit)
|
|
66
|
+
return hit.id;
|
|
67
|
+
const out = wrangler(c, ["kv", "namespace", "create", title]);
|
|
68
|
+
const m = /"?id"?\s*[:=]\s*"([0-9a-f]{32})"/.exec(out);
|
|
69
|
+
if (!m)
|
|
70
|
+
throw new Error(`couldn't read the new KV namespace id:\n${out}`);
|
|
71
|
+
void accountId;
|
|
72
|
+
return m[1];
|
|
73
|
+
}
|
|
74
|
+
function baseConfig(c, accountId, kv, publicUrl) {
|
|
75
|
+
return {
|
|
76
|
+
$schema: "node_modules/wrangler/config-schema.json",
|
|
77
|
+
name: c.name,
|
|
78
|
+
account_id: accountId,
|
|
79
|
+
main: "node_modules/ownledger/dist/worker/index.js",
|
|
80
|
+
compatibility_date: "2026-11-01",
|
|
81
|
+
compatibility_flags: ["nodejs_compat"],
|
|
82
|
+
workers_dev: true,
|
|
83
|
+
assets: {
|
|
84
|
+
directory: "node_modules/ownledger/assets",
|
|
85
|
+
binding: "ASSETS",
|
|
86
|
+
run_worker_first: ["/api/*", "/mcp", "/mcp/*", "/authorize", "/oauth/*", "/auth/*", "/.well-known/*"],
|
|
87
|
+
},
|
|
88
|
+
kv_namespaces: [{ binding: "OAUTH_KV", id: kv }],
|
|
89
|
+
vars: {
|
|
90
|
+
...(publicUrl ? { PUBLIC_URL: publicUrl } : {}),
|
|
91
|
+
DATA_REPO: c.repo,
|
|
92
|
+
DATA_BRANCH: "main",
|
|
93
|
+
ALLOWED_LOGINS: c.login,
|
|
94
|
+
TIMEZONE: "Asia/Ho_Chi_Minh",
|
|
95
|
+
},
|
|
96
|
+
observability: { enabled: true, head_sampling_rate: 1 },
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function deployOnce(c) {
|
|
100
|
+
say("Deploying the Worker…");
|
|
101
|
+
const out = wrangler(c, ["deploy"]);
|
|
102
|
+
const m = /(https:\/\/[a-z0-9.-]+\.workers\.dev)/i.exec(out);
|
|
103
|
+
if (!m)
|
|
104
|
+
throw new Error(`couldn't read the Worker URL from wrangler:\n${out.slice(-800)}`);
|
|
105
|
+
return m[1];
|
|
106
|
+
}
|
|
107
|
+
function secretNames(c) {
|
|
108
|
+
try {
|
|
109
|
+
return JSON.parse(wrangler(c, ["secret", "list", "--format", "json"]).replace(/^[^[]*/, "")).map((s) => s.name);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return [];
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** GitHub App manifest flow: one click creates the app in the user's account, then install it on the one repo. */
|
|
116
|
+
async function createGitHubApp(c, publicUrl) {
|
|
117
|
+
const port = 8794;
|
|
118
|
+
const state = randomBytes(16).toString("hex");
|
|
119
|
+
const short = c.name.replace(/[^a-z0-9-]/gi, "-").slice(0, 20);
|
|
120
|
+
const manifest = {
|
|
121
|
+
name: `ownledger ${short} ${randomBytes(2).toString("hex")}`.slice(0, 34),
|
|
122
|
+
url: publicUrl,
|
|
123
|
+
description: `Your ownledger Worker's access to ${c.repo} (contents only), and your sign-in.`,
|
|
124
|
+
hook_attributes: { url: publicUrl, active: false },
|
|
125
|
+
redirect_url: `http://localhost:${port}/created`,
|
|
126
|
+
callback_urls: [`${publicUrl}/oauth/callback`, `${publicUrl}/auth/callback`],
|
|
127
|
+
setup_url: `http://localhost:${port}/installed`,
|
|
128
|
+
public: false,
|
|
129
|
+
request_oauth_on_install: false,
|
|
130
|
+
default_permissions: { contents: "write", metadata: "read" },
|
|
131
|
+
default_events: [],
|
|
132
|
+
};
|
|
133
|
+
return new Promise((resolveP, reject) => {
|
|
134
|
+
let creds = null;
|
|
135
|
+
const server = createServer(async (req, res) => {
|
|
136
|
+
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
|
137
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
138
|
+
if (url.pathname === "/") {
|
|
139
|
+
res.end(`<!doctype html><meta charset="utf-8"><body style="font:16px system-ui;max-width:34rem;margin:10vh auto">
|
|
140
|
+
<h2>Create your GitHub App</h2><p>On the next page GitHub shows the app (access: <b>contents</b> of the repos you pick, nothing else). Click <b>Create GitHub App</b>.</p>
|
|
141
|
+
<form method="post" action="https://github.com/settings/apps/new?state=${state}"><input type="hidden" name="manifest" value='${JSON.stringify(manifest).replace(/'/g, "'")}'><button style="font:inherit;padding:.6rem 1rem">Continue to GitHub</button></form>
|
|
142
|
+
<script>document.forms[0].submit()</script></body>`);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (url.pathname === "/created") {
|
|
146
|
+
if (url.searchParams.get("state") !== state) {
|
|
147
|
+
res.statusCode = 400;
|
|
148
|
+
return res.end("state mismatch");
|
|
149
|
+
}
|
|
150
|
+
const r = await fetch(`https://api.github.com/app-manifests/${url.searchParams.get("code")}/conversions`, { method: "POST", headers: { Accept: "application/vnd.github+json", "User-Agent": "ownledger-cli" } });
|
|
151
|
+
if (!r.ok) {
|
|
152
|
+
res.end(`GitHub refused: ${r.status}`);
|
|
153
|
+
return reject(new Error(`app manifest conversion: ${r.status} ${await r.text()}`));
|
|
154
|
+
}
|
|
155
|
+
creds = (await r.json());
|
|
156
|
+
res.statusCode = 302;
|
|
157
|
+
res.setHeader("Location", `https://github.com/apps/${creds.slug}/installations/new`);
|
|
158
|
+
say(`✓ GitHub App created: ${creds.slug}. Now install it: choose "Only select repositories" → ${c.repo} → Install.`);
|
|
159
|
+
return res.end();
|
|
160
|
+
}
|
|
161
|
+
if (url.pathname === "/installed") {
|
|
162
|
+
res.end(`<!doctype html><meta charset="utf-8"><body style="font:16px system-ui;max-width:34rem;margin:10vh auto"><h2>Installed ✓</h2><p>Back to the terminal; you can close this tab.</p></body>`);
|
|
163
|
+
server.close();
|
|
164
|
+
if (creds)
|
|
165
|
+
resolveP(creds);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
res.statusCode = 404;
|
|
169
|
+
res.end();
|
|
170
|
+
});
|
|
171
|
+
server.listen(port, "127.0.0.1", () => {
|
|
172
|
+
const u = `http://localhost:${port}/`;
|
|
173
|
+
say(`\nOpening ${u} to create your GitHub App (if the browser didn't open, open it yourself).`);
|
|
174
|
+
openBrowser(u);
|
|
175
|
+
});
|
|
176
|
+
setTimeout(() => {
|
|
177
|
+
server.close();
|
|
178
|
+
reject(new Error("timed out waiting for the GitHub App (20 min)"));
|
|
179
|
+
}, 20 * 60_000).unref();
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
async function waitForInstallation(appId, pem, repo) {
|
|
183
|
+
for (let i = 0; i < 120; i++) {
|
|
184
|
+
const jwt = await appJwt(appId, pem);
|
|
185
|
+
const r = await fetch(`https://api.github.com/repos/${repo}/installation`, { headers: { Authorization: `Bearer ${jwt}`, Accept: "application/vnd.github+json", "User-Agent": "ownledger-cli" } });
|
|
186
|
+
if (r.ok) {
|
|
187
|
+
const inst = (await r.json());
|
|
188
|
+
const t = (await (await fetch(`https://api.github.com/app/installations/${inst.id}/access_tokens`, { method: "POST", headers: { Authorization: `Bearer ${jwt}`, Accept: "application/vnd.github+json", "User-Agent": "ownledger-cli" } })).json());
|
|
189
|
+
const repos = (await (await fetch("https://api.github.com/installation/repositories", { headers: { Authorization: `Bearer ${t.token}`, Accept: "application/vnd.github+json", "User-Agent": "ownledger-cli" } })).json());
|
|
190
|
+
const names = repos.repositories.map((x) => x.full_name);
|
|
191
|
+
say(`✓ The app can reach: ${names.join(", ")}`);
|
|
192
|
+
if (inst.repository_selection === "all" || names.length > 1)
|
|
193
|
+
say(`! The app is installed on more than ${repo}. It only ever reads ${repo}, but you can limit it on GitHub (Settings → Applications).`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
197
|
+
}
|
|
198
|
+
throw new Error(`the app is not installed on ${repo} (waited 10 minutes)`);
|
|
199
|
+
}
|
|
200
|
+
/* ------------------------------------------------------------------ command */
|
|
201
|
+
export async function cmdDeploy(args) {
|
|
202
|
+
const root = resolve(opt(args, "--dir") ?? ".");
|
|
203
|
+
if (!existsSync(join(root, "data", "meta.yaml")))
|
|
204
|
+
throw new Error(`${root} has no data/meta.yaml (run inside your data repo)`);
|
|
205
|
+
if (!existsSync(join(root, "node_modules", "ownledger")))
|
|
206
|
+
throw new Error("run `npm install` first");
|
|
207
|
+
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
208
|
+
const remote = execFileSync("git", ["remote", "get-url", "origin"], { cwd: root }).toString().trim();
|
|
209
|
+
const repo = /github\.com[/:]([^/]+\/[^/.]+?)(\.git)?$/.exec(remote)?.[1];
|
|
210
|
+
if (!repo)
|
|
211
|
+
throw new Error(`origin is not a GitHub repo: ${remote}`);
|
|
212
|
+
const login = opt(args, "--login") ?? execFileSync("gh", ["api", "user", "--jq", ".login"]).toString().trim();
|
|
213
|
+
const c = { root, name: opt(args, "--name") ?? pkg.name, repo, login, yes: args.includes("--yes") };
|
|
214
|
+
say(`Deploying ${c.name}: data ${repo}, sign-in allowed for ${login}.`);
|
|
215
|
+
const accountId = cloudflareAccount(c, args);
|
|
216
|
+
say(`✓ Cloudflare account ${accountId}`);
|
|
217
|
+
const kv = kvId(c, accountId);
|
|
218
|
+
say(`✓ KV namespace ${kv}`);
|
|
219
|
+
let cfg = readConfig(c);
|
|
220
|
+
let publicUrl = opt(args, "--url") ?? cfg.vars?.PUBLIC_URL;
|
|
221
|
+
if (!publicUrl) {
|
|
222
|
+
writeConfig(c, baseConfig(c, accountId, kv));
|
|
223
|
+
publicUrl = deployOnce(c);
|
|
224
|
+
say(`✓ Worker URL ${publicUrl}`);
|
|
225
|
+
}
|
|
226
|
+
cfg = { ...baseConfig(c, accountId, kv, publicUrl), ...(cfg.routes ? { routes: cfg.routes } : {}) };
|
|
227
|
+
if (cfg.vars && readConfig(c).vars?.ALLOWED_LOGINS)
|
|
228
|
+
cfg.vars.ALLOWED_LOGINS = readConfig(c).vars.ALLOWED_LOGINS;
|
|
229
|
+
writeConfig(c, cfg);
|
|
230
|
+
const have = secretNames(c);
|
|
231
|
+
const needApp = args.includes("--new-app") || !["GITHUB_APP_ID", "GITHUB_APP_PRIVATE_KEY", "GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET"].every((n) => have.includes(n));
|
|
232
|
+
if (needApp) {
|
|
233
|
+
const app = await createGitHubApp(c, publicUrl);
|
|
234
|
+
const pkcs8 = createPrivateKey(app.pem).export({ type: "pkcs8", format: "pem" }).toString();
|
|
235
|
+
await waitForInstallation(String(app.id), pkcs8, repo);
|
|
236
|
+
const secrets = {
|
|
237
|
+
GITHUB_APP_ID: String(app.id),
|
|
238
|
+
GITHUB_APP_PRIVATE_KEY: pkcs8,
|
|
239
|
+
GITHUB_CLIENT_ID: app.client_id,
|
|
240
|
+
GITHUB_CLIENT_SECRET: app.client_secret,
|
|
241
|
+
...(have.includes("COOKIE_SECRET") ? {} : { COOKIE_SECRET: randomBytes(32).toString("base64url") }),
|
|
242
|
+
};
|
|
243
|
+
wrangler(c, ["secret", "bulk"], JSON.stringify(secrets));
|
|
244
|
+
say(`✓ Secrets stored in the Worker (${Object.keys(secrets).join(", ")}); not written anywhere else.`);
|
|
245
|
+
say(` GitHub App: ${app.html_url}`);
|
|
246
|
+
}
|
|
247
|
+
else if (!have.includes("COOKIE_SECRET")) {
|
|
248
|
+
wrangler(c, ["secret", "bulk"], JSON.stringify({ COOKIE_SECRET: randomBytes(32).toString("base64url") }));
|
|
249
|
+
}
|
|
250
|
+
deployOnce(c);
|
|
251
|
+
const meta = await fetch(`${publicUrl}/.well-known/oauth-protected-resource/mcp`);
|
|
252
|
+
say(meta.ok ? "✓ The Worker answers (OAuth metadata ok)" : `! The Worker answered ${meta.status} on its metadata URL`);
|
|
253
|
+
say(`\nDone.\n Connector (MCP): ${publicUrl}/mcp\n Dashboard: ${publicUrl}/\n`);
|
|
254
|
+
say("Add it in Claude: Settings → Connectors → Add custom connector → paste the connector URL → Connect, then sign in with GitHub.");
|
|
255
|
+
say("ChatGPT (plans with custom connectors): Settings → Apps & Connectors → add the same URL.");
|
|
256
|
+
say("\nCommit wrangler.jsonc (no secrets in it). For redeploy on every push, add a Cloudflare API token as a repo secret (see README).");
|
|
257
|
+
return 0;
|
|
258
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** Local data server standing in for GitHub: /head, /files, /commit (writes the files, git commit if a repo). */
|
|
2
|
+
export declare function startDataServer(root: string, port: number): import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>;
|
|
3
|
+
export declare function cmdDev(args: string[]): Promise<number>;
|
package/dist/cli/dev.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { readDataDir } from "../node/files.js";
|
|
7
|
+
import { pkgPath } from "../node/scaffold.js";
|
|
8
|
+
function opt(args, name) {
|
|
9
|
+
const i = args.indexOf(name);
|
|
10
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
11
|
+
}
|
|
12
|
+
/** data/ + imports/*.mapping.yaml, as the Worker would read them from GitHub. */
|
|
13
|
+
function localFiles(root) {
|
|
14
|
+
const files = readDataDir(root);
|
|
15
|
+
const imp = join(root, "imports");
|
|
16
|
+
if (existsSync(imp))
|
|
17
|
+
for (const f of readdirSync(imp))
|
|
18
|
+
if (f.endsWith(".mapping.yaml"))
|
|
19
|
+
files[`imports/${f}`] = readFileSync(join(imp, f), "utf8");
|
|
20
|
+
return files;
|
|
21
|
+
}
|
|
22
|
+
function headOf(files) {
|
|
23
|
+
const h = createHash("sha1");
|
|
24
|
+
for (const [p, c] of Object.entries(files).sort())
|
|
25
|
+
h.update(p + "\0" + c + "\0");
|
|
26
|
+
return h.digest("hex");
|
|
27
|
+
}
|
|
28
|
+
/** Local data server standing in for GitHub: /head, /files, /commit (writes the files, git commit if a repo). */
|
|
29
|
+
export function startDataServer(root, port) {
|
|
30
|
+
const server = createServer((req, res) => {
|
|
31
|
+
const files = localFiles(root);
|
|
32
|
+
if (req.url === "/head")
|
|
33
|
+
return res.end(headOf(files));
|
|
34
|
+
if (req.url === "/files") {
|
|
35
|
+
res.setHeader("Content-Type", "application/json");
|
|
36
|
+
return res.end(JSON.stringify(files));
|
|
37
|
+
}
|
|
38
|
+
if (req.url === "/commit" && req.method === "POST") {
|
|
39
|
+
let body = "";
|
|
40
|
+
req.on("data", (c) => (body += c));
|
|
41
|
+
req.on("end", () => {
|
|
42
|
+
const { baseSha, files: changed, message } = JSON.parse(body);
|
|
43
|
+
if (baseSha !== headOf(files)) {
|
|
44
|
+
res.statusCode = 409;
|
|
45
|
+
return res.end("moved");
|
|
46
|
+
}
|
|
47
|
+
for (const f of changed) {
|
|
48
|
+
const full = join(root, f.path);
|
|
49
|
+
mkdirSync(dirname(full), { recursive: true });
|
|
50
|
+
writeFileSync(full, f.base64 !== undefined ? Buffer.from(f.base64, "base64") : (f.content ?? ""));
|
|
51
|
+
}
|
|
52
|
+
if (existsSync(join(root, ".git"))) {
|
|
53
|
+
try {
|
|
54
|
+
execFileSync("git", ["add", ...changed.map((f) => f.path)], { cwd: root });
|
|
55
|
+
execFileSync("git", ["commit", "-q", "-m", message], { cwd: root });
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
/* nothing to commit */
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
console.log(`[dev] committed: ${message}`);
|
|
62
|
+
res.end(headOf(localFiles(root)));
|
|
63
|
+
});
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
res.statusCode = 404;
|
|
67
|
+
res.end();
|
|
68
|
+
});
|
|
69
|
+
server.listen(port, "127.0.0.1");
|
|
70
|
+
return server;
|
|
71
|
+
}
|
|
72
|
+
export async function cmdDev(args) {
|
|
73
|
+
const root = resolve(args.find((a) => !a.startsWith("-") && !["--port", "--login"].includes(args[args.indexOf(a) - 1] ?? "")) ?? ".");
|
|
74
|
+
if (!existsSync(join(root, "data", "meta.yaml")))
|
|
75
|
+
throw new Error(`${root} has no data/meta.yaml (run inside your data repo)`);
|
|
76
|
+
const port = Number(opt(args, "--port") ?? 8787);
|
|
77
|
+
const dataPort = port + 3;
|
|
78
|
+
const login = opt(args, "--login") ?? "dev";
|
|
79
|
+
startDataServer(root, dataPort);
|
|
80
|
+
const cfgDir = join(root, ".wrangler");
|
|
81
|
+
mkdirSync(cfgDir, { recursive: true });
|
|
82
|
+
const cfg = join(cfgDir, "ownledger-dev.jsonc");
|
|
83
|
+
const assets = pkgPath("assets");
|
|
84
|
+
writeFileSync(cfg, JSON.stringify({
|
|
85
|
+
name: "ownledger-dev",
|
|
86
|
+
main: pkgPath("dist/worker/index.js"),
|
|
87
|
+
compatibility_date: "2026-11-01",
|
|
88
|
+
compatibility_flags: ["nodejs_compat"],
|
|
89
|
+
...(existsSync(assets) ? { assets: { directory: assets, binding: "ASSETS", run_worker_first: ["/api/*", "/mcp", "/authorize", "/oauth/*", "/auth/*", "/.well-known/*"] } } : {}),
|
|
90
|
+
kv_namespaces: [{ binding: "OAUTH_KV", id: "ownledger-dev-kv" }],
|
|
91
|
+
vars: {
|
|
92
|
+
PUBLIC_URL: `http://localhost:${port}`,
|
|
93
|
+
DATA_REPO: "local/dev",
|
|
94
|
+
ALLOWED_LOGINS: login,
|
|
95
|
+
DEV_DATA_URL: `http://127.0.0.1:${dataPort}`,
|
|
96
|
+
DEV_LOGIN: login,
|
|
97
|
+
GITHUB_APP_ID: "dev",
|
|
98
|
+
GITHUB_APP_PRIVATE_KEY: "dev",
|
|
99
|
+
GITHUB_CLIENT_ID: "dev",
|
|
100
|
+
GITHUB_CLIENT_SECRET: "dev",
|
|
101
|
+
COOKIE_SECRET: "dev-only-not-secret",
|
|
102
|
+
},
|
|
103
|
+
}, null, 2));
|
|
104
|
+
console.log(`ownledger dev: data ${root}\n MCP http://localhost:${port}/mcp (sign-in skipped: ${login})\n Dashboard http://localhost:${port}/\n Writes commit to the local folder${existsSync(join(root, ".git")) ? " (git)" : ""}.\n`);
|
|
105
|
+
const child = spawn("npx", ["wrangler", "dev", "-c", cfg, "--port", String(port), "--persist-to", join(cfgDir, "state")], { cwd: root, stdio: "inherit" });
|
|
106
|
+
return new Promise((r) => child.on("exit", (code) => r(code ?? 0)));
|
|
107
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
+
import { checkFiles } from "../engine/check.js";
|
|
5
|
+
import { loadLedger } from "../engine/load.js";
|
|
6
|
+
import { applyChange } from "../engine/write.js";
|
|
7
|
+
import { parseMapping } from "../import/mapping.js";
|
|
8
|
+
import { profileText, profileWorkbook } from "../import/profile.js";
|
|
9
|
+
import { runImport } from "../import/run.js";
|
|
10
|
+
import { readWorkbook } from "../import/workbook.js";
|
|
11
|
+
import { readDataDir } from "../node/files.js";
|
|
12
|
+
import { readPkgFile } from "../node/scaffold.js";
|
|
13
|
+
import { fmtIssue } from "./check.js";
|
|
14
|
+
const n = (x) => (x === null ? "—" : Math.round(x).toLocaleString("en-US"));
|
|
15
|
+
export function importReport(r, verbose = false) {
|
|
16
|
+
const out = [];
|
|
17
|
+
out.push(`Source "${r.source}": ${r.rows} rows read.`);
|
|
18
|
+
out.push(`New transactions: ${r.transactions.length}. Already imported: ${r.skipped}. New accounts: ${r.accounts.length}${r.accounts.length ? ` (${r.accounts.map((a) => `${a.id}:${a.type}`).join(", ")})` : ""}.`);
|
|
19
|
+
const bad = r.reconcile.filter((x) => !x.ok);
|
|
20
|
+
out.push("", `Reconcile against the source's own figures: ${r.reconcile.length - bad.length}/${r.reconcile.length} accounts match.`);
|
|
21
|
+
const show = verbose ? r.reconcile : bad;
|
|
22
|
+
if (show.length) {
|
|
23
|
+
out.push("", "| sheet | account | rows | opening | in | out | closing (source) | closing (imported) | rounding | ok |", "|---|---|---|---|---|---|---|---|---|---|");
|
|
24
|
+
for (const x of show)
|
|
25
|
+
out.push(`| ${x.sheet} | ${x.account} | ${x.rows} | ${n(x.source.opening)} | ${n(x.source.in)} | ${n(x.source.out)} | ${n(x.source.closing)} | ${n(x.imported.closing)} | ${x.rounding} | ${x.ok ? "✓" : "✗ " + x.problems.join("; ")} |`);
|
|
26
|
+
}
|
|
27
|
+
if (r.zeroed.length)
|
|
28
|
+
out.push("", `Closed accounts set to 0 on their closing date (_adjust): ${r.zeroed.map((z) => `${z.account} ${z.amount > 0 ? "+" : ""}${z.amount}`).join(", ")}`);
|
|
29
|
+
if (r.rounding.length)
|
|
30
|
+
out.push("", `Rounding to whole units booked as _adjust: ${r.rounding.map((x) => `${x.sheet} ${x.diff > 0 ? "+" : ""}${x.diff}`).join(", ")}`);
|
|
31
|
+
if (r.unpaired.length) {
|
|
32
|
+
out.push("", `Transfers with no other side in the file (booked against the unmatched account, ${r.unpaired.length}):`);
|
|
33
|
+
for (const u of r.unpaired.slice(0, 50))
|
|
34
|
+
out.push(` - ${u.sheet} row ${u.row}: ${u.date} ${u.time ?? ""} ${n(u.amount)} "${u.note}"`);
|
|
35
|
+
}
|
|
36
|
+
if (r.unresolvedCategories.length) {
|
|
37
|
+
out.push("", "✗ Source categories not in the mapping (add them to `categories`):");
|
|
38
|
+
for (const u of r.unresolvedCategories)
|
|
39
|
+
out.push(` - "${u.key}" (${u.rows} rows, e.g. ${u.example})`);
|
|
40
|
+
}
|
|
41
|
+
if (r.unresolvedRows.length) {
|
|
42
|
+
out.push("", `✗ Rows with no category that are not transfers (add \`uncategorized\` rules, ${r.unresolvedRows.length}):`);
|
|
43
|
+
for (const u of r.unresolvedRows.slice(0, 50))
|
|
44
|
+
out.push(` - ${u.sheet} row ${u.row}: ${u.date} ${n(u.amount)} "${u.note}"`);
|
|
45
|
+
}
|
|
46
|
+
if (r.replace.length)
|
|
47
|
+
out.push("", `Derived opening/rounding transactions updated: ${r.replace.length}`);
|
|
48
|
+
if (r.changed.length) {
|
|
49
|
+
out.push("", `! Rows already imported whose content changed in the source (not applied; decide by hand, ${r.changed.length}):`);
|
|
50
|
+
for (const c of r.changed.slice(0, 30))
|
|
51
|
+
out.push(` - ${c.id}: was ${c.was} now ${c.now}`);
|
|
52
|
+
}
|
|
53
|
+
if (r.gone.length) {
|
|
54
|
+
out.push("", `! Imported earlier but no longer in the source file (not removed; ${r.gone.length}):`);
|
|
55
|
+
for (const g of r.gone.slice(0, 30))
|
|
56
|
+
out.push(` - ${g.id} ${g.date} "${g.note ?? ""}"`);
|
|
57
|
+
}
|
|
58
|
+
for (const e of r.errors)
|
|
59
|
+
out.push(`✗ ${e}`);
|
|
60
|
+
out.push("", r.ok ? "✓ Import is complete and reconciles." : "✗ Import refused: fix the mapping (or the file) and run again.");
|
|
61
|
+
return out.join("\n");
|
|
62
|
+
}
|
|
63
|
+
function findMapping(root, explicit) {
|
|
64
|
+
if (explicit)
|
|
65
|
+
return resolve(explicit);
|
|
66
|
+
const dir = join(root, "imports");
|
|
67
|
+
if (!existsSync(dir))
|
|
68
|
+
return null;
|
|
69
|
+
const maps = readdirSync(dir).filter((f) => f.endsWith(".mapping.yaml"));
|
|
70
|
+
if (maps.length === 1)
|
|
71
|
+
return join(dir, maps[0]);
|
|
72
|
+
if (maps.length > 1)
|
|
73
|
+
throw new Error(`several mappings in imports/ (${maps.join(", ")}): pass --mapping <file>`);
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
function opt(args, name) {
|
|
77
|
+
const i = args.indexOf(name);
|
|
78
|
+
return i >= 0 ? args[i + 1] : args.find((a) => a.startsWith(name + "="))?.slice(name.length + 1);
|
|
79
|
+
}
|
|
80
|
+
export async function cmdImport(args) {
|
|
81
|
+
const positional = args.filter((a, i) => !a.startsWith("-") && !["--mapping", "--dir", "--preset"].includes(args[i - 1] ?? ""));
|
|
82
|
+
const file = positional[0];
|
|
83
|
+
const root = resolve(opt(args, "--dir") ?? ".");
|
|
84
|
+
if (!file) {
|
|
85
|
+
console.error("Usage: ownledger import <export file> [--profile] [--preset misa] [--mapping imports/x.mapping.yaml] [--yes] [--verbose]");
|
|
86
|
+
return 2;
|
|
87
|
+
}
|
|
88
|
+
const data = new Uint8Array(readFileSync(file));
|
|
89
|
+
const wb = readWorkbook(file, data);
|
|
90
|
+
const preset = opt(args, "--preset");
|
|
91
|
+
if (preset) {
|
|
92
|
+
const target = join(root, "imports", `${preset}.mapping.yaml`);
|
|
93
|
+
if (existsSync(target))
|
|
94
|
+
console.log(`${target} exists; not overwritten.`);
|
|
95
|
+
else {
|
|
96
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
97
|
+
writeFileSync(target, readPkgFile(`presets/${preset}.mapping.yaml`));
|
|
98
|
+
console.log(`Wrote ${target} from the ${preset} preset. Fill accounts, categories and uncategorized, then run the import again.`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const mappingPath = findMapping(root, opt(args, "--mapping"));
|
|
102
|
+
if (args.includes("--profile") || preset || !mappingPath) {
|
|
103
|
+
console.log(profileText(profileWorkbook(wb)));
|
|
104
|
+
if (!mappingPath)
|
|
105
|
+
console.log("No mapping yet. Write imports/<source>.mapping.yaml from this profile (see AGENTS.md, \"First import of a new app\"), have the owner review accounts and categories, then run `ownledger import <file>` again.");
|
|
106
|
+
return 0;
|
|
107
|
+
}
|
|
108
|
+
const mapping = parseMapping(readFileSync(mappingPath, "utf8"));
|
|
109
|
+
const files = readDataDir(root);
|
|
110
|
+
const { ledger } = loadLedger(files);
|
|
111
|
+
const r = runImport(wb, mapping, ledger);
|
|
112
|
+
console.log(importReport(r, args.includes("--verbose")));
|
|
113
|
+
if (!r.ok)
|
|
114
|
+
return 1;
|
|
115
|
+
if (!r.transactions.length && !r.accounts.length && !r.replace.length) {
|
|
116
|
+
console.log("Nothing new to import.");
|
|
117
|
+
return 0;
|
|
118
|
+
}
|
|
119
|
+
if (!args.includes("--yes")) {
|
|
120
|
+
console.log("\nPreview only: nothing written. Run again with --yes to write, check and commit.");
|
|
121
|
+
return 0;
|
|
122
|
+
}
|
|
123
|
+
// write: build the new files in memory, check them, then write and commit
|
|
124
|
+
const change = applyChange(files, { addAccounts: r.accounts, addTransactions: r.transactions, replaceTransactions: r.replace });
|
|
125
|
+
const result = checkFiles({ ...files, ...change });
|
|
126
|
+
if (!result.ok) {
|
|
127
|
+
console.log("\n✗ The data would not pass check after this import; nothing written:");
|
|
128
|
+
for (const e of result.errors.slice(0, 30))
|
|
129
|
+
console.log(fmtIssue(e));
|
|
130
|
+
return 1;
|
|
131
|
+
}
|
|
132
|
+
for (const [p, c] of Object.entries(change)) {
|
|
133
|
+
const f = join(root, p);
|
|
134
|
+
mkdirSync(dirname(f), { recursive: true });
|
|
135
|
+
writeFileSync(f, c);
|
|
136
|
+
}
|
|
137
|
+
const rawDir = join(root, "imports", "raw");
|
|
138
|
+
mkdirSync(rawDir, { recursive: true });
|
|
139
|
+
const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
|
|
140
|
+
const raw = join(rawDir, `${stamp}-${basename(file)}`);
|
|
141
|
+
if (!existsSync(raw))
|
|
142
|
+
copyFileSync(file, raw);
|
|
143
|
+
console.log(`\n✓ Written: ${Object.keys(change).length} data file(s), raw copy at ${raw}.`);
|
|
144
|
+
if (existsSync(join(root, ".git")) && !args.includes("--no-commit")) {
|
|
145
|
+
const msg = `Import ${mapping.source}: ${r.transactions.length} transaction(s)${r.accounts.length ? `, ${r.accounts.length} account(s)` : ""}`;
|
|
146
|
+
execFileSync("git", ["add", "data", "imports"], { cwd: root });
|
|
147
|
+
execFileSync("git", ["commit", "-q", "-m", msg], { cwd: root, stdio: "inherit" });
|
|
148
|
+
console.log(`✓ Committed: ${msg}`);
|
|
149
|
+
}
|
|
150
|
+
return 0;
|
|
151
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { pkgVersion } from "../node/scaffold.js";
|
|
3
|
+
import { cmdCheck } from "./check.js";
|
|
4
|
+
import { cmdDeploy } from "./deploy.js";
|
|
5
|
+
import { cmdDev } from "./dev.js";
|
|
6
|
+
import { cmdImport } from "./import.js";
|
|
7
|
+
import { cmdInit } from "./init.js";
|
|
8
|
+
const pkg = { version: pkgVersion() };
|
|
9
|
+
const HELP = `ownledger ${pkg.version}
|
|
10
|
+
|
|
11
|
+
Usage: ownledger <command> [options]
|
|
12
|
+
|
|
13
|
+
init [name] Create a data repo (asks base currency, category language; private GitHub repo via gh)
|
|
14
|
+
check [dir] Check the data repo (default: current folder)
|
|
15
|
+
import <file> Import an export (profile first; preview; --yes writes, checks and commits)
|
|
16
|
+
deploy Deploy your Worker to your Cloudflare (GitHub App, secrets, KV); prints the connector URL
|
|
17
|
+
dev [dir] Run your Worker locally against the local data/ (fake sign-in)
|
|
18
|
+
--version Print the version
|
|
19
|
+
`;
|
|
20
|
+
const commands = {
|
|
21
|
+
init: cmdInit,
|
|
22
|
+
check: cmdCheck,
|
|
23
|
+
import: cmdImport,
|
|
24
|
+
dev: cmdDev,
|
|
25
|
+
deploy: cmdDeploy,
|
|
26
|
+
};
|
|
27
|
+
async function main(argv) {
|
|
28
|
+
const [cmd, ...rest] = argv;
|
|
29
|
+
if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") {
|
|
30
|
+
console.log(HELP);
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
if (cmd === "--version" || cmd === "-v") {
|
|
34
|
+
console.log(pkg.version);
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
37
|
+
const run = commands[cmd];
|
|
38
|
+
if (!run) {
|
|
39
|
+
console.error(`Unknown command "${cmd}".\n\n${HELP}`);
|
|
40
|
+
return 2;
|
|
41
|
+
}
|
|
42
|
+
return run(rest);
|
|
43
|
+
}
|
|
44
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (e) => {
|
|
45
|
+
console.error(e instanceof Error ? e.message : e);
|
|
46
|
+
process.exit(1);
|
|
47
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function cmdInit(args: string[]): Promise<number>;
|
package/dist/cli/init.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { pkgVersion, scaffold } from "../node/scaffold.js";
|
|
6
|
+
function opt(args, name) {
|
|
7
|
+
const i = args.indexOf(name);
|
|
8
|
+
return i >= 0 ? args[i + 1] : args.find((a) => a.startsWith(name + "="))?.slice(name.length + 1);
|
|
9
|
+
}
|
|
10
|
+
function sh(cmd, args, cwd) {
|
|
11
|
+
try {
|
|
12
|
+
return execFileSync(cmd, args, { cwd, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export async function cmdInit(args) {
|
|
19
|
+
const yes = args.includes("--yes") || !process.stdin.isTTY;
|
|
20
|
+
const rl = yes ? null : createInterface({ input: process.stdin, output: process.stdout });
|
|
21
|
+
const ask = async (q, def) => {
|
|
22
|
+
if (!rl)
|
|
23
|
+
return def;
|
|
24
|
+
const a = (await rl.question(`${q} [${def}]: `)).trim();
|
|
25
|
+
return a || def;
|
|
26
|
+
};
|
|
27
|
+
try {
|
|
28
|
+
const flagged = new Set(["--base", "--lang", "--owner", "--dep"]);
|
|
29
|
+
const positional = args.filter((a, i) => !a.startsWith("-") && !flagged.has(args[i - 1] ?? ""));
|
|
30
|
+
const name = positional[0] ?? (await ask("Folder and repo name", "my-money"));
|
|
31
|
+
if (!/^[A-Za-z0-9._-]+$/.test(name))
|
|
32
|
+
throw new Error("name: letters, digits, . _ - only");
|
|
33
|
+
const dir = resolve(name);
|
|
34
|
+
if (existsSync(dir) && readdirSync(dir).filter((f) => f !== ".git").length)
|
|
35
|
+
throw new Error(`${dir} exists and is not empty`);
|
|
36
|
+
const base = (opt(args, "--base") ?? (await ask("Base currency", "VND"))).toUpperCase();
|
|
37
|
+
const lang = (opt(args, "--lang") ?? (await ask("Category language (vi/en)", "vi"))) === "en" ? "en" : "vi";
|
|
38
|
+
const owner = opt(args, "--owner") ?? sh("gh", ["api", "user", "--jq", ".login"]) ?? undefined;
|
|
39
|
+
const version = pkgVersion();
|
|
40
|
+
const files = scaffold({ name, base, lang, owner, version });
|
|
41
|
+
const dep = opt(args, "--dep"); // e.g. file:../ownledger during development
|
|
42
|
+
if (dep) {
|
|
43
|
+
const pkg = JSON.parse(files["package.json"]);
|
|
44
|
+
pkg.dependencies.ownledger = dep;
|
|
45
|
+
files["package.json"] = JSON.stringify(pkg, null, 2) + "\n";
|
|
46
|
+
}
|
|
47
|
+
for (const [p, c] of Object.entries(files)) {
|
|
48
|
+
const f = join(dir, p);
|
|
49
|
+
mkdirSync(dirname(f), { recursive: true });
|
|
50
|
+
writeFileSync(f, c);
|
|
51
|
+
}
|
|
52
|
+
console.log(`✓ Created ${dir} (${Object.keys(files).length} files). Base ${base}, categories in ${lang}${owner ? `, owner ${owner}` : ""}.`);
|
|
53
|
+
if (!existsSync(join(dir, ".git"))) {
|
|
54
|
+
execFileSync("git", ["init", "-q", "-b", "main"], { cwd: dir });
|
|
55
|
+
execFileSync("git", ["add", "-A"], { cwd: dir });
|
|
56
|
+
execFileSync("git", ["commit", "-q", "-m", "ownledger init"], { cwd: dir });
|
|
57
|
+
console.log("✓ git repo with a first commit");
|
|
58
|
+
}
|
|
59
|
+
const wantGh = !args.includes("--no-github") && sh("gh", ["auth", "status"]) !== null;
|
|
60
|
+
if (wantGh) {
|
|
61
|
+
const go = yes ? args.includes("--github") : /^y/i.test(await ask(`Create a PRIVATE GitHub repo ${owner ?? ""}/${name} and push?`, "y"));
|
|
62
|
+
if (go) {
|
|
63
|
+
execFileSync("gh", ["repo", "create", name, "--private", "--source", dir, "--push"], { stdio: "inherit" });
|
|
64
|
+
console.log("✓ private GitHub repo created and pushed");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
console.log(`\nNext:\n cd ${name}\n npm install\n npx ownledger import <your export> # profile → mapping → import\n npx ownledger deploy # your Worker on your Cloudflare`);
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
rl?.close();
|
|
72
|
+
}
|
|
73
|
+
}
|