@ohos-ports/html-minifier-next 8.4.2-beta.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.
Files changed (51) hide show
  1. package/LICENSE.txt +23 -0
  2. package/README.md +776 -0
  3. package/cli.js +1209 -0
  4. package/dist/types/htmlminifier.d.ts +556 -0
  5. package/dist/types/htmlminifier.d.ts.map +1 -0
  6. package/dist/types/htmlparser.d.ts +25 -0
  7. package/dist/types/htmlparser.d.ts.map +1 -0
  8. package/dist/types/lib/attributes.d.ts +155 -0
  9. package/dist/types/lib/attributes.d.ts.map +1 -0
  10. package/dist/types/lib/constants.d.ts +110 -0
  11. package/dist/types/lib/constants.d.ts.map +1 -0
  12. package/dist/types/lib/content.d.ts +51 -0
  13. package/dist/types/lib/content.d.ts.map +1 -0
  14. package/dist/types/lib/elements.d.ts +57 -0
  15. package/dist/types/lib/elements.d.ts.map +1 -0
  16. package/dist/types/lib/fragments.d.ts +46 -0
  17. package/dist/types/lib/fragments.d.ts.map +1 -0
  18. package/dist/types/lib/option-definitions.d.ts +33 -0
  19. package/dist/types/lib/option-definitions.d.ts.map +1 -0
  20. package/dist/types/lib/options.d.ts +120 -0
  21. package/dist/types/lib/options.d.ts.map +1 -0
  22. package/dist/types/lib/unused-css.d.ts +46 -0
  23. package/dist/types/lib/unused-css.d.ts.map +1 -0
  24. package/dist/types/lib/urls.d.ts +15 -0
  25. package/dist/types/lib/urls.d.ts.map +1 -0
  26. package/dist/types/lib/utils.d.ts +102 -0
  27. package/dist/types/lib/utils.d.ts.map +1 -0
  28. package/dist/types/lib/whitespace.d.ts +45 -0
  29. package/dist/types/lib/whitespace.d.ts.map +1 -0
  30. package/dist/types/presets.d.ts +49 -0
  31. package/dist/types/presets.d.ts.map +1 -0
  32. package/dist/types/tokenchain.d.ts +26 -0
  33. package/dist/types/tokenchain.d.ts.map +1 -0
  34. package/html-minifier-next.schema.json +306 -0
  35. package/package.json +100 -0
  36. package/src/htmlminifier.js +2294 -0
  37. package/src/htmlparser.js +1069 -0
  38. package/src/lib/attributes.js +928 -0
  39. package/src/lib/constants.js +285 -0
  40. package/src/lib/content.js +190 -0
  41. package/src/lib/elements.js +274 -0
  42. package/src/lib/file-pool.js +177 -0
  43. package/src/lib/fragments.js +274 -0
  44. package/src/lib/option-definitions.js +231 -0
  45. package/src/lib/options.js +730 -0
  46. package/src/lib/unused-css.js +379 -0
  47. package/src/lib/urls.js +155 -0
  48. package/src/lib/utils.js +861 -0
  49. package/src/lib/whitespace.js +321 -0
  50. package/src/presets.js +57 -0
  51. package/src/tokenchain.js +123 -0
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Unused-CSS removal
3
+ */
4
+
5
+ import { findTagEnd } from './utils.js';
6
+
7
+ // Attributes whose values name elements by ID or hold space-separated ID lists
8
+ const idReferenceAttributes = new Set([
9
+ 'aria-activedescendant',
10
+ 'aria-controls',
11
+ 'aria-describedby',
12
+ 'aria-details',
13
+ 'aria-errormessage',
14
+ 'aria-flowto',
15
+ 'aria-labelledby',
16
+ 'aria-owns',
17
+ 'commandfor',
18
+ 'contextmenu',
19
+ 'for',
20
+ 'form',
21
+ 'headers',
22
+ 'itemref',
23
+ 'list',
24
+ 'popovertarget'
25
+ ]);
26
+
27
+ // Attributes whose value may be a same-document fragment URL (`#main`). `:target`
28
+ // rules and SVG sprite references (`<use href="#icon">`) rest on these, so the ID
29
+ // they name counts as used.
30
+ const fragmentReferenceAttributes = new Set([
31
+ 'action',
32
+ 'cite',
33
+ 'data',
34
+ 'formaction',
35
+ 'href',
36
+ 'poster',
37
+ 'src',
38
+ 'usemap',
39
+ 'xlink:href'
40
+ ]);
41
+
42
+ const attributePattern = /(?:^|[\s/])([-\w:.]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g;
43
+ const identifierPattern = /--[\w-]*|-?[A-Za-z_][\w-]*/g;
44
+ // SVG paints and filters reach elements by ID through `url(#gradient)`, in
45
+ // presentation attributes as well as in `style`
46
+ const fragmentURLPattern = /url\(\s*['"]?#([^)'"\s]+)/gi;
47
+ // Class names routinely carry characters that end a CSS identifier (`md:flex`,
48
+ // `w-1/2`, `p-[3px]`), so scripts and `data-*` values contribute whole tokens
49
+ // besides identifiers; quoted strings are where scripts keep such names
50
+ const stringLiteralPattern = /'((?:[^'\\\n]|\\.)*)'|"((?:[^"\\\n]|\\.)*)"|`((?:[^`\\]|\\.)*)`/g;
51
+
52
+ // CSS identifiers may contain escapes (`.md\:flex`, `.w-1\/2`), which have to be
53
+ // resolved before comparing them against the plain tokens found in the markup
54
+ const cssIdentifierPattern = /(?<![\w\\-])[.#]((?:[-_a-zA-Z]|\\[0-9a-fA-F]{1,6}[ \t\n]?|\\[^\n0-9a-fA-F])(?:[-\w]|\\[0-9a-fA-F]{1,6}[ \t\n]?|\\[^\n0-9a-fA-F])*)/g;
55
+ // `unusedSymbols` also drops `@keyframes` and `@counter-style` rules by name, so any
56
+ // name used there is off limits even when no element carries it as a class or ID
57
+ const reservedAtRulePattern = /@(?:-\w+-)?(?:keyframes|counter-style)\s+(-?[_a-zA-Z][\w-]*)/gi;
58
+ const escapePattern = /\\(?:([0-9a-fA-F]{1,6})[ \t\n]?|(.))/g;
59
+
60
+ /**
61
+ * Resolve CSS escape sequences in an identifier.
62
+ * @param {string} identifier
63
+ * @returns {string}
64
+ */
65
+ function unescapeIdentifier(identifier) {
66
+ if (identifier.indexOf('\\') === -1) {
67
+ return identifier;
68
+ }
69
+ return identifier.replace(escapePattern, (_match, hex, literal) => {
70
+ if (!hex) {
71
+ return literal;
72
+ }
73
+ // Per CSS Syntax spec, a null, surrogate, or out-of-range escape becomes U+FFFD
74
+ const code = parseInt(hex, 16);
75
+ return (code === 0 || code > 0x10FFFF || (code >= 0xD800 && code <= 0xDFFF))
76
+ ? '\uFFFD'
77
+ : String.fromCodePoint(code);
78
+ });
79
+ }
80
+
81
+ /**
82
+ * Lowercase for matching without disturbing offsets.
83
+ *
84
+ * `toLowerCase()` can change a string's length—U+0130 becomes two code units—which
85
+ * would misalign every offset taken from the result. Folding just ASCII preserves
86
+ * length, and tag names are ASCII anyway.
87
+ *
88
+ * @param {string} text
89
+ * @returns {string} Same length as `text`
90
+ */
91
+ function foldCase(text) {
92
+ const lowercased = text.toLowerCase();
93
+ return lowercased.length === text.length
94
+ ? lowercased
95
+ : text.replace(/[A-Z]+/g, uppercase => uppercase.toLowerCase());
96
+ }
97
+
98
+ /**
99
+ * Locate the bodies of a raw-text element (`style`, `script`).
100
+ *
101
+ * Scanning beats one regular expression here: A pattern permissive enough for the
102
+ * end tags browsers accept (`</script\t\n bar>`, `</script/>`) backtracks
103
+ * quadratically over a document full of near-matches, and bounding it would make
104
+ * long start tags go unrecognized.
105
+ *
106
+ * @param {string} haystack - Case-folded markup, as returned by `foldCase`
107
+ * @param {string} tagName - Lowercase element name
108
+ * @returns {Array<{start: number, bodyStart: number, bodyEnd: number, end: number, closed: boolean}>}
109
+ */
110
+ function findRawTextElements(haystack, tagName) {
111
+ /** @type {Array<{start: number, bodyStart: number, bodyEnd: number, end: number, closed: boolean}>} */
112
+ const found = [];
113
+ const openTag = '<' + tagName;
114
+ const closeTag = '</' + tagName;
115
+ // A tag name ends at whitespace, a slash, or the closing bracket—so `<styles>`
116
+ // and `</scriptfoo>` name different elements and must not match
117
+ const endsName = (/** @type {string} */ character) =>
118
+ character === '' || character === '/' || character === '>' || /\s/.test(character);
119
+
120
+ let cursor = 0;
121
+ for (;;) {
122
+ const start = haystack.indexOf(openTag, cursor);
123
+ if (start === -1) {
124
+ break;
125
+ }
126
+ if (!endsName(haystack.charAt(start + openTag.length))) {
127
+ cursor = start + openTag.length;
128
+ continue;
129
+ }
130
+ // A quoted attribute value may hold a `>`, so the tag ends where the parser
131
+ // says it does, not at the next bracket
132
+ const startTagEnd = findTagEnd(haystack, start + openTag.length);
133
+ if (startTagEnd === -1) {
134
+ break;
135
+ }
136
+
137
+ const bodyStart = startTagEnd + 1;
138
+ let search = bodyStart;
139
+ let bodyEnd = -1;
140
+ let end = -1;
141
+ for (;;) {
142
+ const candidate = haystack.indexOf(closeTag, search);
143
+ if (candidate === -1) {
144
+ break;
145
+ }
146
+ if (endsName(haystack.charAt(candidate + closeTag.length))) {
147
+ const closeEnd = findTagEnd(haystack, candidate + closeTag.length);
148
+ if (closeEnd !== -1) {
149
+ bodyEnd = candidate;
150
+ end = closeEnd + 1;
151
+ }
152
+ break;
153
+ }
154
+ search = candidate + closeTag.length;
155
+ }
156
+
157
+ const closed = bodyEnd !== -1;
158
+ found.push({
159
+ start,
160
+ bodyStart,
161
+ bodyEnd: closed ? bodyEnd : haystack.length,
162
+ end: closed ? end : haystack.length,
163
+ closed
164
+ });
165
+ cursor = closed ? end : haystack.length;
166
+ }
167
+
168
+ return found;
169
+ }
170
+
171
+ /**
172
+ * Collect the class names and IDs a document references.
173
+ *
174
+ * Style sheet contents are excluded, so that a style sheet never counts as
175
+ * evidence for its own selectors. An `iframe srcdoc` value is not scanned,
176
+ * either: It holds a document of its own, minified against its own symbol set.
177
+ * Over-collecting is safe here (a symbol wrongly considered used is merely
178
+ * kept), under-collecting is not.
179
+ *
180
+ * @param {string} html - Raw document markup
181
+ * @param {boolean} includeScripts - Also treat identifiers inside inline `script` elements as used
182
+ * @param {((text: string) => string)} [decode] - Resolves character references in attribute values
183
+ * @returns {Set<string>} Symbols to keep
184
+ */
185
+ function collectUsedSymbols(html, includeScripts, decode) {
186
+ const used = new Set();
187
+ const haystack = foldCase(html);
188
+
189
+ // Style sheets are skipped rather than cut out, so both scans share one folded
190
+ // copy and offsets keep pointing into `html`. Only the body is skipped—the start
191
+ // tag carries ordinary attributes, and `<style id="theme">` could be what
192
+ // `#theme` refers to. An unclosed element is not skipped: Reading its contents
193
+ // as markup can only add symbols, whereas ignoring the rest of the document
194
+ // would lose them.
195
+ const skipped = findRawTextElements(haystack, 'style')
196
+ .filter(element => element.closed)
197
+ .map(element => ({ start: element.bodyStart, end: element.bodyEnd }));
198
+
199
+ const addIdentifiers = (/** @type {string} */ text) => {
200
+ identifierPattern.lastIndex = 0;
201
+ let identifier;
202
+ while ((identifier = identifierPattern.exec(text))) {
203
+ used.add(identifier[0]);
204
+ }
205
+ };
206
+
207
+ const addTokens = (/** @type {string} */ text) => {
208
+ for (const token of text.split(/\s+/)) {
209
+ if (token) {
210
+ used.add(token);
211
+ }
212
+ }
213
+ };
214
+
215
+ // Both loops below walk forward, so one cursor over the skipped ranges suffices
216
+ let skipCursor = 0;
217
+ const isSkipped = (/** @type {number} */ index) => {
218
+ while (skipCursor < skipped.length && (skipped[skipCursor]?.end ?? 0) <= index) {
219
+ skipCursor++;
220
+ }
221
+ const element = skipped[skipCursor];
222
+ return element !== undefined && index >= element.start;
223
+ };
224
+
225
+ attributePattern.lastIndex = 0;
226
+ let match;
227
+ while ((match = attributePattern.exec(html))) {
228
+ const raw = match[2] ?? match[3] ?? match[4] ?? '';
229
+ if (!raw || isSkipped(match.index)) {
230
+ continue;
231
+ }
232
+ const name = (match[1] ?? '').toLowerCase();
233
+ // `class="us&#101;d"` names the class `used`, so compare against the decoded value
234
+ const value = (decode && raw.indexOf('&') !== -1) ? decode(raw) : raw;
235
+ if (name === 'class' || name === 'id' || idReferenceAttributes.has(name)) {
236
+ addTokens(value);
237
+ } else if (name.startsWith('data-')) {
238
+ // Class names are commonly parked in `data-*` attributes for scripts to apply later
239
+ addIdentifiers(value);
240
+ addTokens(value);
241
+ } else if (fragmentReferenceAttributes.has(name) && value.charAt(0) === '#') {
242
+ // Only a leading `#`: `href="/page#sec"` names a section of another document
243
+ addTokens(value.slice(1));
244
+ }
245
+ if (value.indexOf('(') !== -1) {
246
+ fragmentURLPattern.lastIndex = 0;
247
+ let reference;
248
+ while ((reference = fragmentURLPattern.exec(value))) {
249
+ addTokens(reference[1] ?? '');
250
+ }
251
+ }
252
+ }
253
+
254
+ if (includeScripts) {
255
+ // Script contents are raw text, so character references stay literal;
256
+ // an unclosed `script` runs to the end of the document, as it does in a browser
257
+ skipCursor = 0;
258
+ for (const element of findRawTextElements(haystack, 'script')) {
259
+ if (isSkipped(element.start)) {
260
+ continue;
261
+ }
262
+ const body = html.slice(element.bodyStart, element.bodyEnd);
263
+ addIdentifiers(body);
264
+ stringLiteralPattern.lastIndex = 0;
265
+ let literal;
266
+ while ((literal = stringLiteralPattern.exec(body))) {
267
+ addTokens(literal[1] ?? literal[2] ?? literal[3] ?? '');
268
+ }
269
+ }
270
+ }
271
+
272
+ return used;
273
+ }
274
+
275
+ /**
276
+ * Determine which class/ID symbols a style sheet defines but the document never references.
277
+ * @param {string} css - Style sheet contents
278
+ * @param {Set<string>} used - Symbols the document references
279
+ * @param {Array<string | RegExp>} safelist - Symbols to keep regardless
280
+ * @returns {string[]} Symbols safe to remove
281
+ */
282
+ function findUnusedSymbols(css, used, safelist) {
283
+ const reserved = new Set();
284
+ reservedAtRulePattern.lastIndex = 0;
285
+ let match;
286
+ while ((match = reservedAtRulePattern.exec(css))) {
287
+ if (match[1]) {
288
+ reserved.add(match[1]);
289
+ }
290
+ }
291
+
292
+ const unused = [];
293
+ const seen = new Set();
294
+ cssIdentifierPattern.lastIndex = 0;
295
+ while ((match = cssIdentifierPattern.exec(css))) {
296
+ const symbol = unescapeIdentifier(match[1] ?? '');
297
+ if (seen.has(symbol)) {
298
+ continue;
299
+ }
300
+ seen.add(symbol);
301
+ if (used.has(symbol) || reserved.has(symbol)) {
302
+ continue;
303
+ }
304
+ if (safelist.some(entry => {
305
+ if (!(entry instanceof RegExp)) {
306
+ return entry === symbol;
307
+ }
308
+ // `test()` advances `lastIndex` on global and sticky patterns, which would
309
+ // make a safelist entry match only every other symbol
310
+ entry.lastIndex = 0;
311
+ return entry.test(symbol);
312
+ })) {
313
+ continue;
314
+ }
315
+ unused.push(symbol);
316
+ }
317
+
318
+ return unused;
319
+ }
320
+
321
+ const unusedCSSKeys = new Set(['safelist', 'scripts']);
322
+
323
+ /**
324
+ * Normalize the `removeUnusedCSS` option into a settled configuration.
325
+ *
326
+ * A misspelled key or a safelist that is not an array would otherwise protect
327
+ * nothing, and that only surfaces as a missing rule much later—so every value
328
+ * that gets dropped is reported.
329
+ *
330
+ * @param {boolean | {safelist?: Array<string | RegExp>, scripts?: boolean} | undefined} option
331
+ * @param {(message: string) => unknown} [warn] - Receives one message per ignored value
332
+ * @returns {{safelist: Array<string | RegExp>, scripts: boolean} | null} Null when disabled
333
+ */
334
+ function normalizeUnusedCSSOptions(option, warn) {
335
+ if (!option) {
336
+ return null;
337
+ }
338
+ const report = warn ?? (() => {});
339
+ const config = /** @type {Record<string, any>} */ (typeof option === 'object' ? option : {});
340
+
341
+ for (const key of Object.keys(config)) {
342
+ if (!unusedCSSKeys.has(key)) {
343
+ report(`Ignoring unknown \`removeUnusedCSS\` key \`${key}\`—expected \`safelist\` or \`scripts\``);
344
+ }
345
+ }
346
+
347
+ /** @type {Array<string | RegExp>} */
348
+ let safelist = [];
349
+ if (config.safelist !== undefined) {
350
+ if (!Array.isArray(config.safelist)) {
351
+ report('Ignoring `removeUnusedCSS.safelist`—it takes an array of strings and regular expressions');
352
+ } else {
353
+ safelist = config.safelist.filter((/** @type {unknown} */ entry) => {
354
+ if (typeof entry === 'string' || entry instanceof RegExp) {
355
+ return true;
356
+ }
357
+ report(`Ignoring \`removeUnusedCSS.safelist\` entry of type ${typeof entry}—entries must be strings or regular expressions`);
358
+ return false;
359
+ });
360
+ }
361
+ }
362
+
363
+ if (config.scripts !== undefined && typeof config.scripts !== 'boolean') {
364
+ report('Ignoring `removeUnusedCSS.scripts`—it takes a boolean');
365
+ }
366
+
367
+ return {
368
+ safelist,
369
+ // Keeping identifiers seen in inline scripts costs a little of the reduction
370
+ // but avoids the most common breakage, so it is the default
371
+ scripts: typeof config.scripts === 'boolean' ? config.scripts : true
372
+ };
373
+ }
374
+
375
+ export {
376
+ collectUsedSymbols,
377
+ findUnusedSymbols,
378
+ normalizeUnusedCSSOptions
379
+ };
@@ -0,0 +1,155 @@
1
+ /**
2
+ * URL minification using Node’s WHATWG URL API
3
+ *
4
+ * Produces the shortest equivalent URL representation:
5
+ * - Same origin: shortest of root-relative or path-relative
6
+ * - Cross-origin, same scheme: scheme-relative (`//host/path`)
7
+ * - Otherwise: normalized absolute URL
8
+ */
9
+
10
+ const REJECTED_SCHEMES = new Set(['data:', 'javascript:', 'mailto:']);
11
+
12
+ const DIRECTORY_INDEXES = ['index.html', 'index.htm'];
13
+
14
+ /**
15
+ * Get the directory portion of a pathname (up to and including the last `/`).
16
+ * @param {string} pathname
17
+ * @returns {string}
18
+ */
19
+ function getDirectory(pathname) {
20
+ const lastSlash = pathname.lastIndexOf('/');
21
+ return pathname.slice(0, lastSlash + 1);
22
+ }
23
+
24
+ /**
25
+ * Compute a path-relative URL from a base directory to a target path.
26
+ * @param {string} baseDir - Base directory path (must end with `/`)
27
+ * @param {string} targetPath - Target pathname
28
+ * @returns {string}
29
+ */
30
+ function relativize(baseDir, targetPath) {
31
+ const baseSegments = baseDir.split('/').filter(Boolean);
32
+ const targetSegments = targetPath.split('/').filter(Boolean);
33
+ const isDirectoryTarget = targetPath.endsWith('/');
34
+
35
+ // Find common prefix length
36
+ let common = 0;
37
+ while (
38
+ common < baseSegments.length &&
39
+ common < targetSegments.length &&
40
+ baseSegments[common] === targetSegments[common]
41
+ ) {
42
+ // Stop before the last target segment only for file targets (not directories)
43
+ if (!isDirectoryTarget && common === targetSegments.length - 1) break;
44
+ common++;
45
+ }
46
+
47
+ const ups = baseSegments.length - common;
48
+ const remaining = targetSegments.slice(common);
49
+
50
+ let relative = '../'.repeat(ups) + remaining.join('/');
51
+
52
+ // Preserve trailing slash
53
+ if (isDirectoryTarget && relative !== '' && !relative.endsWith('/')) {
54
+ relative += '/';
55
+ }
56
+
57
+ // For directory targets, empty result means same directory
58
+ if (relative === '' && isDirectoryTarget) {
59
+ return './';
60
+ }
61
+
62
+ return relative;
63
+ }
64
+
65
+ /**
66
+ * Remove directory index from the end of a pathname.
67
+ * @param {string} pathname
68
+ * @returns {string}
69
+ */
70
+ function removeDirectoryIndex(pathname) {
71
+ for (const index of DIRECTORY_INDEXES) {
72
+ if (pathname.endsWith('/' + index)) {
73
+ return pathname.slice(0, pathname.length - index.length);
74
+ }
75
+ }
76
+ return pathname;
77
+ }
78
+
79
+ /**
80
+ * Create a URL minifier function for the given site context.
81
+ * @param {string} site - The site base URL (used to compute relative URLs)
82
+ * @returns {(url: string) => string} Minifier function that returns the shortest URL
83
+ */
84
+ export function createUrlMinifier(site) {
85
+ let baseUrl;
86
+ try {
87
+ baseUrl = site ? new URL(site) : null;
88
+ } catch {
89
+ baseUrl = null;
90
+ }
91
+
92
+ return function relate(url) {
93
+ if (!url || !url.trim()) return url;
94
+
95
+ // Preserve fragment-only and query-only URLs as shortest form
96
+ const trimmed = url.trim();
97
+ if (trimmed[0] === '#' || trimmed[0] === '?') return url;
98
+
99
+ let targetUrl;
100
+ try {
101
+ targetUrl = new URL(url);
102
+ } catch {
103
+ // Not a valid absolute URL—try resolving against base
104
+ if (baseUrl) {
105
+ try {
106
+ targetUrl = new URL(url, baseUrl);
107
+ } catch {
108
+ return url;
109
+ }
110
+ } else {
111
+ return url;
112
+ }
113
+ }
114
+
115
+ // Skip rejected schemes
116
+ if (REJECTED_SCHEMES.has(targetUrl.protocol)) return url;
117
+
118
+ // Clean up pathname
119
+ targetUrl.pathname = removeDirectoryIndex(targetUrl.pathname);
120
+
121
+ const suffix = targetUrl.search + targetUrl.hash;
122
+
123
+ // No base URL—return normalized absolute URL
124
+ if (!baseUrl) {
125
+ return targetUrl.href;
126
+ }
127
+
128
+ // Preserve userinfo—non-absolute URLs would drop username/password
129
+ if (targetUrl.username || targetUrl.password) {
130
+ return targetUrl.href;
131
+ }
132
+
133
+ // Check if same origin (protocol + hostname + port)
134
+ const sameOrigin =
135
+ targetUrl.protocol === baseUrl.protocol &&
136
+ targetUrl.hostname === baseUrl.hostname &&
137
+ targetUrl.port === baseUrl.port;
138
+
139
+ if (!sameOrigin) {
140
+ // Same scheme, different host—use scheme-relative
141
+ if (targetUrl.protocol === baseUrl.protocol) {
142
+ return '//' + targetUrl.host + targetUrl.pathname + suffix;
143
+ }
144
+ // Different scheme—return normalized absolute
145
+ return targetUrl.href;
146
+ }
147
+
148
+ // Same origin—compute shortest representation
149
+ const targetPath = targetUrl.pathname;
150
+ const rootRelative = targetPath + suffix;
151
+ const pathRelative = relativize(getDirectory(baseUrl.pathname), targetPath) + suffix;
152
+
153
+ return pathRelative && pathRelative.length < rootRelative.length ? pathRelative : rootRelative;
154
+ };
155
+ }