@wirecat/cli-core 0.737.0 → 0.739.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 +49 -0
- package/dist/cli/documents/file-edit.js +79 -34
- package/dist/cli/documents/file-update.d.ts +5 -0
- package/dist/cli/documents/index.d.ts +1 -0
- package/dist/cli/documents/index.js +1 -0
- package/dist/cli/documents/library.js +3 -1
- package/dist/cli/documents/rekey.d.ts +22 -0
- package/dist/cli/documents/rekey.js +25 -0
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/setup-command.js +4 -2
- package/dist/cli/token-session.d.ts +4 -2
- package/dist/cli/token-session.js +8 -4
- package/dist/documents/file-mirror-model.d.ts +4 -1
- package/dist/documents/model.d.ts +6 -0
- package/dist/errors/reasons.js +2 -15
- package/dist/errors/sftp-reasons.d.ts +5 -0
- package/dist/errors/sftp-reasons.js +15 -0
- package/dist/office/create.d.ts +38 -7
- package/dist/office/create.js +84 -20
- package/dist/office/index.d.ts +1 -1
- package/dist/services/documents/file-text.d.ts +4 -1
- package/dist/services/documents/file-text.js +16 -2
- package/dist/services/documents/ingestion.d.ts +5 -0
- package/dist/services/documents/ingestion.js +21 -1
- package/dist/services/documents/plan.js +143 -101
- package/dist/services/files/guarded-write.d.ts +6 -0
- package/dist/services/files/guarded-write.js +7 -1
- package/dist/services/files/mirror.js +2 -3
- package/dist/services/metadata.d.ts +1 -1
- package/dist/setup/plain.d.ts +7 -4
- package/dist/setup/plain.js +7 -5
- package/dist/store/sqlite/file-note-rekey.d.ts +8 -0
- package/dist/store/sqlite/file-note-rekey.js +47 -0
- package/dist/store/sqlite/notes.d.ts +7 -2
- package/dist/store/sqlite/notes.js +4 -1
- package/dist/terminal/hyperlink.d.ts +8 -0
- package/dist/terminal/hyperlink.js +21 -0
- package/package.json +1 -1
package/dist/office/create.js
CHANGED
|
@@ -6,6 +6,8 @@ import { escapeText } from "./xml.js";
|
|
|
6
6
|
const MAX_ROW = 1_048_576;
|
|
7
7
|
const MAX_COLUMN = 16_384;
|
|
8
8
|
const MAX_CELL_TEXT = 32_767;
|
|
9
|
+
const MAX_FORMULA = 8_192;
|
|
10
|
+
const MAX_TABLE_COLUMNS = 63;
|
|
9
11
|
const XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
|
|
10
12
|
const CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
|
|
11
13
|
const PACKAGE_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
|
|
@@ -64,6 +66,14 @@ class SharedStrings {
|
|
|
64
66
|
return `<sst xmlns="${SHEET_NS}" count="${this.count}" uniqueCount="${this.size}">${items.join("")}</sst>`;
|
|
65
67
|
}
|
|
66
68
|
}
|
|
69
|
+
const formulaXml = (address, formula, style) => {
|
|
70
|
+
const text = formula.startsWith("=") ? formula.slice(1) : formula;
|
|
71
|
+
if (!text.trim())
|
|
72
|
+
throw refuse(`${address}: a formula cannot be empty`, "office.invalid-value");
|
|
73
|
+
if (text.length > MAX_FORMULA)
|
|
74
|
+
throw refuse(`${address}: a formula holds at most 8,192 characters`, "office.invalid-value");
|
|
75
|
+
return `<c r="${address}"${style}><f>${escapeText(text)}</f></c>`;
|
|
76
|
+
};
|
|
67
77
|
const cellXml = (address, value, style, strings) => {
|
|
68
78
|
if (typeof value === "boolean")
|
|
69
79
|
return `<c r="${address}"${style} t="b"><v>${value ? 1 : 0}</v></c>`;
|
|
@@ -76,7 +86,7 @@ const cellXml = (address, value, style, strings) => {
|
|
|
76
86
|
throw refuse(`${address}: a cell holds at most 32,767 characters`, "office.invalid-value");
|
|
77
87
|
return `<c r="${address}"${style} t="s"><v>${strings.index(value)}</v></c>`;
|
|
78
88
|
};
|
|
79
|
-
const worksheetXml = (sheet, strings, boldHeader) => {
|
|
89
|
+
const worksheetXml = (sheet, strings, boldHeader, formulas) => {
|
|
80
90
|
if (sheet.rows.length > MAX_ROW)
|
|
81
91
|
throw refuse(`sheet "${sheet.name}" has more than 1,048,576 rows`, "office.invalid-cell");
|
|
82
92
|
let right = 0;
|
|
@@ -84,12 +94,20 @@ const worksheetXml = (sheet, strings, boldHeader) => {
|
|
|
84
94
|
const rows = sheet.rows.flatMap((values, down) => {
|
|
85
95
|
if (values.length > MAX_COLUMN)
|
|
86
96
|
throw refuse(`row ${down + 1} of "${sheet.name}" has more than 16,384 cells`, "office.invalid-cell");
|
|
87
|
-
const
|
|
88
|
-
const cells = values.flatMap((
|
|
97
|
+
const header = (boldHeader || sheet.header === true) && down === 0;
|
|
98
|
+
const cells = values.flatMap((cell, across) => {
|
|
99
|
+
const formatted = cell !== null && typeof cell === "object";
|
|
100
|
+
const value = formatted ? ("formula" in cell ? undefined : cell.value) : cell;
|
|
89
101
|
if (value === null)
|
|
90
102
|
return [];
|
|
91
103
|
right = Math.max(right, across + 1);
|
|
92
|
-
|
|
104
|
+
const address = `${columnName(across + 1)}${down + 1}`;
|
|
105
|
+
const style = header || (formatted && cell.bold === true) ? ' s="1"' : "";
|
|
106
|
+
if (formatted && "formula" in cell) {
|
|
107
|
+
formulas.count++;
|
|
108
|
+
return [formulaXml(address, cell.formula, style)];
|
|
109
|
+
}
|
|
110
|
+
return [cellXml(address, value, style, strings)];
|
|
93
111
|
});
|
|
94
112
|
if (!cells.length)
|
|
95
113
|
return [];
|
|
@@ -113,16 +131,18 @@ const STYLES = `<styleSheet xmlns="${SHEET_NS}">` +
|
|
|
113
131
|
"</styleSheet>";
|
|
114
132
|
/**
|
|
115
133
|
* A new workbook with these sheets and values: strings in a shared strings part (a string that starts with `=` stays
|
|
116
|
-
* text), numbers and booleans typed. No document properties, so the same input gives the same
|
|
134
|
+
* text), numbers and booleans typed, `{formula}` a formula. No document properties, so the same input gives the same
|
|
135
|
+
* bytes.
|
|
117
136
|
*/
|
|
118
137
|
export const createXlsx = (options) => {
|
|
119
138
|
const { sheets, boldHeader = false } = options;
|
|
120
139
|
checkSheetNames(sheets);
|
|
121
140
|
const strings = new SharedStrings();
|
|
141
|
+
const formulas = { count: 0 };
|
|
122
142
|
const parts = {};
|
|
123
143
|
const types = { "xl/workbook.xml": "spreadsheetml.sheet.main+xml" };
|
|
124
144
|
sheets.forEach((sheet, index) => {
|
|
125
|
-
parts[`xl/worksheets/sheet${index + 1}.xml`] = worksheetXml(sheet, strings, boldHeader);
|
|
145
|
+
parts[`xl/worksheets/sheet${index + 1}.xml`] = worksheetXml(sheet, strings, boldHeader, formulas);
|
|
126
146
|
types[`xl/worksheets/sheet${index + 1}.xml`] = "spreadsheetml.worksheet+xml";
|
|
127
147
|
});
|
|
128
148
|
types["xl/styles.xml"] = "spreadsheetml.styles+xml";
|
|
@@ -137,10 +157,12 @@ export const createXlsx = (options) => {
|
|
|
137
157
|
const listed = sheets
|
|
138
158
|
.map((sheet, index) => `<sheet name="${escapeAttribute(sheet.name)}" sheetId="${index + 1}" r:id="rId${index + 1}"/>`)
|
|
139
159
|
.join("");
|
|
160
|
+
// No cached results are written, so Excel and LibreOffice must compute every formula as the file opens.
|
|
161
|
+
const calculation = formulas.count ? '<calcPr calcId="191029" fullCalcOnLoad="1"/>' : "";
|
|
140
162
|
return packed({
|
|
141
163
|
"[Content_Types].xml": contentTypes(types),
|
|
142
164
|
"_rels/.rels": relationships([["officeDocument", "xl/workbook.xml"]]),
|
|
143
|
-
"xl/workbook.xml": `<workbook xmlns="${SHEET_NS}" xmlns:r="${OFFICE_REL}"><sheets>${listed}</sheets
|
|
165
|
+
"xl/workbook.xml": `<workbook xmlns="${SHEET_NS}" xmlns:r="${OFFICE_REL}"><sheets>${listed}</sheets>${calculation}</workbook>`,
|
|
144
166
|
"xl/_rels/workbook.xml.rels": relationships(links),
|
|
145
167
|
"xl/styles.xml": STYLES,
|
|
146
168
|
...(strings.size ? { "xl/sharedStrings.xml": strings.xml() } : {}),
|
|
@@ -173,29 +195,71 @@ const NUMBERING = `<w:numbering xmlns:w="${WORD_NS}"><w:abstractNum w:abstractNu
|
|
|
173
195
|
'<w:multiLevelType w:val="singleLevel"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/>' +
|
|
174
196
|
'<w:lvlText w:val="•"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>' +
|
|
175
197
|
'</w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>';
|
|
176
|
-
const
|
|
177
|
-
if (!NEW_PARAGRAPH_STYLES.includes(style))
|
|
178
|
-
throw refuse(`${style} is not a style here; use ${NEW_PARAGRAPH_STYLES.join(", ")}`, "office.invalid-value");
|
|
179
|
-
// The list's numbering is on the paragraph too: a reader that ignores a style's numbering still sees a bullet.
|
|
180
|
-
const properties = style === "Normal"
|
|
181
|
-
? ""
|
|
182
|
-
: `<w:pPr><w:pStyle w:val="${style}"/>${style === "ListBullet" ? '<w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr>' : ""}</w:pPr>`;
|
|
198
|
+
const runXml = ({ text, bold, italic }) => {
|
|
183
199
|
const content = text
|
|
184
200
|
.replace(/\r\n?/gu, "\n")
|
|
185
201
|
.split(/(\n|\t)/u)
|
|
186
202
|
.filter((piece) => piece !== "")
|
|
187
203
|
.map((piece) => piece === "\n" ? "<w:br/>" : piece === "\t" ? "<w:tab/>" : `<w:t xml:space="preserve">${escapeText(piece)}</w:t>`)
|
|
188
204
|
.join("");
|
|
189
|
-
|
|
205
|
+
if (!content)
|
|
206
|
+
return "";
|
|
207
|
+
const properties = (bold ? "<w:b/><w:bCs/>" : "") + (italic ? "<w:i/><w:iCs/>" : "");
|
|
208
|
+
return `<w:r>${properties ? `<w:rPr>${properties}</w:rPr>` : ""}${content}</w:r>`;
|
|
209
|
+
};
|
|
210
|
+
const paragraphXml = (paragraph) => {
|
|
211
|
+
const { style = "Normal" } = paragraph;
|
|
212
|
+
if (!NEW_PARAGRAPH_STYLES.includes(style))
|
|
213
|
+
throw refuse(`${style} is not a style here; use ${NEW_PARAGRAPH_STYLES.join(", ")}`, "office.invalid-value");
|
|
214
|
+
// The list's numbering is on the paragraph too: a reader that ignores a style's numbering still sees a bullet.
|
|
215
|
+
const properties = style === "Normal"
|
|
216
|
+
? ""
|
|
217
|
+
: `<w:pPr><w:pStyle w:val="${style}"/>${style === "ListBullet" ? '<w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr>' : ""}</w:pPr>`;
|
|
218
|
+
const runs = "runs" in paragraph ? paragraph.runs : [paragraph];
|
|
219
|
+
return `<w:p>${properties}${runs.map(runXml).join("")}</w:p>`;
|
|
220
|
+
};
|
|
221
|
+
// The text width of the A4 page between its margins, in twentieths of a point.
|
|
222
|
+
const TEXT_WIDTH = 11_906 - 2 * 1_417;
|
|
223
|
+
const BORDER = 'w:val="single" w:sz="4" w:space="0" w:color="auto"';
|
|
224
|
+
const tableXml = ({ table, header = false }) => {
|
|
225
|
+
const columns = table.reduce((widest, row) => Math.max(widest, row.length), 1);
|
|
226
|
+
if (columns > MAX_TABLE_COLUMNS)
|
|
227
|
+
throw refuse("a Word table has at most 63 columns", "office.invalid-value");
|
|
228
|
+
const width = Math.floor(TEXT_WIDTH / columns);
|
|
229
|
+
const borders = ["top", "left", "bottom", "right", "insideH", "insideV"].map((side) => `<w:${side} ${BORDER}/>`);
|
|
230
|
+
const rows = (table.length ? table : [[]]).map((cells, down) => {
|
|
231
|
+
const bold = header && down === 0;
|
|
232
|
+
const tcs = Array.from({ length: columns }, (_, across) => {
|
|
233
|
+
const text = cells[across] ?? "";
|
|
234
|
+
return `<w:tc><w:tcPr><w:tcW w:w="${width}" w:type="dxa"/></w:tcPr><w:p>${runXml({ text, bold })}</w:p></w:tc>`;
|
|
235
|
+
});
|
|
236
|
+
return `<w:tr>${bold ? "<w:trPr><w:tblHeader/></w:trPr>" : ""}${tcs.join("")}</w:tr>`;
|
|
237
|
+
});
|
|
238
|
+
return (`<w:tbl><w:tblPr><w:tblW w:w="${width * columns}" w:type="dxa"/><w:tblBorders>${borders.join("")}</w:tblBorders>` +
|
|
239
|
+
`</w:tblPr><w:tblGrid>${`<w:gridCol w:w="${width}"/>`.repeat(columns)}</w:tblGrid>` +
|
|
240
|
+
`${rows.join("")}</w:tbl>`);
|
|
241
|
+
};
|
|
242
|
+
// Word merges two tables that touch and needs a paragraph to end the body, so a table is never last or next to another.
|
|
243
|
+
const bodyXml = (blocks) => {
|
|
244
|
+
let previousTable = false;
|
|
245
|
+
const parts = blocks.flatMap((block) => {
|
|
246
|
+
const isTable = "table" in block;
|
|
247
|
+
const xml = isTable ? tableXml(block) : paragraphXml(block);
|
|
248
|
+
const between = isTable && previousTable ? ["<w:p/>"] : [];
|
|
249
|
+
previousTable = isTable;
|
|
250
|
+
return [...between, xml];
|
|
251
|
+
});
|
|
252
|
+
if (!parts.length || previousTable)
|
|
253
|
+
parts.push("<w:p/>");
|
|
254
|
+
return parts.join("");
|
|
190
255
|
};
|
|
191
256
|
/**
|
|
192
|
-
* A new Word document with these paragraphs, on A4 with 2.5 cm margins, and a styles part that defines
|
|
193
|
-
* Heading1 to Heading3, Normal and ListBullet (a bullet list). No document properties, so the same input gives
|
|
194
|
-
* same bytes.
|
|
257
|
+
* A new Word document with these paragraphs and tables, on A4 with 2.5 cm margins, and a styles part that defines
|
|
258
|
+
* Title, Heading1 to Heading3, Normal and ListBullet (a bullet list). No document properties, so the same input gives
|
|
259
|
+
* the same bytes.
|
|
195
260
|
*/
|
|
196
261
|
export const createDocx = (options) => {
|
|
197
|
-
|
|
198
|
-
const body = options.paragraphs.length ? options.paragraphs.map(paragraphXml).join("") : "<w:p/>";
|
|
262
|
+
const body = bodyXml(options.paragraphs);
|
|
199
263
|
const section = '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1417" w:right="1417" w:bottom="1417" w:left="1417" ' +
|
|
200
264
|
'w:header="708" w:footer="708" w:gutter="0"/></w:sectPr>';
|
|
201
265
|
return packed({
|
package/dist/office/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { type CreateDocxOptions, type CreateXlsxOptions, createDocx, createXlsx, NEW_PARAGRAPH_STYLES, type NewParagraph, type NewParagraphStyle, type NewSheet, } from "./create.js";
|
|
1
|
+
export { type CreateDocxOptions, type CreateXlsxOptions, createDocx, createXlsx, NEW_PARAGRAPH_STYLES, type NewCell, type NewFormulaCell, type NewParagraph, type NewParagraphStyle, type NewRun, type NewSheet, type NewTable, type NewValueCell, } from "./create.js";
|
|
2
2
|
export { type DocxEdit, type DocxParagraph, type EditDocxResult, editDocxParagraphs, readDocxParagraphs, } from "./docx.js";
|
|
3
3
|
export { type CellType, type CellValue, type EditXlsxOptions, type EditXlsxResult, editXlsxCells, type ReadXlsxOptions, readXlsxCells, type XlsxCell, type XlsxEdit, type XlsxSheet, } from "./xlsx.js";
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* A file a documents sync reads the text of: PDF, Word (doc, docx), RTF, OpenDocument (odt, ods, odp), xlsx, pptx,
|
|
3
|
+
* EPUB, HTML, CSV, TSV, plain text and Markdown. Images and scans are kept by name only.
|
|
4
|
+
*/
|
|
2
5
|
export declare const readableFile: ({ name, mime }: {
|
|
3
6
|
name: string;
|
|
4
7
|
mime: string;
|
|
@@ -3,15 +3,29 @@ import { engineHint, extractText, importEngine, MAX_TEXT_CHARS } from "../../att
|
|
|
3
3
|
import { attachmentMaxBytes } from "../../attachments/limits.js";
|
|
4
4
|
const READABLE = new Set([
|
|
5
5
|
"application/pdf",
|
|
6
|
+
"application/msword",
|
|
6
7
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
7
8
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
9
|
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
10
|
+
"application/vnd.oasis.opendocument.text",
|
|
11
|
+
"application/vnd.oasis.opendocument.spreadsheet",
|
|
12
|
+
"application/vnd.oasis.opendocument.presentation",
|
|
13
|
+
"application/epub+zip",
|
|
14
|
+
"application/rtf",
|
|
15
|
+
"text/rtf",
|
|
16
|
+
"text/html",
|
|
17
|
+
"application/xhtml+xml",
|
|
8
18
|
"text/csv",
|
|
9
19
|
"text/tab-separated-values",
|
|
10
20
|
"text/plain",
|
|
11
21
|
"text/markdown",
|
|
12
22
|
]);
|
|
13
|
-
/**
|
|
14
|
-
|
|
23
|
+
/**
|
|
24
|
+
* A file a documents sync reads the text of: PDF, Word (doc, docx), RTF, OpenDocument (odt, ods, odp), xlsx, pptx,
|
|
25
|
+
* EPUB, HTML, CSV, TSV, plain text and Markdown. Images and scans are kept by name only.
|
|
26
|
+
*/
|
|
27
|
+
export const readableFile = ({ name, mime }) => READABLE.has(mime) ||
|
|
28
|
+
/\.(md|markdown|txt|pdf|doc|docx|rtf|odt|ods|odp|xlsx|pptx|epub|html?|xhtml|csv|tsv)$/iu.test(name);
|
|
15
29
|
/**
|
|
16
30
|
* The text of a downloaded file through cli-core's readers, or a `validation_error` that says why there is none, in
|
|
17
31
|
* words a person acts on. `command` names the CLI in the hint for a missing reader.
|
|
@@ -35,6 +35,11 @@ export declare const documentIngestion: <M extends SourceFile>(store: Pick<Messa
|
|
|
35
35
|
until: () => boolean;
|
|
36
36
|
}) => Promise<number>;
|
|
37
37
|
save: (principal: string, content: SourceContent<M>, hash: string) => Promise<string>;
|
|
38
|
+
/**
|
|
39
|
+
* Moves a synced document to the new id its source gave the file, as a replace through a temporary file does, so
|
|
40
|
+
* its tags, the notes about it and its links stay with it. False when the file was never synced.
|
|
41
|
+
*/
|
|
42
|
+
rekey: (principal: string, from: string, to: string) => Promise<boolean>;
|
|
38
43
|
remove: (principal: string, id: string, reason?: SourceRemoval) => Promise<void>;
|
|
39
44
|
prune: (principal: string, before: string) => Promise<{
|
|
40
45
|
versions: number;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CliError } from "@wirecat/cli-base";
|
|
1
|
+
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
2
|
import { walkQuery } from "@wirecat/cli-base/query";
|
|
3
3
|
export const documentIngestion = (store, options) => {
|
|
4
4
|
const folder = async (principal, create) => {
|
|
@@ -101,6 +101,26 @@ export const documentIngestion = (store, options) => {
|
|
|
101
101
|
await options.observed?.(principal, content.metadata, note.id);
|
|
102
102
|
return note.ref;
|
|
103
103
|
},
|
|
104
|
+
/**
|
|
105
|
+
* Moves a synced document to the new id its source gave the file, as a replace through a temporary file does, so
|
|
106
|
+
* its tags, the notes about it and its links stay with it. False when the file was never synced.
|
|
107
|
+
*/
|
|
108
|
+
rekey: async (principal, from, to) => {
|
|
109
|
+
const selected = await folder(principal, false);
|
|
110
|
+
if (!selected)
|
|
111
|
+
return false;
|
|
112
|
+
try {
|
|
113
|
+
const [was, now] = [options.externalId(from), options.externalId(to)];
|
|
114
|
+
const note = await store.notes.renameFileNote(selected.id, was, now, { fold: true });
|
|
115
|
+
await stale(note.ref);
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (isCliError(error) && error.code === "not_found")
|
|
120
|
+
return false;
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
},
|
|
104
124
|
remove: async (principal, id, reason) => {
|
|
105
125
|
const selected = await folder(principal, false);
|
|
106
126
|
if (selected) {
|
|
@@ -228,114 +228,156 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
228
228
|
let spent = 0;
|
|
229
229
|
let listed = 0;
|
|
230
230
|
let stopped = null;
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
// One listing at least per call, so a folder with more children than the bound still moves on.
|
|
240
|
-
// The run's own signal too: a cooperative sync is not cut from outside, and a CLI may pass no budget.
|
|
241
|
-
// The time budget keeps a margin of 5 s or more, so a short run would never list a folder: its first request
|
|
242
|
-
// goes ahead while one still fits before the deadline itself.
|
|
243
|
-
const taken = options.signal?.aborted
|
|
244
|
-
? "cancelled"
|
|
245
|
-
: listed > 0 && spent >= maxEntries
|
|
246
|
-
? "entries"
|
|
247
|
-
: budget?.take();
|
|
248
|
-
stopped = taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
|
|
249
|
-
if (stopped)
|
|
250
|
-
break;
|
|
251
|
-
if (!step.folder) {
|
|
252
|
-
const known = state.folders[step.id];
|
|
253
|
-
let root;
|
|
254
|
-
try {
|
|
255
|
-
root = await source.metadata(step.id, known);
|
|
256
|
-
}
|
|
257
|
-
catch (error) {
|
|
258
|
-
// Without a feed, a folder the last pass held and the provider no longer finds is skipped as unavailable,
|
|
259
|
-
// as a round of changes does, so a moved or deleted root does not fail every sync. A source with a feed
|
|
260
|
-
// walks in full only on a rescan, where a root it cannot read still fails and keeps what it holds.
|
|
261
|
-
if (feed || !known || errorOf(error).code !== "not_found")
|
|
262
|
-
throw error;
|
|
263
|
-
walk.stack.pop();
|
|
264
|
-
visited.add(step.id);
|
|
265
|
-
folders[step.id] = { ...known, trashed: true };
|
|
266
|
-
spent++;
|
|
267
|
-
listed++;
|
|
268
|
-
continue;
|
|
269
|
-
}
|
|
270
|
-
if (!isFolder(root) || root.trashed)
|
|
271
|
-
throw new CliError("validation_error", "configured root is not an accessible folder");
|
|
272
|
-
container(root);
|
|
273
|
-
// Kept on the step, so a call stopped before the listing does not read the root again.
|
|
274
|
-
step.folder = root;
|
|
275
|
-
stopped = charge();
|
|
276
|
-
if (stopped)
|
|
277
|
-
break;
|
|
278
|
-
}
|
|
279
|
-
const folder = step.folder;
|
|
280
|
-
let children;
|
|
281
|
-
let more;
|
|
231
|
+
// A value that is not a whole number would leave the batch empty and end the walk as if it found nothing.
|
|
232
|
+
const asked = source.parallelListings;
|
|
233
|
+
const width = Number.isInteger(asked) && asked > 1 ? Math.min(asked, 8) : 1;
|
|
234
|
+
// A root read in a listing that then fails is still filed, as the walk saves it on the step.
|
|
235
|
+
const rootsRead = new Map();
|
|
236
|
+
const list = async (step) => {
|
|
237
|
+
if (!step.folder) {
|
|
238
|
+
let root;
|
|
282
239
|
try {
|
|
283
|
-
|
|
284
|
-
({ files: children, cursor: more } = await source.childrenPage(folder.id, step.listing, folder));
|
|
285
|
-
else
|
|
286
|
-
children = await source.children(folder.id, folder);
|
|
240
|
+
root = await source.metadata(step.id, state.folders[step.id]);
|
|
287
241
|
}
|
|
288
242
|
catch (error) {
|
|
289
|
-
|
|
243
|
+
// Without a feed, a folder the last pass held and the provider no longer finds is skipped as unavailable,
|
|
244
|
+
// as a round of changes does, so a moved or deleted root does not fail every sync. A source with a feed
|
|
245
|
+
// walks in full only on a rescan, where a root it cannot read still fails and keeps what it holds.
|
|
246
|
+
if (feed || !state.folders[step.id] || errorOf(error).code !== "not_found")
|
|
290
247
|
throw error;
|
|
291
|
-
|
|
292
|
-
// page, which tells a gone folder from a stale cursor, and the files already kept are only kept again.
|
|
293
|
-
if (step.listing !== undefined) {
|
|
294
|
-
delete step.listing;
|
|
295
|
-
spent++;
|
|
296
|
-
listed++;
|
|
297
|
-
continue;
|
|
298
|
-
}
|
|
299
|
-
// Deleted or unshared since the walk saved it: gone, with what is below it, instead of failing every sync.
|
|
300
|
-
// A listing's 404 alone can be passing, so the folder is read again and is gone only when that read is a
|
|
301
|
-
// 404 too or finds it trashed; on any doubt the call fails and the next sync lists it again.
|
|
302
|
-
if (!(await vanished(folder.id, folder)))
|
|
303
|
-
throw error;
|
|
304
|
-
walk.stack.pop();
|
|
305
|
-
visited.add(folder.id);
|
|
306
|
-
folders[folder.id] = { ...folder, trashed: true };
|
|
307
|
-
drop(folder.id, "unavailable");
|
|
308
|
-
spent++;
|
|
309
|
-
listed++;
|
|
310
|
-
continue;
|
|
248
|
+
return { kind: "root-gone" };
|
|
311
249
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
250
|
+
if (!isFolder(root) || root.trashed)
|
|
251
|
+
throw new CliError("validation_error", "configured root is not an accessible folder");
|
|
252
|
+
rootsRead.set(step, root);
|
|
253
|
+
// Kept on the step, so a call stopped before the listing does not read the root again.
|
|
254
|
+
step.folder = root;
|
|
255
|
+
const after = charge();
|
|
256
|
+
if (after)
|
|
257
|
+
return { kind: "root", stopped: after };
|
|
258
|
+
}
|
|
259
|
+
const folder = step.folder;
|
|
260
|
+
try {
|
|
261
|
+
if (!source.childrenPage)
|
|
262
|
+
return { kind: "listed", children: await source.children(folder.id, folder) };
|
|
263
|
+
const page = await source.childrenPage(folder.id, step.listing, folder);
|
|
264
|
+
return { kind: "listed", children: page.files, ...(page.cursor ? { more: page.cursor } : {}) };
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
if (errorOf(error).code !== "not_found")
|
|
268
|
+
throw error;
|
|
269
|
+
// A later page's 404 can be a cursor the provider no longer knows: the folder is listed again from its first
|
|
270
|
+
// page, which tells a gone folder from a stale cursor, and the files already kept are only kept again.
|
|
271
|
+
if (step.listing !== undefined)
|
|
272
|
+
return { kind: "relist" };
|
|
273
|
+
// Deleted or unshared since the walk saved it: gone, with what is below it, instead of failing every sync.
|
|
274
|
+
// A listing's 404 alone can be passing, so the folder is read again and is gone only when that read is a
|
|
275
|
+
// 404 too or finds it trashed; on any doubt the call fails and the next sync lists it again.
|
|
276
|
+
if (!(await vanished(folder.id, folder)))
|
|
277
|
+
throw error;
|
|
278
|
+
return { kind: "gone" };
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
// In the step's own place, so the stack keeps the order a walk one folder at a time has.
|
|
282
|
+
const place = (step, entries) => current.stack.splice(current.stack.indexOf(step), 1, ...entries);
|
|
283
|
+
const apply = (step, result) => {
|
|
284
|
+
if (result.kind === "root") {
|
|
285
|
+
stopped ??= result.stopped;
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
spent++;
|
|
289
|
+
listed++;
|
|
290
|
+
if (result.kind === "relist") {
|
|
291
|
+
delete step.listing;
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (result.kind === "root-gone") {
|
|
295
|
+
place(step, []);
|
|
296
|
+
visited.add(step.id);
|
|
297
|
+
folders[step.id] = { ...state.folders[step.id], trashed: true };
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
const folder = step.folder;
|
|
301
|
+
if (result.kind === "gone") {
|
|
302
|
+
place(step, []);
|
|
303
|
+
visited.add(folder.id);
|
|
304
|
+
folders[folder.id] = { ...folder, trashed: true };
|
|
305
|
+
drop(folder.id, "unavailable");
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
const { children, more } = result;
|
|
309
|
+
spent += children.length;
|
|
310
|
+
current.discovered += children.length;
|
|
311
|
+
folders[folder.id] = folder;
|
|
312
|
+
const nested = [];
|
|
313
|
+
for (const file of children)
|
|
314
|
+
if (isFolder(file)) {
|
|
315
|
+
container(file);
|
|
316
|
+
if (excluded(file))
|
|
317
|
+
continue;
|
|
318
|
+
if (walked(file.id))
|
|
319
|
+
folders[file.id] = file;
|
|
329
320
|
else
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
// A folder with more pages goes back on top with its cursor, above its child folders.
|
|
335
|
-
if (more)
|
|
336
|
-
walk.stack.push({ ...step, folder, listing: more });
|
|
321
|
+
nested.push({ id: file.id, ancestry: [...step.ancestry, folder.id], folder: file });
|
|
322
|
+
}
|
|
323
|
+
else if (file.trashed)
|
|
324
|
+
trash(file);
|
|
337
325
|
else
|
|
338
|
-
|
|
326
|
+
keep(file);
|
|
327
|
+
// A folder with more pages goes back on top with its cursor, above its child folders.
|
|
328
|
+
place(step, [...nested.reverse(), ...(more ? [{ ...step, folder, listing: more }] : [])]);
|
|
329
|
+
if (!more)
|
|
330
|
+
visited.add(folder.id);
|
|
331
|
+
};
|
|
332
|
+
const done = (step) => {
|
|
333
|
+
if (step.ancestry.includes(step.id))
|
|
334
|
+
throw new CliError("invalid_response", "folder traversal contains a cycle");
|
|
335
|
+
return visited.has(step.id);
|
|
336
|
+
};
|
|
337
|
+
try {
|
|
338
|
+
for (;;) {
|
|
339
|
+
for (let top = current.stack.at(-1); top && done(top); top = current.stack.at(-1))
|
|
340
|
+
current.stack.pop();
|
|
341
|
+
// The folders at the top of the stack, listed together on a source that allows it; each takes its request
|
|
342
|
+
// before it starts, so the budget and the deadline bound the batch as they bound one listing.
|
|
343
|
+
const batch = [];
|
|
344
|
+
for (let at = current.stack.length - 1; at >= 0 && batch.length < width; at--) {
|
|
345
|
+
const step = current.stack[at];
|
|
346
|
+
if (done(step) || batch.some((one) => one.id === step.id))
|
|
347
|
+
continue;
|
|
348
|
+
// One listing at least per call, so a folder with more children than the bound still moves on.
|
|
349
|
+
// The run's own signal too: a cooperative sync is not cut from outside, and a CLI may pass no budget.
|
|
350
|
+
// The time budget keeps a margin of 5 s or more, so a short run would never list a folder: its first
|
|
351
|
+
// request goes ahead while one still fits before the deadline itself.
|
|
352
|
+
const taken = options.signal?.aborted
|
|
353
|
+
? "cancelled"
|
|
354
|
+
: (listed > 0 || batch.length > 0) && spent >= maxEntries
|
|
355
|
+
? "entries"
|
|
356
|
+
: budget?.take();
|
|
357
|
+
stopped = taken === "deadline" && budget?.first?.() ? null : (taken ?? null);
|
|
358
|
+
if (stopped)
|
|
359
|
+
break;
|
|
360
|
+
batch.push(step);
|
|
361
|
+
}
|
|
362
|
+
if (!batch.length)
|
|
363
|
+
break;
|
|
364
|
+
const results = await Promise.allSettled(batch.map(list));
|
|
365
|
+
let failure;
|
|
366
|
+
batch.forEach((step, at) => {
|
|
367
|
+
const root = rootsRead.get(step);
|
|
368
|
+
if (root)
|
|
369
|
+
container(root);
|
|
370
|
+
rootsRead.delete(step);
|
|
371
|
+
const result = results[at];
|
|
372
|
+
if (result.status === "fulfilled")
|
|
373
|
+
apply(step, result.value);
|
|
374
|
+
else
|
|
375
|
+
failure ??= { reason: result.reason };
|
|
376
|
+
});
|
|
377
|
+
if (failure)
|
|
378
|
+
throw failure.reason;
|
|
379
|
+
if (stopped)
|
|
380
|
+
break;
|
|
339
381
|
if (now() - savedAt > SAVE_EVERY_MS)
|
|
340
382
|
record();
|
|
341
383
|
}
|
|
@@ -24,6 +24,12 @@ export interface GuardedFileWriteResult {
|
|
|
24
24
|
sha256: string;
|
|
25
25
|
};
|
|
26
26
|
}
|
|
27
|
+
/** The reason of a conflict a target raised for itself, which callers pass on as it is; undefined for the usual one. */
|
|
28
|
+
export declare const ownConflict: (error: {
|
|
29
|
+
details?: {
|
|
30
|
+
reason?: unknown;
|
|
31
|
+
};
|
|
32
|
+
}) => string | undefined;
|
|
27
33
|
export declare const remoteChanged: (path: string, why: string, reread: string) => CliError;
|
|
28
34
|
/**
|
|
29
35
|
* Writes a file only over the content the caller read. Few providers offer a conditional upload, so the current
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
|
+
/** The reason of a conflict a target raised for itself, which callers pass on as it is; undefined for the usual one. */
|
|
3
|
+
export const ownConflict = (error) => {
|
|
4
|
+
const reason = error.details?.reason;
|
|
5
|
+
return typeof reason === "string" && reason !== "mirror.remote-changed" ? reason : undefined;
|
|
6
|
+
};
|
|
2
7
|
export const remoteChanged = (path, why, reread) => new CliError("conflict", `${path} ${why}; nothing was written. Read it again: ${reread}`, {
|
|
3
8
|
reason: "mirror.remote-changed",
|
|
4
9
|
});
|
|
@@ -23,7 +28,8 @@ export const guardedFileWrite = async (write) => {
|
|
|
23
28
|
file = await target.upload(path, from, kept === undefined ? { absent: true } : { sha256: kept }, signal);
|
|
24
29
|
}
|
|
25
30
|
catch (error) {
|
|
26
|
-
|
|
31
|
+
// A target's conflict with its own reason says what it did, which "nothing was written" would hide.
|
|
32
|
+
if (isCliError(error) && error.code === "conflict" && ownConflict(error) === undefined)
|
|
27
33
|
throw remoteChanged(path, kept === undefined ? "appeared since it was read" : "changed since it was read", reread);
|
|
28
34
|
throw error;
|
|
29
35
|
}
|
|
@@ -5,6 +5,7 @@ import { CliError } from "@wirecat/cli-base";
|
|
|
5
5
|
import { eachMirror, heldCheck } from "../documents/mirrors.js";
|
|
6
6
|
import { assertNoLink, localTemp, replaceLocal, safePath, skippedName, } from "../documents/push.js";
|
|
7
7
|
import { excludedBy } from "./exclusions.js";
|
|
8
|
+
import { ownConflict } from "./guarded-write.js";
|
|
8
9
|
import { listRemote } from "./listing.js";
|
|
9
10
|
import { ancestors, copyName, freeSpace, gigabytes, linkFree, MAX_FILES, renameLocal, scan, shortOfSpace, spareFor, trashLocal, under, whole, } from "./local-files.js";
|
|
10
11
|
import { mergeable, mergeText } from "./text-merge.js";
|
|
@@ -747,9 +748,7 @@ export const syncFileMirror = async (options) => {
|
|
|
747
748
|
break;
|
|
748
749
|
}
|
|
749
750
|
if (failure.code === "conflict")
|
|
750
|
-
conflict(step, failure.
|
|
751
|
-
? failure.message
|
|
752
|
-
: `the ${options.remote} file changed during the sync`);
|
|
751
|
+
conflict(step, ownConflict(failure) !== undefined ? failure.message : `the ${options.remote} file changed during the sync`);
|
|
753
752
|
else
|
|
754
753
|
result.errors.push({ path: step.path, code: failure.code, message: failure.message });
|
|
755
754
|
// Not retried: the next listing shows whether it landed, and adopts it when it did.
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
-
error?: undefined;
|
|
18
17
|
chatId: string;
|
|
19
18
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
20
19
|
algorithm: string;
|
|
21
20
|
fetchedAt: string | null;
|
|
22
21
|
source: string;
|
|
22
|
+
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
package/dist/setup/plain.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A setup text for a terminal: Desktop draws its restricted Markdown, a terminal shows `**`, backticks and
|
|
3
|
-
* as typed.
|
|
4
|
-
* a person copies
|
|
2
|
+
* A setup text for a terminal: Desktop draws its restricted Markdown, a terminal shows `#`, `**`, backticks and
|
|
3
|
+
* `[…](…)` as typed. Headings, bold and code lose their marks. A link keeps its address beside its words, since the
|
|
4
|
+
* address is what a person copies, unless `link` draws it, as a terminal that shows OSC 8 links does. Single `*` and
|
|
5
|
+
* `_` stay: in plain text they are as often a product or a name as italics.
|
|
5
6
|
*/
|
|
6
|
-
export declare const plainSetupText: (text: string
|
|
7
|
+
export declare const plainSetupText: (text: string, { link, }?: {
|
|
8
|
+
link?: (label: string, href: string) => string;
|
|
9
|
+
}) => string;
|
package/dist/setup/plain.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A setup text for a terminal: Desktop draws its restricted Markdown, a terminal shows `**`, backticks and
|
|
3
|
-
* as typed.
|
|
4
|
-
* a person copies
|
|
2
|
+
* A setup text for a terminal: Desktop draws its restricted Markdown, a terminal shows `#`, `**`, backticks and
|
|
3
|
+
* `[…](…)` as typed. Headings, bold and code lose their marks. A link keeps its address beside its words, since the
|
|
4
|
+
* address is what a person copies, unless `link` draws it, as a terminal that shows OSC 8 links does. Single `*` and
|
|
5
|
+
* `_` stay: in plain text they are as often a product or a name as italics.
|
|
5
6
|
*/
|
|
6
|
-
export const plainSetupText = (text) => text
|
|
7
|
-
.replace(
|
|
7
|
+
export const plainSetupText = (text, { link = (label, href) => `${label} (${href})`, } = {}) => text
|
|
8
|
+
.replace(/^#{1,3} +/gm, "")
|
|
9
|
+
.replace(/\[([^\]\n]*)\]\(([^)\s]*)\)/g, (_all, label, href) => !label || [href, href.replace(/^https:\/\//, "")].includes(label) ? href : link(label, href))
|
|
8
10
|
.replace(/\*\*([^*\n]+)\*\*/g, "$1")
|
|
9
11
|
.replace(/`([^`\n]+)`/g, "$1");
|