@dogsbay/commands 0.2.0-beta.182 → 0.2.0-beta.183
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/refactor-files.d.ts +6 -0
- package/dist/commands/refactor-files.js +67 -138
- package/dist/commands/validate.js +1 -84
- package/dist/edits.d.ts +16 -1
- package/dist/edits.js +91 -29
- package/dist/index.d.ts +3 -2
- package/dist/index.js +4 -2
- package/dist/indexes.d.ts +10 -0
- package/dist/indexes.js +42 -4
- package/dist/node-storage.d.ts +7 -0
- package/dist/node-storage.js +28 -0
- package/dist/refactor-entry.d.ts +13 -0
- package/dist/refactor-entry.js +13 -0
- package/dist/refactor.d.ts +64 -0
- package/dist/refactor.js +428 -0
- package/dist/site-layout.d.ts +24 -0
- package/dist/site-layout.js +91 -0
- package/dist/storage.d.ts +6 -0
- package/dist/storage.js +7 -0
- package/package.json +10 -6
package/dist/indexes.js
CHANGED
|
@@ -92,6 +92,26 @@ const findHtmlIdSpan = (state, id) => {
|
|
|
92
92
|
}
|
|
93
93
|
return undefined;
|
|
94
94
|
};
|
|
95
|
+
/**
|
|
96
|
+
* The props of a directive that name a page or a file: `href` / `link` (a card, a link card, a
|
|
97
|
+
* badge), `src` / `poster` (a video, a file), and `icon` / `image` when they are an image path (a
|
|
98
|
+
* card's picture; `lucide:rocket` is a name). Not an include's `src` (indexed as an include), an
|
|
99
|
+
* example's `src` (the examples root), a data directive's (the data folder) or an API's `spec`:
|
|
100
|
+
* those are not relative to the page.
|
|
101
|
+
*/
|
|
102
|
+
export const LINK_PROPS = ["href", "link", "src", "poster", "icon", "image"];
|
|
103
|
+
const PROPS_NOT_LINKS = new Set(["include", "example", "openapi", "data-table", "data-cards"]);
|
|
104
|
+
const IMAGE_PATH = /\.(?:png|jpe?g|gif|svg|webp|avif|ico|bmp)(?:[?#].*)?$/i;
|
|
105
|
+
const recordPropHrefs = (state, props) => {
|
|
106
|
+
for (const key of LINK_PROPS) {
|
|
107
|
+
const value = props[key];
|
|
108
|
+
if (typeof value !== "string" || !value.trim() || value.includes("{{"))
|
|
109
|
+
continue;
|
|
110
|
+
if ((key === "icon" || key === "image") && !IMAGE_PATH.test(value))
|
|
111
|
+
continue;
|
|
112
|
+
recordHref(state, value, key === "href" || key === "link" ? "link" : "image");
|
|
113
|
+
}
|
|
114
|
+
};
|
|
95
115
|
const recordHref = (state, href, kind) => {
|
|
96
116
|
if (href.startsWith("key:")) {
|
|
97
117
|
const name = href.slice("key:".length).split("#")[0];
|
|
@@ -164,6 +184,14 @@ const scanInline = (state, nodes) => {
|
|
|
164
184
|
case "html-inline":
|
|
165
185
|
scanHtmlAnchors(state, node.html);
|
|
166
186
|
break;
|
|
187
|
+
case "badge":
|
|
188
|
+
case "icon": {
|
|
189
|
+
// an inline directive's `{href=…}` (`:badge[New]{href="x.md"}`)
|
|
190
|
+
const attrs = node.attrs;
|
|
191
|
+
if (attrs)
|
|
192
|
+
recordPropHrefs(state, attrs);
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
167
195
|
case "highlight":
|
|
168
196
|
scanInline(state, node.children);
|
|
169
197
|
break;
|
|
@@ -210,6 +238,9 @@ const scanTree = (state, nodes) => {
|
|
|
210
238
|
if (typeof src === "string" && src.length > 0)
|
|
211
239
|
recordHref(state, src, "image");
|
|
212
240
|
}
|
|
241
|
+
else if (node.props && !PROPS_NOT_LINKS.has(node.type)) {
|
|
242
|
+
recordPropHrefs(state, node.props);
|
|
243
|
+
}
|
|
213
244
|
if ((node.type === "html" || node.type === "html-container") && node.html) {
|
|
214
245
|
scanHtmlAnchors(state, node.html);
|
|
215
246
|
}
|
|
@@ -346,8 +377,14 @@ const indexDoc = (path, source, templateSource = false) => {
|
|
|
346
377
|
pushDest(m[1] ?? m[2] ?? "", m.index ?? 0);
|
|
347
378
|
for (const m of masked.matchAll(/^[ \t]{0,3}\[[^\]]+\]:[ \t]+(?:<([^>]*)>|(\S+))/gm))
|
|
348
379
|
pushDest(m[1] ?? m[2] ?? "", m.index ?? 0);
|
|
349
|
-
|
|
350
|
-
|
|
380
|
+
// `href="x"` in raw HTML and a directive's `{href="x"}` / `{href=x}`; a `---` props block's `href: x`
|
|
381
|
+
// (in the body: front matter's `image: cover.png` is no link)
|
|
382
|
+
for (const m of masked.matchAll(/(?<![\w-])(?:href|link|src|poster|icon|image)\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s}"'>]+))/g))
|
|
383
|
+
if ((m.index ?? 0) >= bodyStart)
|
|
384
|
+
pushDest(m[1] ?? m[2] ?? m[3] ?? "", m.index ?? 0);
|
|
385
|
+
for (const m of masked.matchAll(/^[ \t]*(?:href|link|src|poster|icon|image)[ \t]*:[ \t]*(?:"([^"]+)"|'([^']+)'|([^\s"'#]+))/gm))
|
|
386
|
+
if ((m.index ?? 0) >= bodyStart)
|
|
387
|
+
pushDest(m[1] ?? m[2] ?? m[3] ?? "", m.index ?? 0);
|
|
351
388
|
// per-href lists were filled regex-by-regex (inline, then reference definitions, then HTML):
|
|
352
389
|
// document order across kinds needs a sort, or a `[ref]: x` + `[q](x)` pair swaps lines
|
|
353
390
|
for (const list of destOffsets.values())
|
|
@@ -650,12 +687,13 @@ export async function buildWorkspaceIndex(storage, options = {}) {
|
|
|
650
687
|
kind: link.kind,
|
|
651
688
|
raw: link.href,
|
|
652
689
|
...(link.fragment ? { fragment: link.fragment } : {}),
|
|
690
|
+
...(link.line !== undefined ? { line: link.line } : {}),
|
|
653
691
|
});
|
|
654
692
|
}
|
|
655
693
|
}
|
|
656
694
|
for (const include of doc.includes) {
|
|
657
695
|
includeCount++;
|
|
658
|
-
addInbound(include.target, { from: doc.path, kind: "include", raw: include.raw });
|
|
696
|
+
addInbound(include.target, { from: doc.path, kind: "include", raw: include.raw, ...(include.line !== undefined ? { line: include.line } : {}) });
|
|
659
697
|
}
|
|
660
698
|
for (const name of doc.keyUses) {
|
|
661
699
|
const users = keyUses.get(name) ?? [];
|
|
@@ -668,7 +706,7 @@ export async function buildWorkspaceIndex(storage, options = {}) {
|
|
|
668
706
|
for (const ref of map.refs) {
|
|
669
707
|
if (ref.target) {
|
|
670
708
|
const hash = ref.href.indexOf("#");
|
|
671
|
-
addInbound(ref.target, { from: map.path, kind: "menu", raw: ref.href, ...(hash >= 0 && hash < ref.href.length - 1 ? { fragment: ref.href.slice(hash + 1) } : {}) });
|
|
709
|
+
addInbound(ref.target, { from: map.path, kind: "menu", raw: ref.href, ...(hash >= 0 && hash < ref.href.length - 1 ? { fragment: ref.href.slice(hash + 1) } : {}), ...(ref.line !== undefined ? { line: ref.line } : {}) });
|
|
672
710
|
}
|
|
673
711
|
}
|
|
674
712
|
}
|
package/dist/node-storage.d.ts
CHANGED
|
@@ -38,5 +38,12 @@ export declare class NodeStorage implements Storage {
|
|
|
38
38
|
}): Promise<Uint8Array>;
|
|
39
39
|
write(path: string, content: string): Promise<void>;
|
|
40
40
|
delete(path: string): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* Move a file as it is. Always contained, whatever `containSymlinks` says: a move takes the file
|
|
43
|
+
* away from where it is, so one reached through a symlink to outside the root is refused (a
|
|
44
|
+
* folder move would otherwise empty the link's target). Never replaces a file, and copies then
|
|
45
|
+
* deletes across filesystems (EXDEV).
|
|
46
|
+
*/
|
|
47
|
+
move(from: string, to: string): Promise<void>;
|
|
41
48
|
exists(path: string): Promise<boolean>;
|
|
42
49
|
}
|
package/dist/node-storage.js
CHANGED
|
@@ -141,6 +141,34 @@ export class NodeStorage {
|
|
|
141
141
|
const fs = await this.fs();
|
|
142
142
|
await fs.unlink(await this.safeAbs(path));
|
|
143
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* Move a file as it is. Always contained, whatever `containSymlinks` says: a move takes the file
|
|
146
|
+
* away from where it is, so one reached through a symlink to outside the root is refused (a
|
|
147
|
+
* folder move would otherwise empty the link's target). Never replaces a file, and copies then
|
|
148
|
+
* deletes across filesystems (EXDEV).
|
|
149
|
+
*/
|
|
150
|
+
async move(from, to) {
|
|
151
|
+
const fs = await this.fs();
|
|
152
|
+
const src = this.abs(from);
|
|
153
|
+
const dst = this.abs(to);
|
|
154
|
+
if (!(await this.isInsideRoot(src)) || !(await this.isInsideRoot(dst)))
|
|
155
|
+
throw new Error(`Path resolves outside the workspace root: ${from} → ${to}`);
|
|
156
|
+
await fs.mkdir(dst.slice(0, dst.lastIndexOf("/")), { recursive: true });
|
|
157
|
+
// COPYFILE_EXCL / link: fail rather than replace a file that appeared after the plan
|
|
158
|
+
try {
|
|
159
|
+
await fs.link(src, dst);
|
|
160
|
+
await fs.unlink(src);
|
|
161
|
+
}
|
|
162
|
+
catch (err) {
|
|
163
|
+
const code = err.code;
|
|
164
|
+
if (code === "EEXIST")
|
|
165
|
+
throw new Error(`${to} already exists`);
|
|
166
|
+
if (code !== "EXDEV" && code !== "EPERM" && code !== "ENOTSUP" && code !== "EOPNOTSUPP")
|
|
167
|
+
throw err;
|
|
168
|
+
await fs.copyFile(src, dst, (await import("node:fs")).constants.COPYFILE_EXCL);
|
|
169
|
+
await fs.unlink(src);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
144
172
|
async exists(path) {
|
|
145
173
|
const fs = await this.fs();
|
|
146
174
|
try {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@dogsbay/commands/refactor` — rename, move and delete as PLANS, for a browser or Worker bundle
|
|
3
|
+
* (the playground's item 36; plans/browser-refactor.md): what would change is computed first, the
|
|
4
|
+
* host shows it and applies it with `applyPlan` as one step.
|
|
5
|
+
*
|
|
6
|
+
* Like `./indexes` it reaches no zod, no command engine, no @dogsbay/render and no Node built-in:
|
|
7
|
+
* `tests/refactor-entry.test.ts` bundles it and fails on any. The main entry exports the same
|
|
8
|
+
* functions, and the `rename-file`, `move-folder` and `safe-delete` verbs run them.
|
|
9
|
+
*/
|
|
10
|
+
export { planMove, planFolderMove, planDelete, applyPlan, type FileMove, type RefactorPlan, type RefactorRefusal, type RefactorRef, type DeletePlan, type PlanOptions, } from "./refactor.js";
|
|
11
|
+
export { type Storage, MemoryStorage, normalizeStoragePath } from "./storage.js";
|
|
12
|
+
export { Workspace } from "./workspace.js";
|
|
13
|
+
export { buildWorkspaceIndex, type WorkspaceIndex, type InboundRef, type RefKind } from "./indexes.js";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@dogsbay/commands/refactor` — rename, move and delete as PLANS, for a browser or Worker bundle
|
|
3
|
+
* (the playground's item 36; plans/browser-refactor.md): what would change is computed first, the
|
|
4
|
+
* host shows it and applies it with `applyPlan` as one step.
|
|
5
|
+
*
|
|
6
|
+
* Like `./indexes` it reaches no zod, no command engine, no @dogsbay/render and no Node built-in:
|
|
7
|
+
* `tests/refactor-entry.test.ts` bundles it and fails on any. The main entry exports the same
|
|
8
|
+
* functions, and the `rename-file`, `move-folder` and `safe-delete` verbs run them.
|
|
9
|
+
*/
|
|
10
|
+
export { planMove, planFolderMove, planDelete, applyPlan, } from "./refactor.js";
|
|
11
|
+
export { MemoryStorage, normalizeStoragePath } from "./storage.js";
|
|
12
|
+
export { Workspace } from "./workspace.js";
|
|
13
|
+
export { buildWorkspaceIndex } from "./indexes.js";
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type RefKind, type WorkspaceIndex } from "./indexes.js";
|
|
2
|
+
import { type Storage } from "./storage.js";
|
|
3
|
+
import { type SiteLayout } from "./site-layout.js";
|
|
4
|
+
export interface FileMove {
|
|
5
|
+
from: string;
|
|
6
|
+
to: string;
|
|
7
|
+
/** The moved file's new text, when its own references changed; else it moves as it is (any bytes). */
|
|
8
|
+
text?: string;
|
|
9
|
+
}
|
|
10
|
+
/** A reference the plan could not rewrite, or (for a delete) one that would break. */
|
|
11
|
+
export interface RefactorRef {
|
|
12
|
+
/** The file holding it. */
|
|
13
|
+
file: string;
|
|
14
|
+
/** 1-based line, when known. */
|
|
15
|
+
line?: number;
|
|
16
|
+
kind: RefKind | "site";
|
|
17
|
+
/** As written. */
|
|
18
|
+
raw: string;
|
|
19
|
+
/** Why it is listed (a miss: why it could not be rewritten). */
|
|
20
|
+
reason?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface RefactorPlan {
|
|
23
|
+
ok: true;
|
|
24
|
+
moves: FileMove[];
|
|
25
|
+
/** Files that stay where they are, with their new text. */
|
|
26
|
+
edits: Map<string, string>;
|
|
27
|
+
/** The files in `edits` (sorted): the referrers that change. */
|
|
28
|
+
changed: string[];
|
|
29
|
+
/** How many references are rewritten, in all. */
|
|
30
|
+
rewritten: number;
|
|
31
|
+
misses: RefactorRef[];
|
|
32
|
+
}
|
|
33
|
+
export interface RefactorRefusal {
|
|
34
|
+
ok: false;
|
|
35
|
+
code: string;
|
|
36
|
+
message: string;
|
|
37
|
+
file?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface PlanOptions {
|
|
40
|
+
/** The workspace index, when the host has one (else it is built from `storage`). */
|
|
41
|
+
index?: WorkspaceIndex;
|
|
42
|
+
}
|
|
43
|
+
/** Plan moving files (`moves`: from → to, workspace paths). Nothing is written. */
|
|
44
|
+
export declare function planMove(storage: Storage, moves: Array<{
|
|
45
|
+
from: string;
|
|
46
|
+
to: string;
|
|
47
|
+
}>, options?: PlanOptions): Promise<RefactorPlan | RefactorRefusal>;
|
|
48
|
+
/** Plan moving a folder and everything in it (`guide` → `guides`). */
|
|
49
|
+
export declare function planFolderMove(storage: Storage, from: string, to: string, options?: PlanOptions): Promise<RefactorPlan | RefactorRefusal>;
|
|
50
|
+
/**
|
|
51
|
+
* Write a plan: the referrers' new text, then each move (a file that did not change moves as it
|
|
52
|
+
* is, through `Storage.move`). Without `Storage.move` a file that is not text (an image) is refused
|
|
53
|
+
* BEFORE anything is written: read and written as text, it would be corrupted.
|
|
54
|
+
*/
|
|
55
|
+
export declare function applyPlan(storage: Storage, plan: RefactorPlan): Promise<void>;
|
|
56
|
+
export interface DeletePlan {
|
|
57
|
+
ok: true;
|
|
58
|
+
file: string;
|
|
59
|
+
/** Every reference that would break, with its file and line: links, props, includes, menus, keys, site paths. */
|
|
60
|
+
referrers: RefactorRef[];
|
|
61
|
+
}
|
|
62
|
+
/** What deleting `file` would break. Nothing is deleted. */
|
|
63
|
+
export declare function planDelete(storage: Storage, file: string, options?: PlanOptions): Promise<DeletePlan | RefactorRefusal>;
|
|
64
|
+
export type { SiteLayout };
|
package/dist/refactor.js
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Moving and deleting files with every reference kept, as PLANS: what would be written, moved and
|
|
3
|
+
* left broken, computed before anything is touched (plans/browser-refactor.md, the playground's
|
|
4
|
+
* item 36). `rename-file`, `move-folder` and `safe-delete` run these; a host shows the plan
|
|
5
|
+
* ("N links in M files will change") and applies it as one step with `applyPlan`.
|
|
6
|
+
*
|
|
7
|
+
* No zod, no engine, no Node: `@dogsbay/commands/refactor` bundles for a browser.
|
|
8
|
+
*
|
|
9
|
+
* One pass for any set of moves (a file, a folder): every file that moves or refers to a file that
|
|
10
|
+
* moves has each reference — a link, an image, a directive prop, an include, a menu path, a key's
|
|
11
|
+
* href, a site path — rewritten from the referrer's NEW place to the target's NEW place. A
|
|
12
|
+
* reference that cannot be rewritten is a miss, with its file and line: never silent.
|
|
13
|
+
*/
|
|
14
|
+
import { dirname } from "@dogsbay/format-topicmap";
|
|
15
|
+
import { buildWorkspaceIndex } from "./indexes.js";
|
|
16
|
+
import { normalizeStoragePath } from "./storage.js";
|
|
17
|
+
import { relativeHref, replaceIncludePath, replaceLinkHrefsAll, replaceMapHref } from "./edits.js";
|
|
18
|
+
import { resolveSitePath, siteLayout } from "./site-layout.js";
|
|
19
|
+
const isExternal = (href) => /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(href) || href.startsWith("//");
|
|
20
|
+
const refuse = (code, message, file) => ({ ok: false, code, message, ...(file ? { file } : {}) });
|
|
21
|
+
/** `path` and the rest (`?query#fragment`) of an href as written. */
|
|
22
|
+
const splitHref = (href) => {
|
|
23
|
+
const at = href.search(/[?#]/);
|
|
24
|
+
return at < 0 ? [href, ""] : [href.slice(0, at), href.slice(at)];
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* A new path as a link destination: percent-encoded when the old one was, or when it holds what
|
|
28
|
+
* would end or split the destination (a space, `<>`, `#`, `?`, unbalanced parentheses).
|
|
29
|
+
*/
|
|
30
|
+
const asWritten = (oldPath, newPath) => {
|
|
31
|
+
const parens = (newPath.match(/\(/g)?.length ?? 0) !== (newPath.match(/\)/g)?.length ?? 0);
|
|
32
|
+
if (!/%[0-9A-Fa-f]{2}/.test(oldPath) && !/[\s<>#?"'{}]/.test(newPath) && !parens)
|
|
33
|
+
return newPath;
|
|
34
|
+
return encodeURI(newPath).replace(/#/g, "%23").replace(/\?/g, "%3F").replace(/'/g, "%27").replace(/\(/g, parens ? "%28" : "(").replace(/\)/g, parens ? "%29" : ")");
|
|
35
|
+
};
|
|
36
|
+
const isIndexPage = (p) => p === "index.md" || p.endsWith("/index.md");
|
|
37
|
+
const folderOfIndex = (p) => p.slice(0, -"index.md".length).replace(/\/$/, "");
|
|
38
|
+
/** The page an address names (`install/`, `../`, `guide/install`): `x.md`, `x.mdx`, `x/index.md`. */
|
|
39
|
+
const pageFor = (files, address) => {
|
|
40
|
+
const bare = address.replace(/\/+$/, "");
|
|
41
|
+
const candidates = bare ? [`${bare}.md`, `${bare}.mdx`, `${bare}/index.md`] : ["index.md", "index.mdx"];
|
|
42
|
+
return candidates.find((c) => files.has(c));
|
|
43
|
+
};
|
|
44
|
+
const PAGE_EXT = /\.(?:md|mdx)$/i;
|
|
45
|
+
/**
|
|
46
|
+
* A page's address under a content root (`guide/install.md` → `guide/install`, `guide/index.md` →
|
|
47
|
+
* `guide`, the root's `index.md` → ``), or undefined when the file is not under the root or sits
|
|
48
|
+
* in a `_` folder the build does not route (`_assets/` is served).
|
|
49
|
+
*/
|
|
50
|
+
const addressUnder = (root, file) => {
|
|
51
|
+
const rel = root ? (file.startsWith(`${root}/`) ? file.slice(root.length + 1) : undefined) : file;
|
|
52
|
+
if (rel === undefined)
|
|
53
|
+
return undefined;
|
|
54
|
+
if (!rel.startsWith("_assets/") && !rel.includes("/_assets/") && rel.split("/").some((seg) => seg.startsWith("_")))
|
|
55
|
+
return undefined;
|
|
56
|
+
if (!PAGE_EXT.test(rel))
|
|
57
|
+
return rel; // an asset keeps its name
|
|
58
|
+
const bare = rel.replace(PAGE_EXT, "");
|
|
59
|
+
return bare === "index" ? "" : bare.replace(/\/index$/, "");
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* The content folder a menu's "/"-rooted `file: /x.md` is read from: the folder of the nearest
|
|
63
|
+
* root menu (`nav.yml` / `nav.yaml` / `nav.json`) at or above the menu file, else the workspace root.
|
|
64
|
+
*/
|
|
65
|
+
const contentFolderOf = (isMenu, menuPath) => {
|
|
66
|
+
for (let dir = dirname(menuPath);; dir = dirname(dir)) {
|
|
67
|
+
const base = dir === "." ? "" : dir;
|
|
68
|
+
if (["nav.yml", "nav.yaml", "nav.json"].some((n) => isMenu(base ? `${base}/${n}` : n)))
|
|
69
|
+
return base;
|
|
70
|
+
if (!base)
|
|
71
|
+
return "";
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
/** Plan moving files (`moves`: from → to, workspace paths). Nothing is written. */
|
|
75
|
+
export async function planMove(storage, moves, options = {}) {
|
|
76
|
+
const move = new Map();
|
|
77
|
+
const targets = new Set();
|
|
78
|
+
for (const m of moves) {
|
|
79
|
+
const from = normalizeStoragePath(m.from);
|
|
80
|
+
const to = normalizeStoragePath(m.to);
|
|
81
|
+
if (!from || !to || from.startsWith("../") || to.startsWith("../") || from === ".." || to === "..")
|
|
82
|
+
return refuse("rename-path-invalid", `"${m.from}" → "${m.to}" is not a path in the workspace`);
|
|
83
|
+
if (from === to)
|
|
84
|
+
return refuse("rename-noop", "from and to are the same path", from);
|
|
85
|
+
if (move.has(from))
|
|
86
|
+
return refuse("rename-duplicate", `${from} is moved twice`, from);
|
|
87
|
+
if (targets.has(to))
|
|
88
|
+
return refuse("rename-target-twice", `two files would move to ${to}`, to);
|
|
89
|
+
move.set(from, to);
|
|
90
|
+
targets.add(to);
|
|
91
|
+
}
|
|
92
|
+
if (!move.size)
|
|
93
|
+
return refuse("rename-noop", "nothing to move");
|
|
94
|
+
for (const [from, to] of move) {
|
|
95
|
+
if (!(await storage.exists(from)))
|
|
96
|
+
return refuse("rename-source-missing", `${from} does not exist`, from);
|
|
97
|
+
// a target may be a file that moves away in the same plan only if… it never is: refuse, rather than order writes
|
|
98
|
+
if (await storage.exists(to))
|
|
99
|
+
return refuse("rename-target-exists", `${to} already exists`, to);
|
|
100
|
+
}
|
|
101
|
+
const index = options.index ?? (await buildWorkspaceIndex(storage));
|
|
102
|
+
const layout = await siteLayout(storage);
|
|
103
|
+
const newPath = (p) => move.get(p) ?? p;
|
|
104
|
+
const moving = (...paths) => paths.some((p) => move.has(p));
|
|
105
|
+
const byFile = new Map();
|
|
106
|
+
const misses = [];
|
|
107
|
+
const want = (file, group, raw, next, ref) => {
|
|
108
|
+
if (next === raw)
|
|
109
|
+
return;
|
|
110
|
+
const pending = byFile.get(file) ?? new Map();
|
|
111
|
+
byFile.set(file, pending);
|
|
112
|
+
const key = `${group}\u0000${raw}`;
|
|
113
|
+
const have = pending.get(key);
|
|
114
|
+
if (have && have.next !== next) {
|
|
115
|
+
misses.push({ ...ref, reason: `"${raw}" is written for two targets in this file` });
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (have)
|
|
119
|
+
have.refs.push(ref);
|
|
120
|
+
else
|
|
121
|
+
pending.set(key, { group, raw, next, refs: [ref] });
|
|
122
|
+
};
|
|
123
|
+
// A site path (`/guide/install`, a menu's `href: /guide/install`) to the new page's address,
|
|
124
|
+
// written in the author's style: their prefix, trailing slash and suffix kept
|
|
125
|
+
const sitePathFor = (raw) => {
|
|
126
|
+
if (!layout.checkable)
|
|
127
|
+
return {};
|
|
128
|
+
const [pathPart, suffix] = splitHref(raw);
|
|
129
|
+
let sitePath = pathPart.replace(/^\/+/, "").replace(/\/+$/, "");
|
|
130
|
+
try {
|
|
131
|
+
sitePath = decodeURIComponent(sitePath);
|
|
132
|
+
}
|
|
133
|
+
catch { /* as written */ }
|
|
134
|
+
if (!sitePath)
|
|
135
|
+
return {};
|
|
136
|
+
const hit = resolveSitePath(index, layout, sitePath);
|
|
137
|
+
if (!hit.file || !move.has(hit.file))
|
|
138
|
+
return {};
|
|
139
|
+
const to = newPath(hit.file);
|
|
140
|
+
const root = layout.roots.find((r) => addressUnder(r, hit.file) !== undefined) ?? "";
|
|
141
|
+
const address = addressUnder(root, to);
|
|
142
|
+
if (address === undefined)
|
|
143
|
+
return { target: hit.file, reason: `${to} is not under the content folder${root ? ` (${root})` : ""}, so it has no site address` };
|
|
144
|
+
const prefix = layout.prefixes.find((pre) => sitePath === pre || sitePath.startsWith(`${pre}/`));
|
|
145
|
+
const path = [prefix, address].filter(Boolean).join("/");
|
|
146
|
+
const slash = pathPart.endsWith("/") && path ? "/" : "";
|
|
147
|
+
return { target: hit.file, next: `/${asWritten(pathPart, path)}${slash}${suffix}` };
|
|
148
|
+
};
|
|
149
|
+
for (const doc of index.docs.values()) {
|
|
150
|
+
const dir = dirname(newPath(doc.path));
|
|
151
|
+
for (const link of doc.links) {
|
|
152
|
+
const ref = { file: doc.path, ...(link.line !== undefined ? { line: link.line } : {}), kind: link.kind, raw: link.href };
|
|
153
|
+
if (link.siteAbsolute) {
|
|
154
|
+
const site = sitePathFor(link.href);
|
|
155
|
+
if (site.reason)
|
|
156
|
+
misses.push({ ...ref, kind: "site", reason: site.reason });
|
|
157
|
+
else if (site.next)
|
|
158
|
+
want(doc.path, "link", link.href, site.next, { ...ref, kind: "site" });
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
// (`../` to the root is the target "")
|
|
162
|
+
if (link.target === undefined || link.href.startsWith("#"))
|
|
163
|
+
continue;
|
|
164
|
+
const [pathPart, suffix] = splitHref(link.href);
|
|
165
|
+
let target = link.target;
|
|
166
|
+
let style = "file";
|
|
167
|
+
// a path above the workspace (`../../x.md`) is kept pointing where it did from the new place
|
|
168
|
+
if (!link.escapes && !index.files.has(target)) {
|
|
169
|
+
// an address, not a file (`install/`, `../`, `../guide/install`): the page it names
|
|
170
|
+
const found = pageFor(index.files, target);
|
|
171
|
+
if (!found) {
|
|
172
|
+
// a folder with no page, or nothing: from a file that moves, it no longer points there
|
|
173
|
+
if (move.has(doc.path))
|
|
174
|
+
misses.push({ ...ref, reason: `"${pathPart}" names no file or page, so it could not follow the move` });
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
target = found;
|
|
178
|
+
style = isIndexPage(found) ? "folder" : "page";
|
|
179
|
+
}
|
|
180
|
+
if (!moving(doc.path, target))
|
|
181
|
+
continue;
|
|
182
|
+
let rel = relativeHref(dir, newPath(target));
|
|
183
|
+
if (style !== "file") {
|
|
184
|
+
const moved = newPath(target);
|
|
185
|
+
if (!PAGE_EXT.test(moved)) {
|
|
186
|
+
misses.push({ ...ref, reason: `${moved} is not a page, so "${pathPart}" has no address to follow it` });
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
rel = isIndexPage(moved)
|
|
190
|
+
? relativeHref(dir, folderOfIndex(moved) ? `${folderOfIndex(moved)}/x` : "x").replace(/\/?x$/, "") || "."
|
|
191
|
+
: rel.replace(PAGE_EXT, "");
|
|
192
|
+
if (pathPart.endsWith("/") && rel !== "." && !rel.endsWith("/"))
|
|
193
|
+
rel += "/";
|
|
194
|
+
}
|
|
195
|
+
want(doc.path, "link", link.href, asWritten(pathPart, rel) + suffix, ref);
|
|
196
|
+
}
|
|
197
|
+
for (const include of doc.includes) {
|
|
198
|
+
if (!moving(doc.path, include.target))
|
|
199
|
+
continue;
|
|
200
|
+
want(doc.path, "include", include.raw, relativeHref(dir, newPath(include.target)), {
|
|
201
|
+
file: doc.path, ...(include.line !== undefined ? { line: include.line } : {}), kind: "include", raw: include.raw,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// where each menu's "/"-rooted paths are read from, before and after the moves
|
|
206
|
+
const newMenus = new Set([...index.maps.keys()].map(newPath));
|
|
207
|
+
const oldRootOf = (menu) => contentFolderOf((p) => index.maps.has(p), menu);
|
|
208
|
+
const newRootOf = (menu) => contentFolderOf((p) => newMenus.has(p), newPath(menu));
|
|
209
|
+
for (const map of index.maps.values()) {
|
|
210
|
+
const dir = dirname(newPath(map.path));
|
|
211
|
+
for (const r of map.refs) {
|
|
212
|
+
const ref = { file: map.path, ...(r.line !== undefined ? { line: r.line } : {}), kind: "menu", raw: r.href };
|
|
213
|
+
if (r.target) {
|
|
214
|
+
if (!moving(map.path, r.target))
|
|
215
|
+
continue;
|
|
216
|
+
const hash = r.href.indexOf("#");
|
|
217
|
+
want(map.path, "menu", r.href, relativeHref(dir, newPath(r.target)) + (hash >= 0 ? r.href.slice(hash) : ""), ref);
|
|
218
|
+
}
|
|
219
|
+
else if (r.rootRelative) {
|
|
220
|
+
// `file: /guide/x.md`: from the content folder
|
|
221
|
+
const [pathPart, suffix] = splitHref(r.href);
|
|
222
|
+
const rel = pathPart.replace(/^\/+/, "");
|
|
223
|
+
const oldRoot = oldRootOf(map.path);
|
|
224
|
+
const target = oldRoot ? `${oldRoot}/${rel}` : rel;
|
|
225
|
+
if (!index.files.has(target))
|
|
226
|
+
continue;
|
|
227
|
+
const newRoot = newRootOf(map.path);
|
|
228
|
+
if (!move.has(target) && newRoot === oldRoot)
|
|
229
|
+
continue;
|
|
230
|
+
const to = newPath(target);
|
|
231
|
+
if (newRoot && !to.startsWith(`${newRoot}/`))
|
|
232
|
+
misses.push({ ...ref, reason: `${to} is not in the content folder (${newRoot}) this menu reads "/" paths from` });
|
|
233
|
+
else
|
|
234
|
+
want(map.path, "menu", r.href, `/${newRoot ? to.slice(newRoot.length + 1) : to}${suffix}`, ref);
|
|
235
|
+
}
|
|
236
|
+
else if (r.field === "href" && r.href.startsWith("/") && !r.href.startsWith("//")) {
|
|
237
|
+
const site = sitePathFor(r.href);
|
|
238
|
+
if (site.reason)
|
|
239
|
+
misses.push({ ...ref, kind: "site", reason: site.reason });
|
|
240
|
+
else if (site.next)
|
|
241
|
+
want(map.path, "menu", r.href, site.next, { ...ref, kind: "site" });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
for (const defs of index.keys.values()) {
|
|
246
|
+
for (const def of defs) {
|
|
247
|
+
const href = def.def.href;
|
|
248
|
+
if (typeof href !== "string" || isExternal(href) || href.startsWith("/"))
|
|
249
|
+
continue;
|
|
250
|
+
const [pathPart, suffix] = splitHref(href);
|
|
251
|
+
const target = normalizeStoragePath(`${dirname(def.file)}/${pathPart}`);
|
|
252
|
+
if (!moving(def.file, target))
|
|
253
|
+
continue;
|
|
254
|
+
want(def.file, "menu", href, relativeHref(dirname(newPath(def.file)), newPath(target)) + suffix, { file: def.file, kind: "key", raw: href });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
// Each file's rewrites: every link in ONE pass (a hub page linking a whole folder), then includes
|
|
258
|
+
// and menu paths through placeholders, so a new value is never matched as another's old one
|
|
259
|
+
const edits = new Map();
|
|
260
|
+
const movedText = new Map();
|
|
261
|
+
let rewritten = 0;
|
|
262
|
+
let n = 0;
|
|
263
|
+
const notFound = (p) => {
|
|
264
|
+
for (const ref of p.refs)
|
|
265
|
+
misses.push({ ...ref, reason: `"${p.raw}" could not be found as written, so it was not changed — update it by hand` });
|
|
266
|
+
};
|
|
267
|
+
for (const [file, pending] of byFile) {
|
|
268
|
+
const original = await storage.read(file);
|
|
269
|
+
const links = [...pending.values()].filter((p) => p.group === "link");
|
|
270
|
+
let text = original;
|
|
271
|
+
if (links.length) {
|
|
272
|
+
const out = replaceLinkHrefsAll(text, new Map(links.map((p) => [p.raw, p.next])));
|
|
273
|
+
text = out.text;
|
|
274
|
+
for (const p of links) {
|
|
275
|
+
if (out.hits.has(p.raw))
|
|
276
|
+
rewritten += p.refs.length;
|
|
277
|
+
else
|
|
278
|
+
notFound(p);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const swaps = [];
|
|
282
|
+
for (const p of pending.values()) {
|
|
283
|
+
if (p.group === "link")
|
|
284
|
+
continue;
|
|
285
|
+
if (p.group === "menu" && p.next.includes("#") && !p.raw.includes("#")) {
|
|
286
|
+
for (const ref of p.refs)
|
|
287
|
+
misses.push({ ...ref, reason: `the new path "${p.next}" has a "#", which a menu reads as a fragment` });
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
const ph = `\u0000${n++}\u0000`;
|
|
291
|
+
const before = text;
|
|
292
|
+
text = p.group === "include" ? replaceIncludePath(text, p.raw, ph) : replaceMapHref(text, p.raw, ph);
|
|
293
|
+
if (text === before) {
|
|
294
|
+
notFound(p);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
swaps.push([ph, p.next]);
|
|
298
|
+
rewritten += p.refs.length;
|
|
299
|
+
}
|
|
300
|
+
for (const [ph, next] of swaps)
|
|
301
|
+
text = text.split(ph).join(next);
|
|
302
|
+
if (text === original)
|
|
303
|
+
continue;
|
|
304
|
+
if (move.has(file))
|
|
305
|
+
movedText.set(file, text);
|
|
306
|
+
else
|
|
307
|
+
edits.set(file, text);
|
|
308
|
+
}
|
|
309
|
+
return {
|
|
310
|
+
ok: true,
|
|
311
|
+
moves: [...move].map(([from, to]) => ({ from, to, ...(movedText.has(from) ? { text: movedText.get(from) } : {}) })),
|
|
312
|
+
edits,
|
|
313
|
+
changed: [...edits.keys()].sort(),
|
|
314
|
+
rewritten,
|
|
315
|
+
misses,
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
/** Plan moving a folder and everything in it (`guide` → `guides`). */
|
|
319
|
+
export async function planFolderMove(storage, from, to, options = {}) {
|
|
320
|
+
const src = normalizeStoragePath(from);
|
|
321
|
+
const dst = normalizeStoragePath(to);
|
|
322
|
+
if (!src || !dst || src.startsWith("..") || dst.startsWith(".."))
|
|
323
|
+
return refuse("rename-path-invalid", `"${from}" → "${to}" is not a folder in the workspace`);
|
|
324
|
+
if (src === dst)
|
|
325
|
+
return refuse("rename-noop", "from and to are the same folder", src);
|
|
326
|
+
if (dst.startsWith(`${src}/`))
|
|
327
|
+
return refuse("rename-into-itself", `${dst} is inside ${src}`, src);
|
|
328
|
+
const files = (await storage.list()).filter((p) => p.startsWith(`${src}/`));
|
|
329
|
+
if (!files.length)
|
|
330
|
+
return refuse("rename-source-missing", `${src}/ holds no files`, src);
|
|
331
|
+
return planMove(storage, files.map((p) => ({ from: p, to: `${dst}${p.slice(src.length)}` })), options);
|
|
332
|
+
}
|
|
333
|
+
/** Files a refactor can move by reading and writing text, when the storage cannot move files. */
|
|
334
|
+
const TEXT_FILE = /\.(?:md|mdx|markdown|txt|ya?ml|json|csv|tsv|toml|html?|xml|svg|css|js|mjs|ts|adoc|rst)$/i;
|
|
335
|
+
/**
|
|
336
|
+
* Write a plan: the referrers' new text, then each move (a file that did not change moves as it
|
|
337
|
+
* is, through `Storage.move`). Without `Storage.move` a file that is not text (an image) is refused
|
|
338
|
+
* BEFORE anything is written: read and written as text, it would be corrupted.
|
|
339
|
+
*/
|
|
340
|
+
export async function applyPlan(storage, plan) {
|
|
341
|
+
if (!storage.move) {
|
|
342
|
+
const binary = plan.moves.find((m) => m.text === undefined && !TEXT_FILE.test(m.from));
|
|
343
|
+
if (binary)
|
|
344
|
+
throw new Error(`${binary.from} is not a text file and this storage cannot move files (Storage.move)`);
|
|
345
|
+
}
|
|
346
|
+
for (const [file, text] of plan.edits)
|
|
347
|
+
await storage.write(file, text);
|
|
348
|
+
for (const m of plan.moves) {
|
|
349
|
+
if (m.text !== undefined) {
|
|
350
|
+
await storage.write(m.to, m.text);
|
|
351
|
+
await storage.delete(m.from);
|
|
352
|
+
}
|
|
353
|
+
else if (storage.move) {
|
|
354
|
+
await storage.move(m.from, m.to);
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
await storage.write(m.to, await storage.read(m.from));
|
|
358
|
+
await storage.delete(m.from);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
/** What deleting `file` would break. Nothing is deleted. */
|
|
363
|
+
export async function planDelete(storage, file, options = {}) {
|
|
364
|
+
const path = normalizeStoragePath(file);
|
|
365
|
+
if (!(await storage.exists(path)))
|
|
366
|
+
return refuse("delete-source-missing", `${path} does not exist`, path);
|
|
367
|
+
const index = options.index ?? (await buildWorkspaceIndex(storage));
|
|
368
|
+
const referrers = (index.inbound.get(path) ?? [])
|
|
369
|
+
.filter((ref) => ref.from !== path)
|
|
370
|
+
.map((ref) => ({ file: ref.from, ...(ref.line !== undefined ? { line: ref.line } : {}), kind: ref.kind, raw: ref.raw }));
|
|
371
|
+
// an address, not a file (`install/`, `/guide/install`), names the page too
|
|
372
|
+
const layout = await siteLayout(storage);
|
|
373
|
+
const seen = new Set(referrers.map((r) => `${r.file}\u0000${r.line}\u0000${r.raw}`));
|
|
374
|
+
const add = (r) => {
|
|
375
|
+
const key = `${r.file}\u0000${r.line}\u0000${r.raw}`;
|
|
376
|
+
if (!seen.has(key)) {
|
|
377
|
+
seen.add(key);
|
|
378
|
+
referrers.push(r);
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
for (const doc of index.docs.values()) {
|
|
382
|
+
if (doc.path === path)
|
|
383
|
+
continue;
|
|
384
|
+
for (const link of doc.links) {
|
|
385
|
+
const at = link.line !== undefined ? { line: link.line } : {};
|
|
386
|
+
if (link.siteAbsolute && layout.checkable && link.sitePath) {
|
|
387
|
+
if (resolveSitePath(index, layout, link.sitePath).file === path)
|
|
388
|
+
add({ file: doc.path, ...at, kind: "site", raw: link.href });
|
|
389
|
+
}
|
|
390
|
+
else if (link.target !== undefined && !link.escapes && !index.files.has(link.target)) {
|
|
391
|
+
if (pageFor(index.files, link.target) === path)
|
|
392
|
+
add({ file: doc.path, ...at, kind: link.kind, raw: link.href });
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
for (const map of index.maps.values()) {
|
|
397
|
+
for (const r of map.refs) {
|
|
398
|
+
if (r.target || !r.href.startsWith("/") || r.href.startsWith("//"))
|
|
399
|
+
continue;
|
|
400
|
+
const at = r.line !== undefined ? { line: r.line } : {};
|
|
401
|
+
if (r.rootRelative) {
|
|
402
|
+
const rel = splitHref(r.href)[0].replace(/^\/+/, "");
|
|
403
|
+
const root = contentFolderOf((p) => index.maps.has(p), map.path);
|
|
404
|
+
if ((root ? `${root}/${rel}` : rel) === path)
|
|
405
|
+
add({ file: map.path, ...at, kind: "menu", raw: r.href });
|
|
406
|
+
}
|
|
407
|
+
else if (layout.checkable) {
|
|
408
|
+
let sp = splitHref(r.href)[0].replace(/^\/+|\/+$/g, "");
|
|
409
|
+
try {
|
|
410
|
+
sp = decodeURIComponent(sp);
|
|
411
|
+
}
|
|
412
|
+
catch { /* as written */ }
|
|
413
|
+
if (sp && resolveSitePath(index, layout, sp).file === path)
|
|
414
|
+
add({ file: map.path, ...at, kind: "site", raw: r.href });
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
for (const defs of index.keys.values()) {
|
|
419
|
+
for (const def of defs) {
|
|
420
|
+
const href = def.def.href;
|
|
421
|
+
if (def.file === path || typeof href !== "string" || isExternal(href) || href.startsWith("/"))
|
|
422
|
+
continue;
|
|
423
|
+
if (normalizeStoragePath(`${dirname(def.file)}/${splitHref(href)[0]}`) === path)
|
|
424
|
+
add({ file: def.file, kind: "key", raw: href, reason: `key "${def.name}"` });
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return { ok: true, file: path, referrers };
|
|
428
|
+
}
|