@jxsuite/server 9.2.1 → 9.3.1
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/package.json +24 -18
- package/src/collab.ts +390 -18
- package/src/jxn-response.ts +41 -0
- package/src/net-guard.ts +4 -3
- package/src/project-events.ts +622 -0
- package/src/project-server.ts +102 -3
- package/src/project-state/collections.ts +108 -0
- package/src/project-state/git-monitor.ts +302 -0
- package/src/project-state/graph.ts +651 -0
- package/src/project-state/host-deps.ts +224 -0
- package/src/project-state/host.ts +2113 -0
- package/src/project-state/overlays.ts +231 -0
- package/src/project-state/rename.ts +473 -0
- package/src/project-state/settle.ts +38 -0
- package/src/refactor/apply.ts +177 -67
- package/src/refactor/find-refs.ts +0 -0
- package/src/refactor/index.ts +2 -1
- package/src/refactor/paths.ts +3 -325
- package/src/refactor/refs.ts +5 -388
- package/src/refactor/scan.ts +17 -4
- package/src/refactor/watcher.ts +47 -2
- package/src/serve.node.ts +1 -0
- package/src/serve.ts +7 -5
- package/src/server.ts +40 -1
- package/src/sse.ts +1 -1
- package/src/studio-api.ts +76 -9
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The usage query's reading of a running host's graph (`specs/project-state.md` §12): the graph
|
|
3
|
+
* answers only once the host is `indexed`, its watcher is not degraded, and it has settled every
|
|
4
|
+
* change it has been told of, so a change the watcher has not delivered yet is never missed. Shared
|
|
5
|
+
* by the desktop session and the dev server, which both run `createProjectStateHost`.
|
|
6
|
+
*
|
|
7
|
+
* @docs studio/desktop
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { ProjectReferences, ProjectStateHost } from "./host.ts";
|
|
11
|
+
|
|
12
|
+
/** How long the usage query waits for the host to settle before it walks the tree, in ms. */
|
|
13
|
+
export const SETTLE_LIMIT_MS = 2000;
|
|
14
|
+
|
|
15
|
+
/** How long the host must be quiet before the usage query reads its graph, in ms. */
|
|
16
|
+
export const SETTLE_QUIET_MS = 100;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The graph's references once `host` has settled, or `null` when it is below `indexed`, its watcher
|
|
20
|
+
* is degraded, or it has not settled within `limitMs`: the caller then walks the tree.
|
|
21
|
+
*/
|
|
22
|
+
export async function settledReferences(
|
|
23
|
+
host: Pick<ProjectStateHost, "idle" | "references">,
|
|
24
|
+
limitMs: number = SETTLE_LIMIT_MS,
|
|
25
|
+
): Promise<ProjectReferences | null> {
|
|
26
|
+
if (host.references() === null) {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
30
|
+
const settled = await Promise.race([
|
|
31
|
+
host.idle(SETTLE_QUIET_MS).then(() => true),
|
|
32
|
+
new Promise<false>((resolveLimit) => {
|
|
33
|
+
timer = setTimeout(resolveLimit, limitMs, false);
|
|
34
|
+
}),
|
|
35
|
+
]);
|
|
36
|
+
clearTimeout(timer);
|
|
37
|
+
return settled ? host.references() : null;
|
|
38
|
+
}
|
package/src/refactor/apply.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { errorMessage } from "@jxsuite/schema/parse";
|
|
|
15
15
|
import { isUnder } from "./paths.ts";
|
|
16
16
|
import { rewriteDocRefs, rewriteTagName } from "./refs.ts";
|
|
17
17
|
import { documentGlob, fwd, loadDoc, skipScanPath } from "./scan.ts";
|
|
18
|
+
import type { LoadedDoc } from "./scan.ts";
|
|
18
19
|
import { invalidateReferenceCache } from "./find-refs.ts";
|
|
19
20
|
import { refactorMounts } from "./mounts.ts";
|
|
20
21
|
import type { RefChange } from "./refs.ts";
|
|
@@ -86,72 +87,104 @@ export async function applyRename(opts: ApplyRenameOptions): Promise<RenameRepor
|
|
|
86
87
|
}
|
|
87
88
|
}
|
|
88
89
|
|
|
89
|
-
/**
|
|
90
|
-
|
|
90
|
+
/** One document the planning half would rewrite, and what it would write. */
|
|
91
|
+
export interface PlannedRewrite {
|
|
92
|
+
/** The document's absolute POSIX path where the plan read it. */
|
|
93
|
+
abs: string;
|
|
94
|
+
/** The file references it rewrote. */
|
|
95
|
+
changes: RefChange[];
|
|
96
|
+
/** How many nodes carry the component tag it renamed. */
|
|
97
|
+
tagCount: number;
|
|
98
|
+
/**
|
|
99
|
+
* The rewritten text, or `null` when no write-back path the format declares can express the
|
|
100
|
+
* change: a tag rename in a format with no serializer, or a format with neither path.
|
|
101
|
+
*/
|
|
102
|
+
contents: string | null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** What a rename would do to the project's documents, before anything is written. */
|
|
106
|
+
export interface RenamePlan {
|
|
107
|
+
/** The component tag derived from the new filename, when the renamed file is a component. */
|
|
108
|
+
tagRename: { from: string; to: string } | null;
|
|
109
|
+
/** Why a component's tag is left as it was. */
|
|
110
|
+
tagSkipped?: string;
|
|
111
|
+
/** Every document with something to rewrite, in the order the plan read them. */
|
|
112
|
+
rewrites: PlannedRewrite[];
|
|
113
|
+
/** Documents that could not be read or parsed, by absolute POSIX path. */
|
|
114
|
+
errors: { abs: string; error: string }[];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface PlanRenameOptions {
|
|
118
|
+
/** Absolute project root. */
|
|
119
|
+
root: string;
|
|
120
|
+
/** Absolute path of the renamed file or directory before the move. */
|
|
121
|
+
absFrom: string;
|
|
122
|
+
/** Absolute path of the renamed file or directory after the move. */
|
|
123
|
+
absTo: string;
|
|
124
|
+
/** Project-relative asset mounts, for rewriting rooted references through the mount lane. */
|
|
125
|
+
mounts: readonly AssetMount[];
|
|
126
|
+
/**
|
|
127
|
+
* Where `documents` and `renamed` are read: `"after"` when the move has already happened (what
|
|
128
|
+
* {@link applyRename} does), `"before"` when it has not (the project state host plans first and
|
|
129
|
+
* moves as the first step of its outbox, `project-state.md` §9.1).
|
|
130
|
+
*/
|
|
131
|
+
phase: "before" | "after";
|
|
132
|
+
/**
|
|
133
|
+
* The renamed file itself, parsed, for a component's tag; `null` for a directory or a
|
|
134
|
+
* non-document.
|
|
135
|
+
*/
|
|
136
|
+
renamed: LoadedDoc | null;
|
|
137
|
+
/** The candidate referrers, absolute POSIX paths in the phase's locations. */
|
|
138
|
+
documents: Iterable<string> | AsyncIterable<string>;
|
|
139
|
+
/** Read and parse one candidate. */
|
|
140
|
+
load: (abs: string) => Promise<LoadedDoc>;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The planning half of a rename: for every candidate document, the rewritten references and, for a
|
|
145
|
+
* component, the renamed tag, as the bytes that would be written. Nothing is written. Pure but for
|
|
146
|
+
* `load`, so a caller decides where the documents come from and what to do with the plan.
|
|
147
|
+
*/
|
|
148
|
+
export async function planRename(opts: PlanRenameOptions): Promise<RenamePlan> {
|
|
91
149
|
const root = fwd(opts.root);
|
|
92
150
|
const absFrom = fwd(opts.absFrom);
|
|
93
151
|
const absTo = fwd(opts.absTo);
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
let isDir = false;
|
|
97
|
-
try {
|
|
98
|
-
const stats = await stat(absTo);
|
|
99
|
-
isDir = stats.isDirectory();
|
|
100
|
-
} catch {
|
|
101
|
-
isDir = false;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
const report: RenameReport = {
|
|
105
|
-
errors: [],
|
|
106
|
-
from: fwd(relative(opts.root, opts.absFrom)),
|
|
107
|
-
isDir,
|
|
108
|
-
ok: true,
|
|
109
|
-
references: { files: [], filesChanged: 0, refsUpdated: 0 },
|
|
110
|
-
to: fwd(relative(opts.root, opts.absTo)),
|
|
111
|
-
};
|
|
152
|
+
const plan: RenamePlan = { errors: [], rewrites: [], tagRename: null };
|
|
112
153
|
|
|
113
154
|
// For a component file rename, derive the new tag from the new filename (Pillar C).
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
if (newTag.includes("-")) {
|
|
122
|
-
tagRename = { from: oldTag, to: newTag };
|
|
123
|
-
} else {
|
|
124
|
-
report.tagSkipped = `Tag "${oldTag}" left unchanged: "${newTag}" is not a valid custom-element name`;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
} catch {
|
|
128
|
-
// Not a parseable component — skip tag derivation.
|
|
155
|
+
const oldTag = isJsonObject(opts.renamed?.doc) ? opts.renamed.doc.tagName : undefined;
|
|
156
|
+
const newTag = deriveTag(absTo);
|
|
157
|
+
if (isString(oldTag) && oldTag.includes("-") && newTag !== oldTag) {
|
|
158
|
+
if (newTag.includes("-")) {
|
|
159
|
+
plan.tagRename = { from: oldTag, to: newTag };
|
|
160
|
+
} else {
|
|
161
|
+
plan.tagSkipped = `Tag "${oldTag}" left unchanged: "${newTag}" is not a valid custom-element name`;
|
|
129
162
|
}
|
|
130
163
|
}
|
|
164
|
+
const { tagRename } = plan;
|
|
131
165
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
for await (const match of scanFiles(documentGlob(opts.registry), opts.root)) {
|
|
136
|
-
if (skipScanPath(match)) {
|
|
137
|
-
continue;
|
|
138
|
-
}
|
|
139
|
-
const fp = fwd(resolve(opts.root, match));
|
|
166
|
+
for await (const candidate of opts.documents) {
|
|
167
|
+
const fp = fwd(candidate);
|
|
140
168
|
try {
|
|
141
|
-
const { doc, rewrite, serialize } = await
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
169
|
+
const { doc, rewrite, serialize } = await opts.load(fp);
|
|
170
|
+
let docOldDir: string;
|
|
171
|
+
let docNewDir: string;
|
|
172
|
+
if (opts.phase === "after") {
|
|
173
|
+
docNewDir = dirname(fp);
|
|
174
|
+
docOldDir = isUnder(fp, absTo) ? dirname(absFrom + fp.slice(absTo.length)) : docNewDir;
|
|
175
|
+
} else {
|
|
176
|
+
docOldDir = dirname(fp);
|
|
177
|
+
docNewDir = isUnder(fp, absFrom) ? dirname(absTo + fp.slice(absFrom.length)) : docOldDir;
|
|
178
|
+
}
|
|
145
179
|
const { changes } = rewriteDocRefs(doc, {
|
|
146
180
|
docNewDir,
|
|
147
181
|
docOldDir,
|
|
148
|
-
mounts,
|
|
182
|
+
mounts: opts.mounts,
|
|
149
183
|
newAbs: absTo,
|
|
150
184
|
oldAbs: absFrom,
|
|
151
185
|
root,
|
|
152
186
|
});
|
|
153
187
|
const tagCount = tagRename ? rewriteTagName(doc, tagRename.from, tagRename.to).count : 0;
|
|
154
|
-
|
|
155
188
|
if (changes.length === 0 && tagCount === 0) {
|
|
156
189
|
continue;
|
|
157
190
|
}
|
|
@@ -167,38 +200,115 @@ async function rewriteReferences(opts: ApplyRenameOptions): Promise<RenameReport
|
|
|
167
200
|
* value edits cannot. A TAG rename is exactly such a change, so a document carrying one and
|
|
168
201
|
* no serializer is still named in the report rather than half-written.
|
|
169
202
|
*/
|
|
170
|
-
const
|
|
203
|
+
const contents =
|
|
171
204
|
serialize === null
|
|
172
205
|
? tagCount === 0 && rewrite !== null
|
|
173
206
|
? await rewrite(changes)
|
|
174
207
|
: null
|
|
175
208
|
: await serialize(doc);
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
209
|
+
plan.rewrites.push({ abs: fp, changes, contents, tagCount });
|
|
210
|
+
} catch (error) {
|
|
211
|
+
plan.errors.push({ abs: fp, error: errorMessage(error) });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return plan;
|
|
215
|
+
}
|
|
181
216
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
217
|
+
/** The refactor pass itself: see {@link applyRename}. */
|
|
218
|
+
async function rewriteReferences(opts: ApplyRenameOptions): Promise<RenameReport> {
|
|
219
|
+
const root = fwd(opts.root);
|
|
220
|
+
const absFrom = fwd(opts.absFrom);
|
|
221
|
+
const absTo = fwd(opts.absTo);
|
|
222
|
+
const mounts = opts.mounts ?? (await refactorMounts(opts.root));
|
|
223
|
+
const rel = (abs: string): string => fwd(relative(root, abs));
|
|
224
|
+
|
|
225
|
+
let isDir = false;
|
|
226
|
+
try {
|
|
227
|
+
const stats = await stat(absTo);
|
|
228
|
+
isDir = stats.isDirectory();
|
|
229
|
+
} catch {
|
|
230
|
+
isDir = false;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const report: RenameReport = {
|
|
234
|
+
errors: [],
|
|
235
|
+
from: fwd(relative(opts.root, opts.absFrom)),
|
|
236
|
+
isDir,
|
|
237
|
+
ok: true,
|
|
238
|
+
references: { files: [], filesChanged: 0, refsUpdated: 0 },
|
|
239
|
+
to: fwd(relative(opts.root, opts.absTo)),
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
let renamed: LoadedDoc | null = null;
|
|
243
|
+
if (!isDir) {
|
|
244
|
+
try {
|
|
245
|
+
renamed = await loadDoc(absTo, opts.registry);
|
|
246
|
+
} catch {
|
|
247
|
+
// Not a parseable component — skip tag derivation.
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function* documents(): AsyncGenerator<string> {
|
|
252
|
+
for await (const match of scanFiles(documentGlob(opts.registry), opts.root)) {
|
|
253
|
+
if (!skipScanPath(match)) {
|
|
254
|
+
yield fwd(resolve(opts.root, match));
|
|
190
255
|
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const plan = await planRename({
|
|
260
|
+
absFrom,
|
|
261
|
+
absTo,
|
|
262
|
+
documents: documents(),
|
|
263
|
+
load: (fp) => loadDoc(fp, opts.registry),
|
|
264
|
+
mounts,
|
|
265
|
+
phase: "after",
|
|
266
|
+
renamed,
|
|
267
|
+
root,
|
|
268
|
+
});
|
|
269
|
+
if (plan.tagSkipped !== undefined) {
|
|
270
|
+
report.tagSkipped = plan.tagSkipped;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
let tagFilesChanged = 0;
|
|
274
|
+
let tagRefsUpdated = 0;
|
|
275
|
+
const errors = new Map(plan.errors.map((entry) => [entry.abs, entry.error]));
|
|
276
|
+
for (const planned of plan.rewrites) {
|
|
277
|
+
const path = rel(planned.abs);
|
|
278
|
+
if (planned.contents === null) {
|
|
279
|
+
report.errors.push({ error: `No serializer for "${path}"`, path });
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
try {
|
|
283
|
+
await writeFile(planned.abs, planned.contents);
|
|
191
284
|
} catch (error) {
|
|
192
|
-
|
|
285
|
+
errors.set(planned.abs, errorMessage(error));
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (planned.changes.length > 0) {
|
|
289
|
+
report.references.files.push({
|
|
290
|
+
changes: planned.changes,
|
|
291
|
+
count: planned.changes.length,
|
|
292
|
+
path,
|
|
293
|
+
});
|
|
294
|
+
report.references.filesChanged += 1;
|
|
295
|
+
report.references.refsUpdated += planned.changes.length;
|
|
296
|
+
}
|
|
297
|
+
if (planned.tagCount > 0) {
|
|
298
|
+
tagFilesChanged += 1;
|
|
299
|
+
tagRefsUpdated += planned.tagCount;
|
|
193
300
|
}
|
|
194
301
|
}
|
|
302
|
+
for (const [abs, error] of errors) {
|
|
303
|
+
report.errors.push({ error, path: rel(abs) });
|
|
304
|
+
}
|
|
195
305
|
|
|
196
|
-
if (tagRename) {
|
|
306
|
+
if (plan.tagRename) {
|
|
197
307
|
report.tag = {
|
|
198
308
|
filesChanged: tagFilesChanged,
|
|
199
|
-
from: tagRename.from,
|
|
309
|
+
from: plan.tagRename.from,
|
|
200
310
|
refsUpdated: tagRefsUpdated,
|
|
201
|
-
to: tagRename.to,
|
|
311
|
+
to: plan.tagRename.to,
|
|
202
312
|
};
|
|
203
313
|
}
|
|
204
314
|
return report;
|
|
Binary file
|
package/src/refactor/index.ts
CHANGED
|
@@ -8,6 +8,7 @@ export type { ApplyRenameOptions, FileChange, RenameReport } from "./apply.ts";
|
|
|
8
8
|
export { findReferences, invalidateReferenceCache } from "./find-refs.ts";
|
|
9
9
|
export type {
|
|
10
10
|
FindReferencesOptions,
|
|
11
|
+
GraphReferences,
|
|
11
12
|
ReferenceFile,
|
|
12
13
|
ReferenceHit,
|
|
13
14
|
ReferencesResult,
|
|
@@ -15,4 +16,4 @@ export type {
|
|
|
15
16
|
export { coalesceFsEvents, toFsEvent } from "./fs-events.ts";
|
|
16
17
|
export type { FsEventPayload } from "./fs-events.ts";
|
|
17
18
|
export { createFsWatcher } from "./watcher.ts";
|
|
18
|
-
export type { FsWatcherHandle } from "./watcher.ts";
|
|
19
|
+
export type { FsWatcherHandle, FsWatcherOptions } from "./watcher.ts";
|
package/src/refactor/paths.ts
CHANGED
|
@@ -1,330 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Paths.ts —
|
|
3
|
-
*
|
|
4
|
-
* Everything here operates on forward-slash POSIX strings and never touches the filesystem, so it
|
|
5
|
-
* unit-tests deterministically. Callers (apply.ts) normalise real paths with `fwd()` before handing
|
|
6
|
-
* them in. The relative-path style mirrors `computeRelativePath` in the studio
|
|
7
|
-
* (packages/studio/src/files/components.ts): "./" for same-dir/descendant targets, "../"-chains
|
|
8
|
-
* otherwise.
|
|
9
|
-
*
|
|
10
|
-
* **A rooted reference is a site URL, not a project path.** `/images/hero.jpg` names whichever file
|
|
11
|
-
* the host serves at that URL, and there are three places it can live: an extension's asset mount,
|
|
12
|
-
* the project root, and `public/`. This module does not re-derive that mapping — it calls
|
|
13
|
-
* `@jxsuite/schema/asset-paths`, the same lane math the canvas, the dev server and the build all
|
|
14
|
-
* use. Resolving a rooted ref against the project root alone was how a rename of any file under
|
|
15
|
-
* `public/` rewrote nothing while promising otherwise (issue 239).
|
|
2
|
+
* Paths.ts — the reference path arithmetic the walk resolves with, re-exported for the server's
|
|
3
|
+
* refactor engine. Its one definition lives in `@jxsuite/protocol/ref-paths`.
|
|
16
4
|
*
|
|
17
5
|
* @docs studio/projects/pages-layouts-components
|
|
18
6
|
*/
|
|
19
7
|
|
|
20
|
-
|
|
21
|
-
import type { AssetLane, AssetMount } from "@jxsuite/schema/asset-paths";
|
|
22
|
-
import { isString } from "@jxsuite/schema/guards";
|
|
23
|
-
import type { JsonValue } from "@jxsuite/schema/types";
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* The lanes a rewritten site URL is re-emitted through, most-publishable first.
|
|
27
|
-
*
|
|
28
|
-
* {@link BUILD_LANES} first, so a file that a deployed build publishes keeps the URL that build
|
|
29
|
-
* serves — `public/images/hero.jpg` re-emits as `/images/hero.jpg`, not the `/public/...` form the
|
|
30
|
-
* dev server would also answer. The `root` lane is the fallback for a file only the dev server can
|
|
31
|
-
* reach: that reference was already build-broken before the rename (the server says so at request
|
|
32
|
-
* time), and preserving it is strictly better than leaving it pointing at a file that has moved.
|
|
33
|
-
*
|
|
34
|
-
* The consequence is that this is total for any non-empty in-project path — a rename can always
|
|
35
|
-
* express its destination — so there is no "unrewritable reference" case to report.
|
|
36
|
-
*/
|
|
37
|
-
const AUTHORED_LANES: readonly AssetLane[] = [...BUILD_LANES, "root"];
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* The lanes a rooted reference is READ through: every place the dev server would look.
|
|
41
|
-
*
|
|
42
|
-
* Deliberately wider than {@link AUTHORED_LANES} and unordered in effect, because the reader checks
|
|
43
|
-
* all of them. Where two lanes both name an existing file, `/hero.jpg` genuinely is ambiguous, and
|
|
44
|
-
* counting both is the safe side of a question asked to warn someone before a delete.
|
|
45
|
-
*/
|
|
46
|
-
const READ_LANES: readonly AssetLane[] = ["mounts", "root", "public"];
|
|
47
|
-
|
|
48
|
-
/** A path-like value split at its first `?` or `#`: the path itself, and what trails it. */
|
|
49
|
-
export interface RefParts {
|
|
50
|
-
core: string;
|
|
51
|
-
suffix: string;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** Classification of a reference string value. */
|
|
55
|
-
export type RefClass =
|
|
56
|
-
| { kind: "none" }
|
|
57
|
-
| { kind: "state" }
|
|
58
|
-
| { kind: "external" }
|
|
59
|
-
| { kind: "path"; core: string; suffix: string; rooted: boolean };
|
|
60
|
-
|
|
61
|
-
/** Split a trailing `?query` or `#fragment` off a path-like value. */
|
|
62
|
-
export function splitQueryHash(value: string): RefParts {
|
|
63
|
-
for (let i = 0; i < value.length; i += 1) {
|
|
64
|
-
const ch = value[i];
|
|
65
|
-
if (ch === "?" || ch === "#") {
|
|
66
|
-
return { core: value.slice(0, i), suffix: value.slice(i) };
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return { core: value, suffix: "" };
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* Classify a reference value. State-scope refs (`#/state/…`, `$map/…`, `parent#…`, `window#…`,
|
|
74
|
-
* `document#…`) and external URLs (`http:`, `data:`, protocol-relative `//…`) are never file paths.
|
|
75
|
-
* Everything else is treated as a `path`; the resolve-and-compare gate in `rewriteRef` provides the
|
|
76
|
-
* actual precision, so bare npm specifiers (which never resolve to the renamed file) are simply
|
|
77
|
-
* never matched.
|
|
78
|
-
*/
|
|
79
|
-
export function classifyRef(value: JsonValue | undefined): RefClass {
|
|
80
|
-
if (!isString(value) || value.length === 0) {
|
|
81
|
-
return { kind: "none" };
|
|
82
|
-
}
|
|
83
|
-
if (
|
|
84
|
-
value === "$map" ||
|
|
85
|
-
value.startsWith("#") ||
|
|
86
|
-
value.startsWith("$map/") ||
|
|
87
|
-
value.startsWith("parent#") ||
|
|
88
|
-
value.startsWith("window#") ||
|
|
89
|
-
value.startsWith("document#")
|
|
90
|
-
) {
|
|
91
|
-
return { kind: "state" };
|
|
92
|
-
}
|
|
93
|
-
// Absolute URL with a scheme (http:, data:, mailto:) or protocol-relative (//host).
|
|
94
|
-
if (value.startsWith("//") || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value)) {
|
|
95
|
-
return { kind: "external" };
|
|
96
|
-
}
|
|
97
|
-
const { core, suffix } = splitQueryHash(value);
|
|
98
|
-
if (core.length === 0) {
|
|
99
|
-
return { kind: "none" };
|
|
100
|
-
}
|
|
101
|
-
return { core, kind: "path", rooted: core.startsWith("/"), suffix };
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/** Collapse `.`/`..` segments in a POSIX path. Absolute paths cannot escape above root. */
|
|
105
|
-
export function normalizeSegments(path: string): string {
|
|
106
|
-
const isAbs = path.startsWith("/");
|
|
107
|
-
const out: string[] = [];
|
|
108
|
-
for (const part of path.split("/")) {
|
|
109
|
-
if (part === "" || part === ".") {
|
|
110
|
-
continue;
|
|
111
|
-
}
|
|
112
|
-
if (part === "..") {
|
|
113
|
-
if (out.length > 0 && out.at(-1) !== "..") {
|
|
114
|
-
out.pop();
|
|
115
|
-
} else if (!isAbs) {
|
|
116
|
-
out.push("..");
|
|
117
|
-
}
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
out.push(part);
|
|
121
|
-
}
|
|
122
|
-
return (isAbs ? "/" : "") + out.join("/");
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* Join `rel` onto an absolute POSIX `base` and normalise (a leading "/" on rel still joins to
|
|
127
|
-
* base).
|
|
128
|
-
*/
|
|
129
|
-
export function joinPosix(base: string, rel: string): string {
|
|
130
|
-
return normalizeSegments(`${base}/${rel}`);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Relative path from directory `fromDir` to `to` (both absolute POSIX). Returns a bare path for
|
|
135
|
-
* descendants ("a/b.json") and "../"-chains otherwise — without a leading "./" (callers add it to
|
|
136
|
-
* preserve author style).
|
|
137
|
-
*/
|
|
138
|
-
export function relativeChain(fromDir: string, to: string): string {
|
|
139
|
-
const fromParts = fromDir.split("/").filter(Boolean);
|
|
140
|
-
const toParts = to.split("/").filter(Boolean);
|
|
141
|
-
let common = 0;
|
|
142
|
-
while (
|
|
143
|
-
common < fromParts.length &&
|
|
144
|
-
common < toParts.length &&
|
|
145
|
-
fromParts[common] === toParts[common]
|
|
146
|
-
) {
|
|
147
|
-
common += 1;
|
|
148
|
-
}
|
|
149
|
-
const ups = fromParts.length - common;
|
|
150
|
-
const remaining = toParts.slice(common);
|
|
151
|
-
return (ups > 0 ? "../".repeat(ups) : "") + remaining.join("/");
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/** True when `p` is `dir` itself or nested under it. */
|
|
155
|
-
export function isUnder(p: string, dir: string): boolean {
|
|
156
|
-
return p === dir || p.startsWith(`${dir}/`);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Remap a resolved absolute target across a rename. If the target is the renamed file (or under the
|
|
161
|
-
* renamed directory), re-root it onto the new location; otherwise it is unaffected.
|
|
162
|
-
*/
|
|
163
|
-
export function remapTarget(targetOld: string, oldAbs: string, newAbs: string): string {
|
|
164
|
-
if (targetOld === oldAbs) {
|
|
165
|
-
return newAbs;
|
|
166
|
-
}
|
|
167
|
-
if (isUnder(targetOld, oldAbs)) {
|
|
168
|
-
return newAbs + targetOld.slice(oldAbs.length);
|
|
169
|
-
}
|
|
170
|
-
return targetOld;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Every project-relative path a rooted (site-URL) reference could name, most-preferred first.
|
|
175
|
-
*
|
|
176
|
-
* @param {string} core - The reference with any `?query`/`#fragment` already split off
|
|
177
|
-
* @param {readonly AssetMount[]} mounts - Project-relative asset mounts
|
|
178
|
-
* @returns {string[]} Candidate project-relative paths
|
|
179
|
-
*/
|
|
180
|
-
export function projectPathsForRootedRef(core: string, mounts: readonly AssetMount[]): string[] {
|
|
181
|
-
return projectPathsForSiteUrl(core, mounts, READ_LANES);
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
/** A final path segment must carry an extension, and the extension must contain a letter. */
|
|
185
|
-
const FILE_SEGMENT_RE = /^[^.][^/]*\.[A-Za-z0-9]{0,7}[A-Za-z][A-Za-z0-9]{0,7}$/;
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* True when a string is shaped like a file a document could reference.
|
|
189
|
-
*
|
|
190
|
-
* The walker in refs.ts knows eleven keys that carry references by name. The commonest media
|
|
191
|
-
* reference in a real project is under none of them — a schema-typed component prop (`$props.bg`),
|
|
192
|
-
* a content entry's frontmatter (`cover:`), `project.json`'s `defaults.layout` — so the walker
|
|
193
|
-
* falls back to SHAPE for every other key, and this is the shape test.
|
|
194
|
-
*
|
|
195
|
-
* It is deliberately not schema-aware. `walkDocRefs` is pure and schema-blind by design, and the
|
|
196
|
-
* write side shares it; a schema oracle would have to be threaded through `applyRename` too, would
|
|
197
|
-
* need a project-wide `tagName → media prop` index from a second pass, and would still miss a prop
|
|
198
|
-
* whose component definition failed to parse.
|
|
199
|
-
*
|
|
200
|
-
* Precision does not come from here. It comes from the resolve-and-compare gate the callers already
|
|
201
|
-
* apply: a candidate only counts when it resolves to the exact file queried. This just has to be
|
|
202
|
-
* cheap and to refuse prose. The extension requirement is what does that — it rejects routes
|
|
203
|
-
* (`/pricing`), bare words, MIME types (`image/png`) and identifiers, and the letter-in-extension
|
|
204
|
-
* rule additionally rejects version strings (`1.2.3`), which are otherwise file-shaped.
|
|
205
|
-
*
|
|
206
|
-
* @param {string} value
|
|
207
|
-
* @returns {boolean}
|
|
208
|
-
*/
|
|
209
|
-
export function looksLikeFileRef(value: string): boolean {
|
|
210
|
-
if (value.length === 0 || /\s/.test(value) || value.includes("${")) {
|
|
211
|
-
return false;
|
|
212
|
-
}
|
|
213
|
-
const cls = classifyRef(value);
|
|
214
|
-
if (cls.kind !== "path") {
|
|
215
|
-
return false;
|
|
216
|
-
}
|
|
217
|
-
const last = cls.core.slice(cls.core.lastIndexOf("/") + 1);
|
|
218
|
-
return FILE_SEGMENT_RE.test(last);
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* Restore a trailing slash the path math dropped, when the author wrote one.
|
|
223
|
-
*
|
|
224
|
-
* `normalizeSegments` discards empty segments, so `./content/posts/` resolves and re-emits as
|
|
225
|
-
* `./content/posts`. For a file that is invisible; for a DIRECTORY reference — a content
|
|
226
|
-
* collection's `source` — it is a gratuitous edit to a line the rename had no business restyling,
|
|
227
|
-
* and `rewriteRef`'s contract is to preserve the authored style. A bare `/` is left alone: it is
|
|
228
|
-
* already only a slash.
|
|
229
|
-
*/
|
|
230
|
-
function keepTrailingSlash(out: string, core: string): string {
|
|
231
|
-
return core.endsWith("/") && core !== "/" && !out.endsWith("/") ? `${out}/` : out;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/** Context describing a single rename, shared by every reference rewrite within one document. */
|
|
235
|
-
export interface RemapCtx {
|
|
236
|
-
/** Absolute POSIX project root. */
|
|
237
|
-
root: string;
|
|
238
|
-
/** Absolute POSIX path of the renamed file/dir, before the move. */
|
|
239
|
-
oldAbs: string;
|
|
240
|
-
/** Absolute POSIX path of the renamed file/dir, after the move. */
|
|
241
|
-
newAbs: string;
|
|
242
|
-
/** Directory the referencing document lived in before the move. */
|
|
243
|
-
docOldDir: string;
|
|
244
|
-
/**
|
|
245
|
-
* Directory the referencing document lives in after the move (differs from docOldDir only when
|
|
246
|
-
* the document itself is inside the moved subtree).
|
|
247
|
-
*/
|
|
248
|
-
docNewDir: string;
|
|
249
|
-
/**
|
|
250
|
-
* Project-relative asset mounts, for resolving rooted references through the mount lane. Absent
|
|
251
|
-
* is the same as none, which leaves the `root` and `public/` lanes.
|
|
252
|
-
*/
|
|
253
|
-
mounts?: readonly AssetMount[];
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
/**
|
|
257
|
-
* Recompute a single path reference for a rename, preserving its original style. Returns the new
|
|
258
|
-
* string, or null when nothing changes.
|
|
259
|
-
*
|
|
260
|
-
* `rootRelativeBare` makes the value resolve against the project root rather than the document
|
|
261
|
-
* directory, in every spelling: `./layouts/base.json` in `pages/blog/[slug].json` names
|
|
262
|
-
* `layouts/base.json`, because the compiler resolves `$layout` with `resolve(projectRoot, ref)`
|
|
263
|
-
* (layout-resolver.ts). Treating a `./` value as document-relative there missed every page's own
|
|
264
|
-
* `$layout`, so a renamed layout left them pointing at the old name. Used for `$layout` and for
|
|
265
|
-
* `build.copy` keys, which are project paths too.
|
|
266
|
-
*/
|
|
267
|
-
export function rewriteRef(
|
|
268
|
-
cls: { core: string; suffix: string; rooted: boolean },
|
|
269
|
-
ctx: RemapCtx,
|
|
270
|
-
rootRelativeBare = false,
|
|
271
|
-
): string | null {
|
|
272
|
-
const { core, rooted, suffix } = cls;
|
|
273
|
-
if (rooted) {
|
|
274
|
-
return rewriteSiteUrl(core, suffix, ctx);
|
|
275
|
-
}
|
|
276
|
-
const baseOld = rootRelativeBare ? ctx.root : ctx.docOldDir;
|
|
277
|
-
const baseNew = rootRelativeBare ? ctx.root : ctx.docNewDir;
|
|
278
|
-
|
|
279
|
-
const targetOld = joinPosix(baseOld, core);
|
|
280
|
-
const targetNew = remapTarget(targetOld, ctx.oldAbs, ctx.newAbs);
|
|
281
|
-
if (targetNew === targetOld && baseOld === baseNew) {
|
|
282
|
-
return null;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
const rel = relativeChain(baseNew, targetNew);
|
|
286
|
-
let out: string;
|
|
287
|
-
if (rel.startsWith("..")) {
|
|
288
|
-
out = rel;
|
|
289
|
-
} else if (core.startsWith("./")) {
|
|
290
|
-
out = `./${rel}`;
|
|
291
|
-
} else {
|
|
292
|
-
out = rel;
|
|
293
|
-
}
|
|
294
|
-
out = keepTrailingSlash(out, core) + suffix;
|
|
295
|
-
return out === core + suffix ? null : out;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
/**
|
|
299
|
-
* Rewrite a rooted reference — a site URL — across a rename, through the lanes that give it
|
|
300
|
-
* meaning.
|
|
301
|
-
*
|
|
302
|
-
* Each lane is tried on its own so the MATCHED one is known: a lane is only a candidate when the
|
|
303
|
-
* file it names is the one that moved. The answer is then re-derived from the destination through
|
|
304
|
-
* {@link AUTHORED_LANES}, which is what turns a `public/` move into the right URL rather than a
|
|
305
|
-
* root-relative path that would 404 on the deployed site.
|
|
306
|
-
*
|
|
307
|
-
* Returns null when no lane names the moved file, which is the overwhelmingly common case — most
|
|
308
|
-
* references in a document have nothing to do with any given rename.
|
|
309
|
-
*/
|
|
310
|
-
function rewriteSiteUrl(core: string, suffix: string, ctx: RemapCtx): string | null {
|
|
311
|
-
const mounts = ctx.mounts ?? [];
|
|
312
|
-
for (const lane of READ_LANES) {
|
|
313
|
-
const [candidate] = projectPathsForSiteUrl(core, mounts, [lane]);
|
|
314
|
-
if (candidate === undefined) {
|
|
315
|
-
continue;
|
|
316
|
-
}
|
|
317
|
-
const targetOld = joinPosix(ctx.root, candidate);
|
|
318
|
-
const targetNew = remapTarget(targetOld, ctx.oldAbs, ctx.newAbs);
|
|
319
|
-
if (targetNew === targetOld) {
|
|
320
|
-
continue;
|
|
321
|
-
}
|
|
322
|
-
const url = siteUrlForPath(relativeChain(ctx.root, targetNew), mounts, AUTHORED_LANES);
|
|
323
|
-
if (url === null) {
|
|
324
|
-
continue;
|
|
325
|
-
}
|
|
326
|
-
const out = keepTrailingSlash(url, core) + suffix;
|
|
327
|
-
return out === core + suffix ? null : out;
|
|
328
|
-
}
|
|
329
|
-
return null;
|
|
330
|
-
}
|
|
8
|
+
export * from "@jxsuite/protocol/ref-paths";
|