@wirecat/cli-core 0.706.0 → 0.708.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/CHANGELOG.md +61 -0
- package/dist/cli/list-query.d.ts +8 -1
- package/dist/cli/list-query.js +14 -2
- package/dist/cli/token-session.d.ts +4 -1
- package/dist/cli/token-session.js +6 -1
- package/dist/content/cli/index.d.ts +2 -2
- package/dist/content/cli/index.js +64 -54
- package/dist/content/manifest/writer.d.ts +4 -1
- package/dist/content/manifest/writer.js +15 -12
- package/dist/content/testing/index.d.ts +1 -0
- package/dist/content/testing/index.js +1 -0
- package/dist/content/testing/manifest-fake.d.ts +54 -0
- package/dist/content/testing/manifest-fake.js +426 -0
- package/dist/content/writer.d.ts +5 -0
- package/dist/content/writer.js +1 -4
- package/dist/content/writes.js +13 -7
- package/dist/crm/cli/changes.d.ts +2 -0
- package/dist/crm/cli/changes.js +4 -2
- package/dist/crm/cli/index.d.ts +2 -0
- package/dist/crm/cli/index.js +17 -13
- package/dist/crm/cli/records.d.ts +2 -0
- package/dist/crm/cli/records.js +25 -8
- package/dist/crm/cli/search-all.d.ts +3 -1
- package/dist/crm/cli/search-all.js +5 -4
- package/package.json +2 -2
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { at } from "../../crm/manifest/map.js";
|
|
3
|
+
import { parseContentManifest } from "../manifest/manifest.js";
|
|
4
|
+
import { utcEpoch } from "../manifest/map.js";
|
|
5
|
+
import { exampleContentRows } from "./source.js";
|
|
6
|
+
const T0 = Date.parse("2026-11-01T10:00:00Z");
|
|
7
|
+
// A time with no offset: what `utcEpoch` reads as UTC, as WordPress's `*_gmt` fields are written.
|
|
8
|
+
const stamp = (ms) => new Date(ms).toISOString().slice(0, 19);
|
|
9
|
+
const digits = (id) => (/^\d+$/.test(id) ? Number(id) : Number(id.replace(/\D/g, "")) || id);
|
|
10
|
+
const pathOf = (rule) => {
|
|
11
|
+
if (rule === undefined || typeof rule === "function")
|
|
12
|
+
return undefined;
|
|
13
|
+
if (typeof rule === "string")
|
|
14
|
+
return rule;
|
|
15
|
+
if ("each" in rule || "value" in rule)
|
|
16
|
+
return undefined;
|
|
17
|
+
if ("first" in rule)
|
|
18
|
+
return rule.first[0];
|
|
19
|
+
if ("join" in rule)
|
|
20
|
+
return rule.join[0];
|
|
21
|
+
if ("all" in rule)
|
|
22
|
+
return rule.all[0];
|
|
23
|
+
return rule.path;
|
|
24
|
+
};
|
|
25
|
+
const put = (row, path, value) => {
|
|
26
|
+
const keys = path.split(".");
|
|
27
|
+
const last = keys.pop();
|
|
28
|
+
let inner = row;
|
|
29
|
+
for (const key of keys) {
|
|
30
|
+
if (typeof inner[key] !== "object" || inner[key] === null || Array.isArray(inner[key]))
|
|
31
|
+
inner[key] = {};
|
|
32
|
+
inner = inner[key];
|
|
33
|
+
}
|
|
34
|
+
inner[last] = value;
|
|
35
|
+
};
|
|
36
|
+
const merged = (row, body) => {
|
|
37
|
+
for (const [key, value] of Object.entries(body)) {
|
|
38
|
+
const inner = row[key];
|
|
39
|
+
if (value && typeof value === "object" && !Array.isArray(value) && inner && typeof inner === "object")
|
|
40
|
+
merged(inner, value);
|
|
41
|
+
else
|
|
42
|
+
row[key] = structuredClone(value);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
/** The service's value a rule maps onto ours: a `map` rule's key whose value is ours. */
|
|
46
|
+
const sourceValue = (rule, ours) => {
|
|
47
|
+
if (rule && typeof rule === "object" && "map" in rule && rule.map)
|
|
48
|
+
return Object.entries(rule.map).find(([, value]) => value === ours)?.[0] ?? ours;
|
|
49
|
+
return ours;
|
|
50
|
+
};
|
|
51
|
+
const constantOf = (entity, field) => {
|
|
52
|
+
const rule = entity.map[field];
|
|
53
|
+
return rule && typeof rule === "object" && "value" in rule ? rule.value : undefined;
|
|
54
|
+
};
|
|
55
|
+
const fixedOf = (value, trail = []) => {
|
|
56
|
+
if (value && typeof value === "object")
|
|
57
|
+
return Object.entries(value).flatMap(([key, inner]) => fixedOf(inner, [...trail, key]));
|
|
58
|
+
if (value === undefined || /^\{\w+\}$/.test(String(value)))
|
|
59
|
+
return [];
|
|
60
|
+
return [[trail.join("."), String(value)]];
|
|
61
|
+
};
|
|
62
|
+
const placeOf = (call, placeholder) => {
|
|
63
|
+
for (const where of ["path", "query"])
|
|
64
|
+
for (const [key, value] of Object.entries(call[where] ?? {}))
|
|
65
|
+
if (value === placeholder)
|
|
66
|
+
return { in: where, name: key };
|
|
67
|
+
return undefined;
|
|
68
|
+
};
|
|
69
|
+
const html = (markdown) => `<p>${markdown.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>")}</p>`;
|
|
70
|
+
const statusOf = (error) => error.code === "not_found"
|
|
71
|
+
? 404
|
|
72
|
+
: error.code === "permission_error"
|
|
73
|
+
? 403
|
|
74
|
+
: error.code === "validation_error"
|
|
75
|
+
? 400
|
|
76
|
+
: 500;
|
|
77
|
+
/**
|
|
78
|
+
* A content service in memory, built from a source manifest and the generated API it names. Our records are written
|
|
79
|
+
* into each entity's shape by its map (the status by its `map`, a post's text by its body format), read back by the
|
|
80
|
+
* calls the manifest names, paged by each operation's own pagination (the page count in its header where it has one,
|
|
81
|
+
* a page past the end refused), and written by the manifest's writes. Service-neutral: a content CLI's own config
|
|
82
|
+
* drives it, as `crmManifestFake` does a CRM's.
|
|
83
|
+
*/
|
|
84
|
+
export const contentManifestFake = (input, options) => {
|
|
85
|
+
const manifest = parseContentManifest(input, options.api);
|
|
86
|
+
const operations = new Map(options.api.operations.map((one) => [one.id, one]));
|
|
87
|
+
const size = options.pageSize ?? 2;
|
|
88
|
+
let last = 0;
|
|
89
|
+
// After every example row by default, as a sync's own clock is: an edit made now is a change since the last sync.
|
|
90
|
+
// Whole seconds, as the service writes its times: a change stamped in the cursor's own second would be lost.
|
|
91
|
+
const clock = options.clock ??
|
|
92
|
+
(() => {
|
|
93
|
+
last = Math.max(last + 1000, Math.ceil(Math.max(Date.now(), T0) / 1000) * 1000 + 1000);
|
|
94
|
+
return last;
|
|
95
|
+
});
|
|
96
|
+
const given = options.rows ?? exampleContentRows();
|
|
97
|
+
const writes = [];
|
|
98
|
+
const refusals = [];
|
|
99
|
+
let lose = false;
|
|
100
|
+
let made = 1000;
|
|
101
|
+
const entities = (kind) => manifest.entities[kind] ?? [];
|
|
102
|
+
// A record goes to the entity whose constant (a term's kind, a post's type) is its own; else the first.
|
|
103
|
+
const entityIndex = (kind, record) => {
|
|
104
|
+
const field = kind === "term" ? "kind" : kind === "post" ? "type" : undefined;
|
|
105
|
+
const found = field ? entities(kind).findIndex((one) => constantOf(one, field) === record[field]) : -1;
|
|
106
|
+
return Math.max(found, 0);
|
|
107
|
+
};
|
|
108
|
+
const termPaths = manifest.writes?.fields.terms ?? {};
|
|
109
|
+
const termKinds = new Map((given.term ?? []).map((one) => [one.externalId, one.kind]));
|
|
110
|
+
const rawOf = (kind, entity, record) => {
|
|
111
|
+
const row = {};
|
|
112
|
+
const time = (value) => (typeof value === "number" ? stamp(value) : value);
|
|
113
|
+
for (const [field, rule] of Object.entries(entity.map)) {
|
|
114
|
+
const path = pathOf(rule);
|
|
115
|
+
const value = record[field];
|
|
116
|
+
if (path === undefined || value === undefined || value === null)
|
|
117
|
+
continue;
|
|
118
|
+
if (field === "terms" && rule && typeof rule === "object" && "all" in rule) {
|
|
119
|
+
for (const one of rule.all)
|
|
120
|
+
put(row, one, []);
|
|
121
|
+
for (const term of value) {
|
|
122
|
+
const into = termPaths[termKinds.get(term) ?? "tag"] ?? rule.all[0];
|
|
123
|
+
if (into)
|
|
124
|
+
at(row, into)?.push(digits(term));
|
|
125
|
+
}
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
// The source keeps one date where ours keeps two: the one this status has goes there.
|
|
129
|
+
if (field === "publishedAt" && record.status === "scheduled")
|
|
130
|
+
continue;
|
|
131
|
+
if (field === "version" && path === pathOf(entity.map.updatedAt))
|
|
132
|
+
continue;
|
|
133
|
+
const written = field === "externalId" || field === "parent"
|
|
134
|
+
? digits(String(value))
|
|
135
|
+
: field === "authors" || field === "terms"
|
|
136
|
+
? value.map(digits)
|
|
137
|
+
: field.endsWith("At") || field === "scheduledFor"
|
|
138
|
+
? time(value)
|
|
139
|
+
: sourceValue(rule, value);
|
|
140
|
+
put(row, path, written);
|
|
141
|
+
}
|
|
142
|
+
if (kind === "post" && entity.body && typeof record.body === "string")
|
|
143
|
+
put(row, entity.body.path, entity.body.format === "markdown" ? record.body : html(record.body));
|
|
144
|
+
return row;
|
|
145
|
+
};
|
|
146
|
+
const rows = {};
|
|
147
|
+
for (const kind of manifest.kinds) {
|
|
148
|
+
rows[kind] = entities(kind).map(() => []);
|
|
149
|
+
for (const record of (given[kind] ?? [])) {
|
|
150
|
+
const index = entityIndex(kind, record);
|
|
151
|
+
const entity = entities(kind)[index];
|
|
152
|
+
if (entity)
|
|
153
|
+
rows[kind]?.[index]?.push(rawOf(kind, entity, record));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const idOf = (entity, row) => String(at(row, pathOf(entity.map.externalId) ?? "id"));
|
|
157
|
+
const changedOf = (entity, row) => {
|
|
158
|
+
const path = entity.changes?.keyset?.field ?? pathOf(entity.map.updatedAt);
|
|
159
|
+
const value = path === undefined ? undefined : at(row, path);
|
|
160
|
+
return utcEpoch(value) ?? 0;
|
|
161
|
+
};
|
|
162
|
+
const stampRow = (entity, row) => {
|
|
163
|
+
const path = entity.changes?.keyset?.field ?? pathOf(entity.map.updatedAt);
|
|
164
|
+
if (path)
|
|
165
|
+
put(row, path, stamp(clock()));
|
|
166
|
+
};
|
|
167
|
+
const routes = manifest.kinds.flatMap((kind) => entities(kind).flatMap((entity, index) => [
|
|
168
|
+
...(entity.changes ? [{ kind, index, role: "changes", call: entity.changes }] : []),
|
|
169
|
+
...(entity.get ? [{ kind, index, role: "get", call: entity.get }] : []),
|
|
170
|
+
{ kind, index, role: "list", call: entity.list },
|
|
171
|
+
...(entity.ids ? [{ kind, index, role: "list", call: entity.ids }] : []),
|
|
172
|
+
...(entity.optional?.requires
|
|
173
|
+
? [{ kind, index, role: "requires", call: entity.optional.requires }]
|
|
174
|
+
: []),
|
|
175
|
+
]));
|
|
176
|
+
const carries = (route, request) => {
|
|
177
|
+
const fixed = fixedOf({ path: route.call.path ?? {}, query: route.call.query ?? {} });
|
|
178
|
+
const own = { path: request.path, query: request.query };
|
|
179
|
+
if (!fixed.every(([path, value]) => String(at(own, path)) === value))
|
|
180
|
+
return false;
|
|
181
|
+
for (const placeholder of ["{since}", "{id}"]) {
|
|
182
|
+
const place = placeOf(route.call, placeholder);
|
|
183
|
+
if (place && request[place.in][place.name] === undefined)
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
return true;
|
|
187
|
+
};
|
|
188
|
+
// The list sits where the source reads it: the call's own `items` first, then the operation's.
|
|
189
|
+
const wrapped = (items, value) => {
|
|
190
|
+
if (items === undefined || items === "")
|
|
191
|
+
return value;
|
|
192
|
+
const body = {};
|
|
193
|
+
put(body, items, value);
|
|
194
|
+
return body;
|
|
195
|
+
};
|
|
196
|
+
const page = (operation, call, list, request) => {
|
|
197
|
+
const pagination = operation.pagination;
|
|
198
|
+
const items = call.items ?? pagination?.items;
|
|
199
|
+
if (!pagination)
|
|
200
|
+
return { body: wrapped(items, list), headers: new Headers() };
|
|
201
|
+
const pageValue = (parameter) => {
|
|
202
|
+
if (parameter.in !== "query")
|
|
203
|
+
throw new CliError("configuration_error", `the content fake pages by a query parameter, not ${parameter.in}`);
|
|
204
|
+
return request.query[parameter.name];
|
|
205
|
+
};
|
|
206
|
+
let from = 0;
|
|
207
|
+
let pages;
|
|
208
|
+
if (pagination.style === "page") {
|
|
209
|
+
const start = pagination.start ?? 1;
|
|
210
|
+
const number = Number(pageValue(pagination.page) ?? start);
|
|
211
|
+
pages = Math.max(1, Math.ceil(list.length / size));
|
|
212
|
+
if (pagination.pagesHeader !== undefined && number - start + 1 > pages)
|
|
213
|
+
throw new CliError("validation_error", "the page number is past the last page");
|
|
214
|
+
from = (number - start) * size;
|
|
215
|
+
}
|
|
216
|
+
else if (pagination.style === "offset")
|
|
217
|
+
from = Number(pageValue(pagination.offset) ?? 0);
|
|
218
|
+
else if (pagination.style === "cursor")
|
|
219
|
+
from = Number(pageValue(pagination.cursor) ?? 0);
|
|
220
|
+
else
|
|
221
|
+
throw new CliError("configuration_error", `the content fake does not page by ${pagination.style}`);
|
|
222
|
+
const rows = list.slice(from, from + size);
|
|
223
|
+
const headers = new Headers(pagination.style === "page" && pagination.pagesHeader ? { [pagination.pagesHeader]: String(pages) } : {});
|
|
224
|
+
if (items === undefined || items === "")
|
|
225
|
+
return { body: rows, headers };
|
|
226
|
+
const body = wrapped(items, rows);
|
|
227
|
+
if ("total" in pagination && pagination.total)
|
|
228
|
+
put(body, pagination.total, list.length);
|
|
229
|
+
if (pagination.style === "cursor") {
|
|
230
|
+
const more = from + size < list.length;
|
|
231
|
+
put(body, pagination.next, more ? String(from + size) : "");
|
|
232
|
+
if (pagination.hasMore)
|
|
233
|
+
put(body, pagination.hasMore, more);
|
|
234
|
+
}
|
|
235
|
+
return { body, headers };
|
|
236
|
+
};
|
|
237
|
+
const read = async (operation, request) => {
|
|
238
|
+
const found = operations.get(operation);
|
|
239
|
+
const route = routes.find((one) => one.call.operation === operation && carries(one, request));
|
|
240
|
+
if (!found || !route) {
|
|
241
|
+
refusals.push(operation);
|
|
242
|
+
throw new CliError("configuration_error", `the content fake answers no ${operation} call like this`);
|
|
243
|
+
}
|
|
244
|
+
const entity = entities(route.kind)[route.index];
|
|
245
|
+
const held = rows[route.kind]?.[route.index] ?? [];
|
|
246
|
+
if (route.role === "requires") {
|
|
247
|
+
const body = {};
|
|
248
|
+
put(body, route.call.check, true);
|
|
249
|
+
return { body, headers: new Headers() };
|
|
250
|
+
}
|
|
251
|
+
if (route.role === "get") {
|
|
252
|
+
const place = placeOf(route.call, "{id}");
|
|
253
|
+
const id = place ? request[place.in][place.name] : undefined;
|
|
254
|
+
const row = held.find((one) => idOf(entity, one) === String(id));
|
|
255
|
+
if (!row)
|
|
256
|
+
throw new CliError("not_found", `no ${route.kind} ${id}`);
|
|
257
|
+
return { body: wrapped(route.call.items, structuredClone(row)), headers: new Headers() };
|
|
258
|
+
}
|
|
259
|
+
let list = [...held].sort((a, b) => Number(digits(idOf(entity, a))) - Number(digits(idOf(entity, b))));
|
|
260
|
+
if (route.role === "changes" && entity.changes) {
|
|
261
|
+
const place = placeOf(entity.changes, "{since}");
|
|
262
|
+
const raw = String(request[place.in][place.name]);
|
|
263
|
+
const since = entity.changes.since === "iso" ? Date.parse(raw) : Number(raw) * (entity.changes.since === "seconds" ? 1000 : 1);
|
|
264
|
+
if (Number.isNaN(since))
|
|
265
|
+
throw new CliError("validation_error", `${raw} is not a time`);
|
|
266
|
+
list = held
|
|
267
|
+
.filter((row) => changedOf(entity, row) > since)
|
|
268
|
+
.sort((a, b) => changedOf(entity, a) - changedOf(entity, b));
|
|
269
|
+
}
|
|
270
|
+
return page(found, route.call, structuredClone(list), request);
|
|
271
|
+
};
|
|
272
|
+
const write = (operation, request) => {
|
|
273
|
+
const ours = manifest.writes;
|
|
274
|
+
const [entity] = entities("post");
|
|
275
|
+
const held = rows.post?.[0];
|
|
276
|
+
if (!ours || !entity || !held)
|
|
277
|
+
throw new CliError("configuration_error", "the source manifest writes no posts");
|
|
278
|
+
const matches = (call) => call?.operation === operation &&
|
|
279
|
+
fixedOf(call.query ?? {}).every(([key, value]) => String(request.query[key]) === value);
|
|
280
|
+
const body = request.body ? JSON.parse(request.body) : {};
|
|
281
|
+
writes.push(operation);
|
|
282
|
+
const find = () => {
|
|
283
|
+
const place = placeOf(ours.update, "{id}") ?? { in: "path", name: "id" };
|
|
284
|
+
const id = request[place.in][place.name];
|
|
285
|
+
const row = held.find((one) => idOf(entity, one) === String(id));
|
|
286
|
+
if (!row)
|
|
287
|
+
throw new CliError("not_found", `no post ${id}`);
|
|
288
|
+
return row;
|
|
289
|
+
};
|
|
290
|
+
let answer;
|
|
291
|
+
if (matches(ours.create)) {
|
|
292
|
+
made += 1;
|
|
293
|
+
const row = {};
|
|
294
|
+
put(row, pathOf(entity.map.externalId) ?? "id", made);
|
|
295
|
+
merged(row, body);
|
|
296
|
+
stampRow(entity, row);
|
|
297
|
+
held.push(row);
|
|
298
|
+
answer = structuredClone(row);
|
|
299
|
+
}
|
|
300
|
+
else if (matches(ours.delete)) {
|
|
301
|
+
const row = find();
|
|
302
|
+
held.splice(held.indexOf(row), 1);
|
|
303
|
+
answer = { deleted: true, previous: structuredClone(row) };
|
|
304
|
+
}
|
|
305
|
+
else if (matches(ours.trash)) {
|
|
306
|
+
const row = find();
|
|
307
|
+
const status = pathOf(entity.map.status);
|
|
308
|
+
if (status)
|
|
309
|
+
put(row, status, sourceValue(entity.map.status, "trashed"));
|
|
310
|
+
stampRow(entity, row);
|
|
311
|
+
answer = structuredClone(row);
|
|
312
|
+
}
|
|
313
|
+
else if (matches(ours.update)) {
|
|
314
|
+
const row = find();
|
|
315
|
+
merged(row, body);
|
|
316
|
+
stampRow(entity, row);
|
|
317
|
+
answer = structuredClone(row);
|
|
318
|
+
}
|
|
319
|
+
else {
|
|
320
|
+
refusals.push(operation);
|
|
321
|
+
throw new CliError("configuration_error", `the content fake takes no ${operation} write like this`);
|
|
322
|
+
}
|
|
323
|
+
if (lose) {
|
|
324
|
+
lose = false;
|
|
325
|
+
throw new CliError("outcome_unknown", "the connection dropped after the service got the write");
|
|
326
|
+
}
|
|
327
|
+
return answer;
|
|
328
|
+
};
|
|
329
|
+
const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
330
|
+
// The server's own path, as /wp-json; a site with a path of its own (`host/blog`) stands before it.
|
|
331
|
+
const serverPath = (options.api.servers?.[0]?.url ?? "").replace(/^https:\/\/[^/]*/, "").replace(/\/+$/, "");
|
|
332
|
+
const base = serverPath ? `(?:/[^/]+)*?${escaped(serverPath)}` : "";
|
|
333
|
+
// A literal segment wins over a placeholder: /users/me is not the user whose id is "me".
|
|
334
|
+
const placeholders = (path) => (path.match(/\{\w+\}/g) ?? []).length;
|
|
335
|
+
const http = [...operations.values()]
|
|
336
|
+
.sort((a, b) => a.binding.kind === "http" && b.binding.kind === "http"
|
|
337
|
+
? placeholders(a.binding.path) - placeholders(b.binding.path) || b.binding.path.length - a.binding.path.length
|
|
338
|
+
: 0)
|
|
339
|
+
.flatMap((operation) => operation.binding.kind === "http"
|
|
340
|
+
? [
|
|
341
|
+
{
|
|
342
|
+
operation,
|
|
343
|
+
method: operation.binding.method,
|
|
344
|
+
names: [...operation.binding.path.matchAll(/\{(\w+)\}/g)].map((one) => one[1]),
|
|
345
|
+
pattern: new RegExp(`^${base}${operation.binding.path
|
|
346
|
+
.split(/\{\w+\}/)
|
|
347
|
+
.map(escaped)
|
|
348
|
+
.join("([^/]+)")}$`),
|
|
349
|
+
},
|
|
350
|
+
]
|
|
351
|
+
: []);
|
|
352
|
+
const fetch = async (target, init) => {
|
|
353
|
+
const url = new URL(target instanceof Request ? target.url : target);
|
|
354
|
+
const method = (init?.method ?? (target instanceof Request ? target.method : "GET")).toUpperCase();
|
|
355
|
+
const found = http.find((one) => one.method === method && one.pattern.test(url.pathname));
|
|
356
|
+
if (!found) {
|
|
357
|
+
refusals.push(`${method} ${url.pathname}`);
|
|
358
|
+
return Response.json({ message: "no such route" }, { status: 404 });
|
|
359
|
+
}
|
|
360
|
+
const values = url.pathname.match(found.pattern)?.slice(1) ?? [];
|
|
361
|
+
const request = {
|
|
362
|
+
path: Object.fromEntries(found.names.map((name, index) => [name, decodeURIComponent(values[index] ?? "")])),
|
|
363
|
+
query: Object.fromEntries(url.searchParams),
|
|
364
|
+
headers: {},
|
|
365
|
+
fields: {},
|
|
366
|
+
...(typeof init?.body === "string" ? { body: init.body } : {}),
|
|
367
|
+
};
|
|
368
|
+
try {
|
|
369
|
+
if (found.operation.effect === "read") {
|
|
370
|
+
const answer = await read(found.operation.id, request);
|
|
371
|
+
return Response.json(answer.body, { headers: answer.headers });
|
|
372
|
+
}
|
|
373
|
+
return Response.json(write(found.operation.id, request));
|
|
374
|
+
}
|
|
375
|
+
catch (error) {
|
|
376
|
+
if (!(error instanceof CliError) || error.code === "outcome_unknown")
|
|
377
|
+
throw error;
|
|
378
|
+
return Response.json({ message: error.message }, { status: statusOf(error) });
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
const call = Object.assign(async (operation, request) => (await read(operation, request)).body, {
|
|
382
|
+
withHeaders: read,
|
|
383
|
+
});
|
|
384
|
+
const locate = (kind, id) => {
|
|
385
|
+
for (const [index, held] of (rows[kind] ?? []).entries()) {
|
|
386
|
+
const entity = entities(kind)[index];
|
|
387
|
+
const row = held.find((one) => idOf(entity, one) === id);
|
|
388
|
+
if (row)
|
|
389
|
+
return { entity, held, row };
|
|
390
|
+
}
|
|
391
|
+
return undefined;
|
|
392
|
+
};
|
|
393
|
+
return {
|
|
394
|
+
call,
|
|
395
|
+
write: async (_command, operation, request) => ({
|
|
396
|
+
operation_id: `op-${writes.length + 1}`,
|
|
397
|
+
result: write(operation, request),
|
|
398
|
+
}),
|
|
399
|
+
fetch,
|
|
400
|
+
rows,
|
|
401
|
+
ids: (kind) => (rows[kind] ?? []).flatMap((held, index) => held.map((row) => idOf(entities(kind)[index], row))),
|
|
402
|
+
writes,
|
|
403
|
+
refusals,
|
|
404
|
+
touch(kind, id) {
|
|
405
|
+
const found = locate(kind, id);
|
|
406
|
+
if (found)
|
|
407
|
+
stampRow(found.entity, found.row);
|
|
408
|
+
},
|
|
409
|
+
trash(id) {
|
|
410
|
+
const found = locate("post", id);
|
|
411
|
+
const status = found && pathOf(found.entity.map.status);
|
|
412
|
+
if (!found || !status)
|
|
413
|
+
return;
|
|
414
|
+
put(found.row, status, sourceValue(found.entity.map.status, "trashed"));
|
|
415
|
+
stampRow(found.entity, found.row);
|
|
416
|
+
},
|
|
417
|
+
remove(kind, id) {
|
|
418
|
+
const found = locate(kind, id);
|
|
419
|
+
if (found)
|
|
420
|
+
found.held.splice(found.held.indexOf(found.row), 1);
|
|
421
|
+
},
|
|
422
|
+
loseNextAnswer() {
|
|
423
|
+
lose = true;
|
|
424
|
+
},
|
|
425
|
+
};
|
|
426
|
+
};
|
package/dist/content/writer.d.ts
CHANGED
|
@@ -18,6 +18,11 @@ export type ContentDraft = ContentFields & {
|
|
|
18
18
|
export interface ContentWriteOptions {
|
|
19
19
|
/** Journaled before the call. */
|
|
20
20
|
operationId: string;
|
|
21
|
+
/**
|
|
22
|
+
* The keys the owner was asked about for this write, those at level `ask`: a writer over the `api` group does not
|
|
23
|
+
* ask them again. A key at `allow` is not among them, and passing one would skip a question the owner set.
|
|
24
|
+
*/
|
|
25
|
+
confirmed?: readonly PermissionKey[];
|
|
21
26
|
/**
|
|
22
27
|
* The version the copy holds. A source whose post has another one now refuses with `content.conflict`: someone
|
|
23
28
|
* changed it since the last sync, and the write would overwrite that.
|
package/dist/content/writer.js
CHANGED
|
@@ -15,7 +15,6 @@ export const CONTENT_WRITE_DEFAULTS = {
|
|
|
15
15
|
"posts.create": "ask",
|
|
16
16
|
"posts.update": "ask",
|
|
17
17
|
[POSTS_PUBLISH_KEY]: "ask",
|
|
18
|
-
"posts.schedule": "ask",
|
|
19
18
|
"posts.unpublish": "ask",
|
|
20
19
|
"posts.delete": "ask",
|
|
21
20
|
[POSTS_DELETE_FORCE_KEY]: "ask",
|
|
@@ -28,11 +27,9 @@ export const contentAlsoChecks = (path) => {
|
|
|
28
27
|
const [noun, command] = path;
|
|
29
28
|
if (path.length !== 2 || noun !== "posts")
|
|
30
29
|
return [];
|
|
31
|
-
if (command === "schedule")
|
|
32
|
-
return [POSTS_PUBLISH_KEY];
|
|
33
30
|
if (command === "update")
|
|
34
31
|
return [{ key: POSTS_PUBLISH_KEY, when: "the post is published or scheduled" }];
|
|
35
32
|
if (command === "delete")
|
|
36
|
-
return [{ key: POSTS_DELETE_FORCE_KEY, when: "--
|
|
33
|
+
return [{ key: POSTS_DELETE_FORCE_KEY, when: "--allow-delete" }];
|
|
37
34
|
return [];
|
|
38
35
|
};
|
package/dist/content/writes.js
CHANGED
|
@@ -14,7 +14,12 @@ const guardOf = (context, extra) => {
|
|
|
14
14
|
/** Checked and journaled once; a lost answer is `outcome_unknown`, and the owner syncs before writing again. */
|
|
15
15
|
const written = async (context, key, extra, operationId, act) => {
|
|
16
16
|
try {
|
|
17
|
-
|
|
17
|
+
// The keys the owner was asked about here (an `ask` level) need not be asked again by a writer's own call; a key
|
|
18
|
+
// allowed here was asked about by nobody, so it confirms nothing.
|
|
19
|
+
const settings = context.writes.settings();
|
|
20
|
+
const defaults = { ...DEFAULT_PERMISSIONS, ...CONTENT_WRITE_DEFAULTS, ...settings.permissionDefaults };
|
|
21
|
+
const asked = [key, ...extra].filter((one) => levelFor(settings.permissions, one, defaults).level === "ask");
|
|
22
|
+
return await guardedWrite(guardOf(context, extra), { chatId: null, kind: "edit", key, operationId }, () => act(asked));
|
|
18
23
|
}
|
|
19
24
|
catch (error) {
|
|
20
25
|
if (!isCliError(error) || error.code !== "outcome_unknown")
|
|
@@ -63,7 +68,7 @@ export const createPost = async (context, draft) => {
|
|
|
63
68
|
if (!draft.title?.trim() && !draft.body?.trim())
|
|
64
69
|
throw new CliError("validation_error", "a new post needs a title or a body", { reason: "content.empty" });
|
|
65
70
|
const operationId = newOperationId();
|
|
66
|
-
const post = await written(context, "posts.create", [], operationId, () => context.writes.writer.createDraft(draft, { operationId }));
|
|
71
|
+
const post = await written(context, "posts.create", [], operationId, (confirmed) => context.writes.writer.createDraft(draft, { operationId, confirmed }));
|
|
67
72
|
return kept(context, post, operationId);
|
|
68
73
|
};
|
|
69
74
|
/**
|
|
@@ -79,7 +84,7 @@ export const updatePost = async (context, externalId, fields, options = {}) => {
|
|
|
79
84
|
"Change only its title, excerpt or tags, or add --replace-body to replace the body anyway", { reason: "content.lossy-body", param: "--replace-body" });
|
|
80
85
|
const operationId = newOperationId();
|
|
81
86
|
const extra = PUBLIC.has(copy.record.status) ? [POSTS_PUBLISH_KEY] : [];
|
|
82
|
-
const post = await written(context, "posts.update", extra, operationId, () => context.writes.writer.update(externalId, fields, { operationId, version: copy.record.version ?? null }));
|
|
87
|
+
const post = await written(context, "posts.update", extra, operationId, (confirmed) => context.writes.writer.update(externalId, fields, { operationId, version: copy.record.version ?? null, confirmed }));
|
|
83
88
|
return kept(context, post, operationId);
|
|
84
89
|
};
|
|
85
90
|
/** Publishes now. A post the copy holds as published is answered as it is, and nothing is sent. */
|
|
@@ -88,7 +93,7 @@ export const publishPost = async (context, externalId) => {
|
|
|
88
93
|
if (copy.record.status === "published")
|
|
89
94
|
return { operationId: "", post: copy.record, unchanged: true };
|
|
90
95
|
const operationId = newOperationId();
|
|
91
|
-
const post = await written(context, POSTS_PUBLISH_KEY, [], operationId, () => context.writes.writer.publish(externalId, { operationId, version: copy.record.version ?? null }));
|
|
96
|
+
const post = await written(context, POSTS_PUBLISH_KEY, [], operationId, (confirmed) => context.writes.writer.publish(externalId, { operationId, version: copy.record.version ?? null, confirmed }));
|
|
92
97
|
return kept(context, post, operationId);
|
|
93
98
|
};
|
|
94
99
|
/** Publishes at `at`, which must be ahead: a source publishes a post dated in the past at once. */
|
|
@@ -102,7 +107,7 @@ export const schedulePost = async (context, externalId, at) => {
|
|
|
102
107
|
reason: "content.already-published",
|
|
103
108
|
});
|
|
104
109
|
const operationId = newOperationId();
|
|
105
|
-
const post = await written(context,
|
|
110
|
+
const post = await written(context, POSTS_PUBLISH_KEY, [], operationId, (confirmed) => context.writes.writer.schedule(externalId, at, { operationId, version: copy.record.version ?? null, confirmed }));
|
|
106
111
|
return kept(context, post, operationId);
|
|
107
112
|
};
|
|
108
113
|
export const unpublishPost = async (context, externalId) => {
|
|
@@ -110,15 +115,16 @@ export const unpublishPost = async (context, externalId) => {
|
|
|
110
115
|
if (copy.record.status === "draft")
|
|
111
116
|
return { operationId: "", post: copy.record, unchanged: true };
|
|
112
117
|
const operationId = newOperationId();
|
|
113
|
-
const post = await written(context, "posts.unpublish", [], operationId, () => context.writes.writer.unpublish(externalId, { operationId, version: copy.record.version ?? null }));
|
|
118
|
+
const post = await written(context, "posts.unpublish", [], operationId, (confirmed) => context.writes.writer.unpublish(externalId, { operationId, version: copy.record.version ?? null, confirmed }));
|
|
114
119
|
return kept(context, post, operationId);
|
|
115
120
|
};
|
|
116
121
|
/** Into the trash; `force` deletes for good and checks its own key. The copy keeps the last text as a revision. */
|
|
117
122
|
export const deletePost = async (context, externalId, options = {}) => {
|
|
118
123
|
const copy = await copyOf(context, externalId);
|
|
119
124
|
const operationId = newOperationId();
|
|
120
|
-
const post = await written(context, "posts.delete", options.force ? [POSTS_DELETE_FORCE_KEY] : [], operationId, () => context.writes.writer.trash(externalId, {
|
|
125
|
+
const post = await written(context, "posts.delete", options.force ? [POSTS_DELETE_FORCE_KEY] : [], operationId, (confirmed) => context.writes.writer.trash(externalId, {
|
|
121
126
|
operationId,
|
|
127
|
+
confirmed,
|
|
122
128
|
version: copy.record.version ?? null,
|
|
123
129
|
...(options.force ? { force: true } : {}),
|
|
124
130
|
}));
|
|
@@ -18,6 +18,8 @@ export interface CrmChangeCommandOptions {
|
|
|
18
18
|
pathOf: (command: Command) => string[];
|
|
19
19
|
/** Also mount `activities list`, for a CLI that copies the CRM's activities. */
|
|
20
20
|
activities?: boolean;
|
|
21
|
+
/** The CRM has leads; true when absent. */
|
|
22
|
+
leads?: boolean;
|
|
21
23
|
}
|
|
22
24
|
/** `changes list`: what happened in the copy in a window, newest first; `--format report` is the morning digest. */
|
|
23
25
|
export declare const addCrmChangeCommands: (program: Command, options: CrmChangeCommandOptions) => void;
|
package/dist/crm/cli/changes.js
CHANGED
|
@@ -124,11 +124,13 @@ const digestState = (schedule) => `crm:digest:${schedule}`;
|
|
|
124
124
|
/** `changes list`: what happened in the copy in a window, newest first; `--format report` is the morning digest. */
|
|
125
125
|
export const addCrmChangeCommands = (program, options) => {
|
|
126
126
|
const { within, example, now, ownerOf, pathOf } = options;
|
|
127
|
+
const deals = options.leads === false ? "deals" : "deals and leads";
|
|
127
128
|
if (options.activities)
|
|
128
129
|
addCrmActivityCommands(program, { within, example, now, ownerOf, pathOf });
|
|
129
|
-
const group = annotate(program.command("changes"), { effects: NO_EFFECTS }).description(
|
|
130
|
+
const group = annotate(program.command("changes"), { effects: NO_EFFECTS }).description(`what changed in the CRM's ${options.leads === false ? "deals" : "deals, leads"}, activities and contacts, ` +
|
|
131
|
+
"as the syncs copied it");
|
|
130
132
|
example(withQuery(answerEntity(annotate(group.command("list"), { effects: LOCAL_READ }), "crm_change", crmChange)
|
|
131
|
-
.description(
|
|
133
|
+
.description(`${deals} made, moved, won, lost and given another owner, activities added and done, and contacts ` +
|
|
132
134
|
"added, newest first; the last day unless at: says otherwise")
|
|
133
135
|
.option("--limit <n>", `changes per page, 1–${MOST}`, integer(MOST), 50)
|
|
134
136
|
.option("--cursor <cursor>", "the next page, as the last answer's page.next gave it")
|
package/dist/crm/cli/index.d.ts
CHANGED
|
@@ -54,6 +54,8 @@ export interface CrmCommandOptions {
|
|
|
54
54
|
* `source.list`/`get`, `user` mounts `users` list/show over `source.users`. None when absent.
|
|
55
55
|
*/
|
|
56
56
|
live?: readonly CrmLiveRecord[];
|
|
57
|
+
/** `words` for a source whose live lists are the service's own search: their help takes words, not field terms. */
|
|
58
|
+
liveQuery?: "fields" | "words";
|
|
57
59
|
activities?: boolean;
|
|
58
60
|
files?: boolean;
|
|
59
61
|
now?: () => number;
|