@sbuilder/cli 0.9.0 → 0.11.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/README.md +272 -12
- package/README.vi.md +265 -13
- package/dist/bin/sb.js +149 -6
- package/dist/bin/sb.js.map +1 -1
- package/dist/src/agentdocs.js +221 -0
- package/dist/src/agentdocs.js.map +1 -0
- package/dist/src/doctor.js +516 -0
- package/dist/src/doctor.js.map +1 -0
- package/dist/src/envtypes.gen.js +1748 -0
- package/dist/src/envtypes.gen.js.map +1 -0
- package/dist/src/host.js +414 -22
- package/dist/src/host.js.map +1 -1
- package/dist/src/hostlink.js +161 -0
- package/dist/src/hostlink.js.map +1 -0
- package/dist/src/init.js +19 -2
- package/dist/src/init.js.map +1 -1
- package/dist/src/login.js +1 -1
- package/dist/src/login.js.map +1 -1
- package/dist/src/next.js +82 -6
- package/dist/src/next.js.map +1 -1
- package/dist/src/repo.js +24 -2
- package/dist/src/repo.js.map +1 -1
- package/dist/src/roottsconfig.js +154 -0
- package/dist/src/roottsconfig.js.map +1 -0
- package/dist/src/route.js +16 -1
- package/dist/src/route.js.map +1 -1
- package/dist/src/scaffold.js +28 -0
- package/dist/src/scaffold.js.map +1 -1
- package/dist/src/site.js +616 -72
- package/dist/src/site.js.map +1 -1
- package/dist/src/sitedev.js +99 -0
- package/dist/src/sitedev.js.map +1 -0
- package/dist/src/siteinit.js +231 -33
- package/dist/src/siteinit.js.map +1 -1
- package/dist/src/sitekinds.js +1048 -0
- package/dist/src/sitekinds.js.map +1 -0
- package/dist/src/sitepaths.js +12 -0
- package/dist/src/sitepaths.js.map +1 -0
- package/dist/src/sitestatus.js +104 -0
- package/dist/src/sitestatus.js.map +1 -0
- package/dist/src/source/meta.js +118 -0
- package/dist/src/source/meta.js.map +1 -0
- package/dist/src/source/parse.js +21 -2
- package/dist/src/source/parse.js.map +1 -1
- package/dist/src/starter.js +61 -0
- package/dist/src/starter.js.map +1 -0
- package/dist/src/vercel.js +379 -0
- package/dist/src/vercel.js.map +1 -0
- package/package.json +9 -1
- package/dist/src/export.js +0 -167
- package/dist/src/export.js.map +0 -1
|
@@ -0,0 +1,1048 @@
|
|
|
1
|
+
import { readdir, stat } from 'node:fs/promises';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { parseFile, parseJson, printFile, printJson, overlayInputOf, overlayMetaOf, } from './source/meta.js';
|
|
5
|
+
import { SourceError } from './source/parse.js';
|
|
6
|
+
import { messageOf } from './dev.js';
|
|
7
|
+
import { errorOf, linkOn, put, readText, refusal, saveManifest, send, sha256, writeBack, } from './site.js';
|
|
8
|
+
import { SAFE_KIND_FILE } from './sitepaths.js';
|
|
9
|
+
/**
|
|
10
|
+
* The rest of a site as source: shared sections (design/globals), overlays
|
|
11
|
+
* (design/overlays), the theme (design/theme.json) and translations
|
|
12
|
+
* (design/translations/<locale>.json). Every kind obeys the rule the page files
|
|
13
|
+
* do, because it is the same promise to the same person:
|
|
14
|
+
*
|
|
15
|
+
* - THREE-WAY, never a silent overwrite: base = what was last synced (the
|
|
16
|
+
* manifest), ours = the file, theirs = the platform now. Only ours changed
|
|
17
|
+
* → send; only theirs → leave it (the file takes it); both the same → nothing;
|
|
18
|
+
* both different → the file is refused, named, exit 1. --force picks the file.
|
|
19
|
+
* - NOTHING IS DELETED by a sync. A gone file is reported; --prune (and --yes
|
|
20
|
+
* off a terminal) deletes, and a section still shown on pages comes back as
|
|
21
|
+
* `in_use` — never forced from here.
|
|
22
|
+
* - Untrusted paths, as pages: a name outside the kind's directory or a symlink
|
|
23
|
+
* anywhere on the path is refused.
|
|
24
|
+
*
|
|
25
|
+
* These read /api/v1 with the repo's own key (a session login does not reach them).
|
|
26
|
+
*/
|
|
27
|
+
const PAGE = 200;
|
|
28
|
+
const none = () => ({ clashes: 0, wrote: 0, sent: 0, failed: 0 });
|
|
29
|
+
// ─── shared helpers ─────────────────────────────────────────────────────────────
|
|
30
|
+
/** `a-name.page.tsx`-style stem from a display name, unique among `taken`. */
|
|
31
|
+
function fileFor(dir, ext, name, id, taken) {
|
|
32
|
+
const stem = name
|
|
33
|
+
.toLowerCase()
|
|
34
|
+
.normalize('NFD')
|
|
35
|
+
.replace(/[̀-ͯ]/g, '')
|
|
36
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
37
|
+
.replace(/^[-.]+|-+$/g, '') || id;
|
|
38
|
+
let file = `${dir}/${stem}${ext}`;
|
|
39
|
+
if (taken.has(file))
|
|
40
|
+
file = `${dir}/${stem}-${id}${ext}`;
|
|
41
|
+
taken.add(file);
|
|
42
|
+
return file;
|
|
43
|
+
}
|
|
44
|
+
/** A file that may be read: a safe name and no symlink on its path. Says why not, or undefined. */
|
|
45
|
+
async function unsafe(ctx, re, file) {
|
|
46
|
+
if (!re.test(file))
|
|
47
|
+
return `${file} is not a plain file name`;
|
|
48
|
+
const link = await linkOn(ctx.dir, file);
|
|
49
|
+
return link ? `${link} is a symbolic link` : undefined;
|
|
50
|
+
}
|
|
51
|
+
/** What a failed list means: skip the kind with a line, never a crash and never silently. */
|
|
52
|
+
async function listFailed(ctx, what, res, scope) {
|
|
53
|
+
const why = res.status === 403
|
|
54
|
+
? `this key cannot read ${what} (it needs ${scope})`
|
|
55
|
+
: res.status === 404 || res.status === 501
|
|
56
|
+
? `this platform does not serve ${what} yet`
|
|
57
|
+
: `reading ${what} failed (server: ${(await errorOf(res)).error})`;
|
|
58
|
+
ctx.warn(` ! ${what}: ${why} — skipped.`);
|
|
59
|
+
}
|
|
60
|
+
const listOf = async (ctx, path, key) => {
|
|
61
|
+
const out = [];
|
|
62
|
+
for (let offset = 0;;) {
|
|
63
|
+
const res = await send(ctx, `${ctx.base}/${path}?limit=${PAGE}&offset=${offset}`, 'GET');
|
|
64
|
+
if (!res.ok)
|
|
65
|
+
return res;
|
|
66
|
+
const body = (await res.json());
|
|
67
|
+
out.push(...body[key]);
|
|
68
|
+
offset += body[key].length;
|
|
69
|
+
if (body[key].length === 0 || offset >= body.total)
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
const KINDS = {
|
|
74
|
+
globals: {
|
|
75
|
+
meta: 'global',
|
|
76
|
+
manifestKey: 'globals',
|
|
77
|
+
dir: 'design/globals',
|
|
78
|
+
route: 'global-sections',
|
|
79
|
+
listKey: 'globalSections',
|
|
80
|
+
itemKey: 'globalSection',
|
|
81
|
+
re: SAFE_KIND_FILE.globals,
|
|
82
|
+
scope: 'pages.read',
|
|
83
|
+
factsOf: (r) => ({ id: r.id, name: r.name, kind: r.kind }),
|
|
84
|
+
keys: ['name'],
|
|
85
|
+
write: (_k, c) => c,
|
|
86
|
+
},
|
|
87
|
+
overlays: {
|
|
88
|
+
meta: 'overlay',
|
|
89
|
+
manifestKey: 'overlays',
|
|
90
|
+
dir: 'design/overlays',
|
|
91
|
+
route: 'overlays',
|
|
92
|
+
listKey: 'overlays',
|
|
93
|
+
itemKey: 'overlay',
|
|
94
|
+
re: SAFE_KIND_FILE.overlays,
|
|
95
|
+
scope: 'pages.read',
|
|
96
|
+
factsOf: overlayMetaOf,
|
|
97
|
+
keys: ['name', 'allPages', 'pages'],
|
|
98
|
+
// allPages and pages are separate facts: each goes up only when the file changed it, so a list
|
|
99
|
+
// push never detaches the edges a pop-up shown on every page keeps.
|
|
100
|
+
write: (kind, c) => {
|
|
101
|
+
const { allPages, pages, ...rest } = c;
|
|
102
|
+
return { ...rest, ...overlayInputOf(kind, { allPages, pages }) };
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
/** Page lists are sets: the same ids in another order are the same fact. */
|
|
107
|
+
const norm = (v) => Array.isArray(v) && v.every((x) => typeof x === 'string') ? [...v].sort() : v;
|
|
108
|
+
const same = (a, b) => isDeepStrictEqual(norm(a), norm(b));
|
|
109
|
+
/** Three-way over named keys (see the header). Returns what to send and what clashes. */
|
|
110
|
+
export function merge3(meta, base, theirs, keys, force) {
|
|
111
|
+
const send = {};
|
|
112
|
+
const conflicts = [];
|
|
113
|
+
for (const k of keys) {
|
|
114
|
+
if (!meta || !(k in meta) || same(meta[k], base[k]))
|
|
115
|
+
continue; // ours unchanged
|
|
116
|
+
if (same(meta[k], theirs[k]))
|
|
117
|
+
continue; // both made the same change
|
|
118
|
+
if (force || same(theirs[k], base[k]))
|
|
119
|
+
send[k] = meta[k];
|
|
120
|
+
else
|
|
121
|
+
conflicts.push(k);
|
|
122
|
+
}
|
|
123
|
+
return { send, conflicts };
|
|
124
|
+
}
|
|
125
|
+
/** No recorded base (a manifest from before this fact was kept): a fact the file states differently is a conflict. */
|
|
126
|
+
export function unrecorded3(meta, theirs, keys, force) {
|
|
127
|
+
const send = {};
|
|
128
|
+
const conflicts = [];
|
|
129
|
+
for (const k of keys) {
|
|
130
|
+
if (!meta || !(k in meta) || same(meta[k], theirs[k]))
|
|
131
|
+
continue;
|
|
132
|
+
if (force)
|
|
133
|
+
send[k] = meta[k];
|
|
134
|
+
else
|
|
135
|
+
conflicts.push(k);
|
|
136
|
+
}
|
|
137
|
+
return { send, conflicts };
|
|
138
|
+
}
|
|
139
|
+
const entriesOf = (ctx, k) => (ctx.manifest[k.manifestKey] ??= {});
|
|
140
|
+
async function pullDocKind(ctx, k) {
|
|
141
|
+
const out = none();
|
|
142
|
+
const rows = await listOf(ctx, k.route, k.listKey);
|
|
143
|
+
if (!Array.isArray(rows)) {
|
|
144
|
+
await listFailed(ctx, k.route.replace('-', ' '), rows, k.scope);
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
const entries = entriesOf(ctx, k);
|
|
148
|
+
const taken = new Set(Object.values(entries).map((e) => e.file));
|
|
149
|
+
for (const row of rows) {
|
|
150
|
+
const entry = entries[row.id];
|
|
151
|
+
const facts = k.factsOf(row);
|
|
152
|
+
if (entry && entry.rev === row.rev && isDeepStrictEqual(entry.facts, facts))
|
|
153
|
+
continue;
|
|
154
|
+
const file = entry?.file ?? fileFor(k.dir, '.page.tsx', row.name, row.id, taken);
|
|
155
|
+
const why = await unsafe(ctx, k.re, file);
|
|
156
|
+
if (why) {
|
|
157
|
+
ctx.warn(` ! ${file}: ${why} — not followed, nothing written.`);
|
|
158
|
+
out.clashes++;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const text = printFile(k.meta, row.document, facts);
|
|
162
|
+
const local = await readText(join(ctx.dir, file));
|
|
163
|
+
if (entry && local !== undefined && sha256(local) !== entry.sha256 && !ctx.o.force) {
|
|
164
|
+
ctx.warn(` ! ${file}: changed here AND in the editor — kept yours. sb site pull --force takes the editor's.`);
|
|
165
|
+
out.clashes++;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (!entry && local !== undefined && local !== text && !ctx.o.force) {
|
|
169
|
+
ctx.warn(` ! ${file}: already exists and is not tracked — kept it. Move it aside, or --force.`);
|
|
170
|
+
out.clashes++;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (!ctx.o.dryRun) {
|
|
174
|
+
await put(join(ctx.dir, file), text);
|
|
175
|
+
entries[row.id] = { file, rev: row.rev, sha256: sha256(text), facts };
|
|
176
|
+
await saveManifest(ctx);
|
|
177
|
+
}
|
|
178
|
+
ctx.log(` ↓ ${file}`);
|
|
179
|
+
out.wrote++;
|
|
180
|
+
}
|
|
181
|
+
const live = new Set(rows.map((r) => r.id));
|
|
182
|
+
for (const [id, e] of Object.entries(entries)) {
|
|
183
|
+
if (live.has(id))
|
|
184
|
+
continue;
|
|
185
|
+
ctx.warn(` ! ${e.file}: deleted on the platform — the file is kept; delete it yourself.`);
|
|
186
|
+
if (!ctx.o.dryRun)
|
|
187
|
+
delete entries[id];
|
|
188
|
+
}
|
|
189
|
+
if (!ctx.o.dryRun)
|
|
190
|
+
await saveManifest(ctx);
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
193
|
+
async function getRow(ctx, k, id) {
|
|
194
|
+
const res = await send(ctx, `${ctx.base}/${k.route}/${encodeURIComponent(id)}`, 'GET');
|
|
195
|
+
return res.ok ? ((await res.json())[k.itemKey] ?? res) : res;
|
|
196
|
+
}
|
|
197
|
+
const parseErr = (file, err) => err instanceof SourceError
|
|
198
|
+
? ` ! ${file}:${err.message} — nothing sent.`
|
|
199
|
+
: ` ! ${file}: ${messageOf(err)} — nothing sent.`;
|
|
200
|
+
async function pushDocKind(ctx, k, prune) {
|
|
201
|
+
const out = none();
|
|
202
|
+
const o = ctx.o;
|
|
203
|
+
const entries = entriesOf(ctx, k);
|
|
204
|
+
const tracked = new Set(Object.values(entries).map((e) => e.file));
|
|
205
|
+
const wanted = (f) => !o.only || o.only.has(f);
|
|
206
|
+
const missing = [];
|
|
207
|
+
/** One file → one PUT (document and the facts that changed, together: all or nothing). */
|
|
208
|
+
async function save(id, entry, text) {
|
|
209
|
+
let parsed;
|
|
210
|
+
try {
|
|
211
|
+
parsed = parseFile(text, k.meta);
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
ctx.warn(parseErr(entry.file, err));
|
|
215
|
+
out.failed++;
|
|
216
|
+
o.report?.(entry.file, 'refused');
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const { document, meta } = parsed;
|
|
220
|
+
if (meta && meta.id !== undefined && meta.id !== id) {
|
|
221
|
+
ctx.warn(` ! ${entry.file}: \`id\` is the platform's — it must stay ${JSON.stringify(id)}. Nothing sent.`);
|
|
222
|
+
out.failed++;
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (meta && meta.kind !== undefined && meta.kind !== entry.facts.kind) {
|
|
226
|
+
ctx.warn(` ! ${entry.file}: the kind of a ${k.meta} cannot change. Nothing sent.`);
|
|
227
|
+
out.failed++;
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
const now = await getRow(ctx, k, id);
|
|
231
|
+
if (!('rev' in now)) {
|
|
232
|
+
ctx.warn(now.status === 404
|
|
233
|
+
? ` ! ${entry.file}: deleted on the platform — nothing sent.`
|
|
234
|
+
: ` ! ${entry.file}: reading it failed (${refusal(await errorOf(now))}) — nothing sent.`);
|
|
235
|
+
out.failed++;
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const theirs = k.factsOf(now);
|
|
239
|
+
const recorded = k.keys.every((f) => f in entry.facts);
|
|
240
|
+
const { send: changes, conflicts } = recorded
|
|
241
|
+
? merge3(meta, entry.facts, theirs, k.keys, o.force)
|
|
242
|
+
: unrecorded3(meta, theirs, k.keys, o.force);
|
|
243
|
+
for (const c of conflicts)
|
|
244
|
+
ctx.warn(recorded
|
|
245
|
+
? ` ! ${entry.file}: ${c} changed here AND in the editor — kept both; ` +
|
|
246
|
+
"pull to take the editor's, or sb site push --force. Nothing sent for this file."
|
|
247
|
+
: ` ! ${entry.file}: ${c} differs from the platform and this repo has no record of the last sync — ` +
|
|
248
|
+
'sb site pull to take the platform’s, or sb site push --force. Nothing sent for this file.');
|
|
249
|
+
if (conflicts.length) {
|
|
250
|
+
out.failed++;
|
|
251
|
+
o.report?.(entry.file, 'refused');
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (o.dryRun) {
|
|
255
|
+
ctx.log(` ↑ ${entry.file} (dry run)`);
|
|
256
|
+
out.sent++;
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
let fields;
|
|
260
|
+
try {
|
|
261
|
+
fields = k.write(String(entry.facts.kind), changes);
|
|
262
|
+
}
|
|
263
|
+
catch (err) {
|
|
264
|
+
ctx.warn(` ! ${entry.file}: ${messageOf(err)} — nothing sent.`);
|
|
265
|
+
out.failed++;
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const url = `${ctx.base}/${k.route}/${encodeURIComponent(id)}`;
|
|
269
|
+
// `base` is the value of each changed fact as this push last saw it (the read just above, which
|
|
270
|
+
// the three-way already compared with the record): the platform refuses (409 source_stale,
|
|
271
|
+
// naming the field) a fact the editor changed since, and a rename does not move `rev`.
|
|
272
|
+
const body = (baseRev, seen) => {
|
|
273
|
+
const base = {};
|
|
274
|
+
for (const f of ['name', 'allPages', 'pages'])
|
|
275
|
+
if (f in fields)
|
|
276
|
+
base[f] = seen[f];
|
|
277
|
+
return { ...fields, ...(Object.keys(base).length ? { base } : {}), document, baseRev };
|
|
278
|
+
};
|
|
279
|
+
let res = await send(ctx, url, 'PUT', body(entry.rev, theirs));
|
|
280
|
+
if (res.status === 409 && o.force) {
|
|
281
|
+
// --force re-reads and sends over what the platform has NOW: the file's change, deliberately.
|
|
282
|
+
const fresh = await getRow(ctx, k, id);
|
|
283
|
+
if ('rev' in fresh)
|
|
284
|
+
res = await send(ctx, url, 'PUT', body(fresh.rev, k.factsOf(fresh)));
|
|
285
|
+
}
|
|
286
|
+
if (!res.ok) {
|
|
287
|
+
const err = await errorOf(res);
|
|
288
|
+
const stale = err.code === 'source_stale';
|
|
289
|
+
ctx.warn(stale && err.details?.field
|
|
290
|
+
? ` ! ${entry.file}: ${err.details.field} changed in the editor since your last pull — nothing sent. ` +
|
|
291
|
+
"Pull to take the editor's, or sb site push --force to overwrite it."
|
|
292
|
+
: stale
|
|
293
|
+
? ` ! ${entry.file}: edited in the editor since your last pull — nothing sent. ` +
|
|
294
|
+
'Pull and merge, or sb site push --force to overwrite the editor’s version.'
|
|
295
|
+
: ` ! ${entry.file}: refused (${refusal(err)})`);
|
|
296
|
+
out.failed++;
|
|
297
|
+
o.report?.(entry.file, stale ? 'stale' : 'refused');
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
const answer = (await res.json());
|
|
301
|
+
for (const w of answer.warnings ?? [])
|
|
302
|
+
ctx.warn(` ! ${entry.file}: the platform says ${w}`);
|
|
303
|
+
const saved = answer[k.itemKey];
|
|
304
|
+
// The file becomes what the platform stored; the base moves to exactly that, after the
|
|
305
|
+
// file holds it (this is one atomic PUT, so there is no half-saved state to record).
|
|
306
|
+
const facts = k.factsOf(saved);
|
|
307
|
+
const back = printFile(k.meta, (saved.document ?? document), facts);
|
|
308
|
+
const wrote = await writeBack(ctx, entry.file, text, back);
|
|
309
|
+
// The recorded facts are what the FILE holds. When the rewrite was declined (a newer save landed
|
|
310
|
+
// meanwhile) only what this push sent, and what the file already stated as the platform has it,
|
|
311
|
+
// advance: an editor-only change must not look like the file's own on the next push.
|
|
312
|
+
const held = { ...entry.facts };
|
|
313
|
+
for (const f of k.keys) {
|
|
314
|
+
if (f in changes)
|
|
315
|
+
held[f] = changes[f];
|
|
316
|
+
else if (meta && f in meta && same(meta[f], theirs[f]))
|
|
317
|
+
held[f] = theirs[f];
|
|
318
|
+
}
|
|
319
|
+
entries[id] = {
|
|
320
|
+
file: entry.file,
|
|
321
|
+
rev: saved.rev,
|
|
322
|
+
// What the file holds: the rewrite, or the text we sent when it was saved over meanwhile.
|
|
323
|
+
sha256: sha256(wrote ? back : text),
|
|
324
|
+
facts: wrote ? facts : held,
|
|
325
|
+
};
|
|
326
|
+
await saveManifest(ctx);
|
|
327
|
+
ctx.log(` ↑ ${entry.file}${k.meta === 'global' ? ' (reaches every page that shows it at its next publish)' : ''}`);
|
|
328
|
+
out.sent++;
|
|
329
|
+
o.report?.(entry.file, 'sent');
|
|
330
|
+
}
|
|
331
|
+
for (const [id, entry] of Object.entries(entries)) {
|
|
332
|
+
if (!wanted(entry.file))
|
|
333
|
+
continue;
|
|
334
|
+
const why = await unsafe(ctx, k.re, entry.file);
|
|
335
|
+
if (why) {
|
|
336
|
+
ctx.warn(` ! ${entry.file}: ${why} — not followed, nothing sent.`);
|
|
337
|
+
out.failed++;
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
const text = await readText(join(ctx.dir, entry.file));
|
|
341
|
+
if (text === undefined) {
|
|
342
|
+
missing.push([id, entry]);
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
if (sha256(text) === entry.sha256)
|
|
346
|
+
continue;
|
|
347
|
+
await save(id, entry, text);
|
|
348
|
+
}
|
|
349
|
+
// An untracked file with `export const global|overlay = { name, kind }` and no id is NEW.
|
|
350
|
+
const local = await readdir(join(ctx.dir, k.dir)).catch(() => []);
|
|
351
|
+
for (const f of local.sort()) {
|
|
352
|
+
const file = `${k.dir}/${f}`;
|
|
353
|
+
if (!f.endsWith('.page.tsx') || tracked.has(file) || !wanted(file))
|
|
354
|
+
continue;
|
|
355
|
+
const why = await unsafe(ctx, k.re, file);
|
|
356
|
+
if (why) {
|
|
357
|
+
ctx.warn(` ! ${file}: ${why} — not read, nothing sent.`);
|
|
358
|
+
out.failed++;
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
const text = (await readText(join(ctx.dir, file)));
|
|
362
|
+
let parsed;
|
|
363
|
+
try {
|
|
364
|
+
parsed = parseFile(text, k.meta);
|
|
365
|
+
}
|
|
366
|
+
catch (err) {
|
|
367
|
+
ctx.warn(parseErr(file, err));
|
|
368
|
+
out.failed++;
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
const meta = parsed.meta;
|
|
372
|
+
if (!meta) {
|
|
373
|
+
ctx.warn(` ? ${file}: not tracked — add \`export const ${k.meta} = { name: "…", kind: "…" }\` to create it, or sb site pull.`);
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
if (meta.id !== undefined && Object.values(entries).every((e) => e.file !== file)) {
|
|
377
|
+
ctx.warn(` ! ${file}: names ${JSON.stringify(meta.id)}, which is not tracked from this file — sb site pull to take it. Nothing sent.`);
|
|
378
|
+
out.failed++;
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
if (typeof meta.name !== 'string' || !meta.name.trim() || typeof meta.kind !== 'string') {
|
|
382
|
+
ctx.warn(` ! ${file}: \`export const ${k.meta}\` needs a name and a kind to create it — nothing sent.`);
|
|
383
|
+
out.failed++;
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
if (o.dryRun) {
|
|
387
|
+
ctx.log(` + ${file} (dry run: would create ${k.meta} ${JSON.stringify(meta.name)})`);
|
|
388
|
+
out.sent++;
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
let extra;
|
|
392
|
+
try {
|
|
393
|
+
extra =
|
|
394
|
+
k.meta === 'overlay'
|
|
395
|
+
? overlayInputOf(meta.kind, { allPages: meta.allPages, pages: meta.pages })
|
|
396
|
+
: {};
|
|
397
|
+
}
|
|
398
|
+
catch (err) {
|
|
399
|
+
ctx.warn(` ! ${file}: ${messageOf(err)} — nothing sent.`);
|
|
400
|
+
out.failed++;
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
const before = await listOf(ctx, k.route, k.listKey);
|
|
404
|
+
const res = await send(ctx, `${ctx.base}/${k.route}`, 'POST', {
|
|
405
|
+
name: meta.name,
|
|
406
|
+
kind: meta.kind,
|
|
407
|
+
document: parsed.document,
|
|
408
|
+
...extra,
|
|
409
|
+
});
|
|
410
|
+
let made;
|
|
411
|
+
if (res.ok) {
|
|
412
|
+
const answer = (await res.json());
|
|
413
|
+
made = answer[k.itemKey];
|
|
414
|
+
for (const w of answer.warnings ?? [])
|
|
415
|
+
ctx.warn(` ! ${file}: the platform says ${w}`);
|
|
416
|
+
}
|
|
417
|
+
else {
|
|
418
|
+
const err = await errorOf(res);
|
|
419
|
+
// An error answer can come AFTER the row exists. Look for the one this POST made — a row with
|
|
420
|
+
// this name and kind that was not there before — and track it, or the next push makes a second.
|
|
421
|
+
const now = res.status >= 500 && Array.isArray(before) ? await listOf(ctx, k.route, k.listKey) : [];
|
|
422
|
+
const had = new Set(Array.isArray(before) ? before.map((r) => r.id) : []);
|
|
423
|
+
made = Array.isArray(now)
|
|
424
|
+
? now.find((r) => !had.has(r.id) && r.name === meta.name && r.kind === meta.kind)
|
|
425
|
+
: undefined;
|
|
426
|
+
if (!made) {
|
|
427
|
+
ctx.warn(err.code === 'cart_exists'
|
|
428
|
+
? ` ! ${file}: the site already has its cart (${err.details?.id ?? 'see the editor'}) — a site has one; pull it. Nothing created.`
|
|
429
|
+
: ` ! ${file}: refused (${refusal(err)}) — nothing created.`);
|
|
430
|
+
out.failed++;
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
ctx.warn(` ! ${file}: the platform answered an error (${refusal(err)}) but the ${k.meta} exists — tracked as ${made.id}.`);
|
|
434
|
+
}
|
|
435
|
+
const facts = k.factsOf(made);
|
|
436
|
+
const back = printFile(k.meta, (made.document ?? parsed.document), facts);
|
|
437
|
+
const wrote = await writeBack(ctx, file, text, back);
|
|
438
|
+
entries[made.id] = { file, rev: made.rev, sha256: sha256(wrote ? back : text), facts };
|
|
439
|
+
await saveManifest(ctx);
|
|
440
|
+
ctx.log(` + ${file} (${k.meta} ${made.id} created)`);
|
|
441
|
+
out.sent++;
|
|
442
|
+
}
|
|
443
|
+
if (missing.length && o.only)
|
|
444
|
+
for (const [, e] of missing)
|
|
445
|
+
ctx.warn(` ! ${e.file}: missing — not deleted (sb site dev never prunes).`);
|
|
446
|
+
if (missing.length && !o.only) {
|
|
447
|
+
if (!o.prune) {
|
|
448
|
+
for (const [id, e] of missing) {
|
|
449
|
+
ctx.warn(` ! ${e.file}: missing — ${JSON.stringify(e.facts.name ?? id)} is kept on the platform; sb site push --prune deletes it.`);
|
|
450
|
+
out.failed++;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
else if (!(await prune(missing)))
|
|
454
|
+
out.failed++;
|
|
455
|
+
}
|
|
456
|
+
return out;
|
|
457
|
+
}
|
|
458
|
+
/** `--prune` for a document kind: ask, then DELETE with If-Match; `in_use` is reported, never forced. */
|
|
459
|
+
async function pruneDocKind(ctx, k, gate, missing) {
|
|
460
|
+
const go = await gate(k.dir, `${missing.length} ${k.meta === 'global' ? 'shared section' : 'overlay'}(s)`, missing.map(([id, e]) => ` - ${e.file} (${JSON.stringify(e.facts.name ?? id)}, ${id})`));
|
|
461
|
+
if (go !== 'delete')
|
|
462
|
+
return go === 'stop';
|
|
463
|
+
const entries = entriesOf(ctx, k);
|
|
464
|
+
let ok = true;
|
|
465
|
+
for (const [id, e] of missing) {
|
|
466
|
+
const res = await send(ctx, `${ctx.base}/${k.route}/${encodeURIComponent(id)}`, 'DELETE', undefined, {
|
|
467
|
+
'If-Match': String(e.rev),
|
|
468
|
+
});
|
|
469
|
+
if (res.ok || res.status === 404) {
|
|
470
|
+
delete entries[id];
|
|
471
|
+
await saveManifest(ctx);
|
|
472
|
+
ctx.log(` ✗ ${e.file} (deleted)`);
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
const err = await errorOf(res);
|
|
476
|
+
ctx.warn(err.code === 'in_use'
|
|
477
|
+
? ` ! ${e.file}: still shown (pages: ${err.details?.pages ?? '?'}) — not deleted. Remove it from those pages in the editor first; sb never forces this.`
|
|
478
|
+
: err.code === 'source_stale'
|
|
479
|
+
? ` ! ${e.file}: changed in the editor since your last pull — not deleted. Pull, then decide.`
|
|
480
|
+
: ` ! ${e.file}: not deleted (${refusal(err)})`);
|
|
481
|
+
ok = false;
|
|
482
|
+
}
|
|
483
|
+
return ok;
|
|
484
|
+
}
|
|
485
|
+
// ─── the theme ──────────────────────────────────────────────────────────────────
|
|
486
|
+
const THEME_FILE = 'design/theme.json';
|
|
487
|
+
async function readTheme(ctx) {
|
|
488
|
+
const res = await send(ctx, `${ctx.base}/theme`, 'GET');
|
|
489
|
+
return res.ok
|
|
490
|
+
? (await res.json()).theme
|
|
491
|
+
: res;
|
|
492
|
+
}
|
|
493
|
+
async function pullTheme(ctx) {
|
|
494
|
+
const out = none();
|
|
495
|
+
const t = await readTheme(ctx);
|
|
496
|
+
if ('status' in t) {
|
|
497
|
+
await listFailed(ctx, 'the theme', t, 'theme.read');
|
|
498
|
+
return out;
|
|
499
|
+
}
|
|
500
|
+
if (t.document === null)
|
|
501
|
+
return out; // nothing saved yet: nothing to hold
|
|
502
|
+
const entry = ctx.manifest.theme;
|
|
503
|
+
if (entry && entry.updatedAt === t.updatedAt)
|
|
504
|
+
return out;
|
|
505
|
+
const file = entry?.file ?? THEME_FILE;
|
|
506
|
+
const why = await unsafe(ctx, SAFE_KIND_FILE.theme, file);
|
|
507
|
+
if (why) {
|
|
508
|
+
ctx.warn(` ! ${file}: ${why} — not followed, nothing written.`);
|
|
509
|
+
out.clashes++;
|
|
510
|
+
return out;
|
|
511
|
+
}
|
|
512
|
+
const text = printJson(t.document);
|
|
513
|
+
const local = await readText(join(ctx.dir, file));
|
|
514
|
+
if (entry && local !== undefined && sha256(local) !== entry.sha256 && !ctx.o.force) {
|
|
515
|
+
ctx.warn(` ! ${file}: changed here AND in the editor — kept yours. sb site pull --force takes the editor's.`);
|
|
516
|
+
out.clashes++;
|
|
517
|
+
return out;
|
|
518
|
+
}
|
|
519
|
+
if (!entry && local !== undefined && local !== text && !ctx.o.force) {
|
|
520
|
+
ctx.warn(` ! ${file}: already exists and is not tracked — kept it. Move it aside, or --force.`);
|
|
521
|
+
out.clashes++;
|
|
522
|
+
return out;
|
|
523
|
+
}
|
|
524
|
+
if (!ctx.o.dryRun) {
|
|
525
|
+
await put(join(ctx.dir, file), text);
|
|
526
|
+
ctx.manifest.theme = { file, updatedAt: t.updatedAt, sha256: sha256(text) };
|
|
527
|
+
await saveManifest(ctx);
|
|
528
|
+
}
|
|
529
|
+
ctx.log(` ↓ ${file}`);
|
|
530
|
+
out.wrote++;
|
|
531
|
+
return out;
|
|
532
|
+
}
|
|
533
|
+
export const THEME_WITHHELD = (file) => ` ! ${file}: changed, but a theme save is LIVE for every visitor at once — nothing sent. ` +
|
|
534
|
+
'Run sb site push --theme to send it.';
|
|
535
|
+
async function pushTheme(ctx) {
|
|
536
|
+
const out = none();
|
|
537
|
+
const o = ctx.o;
|
|
538
|
+
const entry = ctx.manifest.theme;
|
|
539
|
+
const file = entry?.file ?? THEME_FILE;
|
|
540
|
+
if (o.only && !o.only.has(file))
|
|
541
|
+
return out;
|
|
542
|
+
const text = await readText(join(ctx.dir, file));
|
|
543
|
+
if (text === undefined) {
|
|
544
|
+
if (entry && o.only)
|
|
545
|
+
ctx.warn(` ! ${file}: missing — not deleted (sb site dev never prunes).`);
|
|
546
|
+
else if (entry) {
|
|
547
|
+
ctx.warn(` ! ${file}: missing — the theme is kept on the platform (a theme is never deleted from here).`);
|
|
548
|
+
out.failed++;
|
|
549
|
+
}
|
|
550
|
+
return out;
|
|
551
|
+
}
|
|
552
|
+
if (entry && sha256(text) === entry.sha256)
|
|
553
|
+
return out;
|
|
554
|
+
const why = await unsafe(ctx, SAFE_KIND_FILE.theme, file);
|
|
555
|
+
if (why) {
|
|
556
|
+
ctx.warn(` ! ${file}: ${why} — not read, nothing sent.`);
|
|
557
|
+
out.failed++;
|
|
558
|
+
return out;
|
|
559
|
+
}
|
|
560
|
+
let doc;
|
|
561
|
+
try {
|
|
562
|
+
doc = parseJson(text);
|
|
563
|
+
if (typeof doc !== 'object' || doc === null || Array.isArray(doc))
|
|
564
|
+
throw new Error('the theme must be a JSON object');
|
|
565
|
+
}
|
|
566
|
+
catch (err) {
|
|
567
|
+
ctx.warn(` ! ${file}: ${messageOf(err)} — nothing sent.`);
|
|
568
|
+
out.failed++;
|
|
569
|
+
o.report?.(file, 'refused');
|
|
570
|
+
return out;
|
|
571
|
+
}
|
|
572
|
+
if (!o.theme) {
|
|
573
|
+
ctx.warn(THEME_WITHHELD(file));
|
|
574
|
+
return out; // withheld on purpose, said out loud: not a failure
|
|
575
|
+
}
|
|
576
|
+
if (o.dryRun) {
|
|
577
|
+
ctx.log(` ↑ ${file} (dry run)`);
|
|
578
|
+
out.sent++;
|
|
579
|
+
return out;
|
|
580
|
+
}
|
|
581
|
+
const now = await readTheme(ctx);
|
|
582
|
+
if ('status' in now) {
|
|
583
|
+
ctx.warn(` ! ${file}: reading the theme failed (${refusal(await errorOf(now))}) — nothing sent.`);
|
|
584
|
+
out.failed++;
|
|
585
|
+
return out;
|
|
586
|
+
}
|
|
587
|
+
// No record of a sync, but the platform has a theme: sending would replace it unseen.
|
|
588
|
+
if (!entry && now.updatedAt !== '' && !o.force) {
|
|
589
|
+
ctx.warn(` ! ${file}: the platform already has a theme this repo never pulled — sb site pull, or --force. Nothing sent.`);
|
|
590
|
+
out.failed++;
|
|
591
|
+
return out;
|
|
592
|
+
}
|
|
593
|
+
const send1 = (expected) => send(ctx, `${ctx.base}/theme`, 'PUT', { document: doc, expectedUpdatedAt: expected });
|
|
594
|
+
let res = await send1(entry?.updatedAt ?? '');
|
|
595
|
+
if (res.status === 409 && o.force) {
|
|
596
|
+
const err = await errorOf(res);
|
|
597
|
+
if (err.code === 'source_stale' && typeof err.details?.updatedAt === 'string')
|
|
598
|
+
res = await send1(err.details.updatedAt);
|
|
599
|
+
}
|
|
600
|
+
if (!res.ok) {
|
|
601
|
+
const err = await errorOf(res);
|
|
602
|
+
const stale = err.code === 'source_stale';
|
|
603
|
+
ctx.warn(stale
|
|
604
|
+
? ` ! ${file}: edited in the editor since your last pull — nothing sent. Pull and merge, or sb site push --theme --force to overwrite it.`
|
|
605
|
+
: ` ! ${file}: refused (${refusal(err)})`);
|
|
606
|
+
out.failed++;
|
|
607
|
+
o.report?.(file, stale ? 'stale' : 'refused');
|
|
608
|
+
return out;
|
|
609
|
+
}
|
|
610
|
+
const saved = (await res.json()).theme;
|
|
611
|
+
const back = printJson(saved.document ?? doc);
|
|
612
|
+
const wrote = await writeBack(ctx, file, text, back);
|
|
613
|
+
ctx.manifest.theme = { file, updatedAt: saved.updatedAt, sha256: sha256(wrote ? back : text) };
|
|
614
|
+
await saveManifest(ctx);
|
|
615
|
+
ctx.log(` ↑ ${file} (the theme is live now)`);
|
|
616
|
+
out.sent++;
|
|
617
|
+
o.report?.(file, 'sent');
|
|
618
|
+
return out;
|
|
619
|
+
}
|
|
620
|
+
// ─── translations ───────────────────────────────────────────────────────────────
|
|
621
|
+
const SOURCES = ['human', 'machine'];
|
|
622
|
+
const HASH = /^[0-9a-f]{8}$/;
|
|
623
|
+
const BATCH = 200;
|
|
624
|
+
/** Internal key = entityType, entityId and field joined by this: none of them can hold it, a "/" they can. */
|
|
625
|
+
export const SEP = '\u001f';
|
|
626
|
+
const keyOf = (type, id, field) => [type, id, field].join(SEP);
|
|
627
|
+
const parts = (k) => k.split(SEP);
|
|
628
|
+
const show = (k) => parts(k).join('/');
|
|
629
|
+
/**
|
|
630
|
+
* The file shape is NESTED — `{ "<entityType>": { "<entityId>": { "<field>": { value, … } } } }` —
|
|
631
|
+
* because a merchant's label text is an entity id and an attribute name is a field, and either may
|
|
632
|
+
* hold a "/": a flat `type/id/field` key could not be split back. These two are exact inverses.
|
|
633
|
+
*/
|
|
634
|
+
export function nestTranslations(flat) {
|
|
635
|
+
const out = {};
|
|
636
|
+
for (const k of Object.keys(flat).sort()) {
|
|
637
|
+
const [t, i, f] = parts(k);
|
|
638
|
+
((out[t] ??= {})[i] ??= {})[f] = flat[k];
|
|
639
|
+
}
|
|
640
|
+
return out;
|
|
641
|
+
}
|
|
642
|
+
export function flattenTranslations(nested) {
|
|
643
|
+
const out = {};
|
|
644
|
+
for (const [t, ids] of Object.entries(nested))
|
|
645
|
+
for (const [i, fields] of Object.entries(ids))
|
|
646
|
+
for (const [f, e] of Object.entries(fields))
|
|
647
|
+
out[keyOf(t, i, f)] = e;
|
|
648
|
+
return out;
|
|
649
|
+
}
|
|
650
|
+
const textOf = (m) => printJson(nestTranslations(m));
|
|
651
|
+
/** The server's `keys` detail: a string "a,b" today, an array once it sends one. */
|
|
652
|
+
const keysOf = (v) => Array.isArray(v) ? v.join(', ') : typeof v === 'string' ? v.split(',').join(', ') : '';
|
|
653
|
+
async function fetchLocale(ctx, locale) {
|
|
654
|
+
const out = {};
|
|
655
|
+
for (let cursor = '';;) {
|
|
656
|
+
const q = new URLSearchParams({ locale, limit: '200', ...(cursor ? { cursor } : {}) });
|
|
657
|
+
const res = await send(ctx, `${ctx.base}/translations?${q}`, 'GET');
|
|
658
|
+
if (!res.ok)
|
|
659
|
+
return res;
|
|
660
|
+
const body = (await res.json());
|
|
661
|
+
for (const t of body.translations)
|
|
662
|
+
out[keyOf(t.entityType, t.entityId, t.field)] = {
|
|
663
|
+
value: t.value,
|
|
664
|
+
source: t.source,
|
|
665
|
+
...(t.sourceHash ? { sourceHash: t.sourceHash } : {}),
|
|
666
|
+
};
|
|
667
|
+
if (!body.nextCursor)
|
|
668
|
+
return out;
|
|
669
|
+
cursor = body.nextCursor;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
/** The locales this repo handles: the platform's own list, plus any this repo already holds. */
|
|
673
|
+
async function localesOf(ctx) {
|
|
674
|
+
const have = new Set(Object.keys(ctx.manifest.translations ?? {}));
|
|
675
|
+
for (const f of await readdir(join(ctx.dir, 'design/translations')).catch(() => []))
|
|
676
|
+
if (f.endsWith('.json'))
|
|
677
|
+
have.add(f.slice(0, -5));
|
|
678
|
+
const probe = [...have][0] ?? 'en';
|
|
679
|
+
const res = await send(ctx, `${ctx.base}/translations/progress?${new URLSearchParams({ locale: probe })}`, 'GET');
|
|
680
|
+
if (res.ok)
|
|
681
|
+
for (const l of (await res.json()).locales ?? [])
|
|
682
|
+
have.add(l);
|
|
683
|
+
return [...have]
|
|
684
|
+
.filter((l) => SAFE_KIND_FILE.translations.test(`design/translations/${l}.json`))
|
|
685
|
+
.sort();
|
|
686
|
+
}
|
|
687
|
+
async function pullTranslations(ctx) {
|
|
688
|
+
const out = none();
|
|
689
|
+
for (const locale of await localesOf(ctx)) {
|
|
690
|
+
const theirs = await fetchLocale(ctx, locale);
|
|
691
|
+
if (theirs instanceof Response) {
|
|
692
|
+
await listFailed(ctx, `translations (${locale})`, theirs, 'translations.read');
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
const entry = ctx.manifest.translations?.[locale];
|
|
696
|
+
const file = entry?.file ?? `design/translations/${locale}.json`;
|
|
697
|
+
if (entry &&
|
|
698
|
+
isDeepStrictEqual(entry.base, theirs) &&
|
|
699
|
+
(await readText(join(ctx.dir, file))) !== undefined)
|
|
700
|
+
continue;
|
|
701
|
+
if (!entry && Object.keys(theirs).length === 0)
|
|
702
|
+
continue;
|
|
703
|
+
const why = await unsafe(ctx, SAFE_KIND_FILE.translations, file);
|
|
704
|
+
if (why) {
|
|
705
|
+
ctx.warn(` ! ${file}: ${why} — not followed, nothing written.`);
|
|
706
|
+
out.clashes++;
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
const text = textOf(theirs);
|
|
710
|
+
const local = await readText(join(ctx.dir, file));
|
|
711
|
+
if (entry && local !== undefined && sha256(local) !== entry.sha256 && !ctx.o.force) {
|
|
712
|
+
ctx.warn(` ! ${file}: changed here AND in the editor — kept yours. sb site pull --force takes the editor's.`);
|
|
713
|
+
out.clashes++;
|
|
714
|
+
continue;
|
|
715
|
+
}
|
|
716
|
+
if (!entry && local !== undefined && local !== text && !ctx.o.force) {
|
|
717
|
+
ctx.warn(` ! ${file}: already exists and is not tracked — kept it. Move it aside, or --force.`);
|
|
718
|
+
out.clashes++;
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
721
|
+
if (!ctx.o.dryRun) {
|
|
722
|
+
await put(join(ctx.dir, file), text);
|
|
723
|
+
(ctx.manifest.translations ??= {})[locale] = { file, sha256: sha256(text), base: theirs };
|
|
724
|
+
await saveManifest(ctx);
|
|
725
|
+
}
|
|
726
|
+
ctx.log(` ↓ ${file}`);
|
|
727
|
+
out.wrote++;
|
|
728
|
+
}
|
|
729
|
+
return out;
|
|
730
|
+
}
|
|
731
|
+
/** The file's entries as flat internal keys, validated: nested type → id → field → { value, source?, sourceHash? }. */
|
|
732
|
+
export function parseTranslations(text) {
|
|
733
|
+
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
734
|
+
const root = parseJson(text);
|
|
735
|
+
if (!isObj(root))
|
|
736
|
+
throw new Error('translations must be a JSON object keyed by entity type');
|
|
737
|
+
const out = {};
|
|
738
|
+
for (const [t, ids] of Object.entries(root)) {
|
|
739
|
+
if (!isObj(ids))
|
|
740
|
+
throw new Error(`${JSON.stringify(t)} must be an object keyed by entity id`);
|
|
741
|
+
for (const [i, fields] of Object.entries(ids)) {
|
|
742
|
+
if (!isObj(fields))
|
|
743
|
+
throw new Error(`${JSON.stringify(`${t}/${i}`)} must be an object keyed by field`);
|
|
744
|
+
for (const [f, e] of Object.entries(fields)) {
|
|
745
|
+
const where = JSON.stringify(`${t}/${i}/${f}`);
|
|
746
|
+
if (`${t}${i}${f}`.includes(SEP))
|
|
747
|
+
throw new Error(`${where} holds a control character`);
|
|
748
|
+
if (!isObj(e) || typeof e.value !== 'string')
|
|
749
|
+
throw new Error(`${where} needs a string "value"`);
|
|
750
|
+
for (const x of Object.keys(e))
|
|
751
|
+
if (!['value', 'source', 'sourceHash'].includes(x))
|
|
752
|
+
throw new Error(`${where} has no "${x}" (value, source, sourceHash)`);
|
|
753
|
+
if (e.source !== undefined && !SOURCES.includes(String(e.source)))
|
|
754
|
+
throw new Error(`${where}: source must be "human" or "machine"`);
|
|
755
|
+
if (e.sourceHash !== undefined && !HASH.test(String(e.sourceHash)))
|
|
756
|
+
throw new Error(`${where}: sourceHash must be 8 lower-case hex characters`);
|
|
757
|
+
out[keyOf(t, i, f)] = e;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
return out;
|
|
762
|
+
}
|
|
763
|
+
async function pushTranslations(ctx, gate) {
|
|
764
|
+
const out = none();
|
|
765
|
+
const o = ctx.o;
|
|
766
|
+
const known = ctx.manifest.translations ?? {};
|
|
767
|
+
// The locales to push: the tracked ones, and any locale file this repo has never seen — sent whole
|
|
768
|
+
// (an empty base), unless the platform already has that locale (then pull it first).
|
|
769
|
+
const targets = Object.entries(known);
|
|
770
|
+
for (const f of (await readdir(join(ctx.dir, 'design/translations')).catch(() => [])).sort()) {
|
|
771
|
+
const file = `design/translations/${f}`;
|
|
772
|
+
const locale = f.slice(0, -5);
|
|
773
|
+
if (!f.endsWith('.json') || known[locale] || (o.only && !o.only.has(file)))
|
|
774
|
+
continue;
|
|
775
|
+
const why = await unsafe(ctx, SAFE_KIND_FILE.translations, file);
|
|
776
|
+
if (why) {
|
|
777
|
+
ctx.warn(` ! ${file}: ${why} — not read, nothing sent.`);
|
|
778
|
+
out.failed++;
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
const theirs = await fetchLocale(ctx, locale);
|
|
782
|
+
if (theirs instanceof Response || Object.keys(theirs).length > 0) {
|
|
783
|
+
ctx.warn(` ! ${file}: the platform already has ${locale} translations this repo never pulled — sb site pull, then edit. Nothing sent.`);
|
|
784
|
+
out.failed++;
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
targets.push([locale, { file, sha256: '', base: {} }]);
|
|
788
|
+
}
|
|
789
|
+
for (const [locale, entry] of targets) {
|
|
790
|
+
if (o.only && !o.only.has(entry.file))
|
|
791
|
+
continue;
|
|
792
|
+
const why = await unsafe(ctx, SAFE_KIND_FILE.translations, entry.file);
|
|
793
|
+
if (why) {
|
|
794
|
+
ctx.warn(` ! ${entry.file}: ${why} — not followed, nothing sent.`);
|
|
795
|
+
out.failed++;
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
const text = await readText(join(ctx.dir, entry.file));
|
|
799
|
+
if (text === undefined) {
|
|
800
|
+
if (o.only)
|
|
801
|
+
ctx.warn(` ! ${entry.file}: missing — not deleted (sb site dev never prunes).`);
|
|
802
|
+
else {
|
|
803
|
+
ctx.warn(` ! ${entry.file}: missing — its translations are kept on the platform (a missing file never deletes them).`);
|
|
804
|
+
out.failed++;
|
|
805
|
+
}
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
if (sha256(text) === entry.sha256)
|
|
809
|
+
continue;
|
|
810
|
+
let ours;
|
|
811
|
+
try {
|
|
812
|
+
ours = parseTranslations(text);
|
|
813
|
+
}
|
|
814
|
+
catch (err) {
|
|
815
|
+
ctx.warn(` ! ${entry.file}: ${messageOf(err)} — nothing sent.`);
|
|
816
|
+
out.failed++;
|
|
817
|
+
o.report?.(entry.file, 'refused');
|
|
818
|
+
continue;
|
|
819
|
+
}
|
|
820
|
+
const theirs = await fetchLocale(ctx, locale);
|
|
821
|
+
if (theirs instanceof Response) {
|
|
822
|
+
ctx.warn(` ! ${entry.file}: reading ${locale} failed (${refusal(await errorOf(theirs))}) — nothing sent.`);
|
|
823
|
+
out.failed++;
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
const sendKeys = [];
|
|
827
|
+
const conflicts = [];
|
|
828
|
+
const removed = [];
|
|
829
|
+
const merged = {};
|
|
830
|
+
for (const k of new Set([
|
|
831
|
+
...Object.keys(entry.base),
|
|
832
|
+
...Object.keys(ours),
|
|
833
|
+
...Object.keys(theirs),
|
|
834
|
+
])) {
|
|
835
|
+
const b = entry.base[k];
|
|
836
|
+
const mine = ours[k];
|
|
837
|
+
const t = theirs[k];
|
|
838
|
+
if (mine === undefined) {
|
|
839
|
+
// Not in the file. Dropped since the last sync: said, never deleted — and if the editor
|
|
840
|
+
// changed it meanwhile, a conflict (deleting would throw that edit away).
|
|
841
|
+
if (b !== undefined && t !== undefined) {
|
|
842
|
+
if (isDeepStrictEqual(t, b) || o.force)
|
|
843
|
+
removed.push(k);
|
|
844
|
+
else
|
|
845
|
+
conflicts.push(`${show(k)} was removed here AND changed in the editor`);
|
|
846
|
+
}
|
|
847
|
+
else if (t !== undefined)
|
|
848
|
+
merged[k] = t; // new in the editor: the file takes it
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
851
|
+
const oursChanged = !isDeepStrictEqual(mine, b);
|
|
852
|
+
if (!oursChanged || isDeepStrictEqual(mine, t)) {
|
|
853
|
+
merged[k] = t ?? mine;
|
|
854
|
+
continue;
|
|
855
|
+
}
|
|
856
|
+
if (o.force || isDeepStrictEqual(t, b)) {
|
|
857
|
+
sendKeys.push(k);
|
|
858
|
+
merged[k] = mine;
|
|
859
|
+
}
|
|
860
|
+
else
|
|
861
|
+
conflicts.push(`${show(k)} changed here AND in the editor`);
|
|
862
|
+
}
|
|
863
|
+
for (const c of conflicts.slice(0, 20))
|
|
864
|
+
ctx.warn(` ! ${entry.file}: ${c} — kept both; pull to take the editor's, or sb site push --force. Nothing sent for this file.`);
|
|
865
|
+
if (conflicts.length > 20)
|
|
866
|
+
ctx.warn(` ! … and ${conflicts.length - 20} more entries in conflict.`);
|
|
867
|
+
if (conflicts.length) {
|
|
868
|
+
out.failed++;
|
|
869
|
+
o.report?.(entry.file, 'refused');
|
|
870
|
+
continue;
|
|
871
|
+
}
|
|
872
|
+
if (o.dryRun) {
|
|
873
|
+
ctx.log(` ↑ ${entry.file} (dry run)`);
|
|
874
|
+
out.sent++;
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
// Recorded as soon as anything is sent, so a refused later batch is remembered.
|
|
878
|
+
const track = () => ((ctx.manifest.translations ??= {})[locale] = entry);
|
|
879
|
+
const base = { ...entry.base };
|
|
880
|
+
let ok = true;
|
|
881
|
+
for (let i = 0; i < sendKeys.length && ok; i += BATCH) {
|
|
882
|
+
const keys = sendKeys.slice(i, i + BATCH);
|
|
883
|
+
/** One request for these keys; `seen(k)` is the value this repo last saw ("" = none). */
|
|
884
|
+
const putBatch = (batch, seen) => send(ctx, `${ctx.base}/translations`, 'PUT', {
|
|
885
|
+
entries: batch.map((k) => {
|
|
886
|
+
const [entityType, entityId, field] = parts(k);
|
|
887
|
+
const e = ours[k];
|
|
888
|
+
// A value with no stated source is the program's, not a person's (O-A3).
|
|
889
|
+
return {
|
|
890
|
+
locale,
|
|
891
|
+
entityType,
|
|
892
|
+
entityId,
|
|
893
|
+
field,
|
|
894
|
+
value: e.value,
|
|
895
|
+
source: e.source ?? 'machine',
|
|
896
|
+
...(e.sourceHash ? { sourceHash: e.sourceHash } : {}),
|
|
897
|
+
// The platform refuses the WHOLE request, writing nothing, if any entry has changed since.
|
|
898
|
+
expected: seen(k),
|
|
899
|
+
};
|
|
900
|
+
}),
|
|
901
|
+
});
|
|
902
|
+
let res = await putBatch(keys, (k) => entry.base[k]?.value ?? '');
|
|
903
|
+
if (res.status === 409 && o.force) {
|
|
904
|
+
// --force re-reads and sends over what the platform has now.
|
|
905
|
+
const fresh = await fetchLocale(ctx, locale);
|
|
906
|
+
if (!(fresh instanceof Response))
|
|
907
|
+
res = await putBatch(keys, (k) => fresh[k]?.value ?? '');
|
|
908
|
+
}
|
|
909
|
+
if (!res.ok) {
|
|
910
|
+
const err = await errorOf(res);
|
|
911
|
+
const at = Number(err.details?.index);
|
|
912
|
+
if (res.status === 409 && err.code === 'source_stale') {
|
|
913
|
+
ctx.warn(` ! ${entry.file}: ${keysOf(err.details?.keys) || 'entries'} changed in the editor since your last pull — nothing in this batch was saved. ` +
|
|
914
|
+
"Pull to take the editor's, or sb site push --force to overwrite them.");
|
|
915
|
+
out.failed++;
|
|
916
|
+
ok = false;
|
|
917
|
+
break;
|
|
918
|
+
}
|
|
919
|
+
ctx.warn(err.code === 'field_not_translatable'
|
|
920
|
+
? ` ! ${entry.file}: ${keys[at] ? show(keys[at]) : 'an entry'} is not a translatable field — nothing in this batch was saved (${err.error}).`
|
|
921
|
+
: ` ! ${entry.file}: refused (${refusal(err)})`);
|
|
922
|
+
out.failed++;
|
|
923
|
+
ok = false;
|
|
924
|
+
break;
|
|
925
|
+
}
|
|
926
|
+
for (const k of keys)
|
|
927
|
+
base[k] = ours[k]; // the file holds these exactly
|
|
928
|
+
}
|
|
929
|
+
if (!ok) {
|
|
930
|
+
// Only what was sent advances the base: the rest still differs from the file, and says so next time.
|
|
931
|
+
entry.base = base;
|
|
932
|
+
track();
|
|
933
|
+
await saveManifest(ctx);
|
|
934
|
+
o.report?.(entry.file, 'refused');
|
|
935
|
+
continue;
|
|
936
|
+
}
|
|
937
|
+
// What the file is rewritten to: entries it dropped stay out of it (and on the platform).
|
|
938
|
+
const fileMap = {};
|
|
939
|
+
for (const k of Object.keys(merged))
|
|
940
|
+
if (!removed.includes(k))
|
|
941
|
+
fileMap[k] = merged[k];
|
|
942
|
+
const back = textOf(fileMap);
|
|
943
|
+
const wrote = await writeBack(ctx, entry.file, text, back);
|
|
944
|
+
// The base for a dropped entry stays what it was at the last sync (the editor's change, if any, is theirs).
|
|
945
|
+
const nextBase = { ...merged };
|
|
946
|
+
for (const k of removed)
|
|
947
|
+
nextBase[k] = entry.base[k];
|
|
948
|
+
// A declined rewrite leaves the file as it was saved: only what was sent is the file's value.
|
|
949
|
+
entry.base = wrote ? nextBase : base;
|
|
950
|
+
// A file that dropped entries is never 'synced': the next push must see it again (and prune).
|
|
951
|
+
entry.sha256 = removed.length ? '' : sha256(wrote ? back : text);
|
|
952
|
+
track();
|
|
953
|
+
await saveManifest(ctx);
|
|
954
|
+
if (removed.length)
|
|
955
|
+
ctx.warn(` ! ${entry.file}: ${removed.length} entr${removed.length === 1 ? 'y' : 'ies'} removed from the file — kept on the platform; sb site push --prune deletes them.`);
|
|
956
|
+
ctx.log(` ↑ ${entry.file}`);
|
|
957
|
+
out.sent++;
|
|
958
|
+
o.report?.(entry.file, 'sent');
|
|
959
|
+
if (o.prune && removed.length && !o.only) {
|
|
960
|
+
const go = await gate('design/translations', `${removed.length} translation(s) in ${locale}`, removed.map((k) => ` - ${show(k)}`));
|
|
961
|
+
if (go === 'fail')
|
|
962
|
+
out.failed++;
|
|
963
|
+
if (go !== 'delete')
|
|
964
|
+
continue;
|
|
965
|
+
// Re-read: an entry the editor changed since is not deleted on the strength of a stale base.
|
|
966
|
+
const fresh = await fetchLocale(ctx, locale);
|
|
967
|
+
if (fresh instanceof Response) {
|
|
968
|
+
ctx.warn(` ! ${entry.file}: re-reading ${locale} failed — nothing deleted.`);
|
|
969
|
+
out.failed++;
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
for (const k of removed) {
|
|
973
|
+
if (fresh[k] === undefined) {
|
|
974
|
+
delete entry.base[k];
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
if (!isDeepStrictEqual(fresh[k], entry.base[k])) {
|
|
978
|
+
ctx.warn(` ! ${entry.file}: ${show(k)} changed in the editor since your last pull — not deleted.`);
|
|
979
|
+
out.failed++;
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
982
|
+
const [entityType, entityId, field] = parts(k);
|
|
983
|
+
const q = new URLSearchParams({ locale, entityType, entityId, field });
|
|
984
|
+
const res = await send(ctx, `${ctx.base}/translations?${q}`, 'DELETE');
|
|
985
|
+
if (res.ok) {
|
|
986
|
+
delete entry.base[k];
|
|
987
|
+
ctx.log(` ✗ ${locale} ${show(k)}`);
|
|
988
|
+
}
|
|
989
|
+
else {
|
|
990
|
+
ctx.warn(` ! ${entry.file}: ${show(k)} not deleted (${refusal(await errorOf(res))})`);
|
|
991
|
+
out.failed++;
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
await saveManifest(ctx);
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
return out;
|
|
998
|
+
}
|
|
999
|
+
// ─── the entry points site.ts calls ─────────────────────────────────────────────
|
|
1000
|
+
/** Is any of these kinds on disk or in the manifest? A session login skips them — out loud. */
|
|
1001
|
+
async function present(ctx) {
|
|
1002
|
+
const m = ctx.manifest;
|
|
1003
|
+
if (m.globals || m.overlays || m.theme || m.translations)
|
|
1004
|
+
return true;
|
|
1005
|
+
for (const p of ['design/globals', 'design/overlays', 'design/theme.json', 'design/translations'])
|
|
1006
|
+
if (await stat(join(ctx.dir, p)).then(() => true, () => false))
|
|
1007
|
+
return true;
|
|
1008
|
+
return false;
|
|
1009
|
+
}
|
|
1010
|
+
const NEEDS_KEY = ' · globals, overlays, the theme and translations sync only with an API key (a repo made by sb site init has one in .env) — skipped.';
|
|
1011
|
+
export async function pullKinds(ctx) {
|
|
1012
|
+
if (!ctx.v1) {
|
|
1013
|
+
if (await present(ctx))
|
|
1014
|
+
ctx.warn(NEEDS_KEY);
|
|
1015
|
+
return none();
|
|
1016
|
+
}
|
|
1017
|
+
const all = none();
|
|
1018
|
+
for (const r of [
|
|
1019
|
+
await pullDocKind(ctx, KINDS.globals),
|
|
1020
|
+
await pullDocKind(ctx, KINDS.overlays),
|
|
1021
|
+
await pullTheme(ctx),
|
|
1022
|
+
await pullTranslations(ctx),
|
|
1023
|
+
]) {
|
|
1024
|
+
all.clashes += r.clashes;
|
|
1025
|
+
all.wrote += r.wrote;
|
|
1026
|
+
}
|
|
1027
|
+
return all;
|
|
1028
|
+
}
|
|
1029
|
+
export async function pushKinds(ctx, gate) {
|
|
1030
|
+
if (!ctx.v1) {
|
|
1031
|
+
if (await present(ctx))
|
|
1032
|
+
ctx.warn(NEEDS_KEY);
|
|
1033
|
+
return none();
|
|
1034
|
+
}
|
|
1035
|
+
const all = none();
|
|
1036
|
+
const prune = (k) => (missing) => pruneDocKind(ctx, k, gate, missing);
|
|
1037
|
+
for (const r of [
|
|
1038
|
+
await pushDocKind(ctx, KINDS.globals, prune(KINDS.globals)),
|
|
1039
|
+
await pushDocKind(ctx, KINDS.overlays, prune(KINDS.overlays)),
|
|
1040
|
+
await pushTheme(ctx),
|
|
1041
|
+
await pushTranslations(ctx, gate),
|
|
1042
|
+
]) {
|
|
1043
|
+
all.sent += r.sent;
|
|
1044
|
+
all.failed += r.failed;
|
|
1045
|
+
}
|
|
1046
|
+
return all;
|
|
1047
|
+
}
|
|
1048
|
+
//# sourceMappingURL=sitekinds.js.map
|