layero 0.11.18 → 0.11.19
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/dist/agent.js +5 -0
- package/dist/api.js +18 -0
- package/dist/commands/data-api.js +36 -2
- package/dist/commands/data-probe.js +4 -1
- package/dist/commands/db.js +9 -2
- package/dist/commands/env.js +10 -2
- package/dist/detect.js +4 -0
- package/dist/logs.js +25 -4
- package/package.json +1 -1
package/dist/agent.js
CHANGED
|
@@ -142,6 +142,11 @@ function renderHuman(event) {
|
|
|
142
142
|
process.stdout.write(` → ${event.next_action}\n`);
|
|
143
143
|
for (const w of event.layero_warnings ?? [])
|
|
144
144
|
process.stdout.write(`! ${w}\n`);
|
|
145
|
+
if (event.skipped_build_script) {
|
|
146
|
+
process.stderr.write(`\n⚠ Это статика: скрипт сборки «${event.skipped_build_script}» из package.json НЕ запустится,\n` +
|
|
147
|
+
" файлы уйдут как есть. Если сайт надо собрать, добавьте layero.json:\n" +
|
|
148
|
+
' {"framework":"generic","buildCommand":"npm run build","outputDirectory":"<папка с index.html после сборки>"}\n\n');
|
|
149
|
+
}
|
|
145
150
|
break;
|
|
146
151
|
case "plan": {
|
|
147
152
|
const src = event.sources;
|
package/dist/api.js
CHANGED
|
@@ -74,7 +74,17 @@ export class ApiClient {
|
|
|
74
74
|
listOrganizations() {
|
|
75
75
|
return this.request("GET", "/organizations");
|
|
76
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* Проект по идентификатору; слаг уходит в `resolveProject`.
|
|
79
|
+
*
|
|
80
|
+
* 🚨 Справки `env`, `domains`, `perf`, `analytics`, `db` обещают
|
|
81
|
+
* `--project <id|slug>`, а слаг уезжал в путь как есть: сырой 422 «Input
|
|
82
|
+
* should be a valid UUID», и деплой следом собирался без переменных (G-10,
|
|
83
|
+
* 26.10). Резолв по форме — здесь, один раз для всех команд.
|
|
84
|
+
*/
|
|
77
85
|
getProject(idOrSlug) {
|
|
86
|
+
if (!looksLikeId(idOrSlug))
|
|
87
|
+
return this.resolveProject(idOrSlug);
|
|
78
88
|
return this.request("GET", `/projects/${idOrSlug}`);
|
|
79
89
|
}
|
|
80
90
|
/**
|
|
@@ -305,6 +315,14 @@ export class ApiClient {
|
|
|
305
315
|
setDataLevels(org, dbId, input) {
|
|
306
316
|
return this.request("POST", `/organizations/${org}/databases/${dbId}/api/levels`, input);
|
|
307
317
|
}
|
|
318
|
+
/** Вход (схема `auth`, `auth.uid()`) — та же ручка, что у кнопки панели (G-05). */
|
|
319
|
+
enableDataAuth(org, dbId) {
|
|
320
|
+
return this.request("POST", `/organizations/${org}/databases/${dbId}/api/auth/enable`, {});
|
|
321
|
+
}
|
|
322
|
+
/** Файлы (схема `storage`) — та же ручка, что у кнопки панели (G-05). */
|
|
323
|
+
enableDataStorage(org, dbId) {
|
|
324
|
+
return this.request("POST", `/organizations/${org}/databases/${dbId}/api/storage/enable`);
|
|
325
|
+
}
|
|
308
326
|
enableDataApi(org, dbId, withSecret) {
|
|
309
327
|
return this.request("POST", `/organizations/${org}/databases/${dbId}/api/enable?with_secret=${withSecret ? "true" : "false"}`);
|
|
310
328
|
}
|
|
@@ -305,8 +305,12 @@ export async function dataMethodsCmd(opts) {
|
|
|
305
305
|
if (res.tables.length)
|
|
306
306
|
console.log(chalk.bold("REST"));
|
|
307
307
|
for (const t of res.tables) {
|
|
308
|
+
// Право на часть колонок — рядом с уровнем (G-09): уровень честный, но
|
|
309
|
+
// писать можно не всё; панель зовёт это «частичный доступ».
|
|
310
|
+
const partly = new Set(t.column_only ?? []);
|
|
308
311
|
const levels = Object.entries(t.levels)
|
|
309
|
-
.map(([m, l]) => `${m} ${l === "closed" ? chalk.dim(LEVEL_WORD[l]) : LEVEL_WORD[l] ?? l}`
|
|
312
|
+
.map(([m, l]) => `${m} ${l === "closed" ? chalk.dim(LEVEL_WORD[l]) : LEVEL_WORD[l] ?? l}` +
|
|
313
|
+
(partly.has(m) ? chalk.dim(" (часть колонок)") : ""))
|
|
310
314
|
.join(" · ");
|
|
311
315
|
const view = t.kind === "view" ? chalk.dim(" (представление)") : "";
|
|
312
316
|
const profile = t.shadowed_by
|
|
@@ -465,11 +469,36 @@ const REPAIR_LOSS = "роли Data API и права по умолчанию б
|
|
|
465
469
|
* именно его советуют отказы «роли Data API в базе нет — включите API заново». Он
|
|
466
470
|
* требует явного `--db` и подтверждения с предупреждением о `public`.
|
|
467
471
|
*/
|
|
472
|
+
/** Вход и файлы базы — ручками панели. `quiet` — итог печатает включение API. */
|
|
473
|
+
async function enableExtras(api, org, db, ref, opts, quiet = false) {
|
|
474
|
+
if (opts.auth)
|
|
475
|
+
await api.enableDataAuth(org, db.id);
|
|
476
|
+
if (opts.storage)
|
|
477
|
+
await api.enableDataStorage(org, db.id);
|
|
478
|
+
if (asJson(opts)) {
|
|
479
|
+
emit({ event: "data_services_enabled", org, database: ref, auth: Boolean(opts.auth), storage: Boolean(opts.storage) });
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
if (quiet && !opts.auth && !opts.storage)
|
|
483
|
+
return;
|
|
484
|
+
if (opts.auth) {
|
|
485
|
+
console.log(`${chalk.green("✓")} вход включён у базы «${db.name}»: схема auth и auth.uid() появились — миграции с политиками можно гнать`);
|
|
486
|
+
}
|
|
487
|
+
if (opts.storage) {
|
|
488
|
+
console.log(`${chalk.green("✓")} файлы включены у базы «${db.name}»: схема storage, бакеты — в панели или SQL (storage.buckets)`);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
468
491
|
export async function dataEnableCmd(opts) {
|
|
469
492
|
if (opts.repair && !opts.db) {
|
|
470
493
|
throw new LayeroError("database_unknown", `переприменение Data API меняет умолчания прав у ролей базы — базу нужно указать явно`, "layero data enable --db <база> --repair");
|
|
471
494
|
}
|
|
472
495
|
const { api, org, db, ref } = await target(opts, "enable");
|
|
496
|
+
// Вход и файлы — тем же шагом (G-05, 26.10): миграция с `auth.uid()` в
|
|
497
|
+
// политиках иначе требовала кликов в панели, и стенд не описывался кодом.
|
|
498
|
+
if (db.api_enabled && !opts.repair && (opts.auth || opts.storage)) {
|
|
499
|
+
await enableExtras(api, org, db, ref, opts);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
473
502
|
if (db.api_enabled && !opts.repair) {
|
|
474
503
|
throw new LayeroError("data_api_already_enabled", `у базы «${db.name}» Data API уже включён — повторное включение ничего не выпускает, а ${REPAIR_LOSS}`,
|
|
475
504
|
// `--with-secret` здесь ничего не выпустит: секретный ключ выпускается отдельной командой.
|
|
@@ -491,6 +520,8 @@ export async function dataEnableCmd(opts) {
|
|
|
491
520
|
}
|
|
492
521
|
}
|
|
493
522
|
const res = await api.enableDataApi(org, db.id, Boolean(opts.withSecret));
|
|
523
|
+
if (opts.auth || opts.storage)
|
|
524
|
+
await enableExtras(api, org, db, ref, opts, true);
|
|
494
525
|
const publicKey = res.key?.key ?? null;
|
|
495
526
|
const secretKey = res.secret_key?.key ?? null;
|
|
496
527
|
const reapplied = Boolean(opts.repair);
|
|
@@ -541,7 +572,8 @@ export async function dataEnableCmd(opts) {
|
|
|
541
572
|
console.log(chalk.dim(` ключи уже были — список: layero data keys list --db ${ref}`));
|
|
542
573
|
if (!reapplied) {
|
|
543
574
|
console.log(chalk.dim("\n Как в Supabase: новые таблицы public открыты ролям, строки решает RLS — включайте его у " +
|
|
544
|
-
"каждой таблицы. Что открыто: layero data methods"
|
|
575
|
+
"каждой таблицы. Что открыто: layero data methods\n" +
|
|
576
|
+
` Вход (auth.uid() в политиках) и файлы: layero data enable --db ${shellArg(ref)} --auth --storage`));
|
|
545
577
|
}
|
|
546
578
|
}
|
|
547
579
|
/**
|
|
@@ -604,6 +636,8 @@ export function registerDataApiCommands(data, program) {
|
|
|
604
636
|
.description("Enable the Data API for a database: sets up the api schema and roles, issues a public key. " +
|
|
605
637
|
"As in Supabase, new tables, sequences and functions in public are open to the API roles; rows are decided by RLS.")
|
|
606
638
|
.option("--with-secret", "also issue a secret key for the server")
|
|
639
|
+
.option("--auth", "also enable sign-in: the auth schema and auth.uid() for RLS policies")
|
|
640
|
+
.option("--storage", "also enable files: the storage schema (buckets, storage.objects)")
|
|
607
641
|
.option("--repair", "re-apply the roles and the api schema for a database whose Data API is already enabled; table grants are kept, default privileges for new tables are removed")
|
|
608
642
|
.option("-y, --yes", "do not ask for confirmation for --repair")).action(async (opts) => dataEnableCmd(json(opts)));
|
|
609
643
|
registerDataProbeCommand(data, withDb, json);
|
|
@@ -525,7 +525,9 @@ export function registerDataProbeCommand(data, withDb, json) {
|
|
|
525
525
|
.option("--body-file <file>", "body from a JSON file")
|
|
526
526
|
.option("--schema <schema>", "table schema: api, public or app; without the flag the gateway looks in api, then public, then app")
|
|
527
527
|
.option("--expect <status>", "expected status: 200, 2xx or a comma-separated list; a mismatch is an error")
|
|
528
|
-
.addHelpText("after", "\nPaths: /rest/v1/<table>, /rest/v1/rpc/<function> (GET or POST), /whoami (GET only)
|
|
528
|
+
.addHelpText("after", "\nPaths: /rest/v1/<table>, /rest/v1/rpc/<function> (GET or POST), /whoami (GET only),\n" +
|
|
529
|
+
"files without writing: POST /storage/v1/object/list/<bucket>, GET /storage/v1/object/info/<bucket>/<path>,\n" +
|
|
530
|
+
"POST /storage/v1/object/sign/<bucket>/<path> (read), POST /storage/v1/object/upload/sign/<bucket>/<path> (may upload?).\n" +
|
|
529
531
|
"Pass parameters as --query flags, not with a \"?\" in the path.\n" +
|
|
530
532
|
"\nExamples:\n" +
|
|
531
533
|
" $ layero data probe GET /rest/v1/products --query select=id,title --query limit=5\n" +
|
|
@@ -533,6 +535,7 @@ export function registerDataProbeCommand(data, withDb, json) {
|
|
|
533
535
|
" $ layero data probe POST /rest/v1/rpc/order_create --body-file order.json --as server\n" +
|
|
534
536
|
" $ layero data probe GET /rest/v1/orders --expect 401,403 # is it closed to visitors?\n" +
|
|
535
537
|
" $ layero data probe GET /whoami\n" +
|
|
538
|
+
" $ layero data probe POST /storage/v1/object/list/avatars --as user --user <id> # whose files are visible\n" +
|
|
536
539
|
`\nWrites are rolled back. Not rolled back: ${NOT_UNDONE_HELP}.\n` +
|
|
537
540
|
"\nExit code, decided in this order:\n" +
|
|
538
541
|
" 1. the write rollback was not confirmed — error data_probe_not_rolled_back;\n" +
|
package/dist/commands/db.js
CHANGED
|
@@ -247,9 +247,16 @@ export async function dbConnectCmd(ref, opts) {
|
|
|
247
247
|
// из `userdb_roles`. Пока здесь говорилось только про переменные, человек,
|
|
248
248
|
// у которого сайт отбивался по CORS, не имел ни одной причины связать это со
|
|
249
249
|
// своей ненажатой командой — а отказ шлюза именно её и советует.
|
|
250
|
+
// 🚨 Что именно приедет и куда (G-11, 26.10). Клиент со статическим сайтом
|
|
251
|
+
// увидел в переменных строку с паролем, не увидел ключей Data API и положил
|
|
252
|
+
// их руками. А строка подключения в сборку не попадает вовсе — только в
|
|
253
|
+
// контейнер серверного приложения, — адрес и ключ платформа кладёт в сборку сама.
|
|
250
254
|
console.log(`${chalk.green("✓")} проект «${project.slug}» подключён к базе «${db.name}»\n` +
|
|
251
|
-
chalk.dim(
|
|
252
|
-
chalk.dim(
|
|
255
|
+
chalk.dim(` домены проекта разрешены для Data API базы «${db.name}»\n`) +
|
|
256
|
+
chalk.dim(" в сборку сайта платформа сама положит адрес и публичный ключ Data API:\n") +
|
|
257
|
+
chalk.dim(" VITE_LAYERO_DATA_URL / VITE_LAYERO_DATA_KEY (для Next.js — NEXT_PUBLIC_LAYERO_DATA_…);\n") +
|
|
258
|
+
chalk.dim(" у сайта без сборки — файл /layero-data.js. Класть их через env set не нужно\n") +
|
|
259
|
+
chalk.dim(" строка подключения с паролем — только серверному коду, в сборку и в браузер не попадает"));
|
|
253
260
|
}
|
|
254
261
|
export async function dbDisconnectCmd(ref, opts) {
|
|
255
262
|
// 🚨 ОБРАТНОГО ДЕЙСТВИЯ НЕ БЫЛО ВОВСЕ. `db connect` существовал с самого
|
package/dist/commands/env.js
CHANGED
|
@@ -24,7 +24,14 @@ export async function envListCmd(opts) {
|
|
|
24
24
|
emit({
|
|
25
25
|
event: "env_vars",
|
|
26
26
|
project: project.slug,
|
|
27
|
-
vars: rows.map((r) => ({
|
|
27
|
+
vars: rows.map((r) => ({
|
|
28
|
+
key: r.key,
|
|
29
|
+
length: r.length,
|
|
30
|
+
managed: !!r.managed,
|
|
31
|
+
// Куда платформа кладёт свою переменную (G-11): `runtime` — только в
|
|
32
|
+
// контейнер сервера, в сборку не попадает; `build` — в сборку сайта.
|
|
33
|
+
...(r.managed ? { scope: r.scope ?? null } : {}),
|
|
34
|
+
})),
|
|
28
35
|
});
|
|
29
36
|
return;
|
|
30
37
|
}
|
|
@@ -38,8 +45,9 @@ export async function envListCmd(opts) {
|
|
|
38
45
|
// базе — часть ответа. Но менять её нельзя: она пересобирается из связи
|
|
39
46
|
// проекта с базой, и предложить правку значило бы пообещать несбыточное.
|
|
40
47
|
for (const r of rows) {
|
|
48
|
+
const where = r.scope === "build" ? ", в сборку сайта" : r.scope === "runtime" ? ", только серверу — в сборку не попадает" : "";
|
|
41
49
|
const tail = r.managed
|
|
42
|
-
? chalk.dim(` (${r.length} симв., ставит
|
|
50
|
+
? chalk.dim(` (${r.length} симв., ставит платформа${where})`)
|
|
43
51
|
: chalk.dim(` (${r.length} симв.)`);
|
|
44
52
|
console.log(`${r.key}${tail}`);
|
|
45
53
|
}
|
package/dist/detect.js
CHANGED
|
@@ -665,6 +665,7 @@ async function detectFromSnapshot(cwd, snap, opts) {
|
|
|
665
665
|
let confident = declared || plan.confident;
|
|
666
666
|
let shape = null;
|
|
667
667
|
const notes = [];
|
|
668
|
+
let skippedBuild = null;
|
|
668
669
|
let flagNextAction;
|
|
669
670
|
if (framework === "static") {
|
|
670
671
|
// Статика не собирается НИКОГДА: команда сборки у неё не «true», а
|
|
@@ -678,6 +679,7 @@ async function detectFromSnapshot(cwd, snap, opts) {
|
|
|
678
679
|
if (await rootHasIndexHtml(cwd)) {
|
|
679
680
|
confident = true;
|
|
680
681
|
if (buildScript && !declared) {
|
|
682
|
+
skippedBuild = buildScript;
|
|
681
683
|
notes.push(`package.json has a build script (\`${buildScript}\`), but a static site is served as it is and the script is not run. ` +
|
|
682
684
|
'If it must run: layero.json {"framework":"generic","buildCommand":"npm run build","outputDirectory":"<folder>"}.');
|
|
683
685
|
}
|
|
@@ -761,6 +763,7 @@ async function detectFromSnapshot(cwd, snap, opts) {
|
|
|
761
763
|
...(shape?.next_action ?? flagNextAction ? { next_action: shape?.next_action ?? flagNextAction } : {}),
|
|
762
764
|
...(shape?.candidates?.length ? { candidates: shape.candidates } : {}),
|
|
763
765
|
...(warning ? { ssr_warning: warning } : {}),
|
|
766
|
+
...(skippedBuild ? { skipped_build_script: skippedBuild } : {}),
|
|
764
767
|
};
|
|
765
768
|
}
|
|
766
769
|
/** Событие `detected` — одно на `init`, `deploy` и `deploy --dry-run`. */
|
|
@@ -778,5 +781,6 @@ export function detectedEvent(d) {
|
|
|
778
781
|
...(d.candidates?.length ? { candidates: d.candidates } : {}),
|
|
779
782
|
...(d.ssr_warning ? { ssr_warning: d.ssr_warning } : {}),
|
|
780
783
|
...(d.layero_warnings?.length ? { layero_warnings: d.layero_warnings } : {}),
|
|
784
|
+
...(d.skipped_build_script ? { skipped_build_script: d.skipped_build_script } : {}),
|
|
781
785
|
};
|
|
782
786
|
}
|
package/dist/logs.js
CHANGED
|
@@ -60,6 +60,7 @@ export async function streamDeployLogs(api, deployId) {
|
|
|
60
60
|
const announced = new Set();
|
|
61
61
|
const startedAt = Date.now();
|
|
62
62
|
let lastQueuedAt = startedAt;
|
|
63
|
+
let queueShown = false;
|
|
63
64
|
const sleep = (ms) => new Promise((res) => setTimeout(res, retryDelayScale() * ms));
|
|
64
65
|
const announce = (name) => {
|
|
65
66
|
if (name === lastStage || announced.has(name))
|
|
@@ -120,12 +121,32 @@ export async function streamDeployLogs(api, deployId) {
|
|
|
120
121
|
}
|
|
121
122
|
if (poll.current_stage)
|
|
122
123
|
announce(poll.current_stage);
|
|
123
|
-
if (
|
|
124
|
-
poll.status === "queued" &&
|
|
124
|
+
if (poll.status === "queued" &&
|
|
125
125
|
announced.size === 0 &&
|
|
126
|
-
Date.now() - lastQueuedAt >= QUEUED_EVERY_MS) {
|
|
126
|
+
(Date.now() - lastQueuedAt >= QUEUED_EVERY_MS || (!queueShown && poll.queue_message))) {
|
|
127
127
|
lastQueuedAt = Date.now();
|
|
128
|
-
|
|
128
|
+
// 🚨 Место и оценка — от сервера (G-14, 26.10). Раньше человек видел
|
|
129
|
+
// тишину, а агент — один `waited_s`: восемь минут без причины читались
|
|
130
|
+
// как зависание, и деплой запускали ещё раз.
|
|
131
|
+
const q = (poll.queue ?? null);
|
|
132
|
+
const waited = Math.round((Date.now() - startedAt) / 1000);
|
|
133
|
+
if (json) {
|
|
134
|
+
emit({
|
|
135
|
+
event: "queued",
|
|
136
|
+
waited_s: waited,
|
|
137
|
+
...(q ? {
|
|
138
|
+
position: q.position,
|
|
139
|
+
ahead: q.ahead,
|
|
140
|
+
running: q.running,
|
|
141
|
+
estimated_wait_s: q.estimated_wait_s ?? null,
|
|
142
|
+
} : {}),
|
|
143
|
+
...(poll.queue_message ? { message: poll.queue_message } : {}),
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
else if (poll.queue_message) {
|
|
147
|
+
process.stderr.write(chalk.dim(`… ${poll.queue_message}\n`));
|
|
148
|
+
}
|
|
149
|
+
queueShown = true;
|
|
129
150
|
}
|
|
130
151
|
if (poll.terminal) {
|
|
131
152
|
return poll;
|
package/package.json
CHANGED