boggo 0.0.1 → 0.1.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.
@@ -0,0 +1,716 @@
1
+ // Komennot, jotka puhuvat Boggo Cloudin kanssa: login, logout, whoami, projects, init, link, push, promote ja open.
2
+ // Kulku uudelle projektille: boggo login → boggo init (uusi projekti tai olemassa oleva) → boggo push --prod.
3
+ // Tekstit: src/command-texts.js (suomi ja englanti).
4
+ import { spawn } from "node:child_process";
5
+ import { ApiError, call, deleteLogin, deviceName, portalUrl, readLogin, saveLogin, TOKEN_RE, uploadTimeoutMs } from "./api.js";
6
+ import { CMD } from "./command-texts.js";
7
+ import { lineReader } from "./lang.js";
8
+ import { SITE_URL } from "./messages.js";
9
+ import { highlight, painter, safe } from "./paint.js";
10
+ import { readLink, saveLink, suggestName } from "./link.js";
11
+ import { collect, packEntries, sizeText, UPLOAD_MAX_BYTES } from "./pack.js";
12
+
13
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
14
+
15
+ // Yhteinen tila: tekstit, tulosteet, kysymykset ja portaali.
16
+ export function context(io, lang, args, version) {
17
+ const t = CMD[lang];
18
+ const login = readLogin(io.home, io.env);
19
+ const ci = Boolean(io.env.CI && io.env.CI !== "false" && io.env.CI !== "0");
20
+ const interactive = Boolean(io.stdin.isTTY && io.stderr.isTTY) && !ci;
21
+ // Elävä rivi (pyörivä merkki, aika, edistymispalkki) vain päätteeseen: CI:n lokiin, putkeen ja tiedostoon tavalliset rivit.
22
+ const animate = Boolean(io.stderr.isTTY) && io.env.TERM !== "dumb" && !ci;
23
+ let lines = null;
24
+ // Värit erikseen kummallekin virralle (putki tai tiedosto saa pelkän tekstin). blank: viimeisin rivi oli tyhjä, jotta gap()
25
+ // ei koskaan tulosta kahta tyhjää riviä peräkkäin.
26
+ const c = painter(io.stderr, io.env);
27
+ const o = painter(io.stdout, io.env);
28
+ let blank = false;
29
+ let live = null;
30
+ const CLEAR = "\r\u001b[2K";
31
+ // Tavallinen rivi elävän rivin aikana: elävä rivi pyyhitään, rivi kirjoitetaan ja elävä piirretään sen alle uudelleen.
32
+ const write = (stream, paint, s) => {
33
+ if (live) io.stderr.write(CLEAR);
34
+ stream.write(`${highlight(paint, safe(s))}\n`);
35
+ blank = s === "";
36
+ live?.draw();
37
+ };
38
+ const ctx = {
39
+ t,
40
+ lang,
41
+ io,
42
+ args,
43
+ version,
44
+ portal: portalUrl(io.env),
45
+ token: login?.tunnus ?? null,
46
+ login,
47
+ interactive,
48
+ cwd: io.cwd ?? process.cwd(),
49
+ fetch: io.fetch ?? fetch,
50
+ sleep: io.sleep ?? sleep,
51
+ now: io.now ?? Date.now,
52
+ c,
53
+ o,
54
+ out: (s = "") => write(io.stdout, o, s),
55
+ err: (s = "") => write(io.stderr, c, s),
56
+ // Koneluettava tuloste (--json) sellaisenaan.
57
+ raw: (s) => io.stdout.write(`${s}\n`),
58
+ // Tyhjä rivi osien väliin (stderr, joten stdoutin skriptikäyttö ei muutu).
59
+ gap() {
60
+ if (blank) return;
61
+ if (live) io.stderr.write(CLEAR);
62
+ io.stderr.write("\n");
63
+ blank = true;
64
+ live?.draw();
65
+ },
66
+ // Elävä rivi: render() palauttaa tekstin, joka piirretään pyörivän merkin perään 10 kertaa sekunnissa. null = ei päätettä
67
+ // (kutsuja tulostaa tavalliset rivit). Rivi pyyhitään stopLive()lla; runCommand pysäyttää sen aina myös virheessä.
68
+ startLive(render, { indent = "" } = {}) {
69
+ if (!animate) return null;
70
+ ctx.stopLive();
71
+ const frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
72
+ let i = 0;
73
+ const handle = {
74
+ draw: () => io.stderr.write(`${CLEAR}${indent}${highlight(c, safe(`${c.cyan(frames[i++ % frames.length])} ${render()}`))}`),
75
+ };
76
+ handle.timer = setInterval(handle.draw, 100);
77
+ handle.timer.unref?.();
78
+ live = handle;
79
+ handle.draw();
80
+ return handle;
81
+ },
82
+ stopLive() {
83
+ if (!live) return;
84
+ clearInterval(live.timer);
85
+ live = null;
86
+ io.stderr.write(CLEAR);
87
+ },
88
+ async ask(question, fallback = "") {
89
+ lines ??= lineReader(io.stdin);
90
+ io.stderr.write(safe(`${c.bold(question)}${fallback ? c.dim(` (${fallback})`) : ""}: `));
91
+ blank = false;
92
+ const line = await lines.next();
93
+ if (line === null) throw new UserError(t.inputEnded);
94
+ return line.trim() || fallback;
95
+ },
96
+ // Valinta numerolla; Enter = oletus.
97
+ async choose(question, options, def = 0) {
98
+ ctx.gap();
99
+ io.stderr.write(`${c.bold(question)}\n`);
100
+ options.forEach((opt, i) => io.stderr.write(safe(` ${c.cyan(`${i + 1})`)} ${opt}${i === def ? ` ${c.dim(t.defaultMark)}` : ""}\n`)));
101
+ for (;;) {
102
+ const v = await ctx.ask(">", String(def + 1));
103
+ const n = Number(v);
104
+ if (Number.isInteger(n) && n >= 1 && n <= options.length) return n - 1;
105
+ io.stderr.write(`${t.pickNumber(options.length)}\n`);
106
+ }
107
+ },
108
+ async confirm(question) {
109
+ const v = (await ctx.ask(`${question} [${t.yesNo}]`, t.yes)).toLowerCase();
110
+ return v === t.yes.toLowerCase() || v === "y" || v === "k" || v === "yes" || v === "kyllä";
111
+ },
112
+ close: () => lines?.close(),
113
+ api: (method, path, opts = {}) => call({ portal: ctx.portal, token: ctx.token, version, t }, method, path, { fetchImpl: ctx.fetch, ...opts }),
114
+ };
115
+ return ctx;
116
+ }
117
+
118
+ // Käyttäjälle näytettävä virhe ilman pinoa.
119
+ class UserError extends Error {}
120
+
121
+ export async function runCommand(ctx, command) {
122
+ ctx.gap();
123
+ try {
124
+ switch (command) {
125
+ case "login":
126
+ return await login(ctx);
127
+ case "logout":
128
+ return await logout(ctx);
129
+ case "whoami":
130
+ return await whoami(ctx);
131
+ case "projects":
132
+ return await projects(ctx);
133
+ case "init":
134
+ return await init(ctx);
135
+ case "link":
136
+ return await link(ctx);
137
+ case "push":
138
+ return await push(ctx);
139
+ case "promote":
140
+ return await promote(ctx);
141
+ case "open":
142
+ return await open(ctx);
143
+ default:
144
+ throw new UserError(ctx.t.unknown(command));
145
+ }
146
+ } catch (e) {
147
+ ctx.stopLive();
148
+ if (e instanceof UserError || e instanceof ApiError) {
149
+ ctx.gap();
150
+ ctx.err(`${ctx.c.red(ctx.c.bold(ctx.t.errorMark))} ${e.message}`);
151
+ return 1;
152
+ }
153
+ throw e;
154
+ } finally {
155
+ ctx.stopLive();
156
+ ctx.gap();
157
+ ctx.close();
158
+ }
159
+ }
160
+
161
+ const warn = (ctx, text) => ctx.err(`${ctx.c.yellow(ctx.c.bold(ctx.t.warnMark))} ${text}`);
162
+ const done = (ctx, text) => ctx.out(`${ctx.o.green("✓")} ${ctx.o.bold(text)}`);
163
+
164
+ function requireLogin(ctx) {
165
+ if (ctx.login?.invalid) throw new UserError(ctx.t.tokenInvalid);
166
+ if (!ctx.token) throw new UserError(ctx.t.notLoggedIn);
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------------------------------------
170
+ // login, logout, whoami
171
+
172
+ // Selaimen avauskomento. Windowsissa ei cmd /c start: cmd tulkitsee osoitteen &-merkin komentojen erottimeksi, joten osoite
173
+ // katkeaisi ja loppu ajettaisiin komentona. rundll32 saa osoitteen yhtenä argumenttina.
174
+ export function browserCommand(platform, url) {
175
+ if (platform === "darwin") return ["open", [url]];
176
+ if (platform === "win32") return ["rundll32", ["url.dll,FileProtocolHandler", url]];
177
+ return ["xdg-open", [url]];
178
+ }
179
+
180
+ function openBrowser(ctx, url) {
181
+ if (ctx.io.env.BOGGO_NO_BROWSER || !ctx.interactive) return false;
182
+ // Osoite voi tulla kansion .boggo-tiedostosta tai portaalista: vain verkko-osoitteet, ei file:// eikä muita ohjelmia avaavia.
183
+ if (!/^https?:\/\/\S+$/i.test(url)) return false;
184
+ const [cmd, args] = browserCommand(process.platform, url);
185
+ try {
186
+ const child = spawn(cmd, args, { stdio: "ignore", detached: true });
187
+ child.on("error", () => {});
188
+ child.unref();
189
+ return true;
190
+ } catch {
191
+ return false;
192
+ }
193
+ }
194
+
195
+ // Kirjautumisen reitit eivät vaadi kirjautumista eivätkä koskaan vastaa 401, 404 tai 405 (portaalin src/app/api/cli/laite).
196
+ // Sellainen vastaus tulee siis jostain muusta kuin CLI-rajapinnasta: portaalissa ei vielä ole komentoriviä (sen kirjautumis-
197
+ // tarkistus vastaa "Kirjaudu sisään."), tai BOGGO_URL osoittaa väärään paikkaan. Portaalin omat virheet (429, 410, 503) näytetään.
198
+ const NOT_CLI_STATUSES = [401, 404, 405];
199
+
200
+ function cliNotSupported(ctx) {
201
+ const { t } = ctx;
202
+ return new UserError(`${t.cliNotSupported(ctx.portal)}${ctx.portal !== SITE_URL ? ` ${t.checkPortalUrl}` : ""}`);
203
+ }
204
+
205
+ async function loginApi(ctx, path, body) {
206
+ try {
207
+ return await ctx.api("POST", path, { body });
208
+ } catch (e) {
209
+ if (e instanceof ApiError && NOT_CLI_STATUSES.includes(e.status)) throw cliNotSupported(ctx);
210
+ throw e;
211
+ }
212
+ }
213
+
214
+ async function login(ctx) {
215
+ const { t } = ctx;
216
+ if (ctx.login?.env) throw new UserError(ctx.login.invalid ? t.tokenInvalid : t.tokenFromEnv);
217
+ ctx.token = null;
218
+ const { data: start } = await loginApi(ctx, "/api/cli/laite", { nimi: deviceName() });
219
+ // Vastaus ilman laitekoodia ei ole CLI-rajapinnan (esim. HTML-sivu tilakoodilla 200).
220
+ if (typeof start.laitekoodi !== "string" || typeof start.kayttajakoodi !== "string" || typeof start.osoite !== "string") throw cliNotSupported(ctx);
221
+ ctx.err(t.loginOpen);
222
+ ctx.gap();
223
+ ctx.err(` ${ctx.c.underline(start.osoite)}`);
224
+ ctx.gap();
225
+ ctx.err(t.loginCode(ctx.c.bold(start.kayttajakoodi)));
226
+ openBrowser(ctx, start.osoite);
227
+ ctx.gap();
228
+ ctx.err(ctx.c.dim(t.loginWaiting));
229
+ const deadline = ctx.now() + (start.voimassa_s ?? 600) * 1000;
230
+ while (ctx.now() < deadline) {
231
+ await ctx.sleep((start.valit_s ?? 2) * 1000);
232
+ let res;
233
+ try {
234
+ res = await loginApi(ctx, "/api/cli/laite/tunnus", { laitekoodi: start.laitekoodi });
235
+ } catch (e) {
236
+ if (e instanceof ApiError && e.status === 0) continue;
237
+ throw e;
238
+ }
239
+ if (res.status === 202) continue;
240
+ if (!TOKEN_RE.test(res.data.tunnus ?? "")) throw cliNotSupported(ctx);
241
+ saveLogin(ctx.io.home, { tunnus: res.data.tunnus, portaali: ctx.portal, sahkoposti: res.data.kayttaja?.sahkoposti ?? "" });
242
+ ctx.gap();
243
+ done(ctx, t.loggedIn(res.data.kayttaja?.sahkoposti ?? ""));
244
+ ctx.gap();
245
+ ctx.out(t.nextInit);
246
+ return 0;
247
+ }
248
+ throw new UserError(t.loginExpired);
249
+ }
250
+
251
+ async function logout(ctx) {
252
+ const { t } = ctx;
253
+ if (ctx.login?.env) throw new UserError(ctx.login.invalid ? t.tokenInvalid : t.tokenFromEnv);
254
+ if (!ctx.token) {
255
+ ctx.out(t.notLoggedInShort);
256
+ return 0;
257
+ }
258
+ try {
259
+ await ctx.api("DELETE", "/api/cli/tunnus");
260
+ } catch (e) {
261
+ // Vanhentunut tai jo mitätöity tunnus: poistetaan silti koneelta.
262
+ if (!(e instanceof ApiError && e.status === 401)) warn(ctx, t.revokeFailed);
263
+ }
264
+ deleteLogin(ctx.io.home);
265
+ done(ctx, t.loggedOut);
266
+ return 0;
267
+ }
268
+
269
+ async function me(ctx) {
270
+ requireLogin(ctx);
271
+ return (await ctx.api("GET", "/api/cli/mina", { org: ctx.args.org })).data;
272
+ }
273
+
274
+ async function whoami(ctx) {
275
+ const m = await me(ctx);
276
+ if (ctx.args.json) {
277
+ ctx.raw(JSON.stringify(m, null, 2));
278
+ return 0;
279
+ }
280
+ const { o: paint } = ctx;
281
+ ctx.out(m.kayttaja.nimi ? `${paint.bold(m.kayttaja.nimi)} ${paint.dim(`<${m.kayttaja.sahkoposti}>`)}` : paint.bold(m.kayttaja.sahkoposti));
282
+ for (const org of m.organisaatiot) {
283
+ const current = org.tunnus === m.organisaatio;
284
+ ctx.out(` ${current ? paint.green("*") : " "} ${current ? paint.bold(org.nimi) : org.nimi} ${paint.dim(`(${org.tunnus}) · ${ctx.t.roles[org.rooli] ?? org.rooli}`)}`);
285
+ }
286
+ return 0;
287
+ }
288
+
289
+ // ---------------------------------------------------------------------------------------------------------
290
+ // Organisaatio ja projektit
291
+
292
+ // Organisaatio: --org, kansion yhteys, tai valinta, jos käyttäjä kuuluu useampaan.
293
+ async function pickOrg(ctx) {
294
+ if (ctx.args.org) return ctx.args.org;
295
+ const linked = readLink(ctx.cwd);
296
+ if (linked?.organisaatio) return linked.organisaatio;
297
+ const m = await me(ctx);
298
+ if (m.organisaatiot.length <= 1) return m.organisaatio;
299
+ // Ilman päätettä (CI) ei valita hiljaa oletusorganisaatiota: projekti voisi syntyä tai julkaisu mennä väärään organisaatioon.
300
+ if (!ctx.interactive) throw new UserError(ctx.t.needOrg(m.organisaatiot.map((o) => o.tunnus)));
301
+ const i = await ctx.choose(
302
+ ctx.t.pickOrg,
303
+ m.organisaatiot.map((o) => `${o.nimi} (${o.tunnus})`),
304
+ Math.max(0, m.organisaatiot.findIndex((o) => o.tunnus === m.organisaatio)),
305
+ );
306
+ return m.organisaatiot[i].tunnus;
307
+ }
308
+
309
+ async function projectList(ctx, org) {
310
+ return (await ctx.api("GET", "/api/cli/projektit", { org })).data;
311
+ }
312
+
313
+ async function projects(ctx) {
314
+ requireLogin(ctx);
315
+ const org = ctx.args.org ?? readLink(ctx.cwd)?.organisaatio;
316
+ const list = await projectList(ctx, org);
317
+ if (ctx.args.json) {
318
+ ctx.raw(JSON.stringify(list.projektit, null, 2));
319
+ return 0;
320
+ }
321
+ if (!list.projektit.length) {
322
+ ctx.out(ctx.t.noProjects);
323
+ return 0;
324
+ }
325
+ // Leveys ennen värejä: värikoodit eivät näy, mutta lasketaan merkkijonon pituuteen.
326
+ const { o } = ctx;
327
+ const stateColor = { valmis: o.green, luodaan: o.yellow, virhe: o.red };
328
+ const width = Math.max(...list.projektit.map((p) => p.nimi.length)) + 2;
329
+ for (const p of list.projektit) {
330
+ const state = (ctx.t.states[p.tila] ?? p.tila).padEnd(10);
331
+ ctx.out(` ${o.bold(p.nimi.padEnd(width))}${o.dim((ctx.t.kinds[p.tyyppi] ?? p.tyyppi).padEnd(12))}${(stateColor[p.tila] ?? String)(state)}${p.osoite ?? ""}`);
332
+ }
333
+ return 0;
334
+ }
335
+
336
+ // ---------------------------------------------------------------------------------------------------------
337
+ // init ja link
338
+
339
+ // Sovellus kansiosta portaalin säännöillä (sama kuin Tuo GitHubista). null = juuresta ei löytynyt.
340
+ async function detect(ctx, org) {
341
+ const { entries, detect: files } = collect(ctx.cwd);
342
+ const paths = entries.filter((e) => e.type === "file").map((e) => e.path);
343
+ const { data } = await ctx.api("POST", "/api/cli/tunnista", { org, body: { tiedostot: paths.slice(0, 20_000), sisallot: files } });
344
+ return data.sovellukset.find((a) => a.kansio === "") ?? null;
345
+ }
346
+
347
+ function saveAndTell(ctx, org, p) {
348
+ const gitignore = saveLink(ctx.cwd, { organisaatio: org, projekti: p.nimi, vmid: p.vmid, portaali: ctx.portal });
349
+ ctx.gap();
350
+ done(ctx, ctx.t.linked(p.nimi));
351
+ if (gitignore) ctx.out(ctx.o.dim(ctx.t.gitignoreAdded));
352
+ }
353
+
354
+ async function init(ctx) {
355
+ const { t } = ctx;
356
+ requireLogin(ctx);
357
+ const existing = readLink(ctx.cwd);
358
+ if (existing && !ctx.args.force) {
359
+ ctx.out(t.alreadyLinked(ctx.o.bold(existing.projekti)));
360
+ ctx.gap();
361
+ ctx.out(t.nextPush);
362
+ return 0;
363
+ }
364
+ const org = await pickOrg(ctx);
365
+ const app = await detect(ctx, org);
366
+ if (!app) throw new UserError(t.noApp);
367
+ ctx.err(t.found(ctx.c.bold(app.tyyppi)));
368
+
369
+ const list = await projectList(ctx, org);
370
+ const deployable = list.projektit.filter((p) => p.julkaistava);
371
+ if (!ctx.args.name && !ctx.args.yes && ctx.interactive && deployable.length) {
372
+ const i = await ctx.choose(t.newOrExisting, [t.newProject, t.existingProject], 0);
373
+ if (i === 1) return linkTo(ctx, org, deployable);
374
+ }
375
+
376
+ // Nimi: --name, kysymys tai kansion nimi; varattu nimi ei koskaan muutu hiljaa (portaalin sääntö).
377
+ let name = ctx.args.name ?? (ctx.interactive && !ctx.args.yes ? await ctx.ask(t.askName, suggestName(ctx.cwd)) : suggestName(ctx.cwd));
378
+ for (;;) {
379
+ const { data: n } = await ctx.api("GET", "/api/cli/nimi", { org, query: { nimi: name } });
380
+ if (n.vapaa) break;
381
+ const why = n.syy ?? t.nameTaken(name);
382
+ if (!ctx.interactive || ctx.args.name || ctx.args.yes) throw new UserError(`${why}${n.ehdotukset?.length ? ` ${t.suggestions(n.ehdotukset.join(", "))}` : ""}`);
383
+ warn(ctx, `${why}${n.ehdotukset?.length ? ` ${t.suggestions(n.ehdotukset.join(", "))}` : ""}`);
384
+ name = await ctx.ask(t.askName, n.ehdotukset?.[0] ?? "");
385
+ }
386
+
387
+ const uses = ["verkkosivu", "rajapinta"];
388
+ // Portaalin ehdotus voi olla jokin muu (esim. "muu" tai puuttuva); silloin oletus on Verkkosivu, jotta pelkkä Enter kelpaa.
389
+ let use = ctx.args.use ? normalizeUse(ctx.args.use) : uses.includes(app.kaytto) ? app.kaytto : "verkkosivu";
390
+ if (!use) throw new UserError(t.badUse);
391
+ if (!ctx.args.use && ctx.interactive && !ctx.args.yes) use = uses[await ctx.choose(t.askUse, [t.useSite, t.useApi], uses.indexOf(use))];
392
+
393
+ const sizes = list.koot ?? [];
394
+ let size = ctx.args.size ? normalizeSize(ctx.args.size) : "perus";
395
+ if (!size) throw new UserError(t.badSize);
396
+ if (!ctx.args.size && ctx.interactive && !ctx.args.yes && sizes.length)
397
+ size = sizes[await ctx.choose(t.askSize, sizes.map((s) => `${s.nimi} · ${s.kuvaus} · ${s.hinta}`), Math.max(0, sizes.findIndex((s) => s.id === size)))].id;
398
+ const chosen = sizes.find((s) => s.id === size);
399
+
400
+ if (ctx.interactive && !ctx.args.yes) {
401
+ ctx.gap();
402
+ if (!(await ctx.confirm(t.confirmCreate(name, chosen ? `${chosen.nimi}, ${chosen.hinta}` : size)))) {
403
+ ctx.out(t.cancelled);
404
+ return 1;
405
+ }
406
+ }
407
+ ctx.gap();
408
+ ctx.err(ctx.c.dim(t.creating(name)));
409
+ const { data: created } = await ctx.api("POST", "/api/cli/projektit", { org, body: { nimi: name, koko: size, kaytto: use }, timeoutMs: 300_000 });
410
+ done(ctx, t.created(created.nimi, created.osoite));
411
+ saveAndTell(ctx, org, { nimi: created.nimi, vmid: created.vmid });
412
+ ctx.gap();
413
+ ctx.out(t.nextPush);
414
+ return 0;
415
+ }
416
+
417
+ const normalizeUse = (v) => ({ verkkosivu: "verkkosivu", site: "verkkosivu", web: "verkkosivu", rajapinta: "rajapinta", api: "rajapinta" })[String(v).toLowerCase()] ?? null;
418
+ const normalizeSize = (v) => ({ pieni: "pieni", small: "pieni", perus: "perus", basic: "perus", iso: "iso", large: "iso" })[String(v).toLowerCase()] ?? null;
419
+
420
+ async function linkTo(ctx, org, deployable) {
421
+ const { t } = ctx;
422
+ let p;
423
+ if (ctx.args.project) {
424
+ p = deployable.find((x) => x.nimi === ctx.args.project);
425
+ if (!p) throw new UserError(t.projectNotDeployable(ctx.args.project));
426
+ } else {
427
+ if (!deployable.length) throw new UserError(t.noDeployable);
428
+ if (!ctx.interactive) throw new UserError(t.needProject);
429
+ p = deployable[await ctx.choose(t.pickProject, deployable.map((x) => `${x.nimi}${x.osoite ? ` · ${x.osoite}` : ""}`), 0)];
430
+ }
431
+ saveAndTell(ctx, org, p);
432
+ ctx.gap();
433
+ ctx.out(t.nextPush);
434
+ return 0;
435
+ }
436
+
437
+ async function link(ctx) {
438
+ requireLogin(ctx);
439
+ const org = await pickOrg(ctx);
440
+ const list = await projectList(ctx, org);
441
+ return linkTo(ctx, org, list.projektit.filter((p) => p.julkaistava));
442
+ }
443
+
444
+ // ---------------------------------------------------------------------------------------------------------
445
+ // push
446
+
447
+ // Kohde: --project (organisaation listalta) tai kansion yhteys; ilman niitä päätteessä init.
448
+ // noInit: komento (promote) ei aloita initiä yhdistämättömässä kansiossa.
449
+ async function target(ctx, { noInit = false } = {}) {
450
+ if (ctx.args.project) {
451
+ const org = await pickOrg(ctx);
452
+ const p = (await projectList(ctx, org)).projektit.find((x) => x.nimi === ctx.args.project);
453
+ if (!p) throw new UserError(ctx.t.projectNotFound(ctx.args.project));
454
+ return { org, projekti: p.nimi, vmid: p.vmid };
455
+ }
456
+ const linked = readLink(ctx.cwd);
457
+ // Toisen portaalin (esim. testiympäristön) projektinumero osoittaisi tässä portaalissa eri projektiin.
458
+ if (linked?.portaali && linked.portaali !== ctx.portal) throw new UserError(ctx.t.linkOtherPortal(linked.portaali, ctx.portal));
459
+ if (linked) return { org: linked.organisaatio, projekti: linked.projekti, vmid: linked.vmid };
460
+ if (!ctx.interactive || noInit) throw new UserError(ctx.t.notLinked);
461
+ ctx.err(ctx.t.notLinkedInit);
462
+ // init kertoo itse perumisen ("Peruttu."), joten tässä ei toista viestiä: null = push päättyy paluukoodiin 1.
463
+ if ((await init(ctx)) !== 0) return null;
464
+ const now = readLink(ctx.cwd);
465
+ return { org: now.organisaatio, projekti: now.projekti, vmid: now.vmid };
466
+ }
467
+
468
+ const STAGES = ["jonossa", "haetaan", "rakennetaan", "siirretaan", "kaynnistetaan"];
469
+
470
+ // Kesto lyhyesti: 42 s, 3 min 05 s.
471
+ function duration(ms) {
472
+ const s = Math.max(0, Math.round(ms / 1000));
473
+ return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${String(s % 60).padStart(2, "0")} s`;
474
+ }
475
+
476
+ // Edistymispalkki: täytetty osa syaanilla, loput himmeänä.
477
+ function progressBar(c, ratio, width = 24) {
478
+ const full = Math.round(Math.min(1, Math.max(0, ratio)) * width);
479
+ return `${c.cyan("━".repeat(full))}${c.dim("─".repeat(width - full))}`;
480
+ }
481
+ const FOLLOW_MAX_MS = 45 * 60_000;
482
+ const CONNECTION_LOST_MS = 5 * 60_000;
483
+
484
+ async function push(ctx) {
485
+ const { t } = ctx;
486
+ requireLogin(ctx);
487
+ const prod = Boolean(ctx.args.prod);
488
+ const dest = await target(ctx);
489
+ if (!dest) return 1;
490
+
491
+ const { entries, skipped, unreadable } = collect(ctx.cwd);
492
+ if (unreadable.length) throw new UserError(t.unreadable(unreadable.slice(0, 5).map((u) => `${u.path} (${u.code})`), unreadable.length));
493
+ const files = entries.filter((e) => e.type === "file");
494
+ if (!files.length) throw new UserError(t.emptyFolder);
495
+ for (const s of skipped) warn(ctx, s.reason === "size" ? t.skippedBig(s.path, sizeText(s.size, ctx.lang)) : t.skippedLink(s.path));
496
+ let pkg;
497
+ try {
498
+ pkg = await packEntries(entries);
499
+ } catch (e) {
500
+ if (e.code === "too_big") throw new UserError(t.tooBig(sizeText(UPLOAD_MAX_BYTES, ctx.lang)));
501
+ if (e.code === "unreadable") throw new UserError(t.unreadable([`${e.path} (${e.reason})`], 1));
502
+ throw e;
503
+ }
504
+ ctx.err(t.uploading(files.length, sizeText(pkg.length, ctx.lang), ctx.c.bold(dest.projekti)));
505
+ // Päätteessä palkki: lähetetty osuus ja määrä; kun kaikki on lähetetty, Boggo Cloud vielä tarkistaa paketin ennen vastausta.
506
+ let sent = 0;
507
+ const total = pkg.length;
508
+ const progress = ctx.startLive(
509
+ () =>
510
+ sent < total
511
+ ? `${progressBar(ctx.c, sent / total)} ${Math.floor((sent / total) * 100)} % · ${sizeText(sent, ctx.lang)} / ${sizeText(total, ctx.lang)}`
512
+ : `${progressBar(ctx.c, 1)} 100 % · ${ctx.c.dim(t.uploadChecking)}`,
513
+ { indent: " " },
514
+ );
515
+
516
+ // Uusi projekti voi olla vielä luonnissa: odotetaan enintään 5 min.
517
+ let started;
518
+ const until = ctx.now() + 5 * 60_000;
519
+ const deploymentsUrl = `${ctx.portal}/${dest.projekti}/julkaisut`;
520
+ for (;;) {
521
+ try {
522
+ started = (
523
+ await ctx.api("POST", `/api/cli/projektit/${dest.vmid}/julkaisut`, {
524
+ org: dest.org,
525
+ body: pkg,
526
+ query: { tuotanto: prod ? 1 : undefined },
527
+ timeoutMs: uploadTimeoutMs(pkg.length),
528
+ onProgress: progress ? (n) => (sent = n) : undefined,
529
+ })
530
+ ).data;
531
+ break;
532
+ } catch (e) {
533
+ // Aikaraja: paketti voi olla jo perillä ja julkaisu alkanut, joten ei lähetetä uudelleen vaan ohjataan tarkistamaan.
534
+ if (e instanceof ApiError && e.status === 0 && e.data?.timeout) throw new UserError(t.uploadTimedOut(deploymentsUrl));
535
+ // Projekti luonnissa: portaalin koodi syy = luonti_kesken (vanhempi portaali: tunnistus tekstistä).
536
+ if (e instanceof ApiError && e.status === 409 && (e.data?.syy === "luonti_kesken" || (!e.data?.syy && /valmis|ready/i.test(e.message))) && ctx.now() < until) {
537
+ ctx.err(ctx.c.dim(t.waitingCreate));
538
+ await ctx.sleep(10_000);
539
+ continue;
540
+ }
541
+ throw e;
542
+ }
543
+ }
544
+ ctx.stopLive();
545
+ const label = prod ? t.deployment(started.numero) : t.build(started.numero);
546
+ ctx.err(t.queued(ctx.c.bold(label), started.sovellus));
547
+ ctx.gap();
548
+ return follow(ctx, dest, started.numero, prod, started.osoite);
549
+ }
550
+
551
+ // Seuraa julkaisua tai rakennusta numerolla, kunnes se päättyy (push ja promote). Paluukoodi 0 = onnistui.
552
+ async function follow(ctx, dest, numero, prod, address) {
553
+ const { t } = ctx;
554
+ const deploymentsUrl = `${ctx.portal}/${dest.projekti}/julkaisut`;
555
+
556
+ // Seuranta: uusi vaihe kerran, aika vaiheen alusta. Seuranta päättyy aina: julkaisu kestää yli FOLLOW_MAX_MS tai
557
+ // Boggo Cloudiin ei saada yhteyttä CONNECTION_LOST_MS:ään. Kummassakin paluukoodi on 1, koska julkaisun tulos ei ole
558
+ // tiedossa (CI ei saa tulkita sitä onnistumiseksi).
559
+ const shown = new Set();
560
+ const began = ctx.now();
561
+ const followUrl = deploymentsUrl;
562
+ let lastOk = began;
563
+ let d;
564
+ // Päätteessä käynnissä oleva vaihe elävänä rivinä (kesto kasvaa) ja valmis vaihe ✓-rivinä kestoineen; muualla vaihe kerran.
565
+ let current = null;
566
+ const stageName = (vaihe) => t.stages[vaihe] ?? vaihe;
567
+ const live = ctx.startLive(() => `${stageName(current?.vaihe ?? "jonossa")}… ${ctx.c.dim(duration(ctx.now() - (current?.seen ?? began)))}`, { indent: " " });
568
+ // Päättynyt vaihe ✓- tai ✗-rivinä. Kutsuja vaihtaa elävän rivin vaiheen ensin, jotta rivin alle ei piirry vanha vaihe.
569
+ const finishStage = (stage, ok) => {
570
+ if (!stage) return;
571
+ // Kesto portaalin aikaleimoista, jos vaihe on niissä päättynyt; muuten siitä, kun vaihe nähtiin.
572
+ const step = (d?.steps ?? []).find((s) => s.vaihe === stage.vaihe);
573
+ const server = step?.paattyi ? Date.parse(step.paattyi) - Date.parse(step.alkoi) : NaN;
574
+ const ms = Number.isFinite(server) && server >= 0 ? server : ctx.now() - stage.seen;
575
+ ctx.err(` ${ok ? ctx.c.green("✓") : ctx.c.red("✗")} ${stageName(stage.vaihe)} ${ctx.c.dim(duration(ms))}`);
576
+ };
577
+ for (;;) {
578
+ await ctx.sleep(2000);
579
+ if (ctx.now() - began > FOLLOW_MAX_MS) {
580
+ ctx.stopLive();
581
+ ctx.gap();
582
+ warn(ctx, t.stillRunning(followUrl));
583
+ return 1;
584
+ }
585
+ try {
586
+ d = (await ctx.api("GET", `/api/cli/projektit/${dest.vmid}/julkaisut/${numero}`, { org: dest.org })).data;
587
+ lastOk = ctx.now();
588
+ } catch (e) {
589
+ if (!(e instanceof ApiError && (e.status === 0 || e.status >= 500))) throw e;
590
+ if (ctx.now() - lastOk > CONNECTION_LOST_MS) {
591
+ ctx.stopLive();
592
+ ctx.gap();
593
+ warn(ctx, t.lostTrack(followUrl));
594
+ return 1;
595
+ }
596
+ continue;
597
+ }
598
+ for (const s of d.steps ?? []) {
599
+ if (shown.has(s.vaihe) || !STAGES.includes(s.vaihe)) continue;
600
+ shown.add(s.vaihe);
601
+ if (!live) {
602
+ ctx.err(` ${ctx.c.cyan("›")} ${stageName(s.vaihe)}…`);
603
+ continue;
604
+ }
605
+ const previous = current;
606
+ current = { vaihe: s.vaihe, seen: ctx.now() };
607
+ finishStage(previous, true);
608
+ }
609
+ const status = d.deployment.status;
610
+ if (status === "valmis" || status === "epaonnistui" || status === "korvattu") break;
611
+ }
612
+ ctx.stopLive();
613
+ if (live) finishStage(current, d.deployment.status === "valmis");
614
+ const secs = Math.round((ctx.now() - began) / 1000);
615
+ ctx.gap();
616
+ if (d.deployment.status === "valmis") {
617
+ if (prod) {
618
+ done(ctx, t.deployed(secs));
619
+ if (address) ctx.out(` ${ctx.o.underline(address)}`);
620
+ } else {
621
+ done(ctx, t.built(secs));
622
+ ctx.gap();
623
+ // Portaali kertoo, voiko rakennuksen julkaista sellaisenaan (rakentajan sopimus luku 9); muuten uusi rakennus --prodilla.
624
+ if (d.deployment.promote) {
625
+ rememberBuild(ctx, dest, numero);
626
+ ctx.out(t.nextPromote);
627
+ } else ctx.out(t.nextProd);
628
+ }
629
+ return 0;
630
+ }
631
+ if (d.deployment.status === "korvattu") {
632
+ warn(ctx, t.replaced);
633
+ return 1;
634
+ }
635
+ ctx.err(`${ctx.c.red(ctx.c.bold(t.errorMark))} ${d.deployment.error ?? t.failed}`);
636
+ // Rakennuksen loki kehittäjälle (portaali antaa sen vain kehittäjän roolilla): viimeiset rivit.
637
+ const lines = (d.log ?? []).filter((l) => l.taso !== "info" || l.vaihe === "rakennetaan" || l.lahde === "sovellus").slice(-25);
638
+ if (lines.length) {
639
+ ctx.gap();
640
+ for (const l of lines) ctx.err(` ${l.taso === "virhe" ? ctx.c.red(l.teksti) : ctx.c.dim(l.teksti)}`);
641
+ }
642
+ ctx.gap();
643
+ ctx.err(t.seeLog(`${ctx.portal}/${dest.projekti}/julkaisut`));
644
+ return 1;
645
+ }
646
+
647
+ // ---------------------------------------------------------------------------------------------------------
648
+ // promote
649
+
650
+ // Viimeisin julkaistavissa oleva rakennus kansion yhteyteen (.boggo/projekti.json), jotta boggo promote löytää sen ilman numeroa.
651
+ function rememberBuild(ctx, dest, numero) {
652
+ const linked = readLink(ctx.cwd);
653
+ if (!linked || linked.vmid !== dest.vmid) return;
654
+ try {
655
+ saveLink(ctx.cwd, { ...linked, rakennus: numero });
656
+ } catch {
657
+ /* ei estä mitään: boggo promote <numero> toimii silti */
658
+ }
659
+ }
660
+
661
+ // boggo promote [numero]: julkaisee onnistuneen rakennuksen (boggo push) tuotantoon ilman uutta rakennusta. Ilman numeroa kansion
662
+ // viimeisin rakennus. Julkiset muuttujat (NEXT_PUBLIC_, VITE_) ovat rakennuksessa: jos ne ovat muuttuneet, kysytään (tai --force).
663
+ async function promote(ctx) {
664
+ const { t } = ctx;
665
+ requireLogin(ctx);
666
+ const given = ctx.args.positionals?.[0];
667
+ if (given !== undefined && !/^[1-9]\d{0,8}$/.test(given)) throw new UserError(t.badBuildNumber(given));
668
+ const dest = await target(ctx, { noInit: true });
669
+ if (!dest) return 1;
670
+ const linked = readLink(ctx.cwd);
671
+ const numero = given !== undefined ? Number(given) : linked?.vmid === dest.vmid ? linked.rakennus : undefined;
672
+ if (!Number.isSafeInteger(numero) || numero <= 0) throw new UserError(t.noBuild);
673
+ let started;
674
+ let force = Boolean(ctx.args.force);
675
+ for (;;) {
676
+ try {
677
+ started = (
678
+ await ctx.api("POST", `/api/cli/projektit/${dest.vmid}/julkaisut/${numero}`, { org: dest.org, body: force ? { pakota: true } : {} })
679
+ ).data;
680
+ break;
681
+ } catch (e) {
682
+ if (!(e instanceof ApiError && e.status === 409 && e.data?.muuttujat === "muuttuneet") || force) throw e;
683
+ warn(ctx, e.message);
684
+ if (!ctx.interactive) throw new UserError(t.varsChangedForce);
685
+ if (!(await ctx.confirm(t.promoteAnyway))) {
686
+ ctx.out(t.cancelled);
687
+ return 1;
688
+ }
689
+ force = true;
690
+ }
691
+ }
692
+ ctx.err(t.promoting(ctx.c.bold(t.build(numero)), ctx.c.bold(t.deployment(started.numero))));
693
+ ctx.gap();
694
+ return follow(ctx, dest, started.numero, true, started.osoite);
695
+ }
696
+
697
+ // ---------------------------------------------------------------------------------------------------------
698
+ // open
699
+
700
+ async function open(ctx) {
701
+ const linked = readLink(ctx.cwd);
702
+ const name = ctx.args.project ?? linked?.projekti;
703
+ if (!name) throw new UserError(ctx.t.notLinked);
704
+ let url;
705
+ if (ctx.args.portal) url = `${linked?.portaali ?? ctx.portal}/${name}`;
706
+ else {
707
+ requireLogin(ctx);
708
+ const p = (await projectList(ctx, ctx.args.org ?? linked?.organisaatio)).projektit.find((x) => x.nimi === name);
709
+ if (!p) throw new UserError(ctx.t.projectNotFound(name));
710
+ if (!p.osoite) throw new UserError(ctx.t.noAddress(name));
711
+ url = p.osoite;
712
+ }
713
+ ctx.out(url);
714
+ openBrowser(ctx, url);
715
+ return 0;
716
+ }