urlmason 1.0.0 → 1.1.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/dist/tables.mjs CHANGED
@@ -1,122 +1,247 @@
1
- import { decodePercent, getRegistrableDomain, isHostOf, isHttpUrl, parseUrl, stripWww } from "./node_modules/trousse/dist/urls.mjs";
2
- import { escapeRegex, isAnyOf, isSameText, startsWithAnyOf } from "./node_modules/trousse/dist/matching.mjs";
3
- import { isFunction, isPlainObject, isString } from "./node_modules/trousse/dist/is.mjs";
1
+ import { decodeFormPart, decodePath, decodePercent, isHostOf, isHttpUrl, parseUrl, stripWww } from "./node_modules/trousse/dist/urls.mjs";
2
+ import { endsWithAnyOf, escapeRegex, isAnyOf, isLooseMatch, startsWithAnyOf } from "./node_modules/trousse/dist/matching.mjs";
3
+ import { isFunction, isPlainObject, isPresent, isString } from "./node_modules/trousse/dist/is.mjs";
4
+ import { omit, setKey, trimObject } from "./node_modules/trousse/dist/objects.mjs";
4
5
  import { t } from "./node_modules/trousse/dist/locales.mjs";
5
- import { trimObject } from "./node_modules/trousse/dist/objects.mjs";
6
6
  import { errors } from "./locales.json.mjs";
7
- import { appendValue, decodeQueryValue, encodeText, entityPrefix, isEntityPair, parseQuery, readAmpersandEntities, readUrlQuery, sortPairs, toPair, toUrlQuery, writeQuery } from "./queries.mjs";
8
- import { basePlaceholder, compileTemplate, decodePath, dotSegmentRegex, encodeLiteral, isMultiSegment, mapTemplate, openTailName, openTailSuffix, parseTemplate, placeholderRegex, sharedPartMaxLength, splitPath, toBareName, toLengthGuard, toRegexSource, toSegments, toStrictPair, toValueText, trailingSlashRegex, writeBase } from "./templates.mjs";
7
+ import { validateCaseMark, validateCheckNames, validateCheckRegexAnchors, validateCheckRegexFlags, validateEntityNames, validateListNames, validateListSplit, validateOpenTail, validatePatternGroups, validateSemicolons, validateTenantHost } from "./rules.mjs";
8
+ import { basePlaceholder, compileTemplate, encodeLiteral, encodeParserText, encodeReservedSlot, isMultiSegment, isTypedValue, mapTemplate, openTailName, parseTemplate, placeholderRegex, sharedPartMaxLength, splitPath, toAsciiHost, toBareName, toRegexSource, toSlotText, toValueParts, toValueText } from "./templates.mjs";
9
+ import { isUtf8Text, singleEscapeRegex, toDecodedText, toLowerCaseValue } from "./utils/escapes.mjs";
10
+ import { isApexHost } from "./utils/hosts.mjs";
11
+ import { dotSegmentRegex, toSegments, toWrittenOffset, trailingSlashRegex } from "./utils/paths.mjs";
12
+ import { appendValue, cutHref, isEntityPair, isNamed, parseQuery, readAmpersandEntities, readSemicolons, toFlagNames, toPair, toStrictPair, toUrlQuery, writeBase, writeQuery } from "./utils/queries.mjs";
13
+ import { groupReferenceRegex, splitAlternatives, toLengthGuard } from "./utils/regexes.mjs";
14
+ import { toAsciiLowerCaseText } from "./utils/texts.mjs";
9
15
  // src/tables.ts
10
16
  const leadingSlashesRegex = /^\/{2,}/;
11
17
  const anchorsRegex = /^\^|\$$/g;
12
18
  const plainValueRegex = /^[\w.~-]+$/;
13
19
  const captureRegex = /\(\?<p\d+>/g;
14
- const escapeSplitRegex = /(%[0-9a-f]{2})/i;
20
+ const escapedPipeRegex = /%7c/gi;
21
+ const percentEscapeRegex = /%[0-9a-f]{2}/gi;
15
22
  const fixedPathTextRegex = /[^/]/;
23
+ const originRegex = /^[^:/?#]+:\/\/[^/?#]*/;
24
+ const portRegex = /:\d+$/;
16
25
  const standInOrigin = "https://root.invalid";
17
- const hostPlaceholder = "{host}";
18
26
  const anyDomainSource = "[^./]+(?:\\.[^./]+)+";
19
- const isNamed = (pair, names) => {
20
- return isAnyOf(pair.name, names) || isAnyOf(pair.sortName, names);
21
- };
27
+ const anyHostSource = "[^/]+";
28
+ const sampleValues = [
29
+ "1",
30
+ "a",
31
+ "en"
32
+ ];
33
+ const sampleReservedValues = ["https://example.com/a/b", "a/b"];
34
+ const sampleLists = [["a", "b"], ["1"]];
22
35
  const toShapePlaceholder = (_, name) => {
23
36
  return name.endsWith("*") ? "{*}" : "{}";
24
37
  };
25
- const toLowerCaseValue = (value) => {
26
- return value.split(escapeSplitRegex).map((piece, index) => index % 2 === 1 ? piece : piece.toLowerCase()).join("");
27
- };
28
- const asciiUpperCaseRegex = /[A-Z]+/g;
29
38
  const toAsciiLowerCase = (value) => {
30
- const lowercase = (text) => {
31
- return text.replace(asciiUpperCaseRegex, (letters) => letters.toLowerCase());
32
- };
33
- if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([name, text]) => [name, lowercase(text)]));
34
- return Array.isArray(value) ? value.map(lowercase) : lowercase(value);
39
+ if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([name, text]) => {
40
+ return [name, isString(text) ? toAsciiLowerCaseText(text) : text.map(toAsciiLowerCaseText)];
41
+ }));
42
+ return Array.isArray(value) ? value.map(toAsciiLowerCaseText) : toAsciiLowerCaseText(value);
43
+ };
44
+ const toUpperCaseEscapes = (text) => {
45
+ return text.replace(percentEscapeRegex, (triplet) => triplet.toUpperCase());
35
46
  };
36
47
  const toCheckParams = (params) => {
37
48
  return Object.fromEntries(Object.entries(params).map(([name, value]) => [name, toValueText(value)]));
38
49
  };
50
+ const lowercaseMarked = (params, caseNames, checks, rowChecks) => {
51
+ const markedNames = (caseNames ?? []).filter((name) => params[name] !== void 0);
52
+ if (markedNames.length === 0) return params;
53
+ const values = { ...params };
54
+ for (const name of markedNames) values[name] = toAsciiLowerCase(params[name]);
55
+ const checkParams = toCheckParams(values);
56
+ return markedNames.some((name) => checks[name]?.(checkParams[name]) === false) || Object.entries(checkParams).some(([checkName, text]) => {
57
+ return rowChecks[checkName]?.(text, checkParams) === false;
58
+ }) ? params : values;
59
+ };
39
60
  const isSameValue = (left, right, isSame) => {
40
61
  if (left === right) return true;
62
+ if (isPlainObject(left) && isPlainObject(right)) {
63
+ const names = Object.keys(left);
64
+ return names.length === Object.keys(right).length && names.every((name) => isSameValue(left[name], right[name], isSame));
65
+ }
41
66
  if (!Array.isArray(left) || !Array.isArray(right)) return isString(left) && isString(right) && isSame(left, right);
42
67
  return left.length === right.length && left.every((segment, index) => isSame(segment, right[index]));
43
68
  };
44
- const portRegex = /:\d+$/;
45
69
  const hasFixedPath = (parsed) => {
46
70
  return fixedPathTextRegex.test(parsed.path.replace(placeholderRegex, ""));
47
71
  };
48
- const toCheckFunctions = (checks = {}) => {
72
+ const toCheckFunctions = (checks = {}, hostNames = []) => {
49
73
  const functions = {};
50
74
  for (const [name, check] of Object.entries(checks)) {
51
75
  if (!check) continue;
52
76
  if (isFunction(check)) {
53
- functions[name] = check;
77
+ setKey(functions, name, check);
54
78
  continue;
55
79
  }
56
- if (check.global || check.sticky) throw new Error(t(errors.statefulCheckRegex, { name }));
57
- if (!check.source.startsWith("^") || !check.source.endsWith("$")) throw new Error(t(errors.unanchoredCheckRegex, { name }));
58
- const wholeRegex = new RegExp(`^(?:${check.source})$`, check.flags);
59
- functions[name] = (value, ..._rest) => wholeRegex.test(value);
80
+ validateCheckRegexFlags(name, check);
81
+ validateCheckRegexAnchors(name, check);
82
+ validatePatternGroups(name, check);
83
+ const wholeRegex = new RegExp(`^(?:${check.source})$`, check.flags.replace("m", ""));
84
+ setKey(functions, name, (value, ..._rest) => {
85
+ return wholeRegex.test(value);
86
+ });
87
+ }
88
+ for (const name of hostNames) {
89
+ const hostCheck = functions[name];
90
+ if (hostCheck) functions[name] = (value, ...rest) => {
91
+ return hostCheck(value.replace(portRegex, ""), ...rest);
92
+ };
60
93
  }
61
- const hostCheck = functions.host;
62
- if (hostCheck) functions.host = (value, ...rest) => hostCheck(value.replace(portRegex, ""), ...rest);
63
94
  return functions;
64
95
  };
96
+ const toJobValues = (jobs, origin) => {
97
+ const values = {};
98
+ if (jobs?.schemeName !== void 0) values[jobs.schemeName] = origin.scheme;
99
+ if (jobs?.hostName !== void 0) values[jobs.hostName] = origin.host;
100
+ if (jobs?.parentName !== void 0) values[jobs.parentName] = origin.parent;
101
+ return values;
102
+ };
65
103
  const copyRow = (row) => {
66
104
  const copy = { ...row };
67
105
  if (row.checks) copy.checks = { ...row.checks };
106
+ if (row.lenient) copy.lenient = { ...row.lenient };
68
107
  return copy;
69
108
  };
70
- const toTableUrl = (url) => {
71
- const path = url.pathname.replace(leadingSlashesRegex, "/");
72
- const hostPath = url.hostname + decodePath(path);
73
- return {
109
+ const toTableUrl = (url, path = url.pathname.replace(leadingSlashesRegex, "/")) => {
110
+ const toHostPath = (text) => {
111
+ return `${url.hostname}${decodePath(text)}`.replace(trailingSlashRegex, "");
112
+ };
113
+ const tableUrl = {
74
114
  url,
75
115
  hostname: url.hostname,
76
- hostPath: hostPath.replace(trailingSlashRegex, "")
116
+ path,
117
+ hostPath: toHostPath(path),
118
+ isSlashed: path.endsWith("/")
119
+ };
120
+ if (path !== url.pathname) tableUrl.written = {
121
+ path: url.pathname,
122
+ hostPath: toHostPath(url.pathname)
123
+ };
124
+ return tableUrl;
125
+ };
126
+ const toTemplateUrl = (template, tableUrl) => {
127
+ if (!template.isSlashWritten || !tableUrl.written) return tableUrl;
128
+ return {
129
+ ...tableUrl,
130
+ ...tableUrl.written
77
131
  };
78
132
  };
133
+ const isHostPathTaken = (regex, tableUrl) => {
134
+ return [tableUrl, tableUrl.written].some((form) => form !== void 0 && regex.test(form.hostPath));
135
+ };
79
136
  const readQuery = (tableUrl) => {
80
- if (!tableUrl.query) tableUrl.query = readUrlQuery(tableUrl.url);
137
+ if (!tableUrl.query) {
138
+ const { search, hash } = cutHref(tableUrl.url);
139
+ tableUrl.query = toUrlQuery(parseQuery(search), hash);
140
+ }
81
141
  return tableUrl.query;
82
142
  };
143
+ const readWrittenRest = (tableUrl) => {
144
+ const { search, hash } = cutHref(tableUrl.url);
145
+ return `${search}${hash}`;
146
+ };
147
+ const toReadTableUrl = (url) => {
148
+ const parsedUrl = parseUrl(url);
149
+ if (!parsedUrl || !isHttpUrl(parsedUrl)) return {
150
+ url,
151
+ tableUrl: void 0
152
+ };
153
+ parsedUrl.pathname = encodeParserText(parsedUrl.pathname, "path");
154
+ return {
155
+ url,
156
+ tableUrl: toTableUrl(parsedUrl)
157
+ };
158
+ };
83
159
  let lastTableUrl;
84
160
  const readTableUrl = (url) => {
85
- if (lastTableUrl?.url === url) return lastTableUrl.tableUrl;
86
- const parsedUrl = parseUrl(url);
87
- const tableUrl = parsedUrl && isHttpUrl(parsedUrl) ? toTableUrl(parsedUrl) : void 0;
88
- lastTableUrl = {
161
+ if (!lastTableUrl || lastTableUrl.url !== url) lastTableUrl = toReadTableUrl(url);
162
+ return lastTableUrl.tableUrl;
163
+ };
164
+ let lastRootedUrl;
165
+ const readRootedUrl = (url) => {
166
+ if (lastRootedUrl?.url === url) return lastRootedUrl;
167
+ const parsedUrl = readTableUrl(url)?.url;
168
+ if (!parsedUrl) return;
169
+ const segments = parsedUrl.pathname.split("/");
170
+ const baseLengths = [];
171
+ const maxBaseLength = Math.min(segments.length, 9);
172
+ for (let baseLength = 1; baseLength <= maxBaseLength; baseLength++) {
173
+ if (baseLength > 1 && !segments[baseLength - 1]) break;
174
+ baseLengths.push(baseLength);
175
+ }
176
+ lastRootedUrl = {
89
177
  url,
90
- tableUrl
178
+ parsedUrl,
179
+ segments,
180
+ baseLengths,
181
+ bases: segments.map(decodePercent),
182
+ standInUrls: []
91
183
  };
92
- return tableUrl;
184
+ return lastRootedUrl;
185
+ };
186
+ const toStandInUrl = (rootedUrl, baseLength) => {
187
+ const { parsedUrl, segments, standInUrls } = rootedUrl;
188
+ let standInUrl = standInUrls[baseLength];
189
+ if (!standInUrl) {
190
+ const rest = segments.slice(baseLength).map((segment) => `/${segment}`).join("");
191
+ standInUrl = toReadTableUrl(`${standInOrigin}${rest}${parsedUrl.search}${parsedUrl.hash}`);
192
+ standInUrls[baseLength] = standInUrl;
193
+ }
194
+ lastTableUrl = standInUrl;
195
+ return standInUrl.url;
93
196
  };
94
197
  const joinRegexes = (regexes) => {
95
198
  const sources = regexes.map((regex) => `(?:${regex.source.replace(captureRegex, "(?:")})`);
96
199
  return new RegExp([...new Set(sources)].join("|") || "(?!)", "i");
97
200
  };
201
+ const isTestedEntry = (entry) => {
202
+ if (isString(entry)) return false;
203
+ return isFunction(entry) || !isAnyOf(entry.flags, ["", "i"]) || groupReferenceRegex.test(entry.source);
204
+ };
98
205
  const toEntrySource = (entry) => {
99
- if (isFunction(entry)) return anyDomainSource;
100
- return isString(entry) ? escapeRegex(entry) : `(?:${entry.source.replace(anchorsRegex, "")})`;
206
+ if (isString(entry)) return escapeRegex(entry);
207
+ if (isFunction(entry) || isTestedEntry(entry)) return anyDomainSource;
208
+ return `(?:${splitAlternatives(entry.source).map((alternative) => {
209
+ return alternative.replace(anchorsRegex, "");
210
+ }).join("|")})`;
211
+ };
212
+ const toAsciiHosts = (hosts) => {
213
+ if (!hosts) return;
214
+ const toAsciiEntries = (entries) => {
215
+ return entries?.map((entry) => isString(entry) ? toAsciiHost(entry) : entry);
216
+ };
217
+ return {
218
+ exact: toAsciiEntries(hosts.exact),
219
+ tenant: toAsciiEntries(hosts.tenant),
220
+ subdomain: toAsciiEntries(hosts.subdomain)
221
+ };
101
222
  };
102
223
  const isListedIn = (value, entries = []) => {
103
224
  return entries.some((entry) => {
104
225
  return isFunction(entry) ? entry(value) : isHostOf(`https://${value}`, entry);
105
226
  });
106
227
  };
228
+ const getListedDomain = (host, entries) => {
229
+ let start = 0;
230
+ while (start !== -1) {
231
+ const domain = host.slice(start);
232
+ if (isListedIn(domain, entries)) return domain;
233
+ const dot = host.indexOf(".", start);
234
+ start = dot === -1 ? -1 : dot + 1;
235
+ }
236
+ };
107
237
  const isListedHost = (host, options) => {
108
238
  const bareHost = stripWww(host);
109
239
  const parentDomains = (options.isWwwTenant ? [host, bareHost] : [bareHost]).map((form) => form.slice(form.indexOf(".") + 1));
110
- return isListedIn(host, options.hosts?.exact) || isListedIn(bareHost, options.hosts?.exact) || parentDomains.some((domain) => isListedIn(domain, options.hosts?.tenant));
111
- };
112
- const getTenantDomain = (host, tenants = []) => {
113
- for (let index = host.indexOf("."); index !== -1; index = host.indexOf(".", index + 1)) if (isListedIn(host.slice(index + 1), tenants)) return host.slice(index + 1);
114
- };
115
- const isApexHost = (host) => {
116
- return getRegistrableDomain(`https://${host}`) === host;
240
+ const isWwwDropped = !options.isFallThrough || isApexHost(bareHost);
241
+ return isListedIn(host, options.hosts?.exact) || isWwwDropped && isListedIn(bareHost, options.hosts?.exact) || parentDomains.some((domain) => isListedIn(domain, options.hosts?.tenant)) || getListedDomain(host, options.hosts?.subdomain) !== void 0;
117
242
  };
118
- const compileRowTemplate = (template, { key, checks: givenRowChecks }, rowIndex, isAlias, options, checks, rowChecks, lenient, hasAmpersandMark) => {
119
- const built = parseTemplate(template);
243
+ const compileRowTemplate = ({ built, row: { key, checks: givenRowChecks, lenient: rowLenient }, rowIndex, isAlias, options, checks, rowChecks, lenient, originNames }) => {
244
+ const hasAmpersandMark = lenient?.ampersandEntity === true;
120
245
  const hasBase = built.path.startsWith(basePlaceholder);
121
246
  const parsed = hasBase ? {
122
247
  ...built,
@@ -124,115 +249,168 @@ const compileRowTemplate = (template, { key, checks: givenRowChecks }, rowIndex,
124
249
  path: built.path.slice(basePlaceholder.length),
125
250
  names: built.names.filter((name) => name !== "base*")
126
251
  } : built;
127
- const { scheme, host, path, isOpen, names } = parsed;
128
- if (`${host}${path}${parsed.search ?? ""}`.includes("{/tail*}")) throw new Error(t(errors.misplacedOpenTail, { key }));
252
+ const { scheme, host, path, isOpen, jobs, reservedNames, restName, listSplit } = parsed;
253
+ const [lead, firstName] = path.split(placeholderRegex);
254
+ const isValueFirst = firstName !== void 0 && !fixedPathTextRegex.test(lead);
255
+ const isSlashWritten = lead.startsWith("//") || isValueFirst;
256
+ validateListSplit(key, listSplit, [...Object.keys(checks), ...Object.keys(rowChecks)]);
257
+ const isOpenEnded = isOpen || restName !== void 0;
129
258
  const ownNames = parsed.params.map((param) => param.name);
130
- const entityName = ownNames.find((name) => name.startsWith(entityPrefix));
131
- if (hasAmpersandMark && entityName !== void 0) throw new Error(t(errors.ampersandEntityName, {
132
- key,
133
- name: entityName
134
- }));
259
+ validateEntityNames(key, parsed, hasAmpersandMark);
260
+ validateSemicolons(key, parsed.search, lenient);
135
261
  const hosts = options.hosts?.exact ?? [];
136
262
  const tenantDomains = (options.hosts?.tenant ?? []).map((domain) => toEntrySource(domain));
137
263
  const domainSource = `(?:${tenantDomains.join("|")})`;
138
264
  const tenantSource = options.isWwwTenant ? "[^./]+" : "(?!www\\.)[^./]+";
139
- const hasHosts = hosts.length > 0 || tenantDomains.length > 0;
140
- const hasHostCheck = [...hosts, ...options.hosts?.tenant ?? []].some(isFunction);
141
- if (host.includes("{domain}") && tenantDomains.length === 0) throw new Error(t(errors.missingHosts, { key }));
142
- const multiSegmentName = [...path.matchAll(placeholderRegex)].map(([, name]) => name).find(isMultiSegment);
143
- if (isOpen && multiSegmentName !== void 0) {
144
- const name = toBareName(multiSegmentName);
145
- throw new Error(t(errors.openTailBesideMultiSegment, {
146
- key,
147
- name
148
- }));
149
- }
150
- if (isOpen && names.some((name) => toBareName(name) === "tail")) throw new Error(t(errors.openTailName, { key }));
151
- const sharedName = (names.filter(isMultiSegment).length > 1 ? [parsed.text] : [
152
- ...host.split("."),
153
- ...splitPath(path),
154
- ...parsed.params.map((param) => param.value)
155
- ]).map((piece) => [...piece.matchAll(placeholderRegex)].map(([, name]) => toBareName(name))).filter((pieceNames) => pieceNames.length > 1).flat().find((name) => lenient?.case?.includes(name));
156
- if (sharedName !== void 0) throw new Error(t(errors.sharedCaseMark, {
157
- key,
158
- name: sharedName
159
- }));
160
- const pathPatterns = {};
161
- const writtenPathPatterns = {};
162
- for (const segment of splitPath(path)) {
163
- const segmentNames = [...segment.matchAll(placeholderRegex)].map(([, name]) => name);
164
- for (const name of segmentNames.length > 1 ? segmentNames : []) {
265
+ const subdomains = options.hosts?.subdomain ?? [];
266
+ const hasHosts = hosts.length > 0 || tenantDomains.length > 0 || subdomains.length > 0;
267
+ const hasHostCheck = [
268
+ ...hosts,
269
+ ...options.hosts?.tenant ?? [],
270
+ ...subdomains
271
+ ].some(isTestedEntry);
272
+ validateTenantHost(key, jobs.parentName, tenantDomains.length);
273
+ validateOpenTail(key, parsed);
274
+ validateCaseMark(key, parsed, lenient);
275
+ const splitPatterns = {};
276
+ const writtenSplitPatterns = {};
277
+ for (const part of toValueParts(parsed)) {
278
+ const partNames = [...part.matchAll(placeholderRegex)].map(([, name]) => name);
279
+ for (const name of partNames.length > 1 ? partNames : []) {
165
280
  const check = givenRowChecks?.[name] ?? options.checks?.[name];
166
- if (check instanceof RegExp && isAnyOf(check.flags, ["", "i"])) pathPatterns[name] = toEntrySource(check);
167
- if (check instanceof RegExp && !check.flags) writtenPathPatterns[name] = toEntrySource(check);
281
+ if (check instanceof RegExp && isAnyOf(check.flags, ["", "i"])) splitPatterns[name] = toEntrySource(check);
282
+ if (check instanceof RegExp && !check.flags) writtenSplitPatterns[name] = toEntrySource(check);
168
283
  }
169
284
  }
170
- const compiled = compileTemplate(parsed, pathPatterns, writtenPathPatterns);
171
- const builtCompiled = hasBase ? compileTemplate(built, pathPatterns, writtenPathPatterns) : compiled;
285
+ const isFlagValueChecked = (name, value, values) => {
286
+ const isChecked = (text) => {
287
+ const params = {
288
+ ...toCheckParams(values),
289
+ [name]: text
290
+ };
291
+ return (checks[name]?.(text) ?? true) && (rowChecks[name]?.(text, params) ?? true);
292
+ };
293
+ if (isChecked(value)) return true;
294
+ return lenient?.valueCase?.includes(name) === true && isChecked(toAsciiLowerCaseText(value));
295
+ };
296
+ const compileOptions = {
297
+ splitPatterns,
298
+ writtenSplitPatterns,
299
+ lenient,
300
+ isFlagValueChecked
301
+ };
302
+ const compiled = compileTemplate({
303
+ parsed,
304
+ ...compileOptions
305
+ });
306
+ const builtCompiled = hasBase ? compileTemplate({
307
+ parsed: built,
308
+ ...compileOptions
309
+ }) : compiled;
172
310
  const ownParams = compiled.params;
173
311
  const { getCaptured } = compiled;
174
- const hasRowChecks = Object.keys(rowChecks).length > 0;
175
- const passesChecks = (listParams) => {
312
+ const toRefusal = (listParams) => {
176
313
  const params = toCheckParams(listParams);
177
- return Object.entries(params).every(([name, value]) => {
178
- return (checks[name]?.(value) ?? true) && (rowChecks[name]?.(value, params) ?? true);
179
- });
314
+ const entries = Object.entries(params);
315
+ if (entries.some(([name, value]) => !(checks[name]?.(value) ?? true))) return "table";
316
+ if (entries.some(([name, value]) => !(rowChecks[name]?.(value, params) ?? true))) return "row";
180
317
  };
181
- const toHostPathRegex = (isWwwOptional, pathPattern, flags) => {
318
+ const toHostPathRegex = ({ isWwwOptional, pathPattern, flags, isAnyHost = false }) => {
182
319
  const wwwSource = isWwwOptional ? "(?:www\\.)?" : "";
183
320
  const tenantWwwSource = options.isWwwTenantPrefix ? wwwSource : "";
184
- const normalize = (value) => isWwwOptional ? stripWww(value) : value;
185
- const listedHosts = options.isFallThrough ? hosts.filter(isString) : [];
321
+ const normalize = (value) => {
322
+ return isWwwOptional ? stripWww(value) : value;
323
+ };
186
324
  const toPageHostSource = (value) => {
187
325
  const bare = stripWww(value);
188
326
  return isApexHost(bare) ? `${wwwSource}${escapeRegex(bare)}` : escapeRegex(value);
189
327
  };
190
- const hostSources = [...hosts.map((value) => {
191
- if (options.isFallThrough && isString(value)) return toPageHostSource(value);
192
- return `${wwwSource}${toEntrySource(isString(value) ? normalize(value) : value)}`;
193
- }), ...tenantDomains.length > 0 ? [`${tenantWwwSource}${tenantSource}\\.${domainSource}`] : []];
194
- const isFixedHost = !host.startsWith("{") || host.startsWith("{domain}");
328
+ const hostSources = [
329
+ ...hosts.map((value) => {
330
+ if (options.isFallThrough && isString(value)) return toPageHostSource(value);
331
+ return `${wwwSource}${toEntrySource(isString(value) ? normalize(value) : value)}`;
332
+ }),
333
+ ...tenantDomains.length > 0 ? [`${tenantWwwSource}${tenantSource}\\.${domainSource}`] : [],
334
+ ...subdomains.map((value) => {
335
+ return isTestedEntry(value) ? toEntrySource(value) : `(?:[^./]+\\.)*${toEntrySource(value)}`;
336
+ })
337
+ ];
338
+ const isFixedHost = !host.startsWith("{");
195
339
  const bareHost = stripWww(host);
196
- const listedForms = [bareHost, `www.${bareHost}`].filter((form) => listedHosts.includes(form));
197
- const isPageFixedHost = Boolean(options.isFallThrough) && isFixedHost && !host.includes("{");
340
+ const isPageFixedHost = Boolean(options.isFallThrough) && !host.includes("{");
198
341
  const fixedPrefixSource = isFixedHost && !isPageFixedHost ? wwwSource : "";
199
- const tenantPrefixSource = !isFixedHost && !host.startsWith("{host}") ? tenantWwwSource : "";
200
- const hostCaptures = {
201
- host: `(?:${hostSources.join("|")})`,
202
- domain: domainSource
203
- };
204
- const hostSource = toRegexSource(normalize(host), compiled.captureIn("host"), {
205
- source: tenantSource,
206
- unit: "[^./]"
207
- }, hostCaptures);
342
+ const tenantPrefixSource = !isFixedHost && jobs.hostName === void 0 ? tenantWwwSource : "";
343
+ const hostCaptures = {};
344
+ if (jobs.hostName !== void 0) hostCaptures[jobs.hostName] = isAnyHost ? anyHostSource : `(?:${hostSources.join("|")})`;
345
+ if (jobs.parentName !== void 0) hostCaptures[jobs.parentName] = isAnyHost ? anyHostSource : domainSource;
346
+ const hostSource = toRegexSource({
347
+ text: normalize(host),
348
+ wrapCapture: compiled.captureIn("host"),
349
+ capture: {
350
+ source: tenantSource,
351
+ unit: "[^./]"
352
+ },
353
+ captures: hostCaptures,
354
+ patterns: flags.includes("i") ? splitPatterns : writtenSplitPatterns
355
+ });
208
356
  const prefixSource = `${host.split(".").some((label) => {
209
357
  return [...label.matchAll(placeholderRegex)].length > 1;
210
358
  }) ? toLengthGuard(sharedPartMaxLength, "/") : ""}${fixedPrefixSource}${tenantPrefixSource}`;
211
- if (isPageFixedHost) {
212
- const forms = listedForms.length > 0 ? listedForms : [host];
359
+ if (isPageFixedHost && !isAnyHost) {
360
+ const listedForms = [bareHost, `www.${bareHost}`].filter((form) => hosts.includes(form));
361
+ const forms = [.../* @__PURE__ */ new Set([host, ...listedForms])];
213
362
  const sources = isApexHost(bareHost) ? [toPageHostSource(bareHost)] : forms.map(escapeRegex);
214
363
  return new RegExp(`^(?:${sources.join("|")})${pathPattern}$`, flags);
215
364
  }
216
- return new RegExp(`^${prefixSource}${hostSource}${pathPattern}$`, flags);
365
+ return new RegExp(`^${prefixSource}${hostSource}(?![^/])(?<=^[^/]*)${pathPattern}$`, flags);
366
+ };
367
+ const { readPathSource, rawPathSource } = compiled;
368
+ const readOptions = {
369
+ pathPattern: readPathSource,
370
+ flags: reservedNames.length > 0 ? "di" : "i"
371
+ };
372
+ const asGivenRegex = toHostPathRegex({
373
+ ...readOptions,
374
+ isWwwOptional: false
375
+ });
376
+ const optionalWwwRegex = toHostPathRegex({
377
+ ...readOptions,
378
+ isWwwOptional: true
379
+ });
380
+ const builtRegex = toHostPathRegex({
381
+ ...readOptions,
382
+ isWwwOptional: false,
383
+ isAnyHost: true
384
+ });
385
+ const rawOptions = {
386
+ pathPattern: rawPathSource,
387
+ flags: "d"
217
388
  };
218
- const hasSharedSegment = splitPath(path).some((segment) => {
219
- return [...segment.matchAll(placeholderRegex)].length > 1;
389
+ const rawAsGivenRegex = toHostPathRegex({
390
+ ...rawOptions,
391
+ isWwwOptional: false
220
392
  });
221
- const toEndingGuard = (text, mapLiteral) => {
222
- if (!hasSharedSegment || isOpen) return "";
223
- const ending = mapLiteral(text.split(placeholderRegex).at(-1) ?? "");
224
- if (!ending) return "";
225
- return `(?=[^]*${escapeRegex(ending)}$)`;
226
- };
227
- const readPathSource = `${toEndingGuard(path.replace(trailingSlashRegex, ""), decodePath)}${compiled.readPathSource}`;
228
- const rawPathSource = `${toEndingGuard(path, encodeLiteral)}${compiled.rawPathSource}`;
229
- const asGivenRegex = toHostPathRegex(false, readPathSource, "i");
230
- const optionalWwwRegex = toHostPathRegex(true, readPathSource, "i");
231
- const rawAsGivenRegex = toHostPathRegex(false, rawPathSource, "d");
232
- const rawOptionalWwwRegex = toHostPathRegex(true, rawPathSource, "d");
393
+ const rawOptionalWwwRegex = toHostPathRegex({
394
+ ...rawOptions,
395
+ isWwwOptional: true
396
+ });
397
+ const hasSlash = path && !isOpenEnded ? path.endsWith("/") : void 0;
398
+ const isSlashFree = hasSlash !== void 0 && (rowLenient?.trailingSlash ?? lenient?.trailingSlash) === true;
399
+ const isPipeFree = (rowLenient?.pipeEscape ?? lenient?.pipeEscape) === true;
400
+ const everyReservedName = [...reservedNames, ...parsed.fragmentReservedNames];
401
+ const pipeNames = isPipeFree ? everyReservedName : [];
233
402
  const fixedParams = ownParams.filter((param) => !param.value.includes("{"));
234
- const shapeQuery = ownNames.map((name) => name.toLowerCase()).sort((left, right) => left.localeCompare(right)).join("&");
235
- const shape = `${`${host}${path}`.replace(placeholderRegex, toShapePlaceholder)}${isOpen ? "#" : ""}?${shapeQuery}`;
403
+ const flagShapes = parsed.nameFlags.map((text) => text.replace(placeholderRegex, toShapePlaceholder));
404
+ const shapeQuery = [...ownNames, ...flagShapes].map((name) => name.toLowerCase()).sort((left, right) => left.localeCompare(right)).join("&");
405
+ const readPath = path.replace(trailingSlashRegex, "");
406
+ const shapePath = readPath.replace(placeholderRegex, toShapePlaceholder);
407
+ const fixedText = [
408
+ host,
409
+ readPath,
410
+ ...parsed.nameFlags,
411
+ ...ownParams.map((param) => param.value)
412
+ ].join("").replace(placeholderRegex, "");
413
+ const shape = `${shapePath}${isOpenEnded ? "#" : ""}?${shapeQuery}`;
236
414
  const toHostNames = (value) => {
237
415
  const bare = stripWww(value.toLowerCase());
238
416
  return [
@@ -247,42 +425,125 @@ const compileRowTemplate = (template, { key, checks: givenRowChecks }, rowIndex,
247
425
  names: toHostNames(host),
248
426
  suffixes: []
249
427
  };
250
- if (host === hostPlaceholder || host.includes("{domain}")) {
251
- const isHostOnly = host === hostPlaceholder;
252
- if (!tenantEntries.every(isString) || isHostOnly && !hosts.every(isString)) return;
253
- const domains = tenantEntries.filter(isString).map((domain) => domain.toLowerCase());
428
+ if (jobs.hostName !== void 0 || jobs.parentName !== void 0) {
429
+ const isHostOnly = jobs.hostName !== void 0;
430
+ const hostEntries = isHostOnly ? [...hosts, ...subdomains] : [];
431
+ if (!tenantEntries.every(isString) || !hostEntries.every(isString)) return;
432
+ const domains = tenantEntries.map((domain) => domain.toLowerCase());
433
+ const names = hostEntries.flatMap(toHostNames);
434
+ const parents = isHostOnly ? subdomains.filter(isString).map((entry) => entry.toLowerCase()) : [];
254
435
  return {
255
- names: [...isHostOnly ? hosts.filter(isString).flatMap(toHostNames) : [], ...domains.flatMap(toHostNames)],
256
- suffixes: domains.map((domain) => `.${domain}`)
436
+ names: [...names, ...domains.flatMap(toHostNames)],
437
+ suffixes: [...domains, ...parents].map((domain) => `.${domain}`)
257
438
  };
258
439
  }
259
440
  const suffix = host.slice(host.lastIndexOf("}") + 1).toLowerCase();
260
- if (host.includes(hostPlaceholder) || !suffix.startsWith(".")) return;
441
+ if (!suffix.startsWith(".")) return;
261
442
  return {
262
443
  names: [],
263
444
  suffixes: [suffix]
264
445
  };
265
446
  };
266
- const claimsUrls = !host.includes(hostPlaceholder) || hasHosts;
267
- const readParams = (tableUrl, isWwwOptional, base) => {
447
+ const doesClaimUrls = jobs.hostName === void 0 || hasHosts;
448
+ const openDepth = splitPath(path).length - (restName === void 0 ? 0 : 1);
449
+ const readWritten = (tableUrl, name, range) => {
450
+ const writtenPath = tableUrl.path;
451
+ const hostLength = tableUrl.hostname.length;
452
+ const start = toWrittenOffset(writtenPath, range[0] - hostLength);
453
+ const end = toWrittenOffset(writtenPath, range[1] - hostLength);
454
+ if (start === void 0 || end === void 0) return;
455
+ if (name !== restName) return writtenPath.slice(start, end);
456
+ return `${writtenPath.slice(start)}${readWrittenRest(tableUrl)}`;
457
+ };
458
+ const readReserved = (match, tableUrl, params) => {
459
+ for (const [group, range] of Object.entries(match.indices?.groups ?? {})) {
460
+ const { name } = getCaptured(group);
461
+ if (!range || !reservedNames.includes(name)) continue;
462
+ const value = readWritten(tableUrl, name, range);
463
+ if (value === void 0) return false;
464
+ params[name] = value;
465
+ }
466
+ return true;
467
+ };
468
+ const readListSplit = (split, match, tableUrl, params) => {
469
+ const findRange = (name) => {
470
+ return Object.entries(match.indices?.groups ?? {}).find(([group, range]) => range && getCaptured(group).name === name)?.[1] ?? [0, 0];
471
+ };
472
+ const listRange = findRange(split.list);
473
+ const reservedRange = findRange(split.reserved);
474
+ const segments = match.input.slice(listRange[0], reservedRange[1]).split("/");
475
+ const writtenPath = tableUrl.path;
476
+ const hostLength = tableUrl.hostname.length;
477
+ const listStart = toWrittenOffset(writtenPath, listRange[0] - hostLength);
478
+ const end = toWrittenOffset(writtenPath, reservedRange[1] - hostLength);
479
+ if (listStart === void 0 || end === void 0) return params;
480
+ const writtenSegments = writtenPath.slice(listStart, end).split("/");
481
+ const writtenStarts = [listStart + 1];
482
+ for (const [index, segment] of writtenSegments.entries()) writtenStarts.push(writtenStarts[index] + segment.length + (index > 0 ? 1 : 0));
483
+ let rest = "";
484
+ if (split.reserved === restName) rest = `${writtenPath.slice(end)}${readWrittenRest(tableUrl)}`;
485
+ const hasListCheck = (checks[split.list] ?? rowChecks[split.list]) !== void 0;
486
+ const counts = [...segments.keys()];
487
+ for (const count of hasListCheck ? counts.reverse() : counts) {
488
+ const listSegments = segments.slice(0, count);
489
+ const reserved = `${writtenPath.slice(writtenStarts[count], end)}${rest}`;
490
+ if (listSegments.length === 0 || listSegments.includes("") || !reserved) continue;
491
+ const list = listSegments.map(decodePercent);
492
+ const candidate = {
493
+ ...params,
494
+ [split.list]: list,
495
+ [split.reserved]: reserved
496
+ };
497
+ if (toRefusal(candidate) === void 0) return candidate;
498
+ }
499
+ return params;
500
+ };
501
+ const readMatch = (tableUrl, regex, isHostChecked, base) => {
268
502
  const { url, hostPath } = tableUrl;
269
- const match = claimsUrls && (isWwwOptional ? optionalWwwRegex : asGivenRegex).exec(hostPath);
503
+ const match = regex.exec(hostPath);
270
504
  if (!match) return;
271
- const params = compiled.read(match.groups, () => readQuery(tableUrl).searchParams);
272
- if (!params) return;
273
- if (hasHostCheck && ("host" in params || "domain" in params)) {
274
- if (!(isString(params.domain) ? isListedIn(params.domain, options.hosts?.tenant) : isListedHost(url.hostname, options))) return;
505
+ const read = compiled.read(match.groups, () => readQuery(tableUrl).searchParams);
506
+ if (!read) return;
507
+ const params = read.values;
508
+ let { isCaseBlind } = read;
509
+ if (parsed.fragment !== void 0) {
510
+ const fragmentRead = compiled.readFragment(url.hash.slice(1), params);
511
+ if (!fragmentRead) return;
512
+ Object.assign(params, {
513
+ ...fragmentRead.values,
514
+ ...params
515
+ });
516
+ if (fragmentRead.isCaseBlind) isCaseBlind = true;
275
517
  }
276
- if ("host" in params) params.host = url.host;
277
- if (scheme === "{scheme}") params.scheme = url.protocol.slice(0, -1);
518
+ const isPageWww = Boolean(options.isFallThrough) && url.hostname.startsWith("www.");
519
+ const isHostRead = jobs.hostName !== void 0 || jobs.parentName !== void 0;
520
+ if (isHostChecked && (hasHostCheck || isPageWww) && isHostRead) {
521
+ const parentValue = jobs.parentName === void 0 ? void 0 : params[jobs.parentName];
522
+ if (!(isString(parentValue) ? isListedIn(parentValue, options.hosts?.tenant) : isListedHost(url.hostname, options))) return;
523
+ }
524
+ if (jobs.hostName !== void 0) params[jobs.hostName] = url.host;
525
+ if (jobs.schemeName !== void 0) params[jobs.schemeName] = url.protocol.slice(0, -1);
526
+ if (reservedNames.length > 0 && !readReserved(match, tableUrl, params)) return;
278
527
  if (base) Object.assign(params, base);
279
- return params;
528
+ return {
529
+ values: listSplit ? readListSplit(listSplit, match, tableUrl, params) : params,
530
+ isCaseBlind
531
+ };
532
+ };
533
+ const toOriginValues = (origin) => {
534
+ if (!origin) return;
535
+ const values = toJobValues(originNames, origin);
536
+ if (origin.base) values.base = origin.base;
537
+ return values;
538
+ };
539
+ const readParams = (tableUrl, isWwwOptional, isSlashLoose, origin) => {
540
+ if (hasSlash !== void 0 && tableUrl.isSlashed !== hasSlash && !(isSlashLoose && isSlashFree)) return;
541
+ if (!doesClaimUrls) return;
542
+ return readMatch(tableUrl, isWwwOptional ? optionalWwwRegex : asGivenRegex, true, toOriginValues(origin));
280
543
  };
281
544
  const readRawGroups = (rawParams, groups = {}) => {
282
545
  return Object.entries(groups).every(([group, value]) => {
283
- const captured = getCaptured(group);
284
- if (!captured || value === void 0) return true;
285
- const { name, part } = captured;
546
+ const { name, part } = getCaptured(group);
286
547
  if (rawParams[name] && rawParams[name].value !== value) return false;
287
548
  rawParams[name] = {
288
549
  value,
@@ -291,25 +552,20 @@ const compileRowTemplate = (template, { key, checks: givenRowChecks }, rowIndex,
291
552
  return true;
292
553
  });
293
554
  };
294
- const decodeValue = (value, part) => {
295
- if (part === "host") return value;
296
- return part === "path" ? decodePercent(decodePath(value)) : decodeQueryValue(value).trim();
297
- };
298
- const lowercaseValues = (match, listParams) => {
299
- const params = toCheckParams(listParams);
555
+ const respellValues = (match, lowercaseNames) => {
300
556
  const groups = { ...match.groups };
301
557
  let text = match.input;
302
- for (const [group, range] of Object.entries(match.indices?.groups ?? {})) {
558
+ const ranges = Object.entries(match.indices?.groups ?? {}).sort(([, left], [, right]) => {
559
+ return right[0] - left[0];
560
+ });
561
+ for (const [group, range] of ranges) {
303
562
  const captured = getCaptured(group);
304
- if (!range || !captured || !lenient?.case?.includes(captured.name)) continue;
305
- const value = toLowerCaseValue(text.slice(range[0], range[1]));
306
- const { name } = captured;
307
- const decoded = decodeValue(value, captured.part);
308
- if (checks[name]?.(decoded) === false) continue;
309
- if (rowChecks[name]?.(decoded, {
310
- ...params,
311
- [name]: decoded
312
- }) === false) continue;
563
+ const isLowercased = lowercaseNames.includes(captured.name);
564
+ const isPiped = pipeNames.includes(captured.name);
565
+ if (!isLowercased && !isPiped) continue;
566
+ const written = text.slice(range[0], range[1]);
567
+ const lowercased = isLowercased ? toLowerCaseValue(written) : written;
568
+ const value = isPiped ? lowercased.replace(escapedPipeRegex, "|") : lowercased;
313
569
  groups[group] = value;
314
570
  text = `${text.slice(0, range[0])}${value}${text.slice(range[1])}`;
315
571
  }
@@ -318,137 +574,329 @@ const compileRowTemplate = (template, { key, checks: givenRowChecks }, rowIndex,
318
574
  groups
319
575
  };
320
576
  };
321
- const readRawParams = (tableUrl, isWwwOptional, params) => {
577
+ const respellSlash = (pathname) => {
578
+ if (!isSlashFree) return pathname;
579
+ const bare = pathname.replace(trailingSlashRegex, "");
580
+ return hasSlash ? `${bare}/` : bare;
581
+ };
582
+ const readRawParams = (tableUrl, isWwwOptional, params, lowercaseNames, isRespelled, isCaseFree) => {
322
583
  const { url } = tableUrl;
323
584
  const { pairs } = readQuery(tableUrl);
324
- const match = (isWwwOptional ? rawOptionalWwwRegex : rawAsGivenRegex).exec(url.hostname + url.pathname);
585
+ const toRawRegex = (rawRegex) => {
586
+ return isCaseFree ? new RegExp(rawRegex.source, `${rawRegex.flags}i`) : rawRegex;
587
+ };
588
+ const regex = toRawRegex(isWwwOptional ? rawOptionalWwwRegex : rawAsGivenRegex);
589
+ const pathname = isRespelled ? respellSlash(url.pathname) : url.pathname;
590
+ const match = regex.exec(`${url.hostname}${pathname}`);
325
591
  const rawParams = {};
326
592
  if (!match) return;
327
- const respelledHostPath = lowercaseValues(match, params);
593
+ const respelledHostPath = respellValues(match, lowercaseNames);
328
594
  if (!readRawGroups(rawParams, respelledHostPath.groups)) return;
329
595
  const respelledPairs = [...pairs];
596
+ const isGivenOnce = (name, spellings) => {
597
+ const named = pairs.filter((pair) => isLooseMatch(toDecodedText(pair.name), toDecodedText(name)));
598
+ const isSpelled = (pair) => {
599
+ const rawName = toUpperCaseEscapes(pair.rawName);
600
+ return isCaseFree ? isAnyOf(rawName, spellings) : spellings.includes(rawName);
601
+ };
602
+ return named.length < 2 && named.every(isSpelled);
603
+ };
604
+ const lowercasePair = (index) => {
605
+ const { rawName, rawValue = "" } = pairs[index];
606
+ const value = toLowerCaseValue(rawValue);
607
+ if (value !== rawValue) respelledPairs[index] = toPair(`${rawName}=${value}`);
608
+ return value;
609
+ };
610
+ for (const name of parsed.optionalNames) {
611
+ const index = pairs.findIndex((given) => isNamed(given, name));
612
+ if (!isGivenOnce(name, [name])) return;
613
+ if (index === -1 || params[name] === void 0) continue;
614
+ rawParams[name] = {
615
+ value: lowercaseNames.includes(name) ? lowercasePair(index) : pairs[index].rawValue ?? "",
616
+ part: "query"
617
+ };
618
+ }
330
619
  for (const param of ownParams) {
331
- const [index, ...others] = [...pairs.keys()].filter((pairIndex) => {
332
- return isNamed(pairs[pairIndex], param.name);
333
- });
620
+ if (!isGivenOnce(param.name, [param.writtenName])) return;
621
+ const index = pairs.findIndex((pair) => isNamed(pair, param.name));
334
622
  const { rawName, rawValue } = pairs[index];
335
- if (others.length > 0 || ![param.writtenName, param.name].includes(rawName)) return;
336
623
  if (param.isFlag) {
337
- if (rawValue) return;
338
624
  if (rawValue !== void 0) respelledPairs[index] = toPair(rawName);
339
625
  continue;
340
626
  }
341
- const queryMatch = param.rawRegex.exec(rawValue ?? "");
627
+ const queryMatch = toRawRegex(param.rawRegex).exec(rawValue ?? "");
342
628
  if (!queryMatch) return;
343
- const respelledValue = lowercaseValues(queryMatch, params);
629
+ const respelledValue = respellValues(queryMatch, lowercaseNames);
344
630
  if (!readRawGroups(rawParams, respelledValue.groups)) return;
345
631
  if (respelledValue.text !== rawValue) respelledPairs[index] = toPair(`${rawName}=${respelledValue.text}`);
346
632
  }
347
- if ("host" in rawParams) rawParams.host.value = url.host;
348
- if (scheme === "{scheme}") rawParams.scheme = {
633
+ const flagNames = toFlagNames(pairs);
634
+ const flagIndexes = compiled.claimFlags(flagNames, params);
635
+ for (const [flagIndex, flag] of compiled.nameFlags.entries()) {
636
+ const index = flagIndexes[flagIndex];
637
+ const flagMatch = index === -1 ? void 0 : toRawRegex(flag.rawRegex).exec(pairs[index].rawName);
638
+ if (!flagMatch) return;
639
+ const respelledName = respellValues(flagMatch, lowercaseNames);
640
+ if (!readRawGroups(rawParams, respelledName.groups)) return;
641
+ respelledPairs[index] = toPair(respelledName.text);
642
+ }
643
+ if (flagNames.some((name, index) => {
644
+ return name !== void 0 && !flagIndexes.includes(index) && compiled.readFlagName(name, params) !== void 0;
645
+ })) return;
646
+ if (parsed.passedName !== void 0 && lowercaseNames.includes(parsed.passedName)) {
647
+ for (const [index, pair] of pairs.entries()) if (!flagIndexes.includes(index) && !isNamed(pair, [...ownNames, ...parsed.optionalNames])) lowercasePair(index);
648
+ }
649
+ let hash;
650
+ const { rawFragmentRegex } = compiled;
651
+ if (rawFragmentRegex) {
652
+ const fragmentMatch = toRawRegex(rawFragmentRegex).exec(url.hash.slice(1));
653
+ if (!fragmentMatch) return;
654
+ const respelledFragment = respellValues(fragmentMatch, lowercaseNames);
655
+ if (!readRawGroups(rawParams, respelledFragment.groups)) return;
656
+ hash = `#${respelledFragment.text}`;
657
+ }
658
+ if (jobs.hostName !== void 0) rawParams[jobs.hostName] = {
659
+ value: url.host,
660
+ part: "host"
661
+ };
662
+ if (jobs.schemeName !== void 0) rawParams[jobs.schemeName] = {
349
663
  value: url.protocol.slice(0, -1),
350
664
  part: "host"
351
665
  };
352
666
  return {
353
667
  params: rawParams,
668
+ values: params,
354
669
  pathname: respelledHostPath.text.slice(url.hostname.length),
355
- pairs: respelledPairs
670
+ pairs: respelledPairs,
671
+ hash,
672
+ isRespelled
356
673
  };
357
674
  };
358
- const getRawUrl = (rawParams, keptPairs) => {
675
+ const hasNonUtf8Value = (rawRead) => {
676
+ const values = Object.entries(rawRead.params).filter(([name]) => !everyReservedName.includes(name)).map(([, param]) => param.value);
677
+ const namedNames = [...ownNames, ...parsed.optionalNames];
678
+ const passedPairs = parsed.passedName === void 0 ? [] : rawRead.pairs.filter((pair) => !isNamed(pair, namedNames));
679
+ return [...values, ...passedPairs.map((pair) => pair.text)].some((text) => !isUtf8Text(text));
680
+ };
681
+ const getRawUrl = (rawRead, keptPairs) => {
682
+ const rawParams = rawRead.params;
359
683
  let isFilled = true;
684
+ const fillValue = (name, part) => {
685
+ const rawParam = rawParams[name];
686
+ const value = rawRead.values[name];
687
+ if (!rawParam) {
688
+ isFilled = false;
689
+ return "";
690
+ }
691
+ if (rawParam.part === part || plainValueRegex.test(rawParam.value)) return rawParam.value;
692
+ if (part === "host" || !isString(value)) {
693
+ isFilled = false;
694
+ return "";
695
+ }
696
+ return compiled.encodeValue(value, part);
697
+ };
360
698
  const fill = (text, part, mapLiteral) => {
361
699
  const fillPlaceholder = (placeholder) => {
362
- const rawParam = rawParams[toBareName(placeholder)];
363
- if (!rawParam || rawParam.part !== part && !plainValueRegex.test(rawParam.value)) {
364
- isFilled = false;
365
- return "";
366
- }
367
- return rawParam.value;
700
+ return fillValue(toBareName(placeholder), part);
368
701
  };
369
702
  return mapTemplate(text, fillPlaceholder, mapLiteral);
370
703
  };
704
+ const fillText = (text, part) => {
705
+ return fill(text, part, (literal) => encodeLiteral(literal, part));
706
+ };
371
707
  const origin = `${fill(scheme, "host")}://${fill(host, "host")}`;
372
708
  const pairs = ownParams.map((own) => {
373
709
  if (!own.isFilled) return own.pair;
374
- return appendValue(own.pair, fill(own.value, "query", encodeText));
710
+ return appendValue(own.pair, fill(own.value, "query", compiled.encodeQueryText));
375
711
  });
376
- const filledPath = fill(path, "path", encodeLiteral);
712
+ for (const { text } of compiled.nameFlags) pairs.push(compiled.toWrittenPair(fill(text, "query", compiled.encodeQueryName)));
713
+ for (const name of parsed.optionalNames) if (rawParams[name]) pairs.push(toPair(`${name}=${fillValue(name, "query")}`));
714
+ const filledPath = fillText(path, "path");
715
+ const hash = parsed.fragment === void 0 ? void 0 : `#${fillText(parsed.fragment, "fragment")}`;
377
716
  if (!isFilled || filledPath.split("/").some((segment) => dotSegmentRegex.test(segment))) return;
378
- const writtenPairs = [...pairs, ...keptPairs];
717
+ const writtenPairs = compiled.orderPairs([...pairs, ...keptPairs], rawRead.values);
379
718
  return {
380
719
  base: writeBase(`${origin}${filledPath}`, writtenPairs),
381
- pairs: writtenPairs
720
+ pairs: writtenPairs,
721
+ hash
382
722
  };
383
723
  };
384
724
  const getHttpsOrigin = (rawParams) => {
385
725
  if (!isAnyOf(scheme, "https")) return;
386
726
  return `https://${mapTemplate(host, (name) => rawParams[toBareName(name)].value)}`;
387
727
  };
388
- const getUrl = (params = {}, encoding = "pretty") => {
389
- const values = builtCompiled.getValues(params);
390
- if (!values) return;
391
- for (const [name, value] of Object.entries(values)) {
392
- const check = checks[toBareName(name)];
393
- if (check && !check(toValueText(value))) return;
394
- const lowercase = lenient?.case?.includes(toBareName(name)) ? toAsciiLowerCase(value) : value;
395
- values[name] = check && !check(toValueText(lowercase)) ? value : lowercase;
396
- }
397
- if (hasRowChecks) {
398
- const filled = Object.fromEntries(built.names.map((name) => [toBareName(name), toValueText(values[name])]));
399
- if (Object.entries(filled).some(([name, value]) => {
400
- return rowChecks[name]?.(value, filled) === false;
401
- })) return;
728
+ const hostNames = [...host.matchAll(placeholderRegex)].map(([, name]) => name);
729
+ const checkNames = [
730
+ ...built.names.map(toBareName),
731
+ ...parsed.optionalNames,
732
+ ...parsed.passedName === void 0 ? [] : [parsed.passedName],
733
+ ...isOpen ? [openTailName] : []
734
+ ];
735
+ const toPipedText = (name, text) => {
736
+ return pipeNames.includes(name) ? text.replace(escapedPipeRegex, "|") : text;
737
+ };
738
+ const isReadBack = (placeholder, value, readValue) => {
739
+ const name = toBareName(placeholder);
740
+ if (everyReservedName.includes(name)) {
741
+ const part = reservedNames.includes(name) ? "path" : "fragment";
742
+ return toPipedText(name, encodeReservedSlot(value, false, part)) === toPipedText(name, toSlotText(readValue ?? "", placeholder));
402
743
  }
403
- return builtCompiled.fill(values, encoding);
744
+ const builtValue = name === parsed.passedName && !isPlainObject(value) ? { [name]: value } : value;
745
+ const text = toDecodedText(toSlotText(builtValue, placeholder));
746
+ const readText = toDecodedText(toSlotText(readValue ?? "", placeholder));
747
+ if (name === jobs.schemeName || hostNames.includes(name)) return isLooseMatch(toAsciiHost(text), readText);
748
+ return text === readText;
749
+ };
750
+ const getUrl = (givenParams, encoding, site) => {
751
+ const ownParams = givenParams ?? {};
752
+ const callerParams = trimObject(ownParams) ?? {};
753
+ const siteParams = site ? omit(toJobValues(jobs, site), Object.keys(callerParams)) : {};
754
+ const params = site ? {
755
+ ...siteParams,
756
+ ...callerParams
757
+ } : ownParams;
758
+ if (!checkNames.every((name) => isTypedValue(params[name]))) return { refusal: "table" };
759
+ const values = builtCompiled.getValues(params);
760
+ if (!values) return {};
761
+ const bareValues = Object.fromEntries(Object.entries(values).map(([name, value]) => [toBareName(name), value]));
762
+ const lowercaseValues = lowercaseMarked(bareValues, lenient?.valueCase, checks, rowChecks);
763
+ const refusal = toRefusal(lowercaseValues);
764
+ if (refusal && !toRefusal(omit(lowercaseValues, Object.keys(siteParams)))) return {};
765
+ if (refusal) return { refusal };
766
+ for (const name of Object.keys(values)) values[name] = lowercaseValues[toBareName(name)];
767
+ const url = builtCompiled.fill(values, encoding);
768
+ const ownUrl = hasBase ? compiled.fill(values, encoding) : url;
769
+ const parsedUrl = ownUrl === void 0 ? void 0 : parseUrl(ownUrl);
770
+ const tableUrl = parsedUrl && toTableUrl(parsedUrl, parsedUrl.pathname);
771
+ const base = hasBase ? { base: values["base*"] } : void 0;
772
+ const writtenParams = tableUrl && readMatch(tableUrl, builtRegex, false, base)?.values;
773
+ if (!url || !writtenParams) return { refusal: "table" };
774
+ const readValues = lowercaseMarked(writtenParams, lenient?.valueCase, checks, rowChecks);
775
+ if (!Object.entries(values).every(([placeholder, value]) => {
776
+ return isReadBack(placeholder, value, readValues[toBareName(placeholder)]);
777
+ })) return { refusal: "table" };
778
+ const readRefusal = toRefusal(readValues);
779
+ if (readRefusal) return { refusal: readRefusal };
780
+ return {
781
+ url,
782
+ tableUrl: void 0
783
+ };
404
784
  };
405
- const getWrittenText = (pair) => {
406
- const param = ownParams.find((own) => own.name === pair.rawName && own.name === pair.name);
407
- if (!param) return pair.text;
408
- return `${param.writtenName}${pair.text.slice(pair.rawName.length)}`;
785
+ const readOwnPair = (pair, known) => {
786
+ const param = ownParams.find((own) => isNamed(pair, own.name));
787
+ if (param && singleEscapeRegex.test(pair.rawName) && !isAnyOf(toUpperCaseEscapes(pair.rawName), param.writtenName)) return;
788
+ if (param && lenient?.fixedCase !== true && pair.name !== param.name) return;
789
+ const flagMatch = pair.rawValue ? void 0 : compiled.readFlagName(pair.name, known);
790
+ const match = param ? param.regex.exec(decodeFormPart(pair.rawValue ?? "")) : flagMatch;
791
+ if (!match) return;
792
+ const values = [];
793
+ for (const [group, value] of Object.entries(match.groups ?? {})) values.push([getCaptured(group).name, value]);
794
+ return values;
409
795
  };
410
796
  return {
411
797
  rowIndex,
412
798
  isAlias,
799
+ names: built.names,
413
800
  ownNames,
414
801
  optionalNames: parsed.optionalNames,
415
- hostNames: [...host.matchAll(placeholderRegex)].map(([, name]) => name),
802
+ hostNames,
416
803
  fixedQuery: fixedParams.map((param) => [param.name, param.value]),
417
804
  valueNames: ownParams.filter((param) => param.value.includes("{")).map((param) => param.name),
418
- flagTexts: ownParams.filter((param) => param.isFlag).map((param) => `${param.writtenName}=`),
419
- getWrittenText,
805
+ readOwnPair,
420
806
  asGivenRegex,
421
807
  optionalWwwRegex,
422
808
  hostHint: toHostHint(),
423
809
  readParams,
424
810
  readRawParams,
811
+ hasNonUtf8Value,
812
+ isSlashFree,
813
+ isSlashWritten,
814
+ pipeNames,
425
815
  getRawUrl,
426
816
  getHttpsOrigin,
427
- passesChecks,
817
+ isHttpsWritten: isAnyOf(scheme, "https"),
818
+ toRefusal,
428
819
  shape,
429
- openDepth: isOpen ? splitPath(path).length : Number.POSITIVE_INFINITY,
430
- getUrl
820
+ fixedTextLength: fixedText.length,
821
+ openDepth: isOpenEnded ? openDepth : Number.POSITIVE_INFINITY,
822
+ restName,
823
+ hasFragment: parsed.fragment !== void 0,
824
+ nameFlagCount: parsed.nameFlags.length,
825
+ passedName: parsed.passedName,
826
+ checkNames,
827
+ isFlagPair: (pair, values) => {
828
+ return !pair.rawValue && compiled.readFlagName(pair.name, values) !== void 0;
829
+ },
830
+ orderPairs: compiled.orderPairs,
831
+ getUrl,
832
+ fillUrl: (params) => {
833
+ const values = builtCompiled.getValues(params);
834
+ return values && builtCompiled.fill(values);
835
+ }
431
836
  };
432
837
  };
433
- const createTable = (givenRows, options = {}) => {
838
+ const createTable = ({ rows: givenRows, options: givenOptions = {}, originNames = [] }) => {
434
839
  const rows = givenRows.map((row) => copyRow(row));
840
+ const options = {
841
+ ...givenOptions,
842
+ hosts: toAsciiHosts(givenOptions.hosts)
843
+ };
435
844
  const lenient = {
436
845
  ...options.lenient,
437
- case: Array.isArray(options.lenient?.case) ? [...options.lenient.case] : void 0
846
+ valueCase: Array.isArray(options.lenient?.valueCase) ? [...options.lenient.valueCase] : void 0
438
847
  };
439
848
  const hasAmpersandMark = lenient.ampersandEntity === true;
440
- const checks = toCheckFunctions(options.checks);
441
- const rowChecks = rows.map((row) => toCheckFunctions(row.checks));
849
+ const hasFixedCaseMark = lenient.fixedCase === true;
850
+ const parsedRows = rows.map((row) => [row.main, ...row.aliases ?? []].map(parseTemplate));
851
+ const givenHostNames = [...parsedRows.flat().map((parsed) => parsed.jobs.hostName), ...originNames.flat().map((names) => names.hostName)];
852
+ const wholeHostNames = [...new Set(givenHostNames.filter(isPresent))];
853
+ const checks = toCheckFunctions(options.checks, wholeHostNames);
854
+ const rowChecks = rows.map((row) => toCheckFunctions(row.checks, wholeHostNames));
442
855
  const compiledRows = rows.map((row, rowIndex) => {
443
- return [row.main, ...row.aliases ?? []].map((template, index) => {
444
- return compileRowTemplate(template, row, rowIndex, index > 0, options, checks, rowChecks[rowIndex], lenient, hasAmpersandMark);
856
+ return parsedRows[rowIndex].map((parsed, index) => {
857
+ return compileRowTemplate({
858
+ built: parsed,
859
+ row,
860
+ rowIndex,
861
+ isAlias: index > 0,
862
+ options,
863
+ checks,
864
+ rowChecks: rowChecks[rowIndex],
865
+ lenient,
866
+ originNames: originNames[rowIndex]?.[index]
867
+ });
445
868
  });
446
869
  });
447
870
  const compiled = compiledRows.flat();
871
+ const namedTemplates = compiled.map((template) => {
872
+ return {
873
+ key: rows[template.rowIndex].key,
874
+ names: template.names,
875
+ optionalNames: template.optionalNames,
876
+ passedName: template.passedName
877
+ };
878
+ });
879
+ validateListNames(namedTemplates);
880
+ const checkNames = {
881
+ templates: compiled.map((template) => ({
882
+ key: rows[template.rowIndex].key,
883
+ rowIndex: template.rowIndex,
884
+ names: template.checkNames
885
+ })),
886
+ rowCheckNames: rows.map((row) => {
887
+ const givenChecks = row.checks ?? {};
888
+ return Object.keys(givenChecks).filter((name) => givenChecks[name] !== void 0);
889
+ }),
890
+ caseNames: lenient.valueCase ?? []
891
+ };
448
892
  const claimed = compiled.filter((candidate) => !rows[candidate.rowIndex].isBuildOnly);
449
- const bySpecificity = [...claimed].sort((a, b) => {
450
- if (a.openDepth !== b.openDepth) return b.openDepth - a.openDepth;
451
- return b.ownNames.length - a.ownNames.length;
893
+ const bySpecificity = [...claimed].sort((left, right) => {
894
+ if (left.openDepth !== right.openDepth) return right.openDepth - left.openDepth;
895
+ const leftNameCount = left.ownNames.length + left.nameFlagCount;
896
+ const rightNameCount = right.ownNames.length + right.nameFlagCount;
897
+ if (leftNameCount !== rightNameCount) return rightNameCount - leftNameCount;
898
+ if (left.hasFragment !== right.hasFragment) return Number(right.hasFragment) - Number(left.hasFragment);
899
+ return right.fixedTextLength - left.fixedTextLength;
452
900
  });
453
901
  const inReadOrder = options.isFallThrough ? claimed : bySpecificity;
454
902
  const hostHints = claimed.map((candidate) => candidate.hostHint);
@@ -457,8 +905,7 @@ const createTable = (givenRows, options = {}) => {
457
905
  const isAnyHostTaken = hostHints.some((hint) => !hint);
458
906
  const canTakeHost = (hostname) => {
459
907
  if (isAnyHostTaken || hostNames.has(hostname)) return true;
460
- for (const suffix of hostSuffixes) if (hostname.endsWith(suffix)) return true;
461
- return false;
908
+ return endsWithAnyOf(hostname, hostSuffixes);
462
909
  };
463
910
  const asGivenRegex = joinRegexes(claimed.map((candidate) => candidate.asGivenRegex));
464
911
  const optionalWwwRegex = joinRegexes(claimed.map((candidate) => candidate.optionalWwwRegex));
@@ -468,25 +915,25 @@ const createTable = (givenRows, options = {}) => {
468
915
  return rows[rowIndex].key === key && (select?.(copyRow(rows[rowIndex])) ?? true);
469
916
  });
470
917
  };
471
- const buildUrl = (key, params, buildOptions) => {
472
- for (const candidate of getRowTemplates(key, buildOptions?.select).flat()) {
473
- const url = candidate.getUrl(params, buildOptions?.encoding);
474
- if (url) return url;
475
- }
476
- };
477
- const buildUrls = (key, params, buildOptions) => {
918
+ const buildRowUrls = (key, params, buildOptions, site) => {
919
+ const rowUrls = [];
478
920
  for (const templates of getRowTemplates(key, buildOptions?.select)) {
479
- const urls = [];
480
- for (const candidate of templates) {
481
- const url = candidate.getUrl(params, buildOptions?.encoding);
482
- if (url) urls.push(url);
483
- }
484
- if (urls.length > 0) return urls;
921
+ const builds = templates.map((candidate) => {
922
+ return candidate.getUrl(params, buildOptions?.encoding, site);
923
+ });
924
+ if (builds.some((build) => build.refusal === "table")) return;
925
+ const urls = builds.some((build) => build.refusal === "row") ? [] : builds.map((build) => build.url);
926
+ rowUrls.push([...new Set(urls.filter(isPresent))]);
485
927
  }
486
- return [];
928
+ return rowUrls;
487
929
  };
488
- const getSelectorNames = (key) => {
489
- const keyTemplates = compiledRows.filter((_templates, rowIndex) => rows[rowIndex].key === key).flat();
930
+ const buildUrl = (key, params, buildOptions, site) => {
931
+ return buildRowUrls(key, params, buildOptions, site)?.flat()[0];
932
+ };
933
+ const buildUrls = (key, params, buildOptions, site) => {
934
+ return buildRowUrls(key, params, buildOptions, site)?.find((urls) => urls.length > 0) ?? [];
935
+ };
936
+ const getSelectorNames = (keyTemplates) => {
490
937
  const fixedNames = keyTemplates.flatMap((template) => template.fixedQuery.map(([name]) => name));
491
938
  const getFixedValues = (template, name) => {
492
939
  const values = template.fixedQuery.filter(([fixedName]) => fixedName === name).map(([, value]) => value);
@@ -496,8 +943,10 @@ const createTable = (givenRows, options = {}) => {
496
943
  return new Set(keyTemplates.map((template) => getFixedValues(template, name))).size > 1;
497
944
  });
498
945
  };
499
- const keys = [...new Set(rows.map((row) => row.key))];
500
- const keySelectorNames = Object.fromEntries(keys.map((key) => [key, getSelectorNames(key)]));
946
+ const keyRows = Map.groupBy(compiledRows.entries(), ([rowIndex]) => rows[rowIndex].key);
947
+ const keySelectorNames = Object.fromEntries([...keyRows].map(([key, keyEntries]) => {
948
+ return [key, getSelectorNames(keyEntries.flatMap(([, templates]) => templates))];
949
+ }));
501
950
  const fixedQueryTemplates = compiled.filter((candidate) => candidate.fixedQuery.length > 0);
502
951
  const getPathSelectorNames = (template, hostPath, isWwwOptional) => {
503
952
  return fixedQueryTemplates.filter((candidate) => {
@@ -512,58 +961,96 @@ const createTable = (givenRows, options = {}) => {
512
961
  if (!tableUrl.url.search) return false;
513
962
  const row = rows[template.rowIndex];
514
963
  const names = [...keySelectorNames[row.key], ...getPathSelectorNames(template, tableUrl.hostPath, isWwwOptional)];
515
- if (names.length === 0) return false;
964
+ if (names.length === 0 || template.passedName !== void 0) return false;
516
965
  const rowFixedQuery = compiledRows[template.rowIndex].flatMap((candidate) => candidate.fixedQuery);
517
966
  const openNames = [...template.valueNames, ...template.optionalNames];
518
967
  return [...readQuery(tableUrl).searchParams].some(([name, value]) => {
519
- if (!isAnyOf(name, names) || isAnyOf(name, openNames)) return false;
968
+ const isSelectorName = isAnyOf(name, names);
969
+ const isOpenName = isAnyOf(name, openNames);
970
+ if (!isSelectorName || isOpenName) return false;
520
971
  return !rowFixedQuery.some(([fixedName, fixedValue]) => {
521
972
  return isAnyOf(name, fixedName) && isAnyOf(value, fixedValue);
522
973
  });
523
974
  });
524
975
  };
525
- const findTemplate = (tableUrl, isWwwOptional, base) => {
976
+ const isCaseRefused = (template, tableUrl, isWwwOptional, params, lowercaseNames) => {
977
+ if (hasFixedCaseMark) return false;
978
+ const isRead = (isRespelled, isCaseFree) => {
979
+ return template.readRawParams(tableUrl, isWwwOptional, params, lowercaseNames, isRespelled, isCaseFree) !== void 0;
980
+ };
981
+ return !isRead(false, false) && !isRead(true, false) && isRead(true, true);
982
+ };
983
+ const findTemplate = (tableUrl, isWwwOptional, origin, isPassedOn = options.isFallThrough === true) => {
526
984
  let refused;
985
+ let slashRead;
986
+ let checkRefused;
527
987
  for (const template of inReadOrder) {
528
- if (refused && !options.isFallThrough && refused.template.shape !== template.shape) continue;
529
- const params = template.readParams(tableUrl, isWwwOptional, base);
530
- if (!params) continue;
531
- const isCheckRefused = !template.passesChecks(params);
532
- const isSelectorRefused = !isCheckRefused && hasUnlistedSelector(template, tableUrl, isWwwOptional);
533
- if (!isCheckRefused && !isSelectorRefused) return {
534
- template,
535
- params,
536
- tableUrl,
537
- isWwwOptional
538
- };
539
- if (isSelectorRefused && !options.isFallThrough) return {
540
- template,
541
- tableUrl,
542
- isWwwOptional
543
- };
988
+ if (checkRefused && checkRefused.shape !== template.shape) continue;
989
+ if (slashRead && slashRead.template.shape !== template.shape) continue;
990
+ const templateUrl = toTemplateUrl(template, tableUrl);
991
+ const spelledRead = template.readParams(templateUrl, isWwwOptional, false, origin);
992
+ let read = spelledRead;
993
+ if (!read && template.isSlashFree && !slashRead) read = template.readParams(templateUrl, isWwwOptional, true, origin);
994
+ if (!read) continue;
995
+ const writtenParams = read.values;
996
+ const pipedParams = { ...writtenParams };
997
+ for (const name of template.pipeNames) {
998
+ const value = pipedParams[name];
999
+ if (isString(value)) pipedParams[name] = value.replace(escapedPipeRegex, "|");
1000
+ }
1001
+ const isPipeRead = template.pipeNames.some((name) => {
1002
+ return pipedParams[name] !== writtenParams[name];
1003
+ });
1004
+ const params = lowercaseMarked(pipedParams, lenient.valueCase, checks, rowChecks[template.rowIndex]);
1005
+ const isCopyLowercased = read.isCaseBlind && params !== pipedParams;
1006
+ const lowercaseNames = Object.keys(params).filter((name) => {
1007
+ return isCopyLowercased && (lenient.valueCase ?? []).includes(name) || !isSameValue(params[name], pipedParams[name], (left, right) => left === right);
1008
+ });
1009
+ if (isCaseRefused(template, templateUrl, isWwwOptional, params, lowercaseNames)) continue;
1010
+ const isCheckRefused = template.toRefusal(params) !== void 0;
1011
+ if (!isCheckRefused && !hasUnlistedSelector(template, templateUrl, isWwwOptional)) {
1012
+ const taken = {
1013
+ template,
1014
+ params,
1015
+ lowercaseNames,
1016
+ tableUrl: templateUrl,
1017
+ isWwwOptional,
1018
+ isMarkNeeded: isPipeRead || read.isCaseBlind || !spelledRead
1019
+ };
1020
+ if (spelledRead) return taken;
1021
+ slashRead = taken;
1022
+ continue;
1023
+ }
1024
+ if (isCheckRefused && !isPassedOn && !checkRefused) checkRefused = template;
544
1025
  if (!refused) refused = {
545
1026
  template,
546
- tableUrl,
547
- isWwwOptional
1027
+ lowercaseNames: [],
1028
+ tableUrl: templateUrl,
1029
+ isWwwOptional,
1030
+ isMarkNeeded: false
548
1031
  };
549
1032
  }
550
- return refused;
1033
+ return slashRead ?? (refused && {
1034
+ ...refused,
1035
+ checkRefused
1036
+ });
551
1037
  };
552
- const readRawParams = ({ template, params, tableUrl, isWwwOptional }) => {
1038
+ const readRawParams = ({ template, params, lowercaseNames, tableUrl, isWwwOptional }) => {
553
1039
  if (hasAmpersandMark && readQuery(tableUrl).pairs.some((pair) => pair.text.startsWith("amp;"))) return;
554
- return template.readRawParams(tableUrl, isWwwOptional, params);
1040
+ const rawRead = template.readRawParams(tableUrl, isWwwOptional, params, lowercaseNames, false, false);
1041
+ if (rawRead || !(template.isSlashFree || hasFixedCaseMark)) return rawRead;
1042
+ return template.readRawParams(tableUrl, isWwwOptional, params, lowercaseNames, true, hasFixedCaseMark);
555
1043
  };
556
- const readTableTemplate = (tableUrl, base) => {
557
- if (!canTakeHost(tableUrl.hostname)) return;
558
- const asGiven = options.isWwwTenant && asGivenRegex.test(tableUrl.hostPath) ? findTemplate(tableUrl, false, base) : void 0;
1044
+ const readTableTemplate = (tableUrl, origin, isPassedOn) => {
1045
+ const asGiven = options.isWwwTenant && isHostPathTaken(asGivenRegex, tableUrl) ? findTemplate(tableUrl, false, origin, isPassedOn) : void 0;
559
1046
  if (asGiven) return asGiven;
560
- if (optionalWwwRegex.test(tableUrl.hostPath)) return findTemplate(tableUrl, true, base);
1047
+ if (isHostPathTaken(optionalWwwRegex, tableUrl)) return findTemplate(tableUrl, true, origin, isPassedOn);
561
1048
  };
562
- const readTemplate = (url, base) => {
1049
+ const readTemplate = (url, origin) => {
563
1050
  const tableUrl = readTableUrl(url);
564
- if (!tableUrl) return;
1051
+ if (!tableUrl || !canTakeHost(tableUrl.hostname)) return;
565
1052
  const takesHostPath = () => {
566
- return [asGivenRegex, optionalWwwRegex].some((regex) => regex.test(tableUrl.hostPath));
1053
+ return [asGivenRegex, optionalWwwRegex].some((regex) => isHostPathTaken(regex, tableUrl));
567
1054
  };
568
1055
  let readableUrl = tableUrl;
569
1056
  if (hasAmpersandMark && takesHostPath() && readQuery(tableUrl).pairs.some(isEntityPair)) {
@@ -573,90 +1060,185 @@ const createTable = (givenRows, options = {}) => {
573
1060
  query: toUrlQuery(readAmpersandEntities(pairs), hash)
574
1061
  };
575
1062
  }
576
- const found = readTableTemplate(readableUrl, base);
1063
+ if (lenient.semicolonSeparator === true && readableUrl.url.search.includes(";") && takesHostPath()) {
1064
+ const { pairs, hash } = readQuery(readableUrl);
1065
+ readableUrl = {
1066
+ ...readableUrl,
1067
+ query: toUrlQuery(readSemicolons(pairs), hash)
1068
+ };
1069
+ }
1070
+ const found = readTableTemplate(readableUrl, origin);
577
1071
  if (!found?.params) return;
1072
+ const isRewriteRead = readableUrl !== tableUrl && found.template.restName === void 0;
1073
+ const isMarkNeeded = found.isMarkNeeded || isRewriteRead;
578
1074
  return {
579
1075
  ...found,
580
- params: found.params
1076
+ params: found.params,
1077
+ isMarkNeeded
1078
+ };
1079
+ };
1080
+ const buildSampleUrl = (template) => {
1081
+ const parsed = parsedRows[template.rowIndex][compiledRows[template.rowIndex].indexOf(template)];
1082
+ const toSamples = (placeholder) => {
1083
+ const name = toBareName(placeholder);
1084
+ if (name === parsed.jobs.schemeName) return ["https"];
1085
+ if (name === parsed.jobs.hostName) return template.hostHint?.names ?? [];
1086
+ if (name === parsed.jobs.parentName) return (options.hosts?.tenant ?? []).filter(isString);
1087
+ if (isMultiSegment(placeholder)) return sampleLists;
1088
+ return parsed.reservedNames.includes(name) ? sampleReservedValues : sampleValues;
1089
+ };
1090
+ const values = {};
1091
+ for (const placeholder of template.names) {
1092
+ if (placeholder === "base*") continue;
1093
+ const name = toBareName(placeholder);
1094
+ const sample = toSamples(placeholder).find((candidate) => {
1095
+ return template.toRefusal({
1096
+ ...values,
1097
+ [name]: candidate
1098
+ }) === void 0;
1099
+ });
1100
+ if (sample === void 0) return;
1101
+ values[name] = sample;
1102
+ }
1103
+ return template.fillUrl(values);
1104
+ };
1105
+ const findHiddenRead = (template) => {
1106
+ const url = buildSampleUrl(template);
1107
+ const tableUrl = url === void 0 ? void 0 : readTableUrl(url);
1108
+ const refusing = tableUrl && readTableTemplate(tableUrl)?.checkRefused;
1109
+ const hidden = tableUrl && refusing && readTableTemplate(tableUrl, void 0, true);
1110
+ if (!url || !refusing || !hidden?.params) return;
1111
+ return {
1112
+ refusing,
1113
+ hidden: hidden.template,
1114
+ url
1115
+ };
1116
+ };
1117
+ const findHiddenRows = () => {
1118
+ const hiddenReads = [];
1119
+ const hasCheck = [checks, ...rowChecks].some((functions) => Object.keys(functions).length > 0);
1120
+ const shapes = new Set(claimed.map((template) => template.shape));
1121
+ if (options.isFallThrough || !hasCheck || shapes.size < 2) return [];
1122
+ for (const template of claimed) {
1123
+ let hiddenRead;
1124
+ try {
1125
+ hiddenRead = findHiddenRead(template);
1126
+ } catch {}
1127
+ const isListed = hiddenReads.some((listed) => {
1128
+ return listed.refusing.rowIndex === hiddenRead?.refusing.rowIndex && listed.hidden.rowIndex === hiddenRead.hidden.rowIndex;
1129
+ });
1130
+ if (hiddenRead && !isListed) hiddenReads.push(hiddenRead);
1131
+ }
1132
+ const toText = (template) => {
1133
+ const { main, aliases = [] } = rows[template.rowIndex];
1134
+ return [main, ...aliases][compiledRows[template.rowIndex].indexOf(template)];
581
1135
  };
1136
+ return hiddenReads.map(({ refusing, hidden, url }) => {
1137
+ return {
1138
+ key: rows[refusing.rowIndex].key,
1139
+ row: copyRow(rows[refusing.rowIndex]),
1140
+ template: toText(refusing),
1141
+ hiddenRow: copyRow(rows[hidden.rowIndex]),
1142
+ hiddenTemplate: toText(hidden),
1143
+ url
1144
+ };
1145
+ });
582
1146
  };
583
1147
  const toMatch = (match) => {
584
1148
  return match;
585
1149
  };
586
- const defineRootUrls = (isBaseNeeded, takesTemplate) => {
1150
+ const defineRootUrls = ({ isBaseNeeded, takesTemplate }) => {
587
1151
  const rootRows = [];
1152
+ const rootNames = [];
588
1153
  for (const [rootRowIndex, row] of rows.entries()) {
589
1154
  const standIns = [];
1155
+ const standInNames = [];
590
1156
  let isMainRead = false;
591
- for (const [index, template] of [row.main, ...row.aliases ?? []].entries()) {
592
- const parsed = parseTemplate(template);
593
- const hasBase = parsed.path.startsWith(basePlaceholder);
594
- const path = hasBase ? parsed.path.slice(basePlaceholder.length) : parsed.path;
595
- const tail = parsed.isOpen ? openTailSuffix : "";
596
- const standIn = parseTemplate(`${standInOrigin}${path}${tail}${parsed.search ?? ""}`);
597
- if (!(isAnyOf(parsed.host, hostPlaceholder) && (hasBase || !isBaseNeeded) && takesTemplate(standIn))) continue;
1157
+ for (const [index, parsed] of parsedRows[rootRowIndex].entries()) {
1158
+ const { schemeName, hostName } = parsed.jobs;
1159
+ if (hostName === void 0) continue;
1160
+ const rest = parsed.text.slice(`${parsed.scheme}://${parsed.host}`.length);
1161
+ const hasBase = rest.startsWith(basePlaceholder);
1162
+ const standInRest = hasBase ? rest.slice(basePlaceholder.length) : rest;
1163
+ const standIn = parseTemplate(`${standInOrigin}${standInRest}`);
1164
+ if (isBaseNeeded && !hasBase || !takesTemplate(standIn)) continue;
598
1165
  standIns.push(standIn.text);
1166
+ standInNames.push({
1167
+ schemeName,
1168
+ hostName
1169
+ });
599
1170
  if (index === 0) isMainRead = true;
600
1171
  }
601
1172
  const [main, ...aliases] = standIns;
602
- if (main !== void 0) rootRows.push({
603
- ...row,
604
- key: row.key,
605
- main,
606
- aliases,
607
- rootRowIndex,
608
- isMainRead
609
- });
1173
+ if (main !== void 0) {
1174
+ rootRows.push({
1175
+ ...row,
1176
+ key: row.key,
1177
+ main,
1178
+ aliases,
1179
+ rootRowIndex,
1180
+ isMainRead
1181
+ });
1182
+ rootNames.push(standInNames);
1183
+ }
610
1184
  }
611
- return createTable(rootRows, {
612
- ...options,
613
- hosts: void 0
1185
+ return createTable({
1186
+ rows: rootRows,
1187
+ options: {
1188
+ ...options,
1189
+ hosts: void 0
1190
+ },
1191
+ originNames: rootNames
614
1192
  });
615
1193
  };
616
1194
  let rootTables;
617
1195
  const getRootTables = () => {
618
1196
  if (!rootTables) rootTables = {
619
- all: defineRootUrls(false, () => true),
620
- fixed: defineRootUrls(false, hasFixedPath),
621
- based: defineRootUrls(true, () => true),
622
- basedFixed: defineRootUrls(true, hasFixedPath)
1197
+ all: defineRootUrls({
1198
+ isBaseNeeded: false,
1199
+ takesTemplate: () => true
1200
+ }),
1201
+ fixed: defineRootUrls({
1202
+ isBaseNeeded: false,
1203
+ takesTemplate: hasFixedPath
1204
+ }),
1205
+ based: defineRootUrls({
1206
+ isBaseNeeded: true,
1207
+ takesTemplate: () => true
1208
+ }),
1209
+ basedFixed: defineRootUrls({
1210
+ isBaseNeeded: true,
1211
+ takesTemplate: hasFixedPath
1212
+ })
623
1213
  };
624
1214
  return rootTables;
625
1215
  };
626
1216
  const readRooted = (url, readOptions) => {
627
- const parsedUrl = parseUrl(url);
628
- if (!parsedUrl || !isHttpUrl(parsedUrl)) return;
1217
+ const rootedUrl = readRootedUrl(url);
1218
+ if (!rootedUrl) return;
1219
+ const { parsedUrl, segments, baseLengths } = rootedUrl;
629
1220
  const tables = getRootTables();
630
- const segments = parsedUrl.pathname.replace(leadingSlashesRegex, "/").split("/");
631
1221
  const readBehind = (isFixed, baseLength) => {
632
- const rest = segments.slice(baseLength).map((segment) => `/${segment}`);
633
- const base = segments.slice(1, baseLength).map(decodePercent);
1222
+ const base = rootedUrl.bases.slice(1, baseLength);
634
1223
  const table = baseLength > 1 ? tables[isFixed ? "basedFixed" : "based"] : tables[isFixed ? "fixed" : "all"];
635
- const readBase = {
1224
+ const origin = {
636
1225
  scheme: parsedUrl.protocol.slice(0, -1),
637
1226
  host: parsedUrl.host,
638
- ...base.length > 0 && { base }
639
- };
640
- const match = table.readStandIn(`${standInOrigin}${rest.join("")}${parsedUrl.search}${parsedUrl.hash}`, readBase);
641
- if (!match) return;
642
- return {
643
- match,
644
- values: {
645
- ...match.values,
646
- ...readBase
647
- }
1227
+ base: base.length > 0 ? base : void 0
648
1228
  };
1229
+ return table.readStandIn(toStandInUrl(rootedUrl, baseLength), origin);
649
1230
  };
650
1231
  const readUnder = (baseLength) => {
651
- const read = readBehind(false, baseLength);
652
- if (!read) return;
653
- const row = rows[read.match.row.rootRowIndex];
1232
+ const match = readBehind(false, baseLength);
1233
+ if (!match) return;
1234
+ const row = rows[match.row.rootRowIndex];
654
1235
  return toMatch({
655
1236
  key: row.key,
656
- values: read.values,
1237
+ values: match.values,
657
1238
  row: copyRow(row),
658
- isAlias: read.match.isAlias || !read.match.row.isMainRead,
659
- isExact: false
1239
+ isAliasMatch: match.isAliasMatch || !match.row.isMainRead,
1240
+ isExactMatch: false,
1241
+ isLenientMatch: match.isLenientMatch
660
1242
  });
661
1243
  };
662
1244
  if (readOptions.base !== void 0) {
@@ -664,13 +1246,10 @@ const createTable = (givenRows, options = {}) => {
664
1246
  const baseLength = basePath.length + 1;
665
1247
  const urlBase = segments.slice(1, baseLength);
666
1248
  if (!(urlBase.length === basePath.length && urlBase.every((segment, index) => {
667
- return isSameText(decodePath(segment), decodePath(basePath[index]));
1249
+ return isLooseMatch(decodePath(segment), decodePath(basePath[index]));
668
1250
  }))) return;
669
1251
  return readUnder(baseLength);
670
1252
  }
671
- const baseLengths = [];
672
- const maxBaseLength = Math.min(segments.length, 9);
673
- for (let baseLength = 1; baseLength <= maxBaseLength; baseLength++) if (!segments.slice(0, baseLength).join("/").endsWith("/")) baseLengths.push(baseLength);
674
1253
  for (const baseLength of baseLengths) {
675
1254
  const match = readBehind(true, baseLength) ? readUnder(baseLength) : void 0;
676
1255
  if (match) return match;
@@ -680,63 +1259,112 @@ const createTable = (givenRows, options = {}) => {
680
1259
  if (match) return match;
681
1260
  }
682
1261
  };
683
- const readOwn = (url, base) => {
684
- const found = readTemplate(url, base);
1262
+ const readOwn = (url, origin) => {
1263
+ const found = readTemplate(url, origin);
685
1264
  if (!found) return;
686
1265
  const row = rows[found.template.rowIndex];
687
- const params = { ...found.params };
688
- delete params[openTailName];
1266
+ const values = omit(found.params, [openTailName]);
1267
+ const rawRead = readRawParams(found);
1268
+ const isLenientMatch = found.isMarkNeeded || found.lowercaseNames.length > 0 || rawRead?.isRespelled === true;
1269
+ const isSchemeRewritten = found.template.isHttpsWritten && found.tableUrl.url.protocol === "http:";
689
1270
  return toMatch({
690
1271
  key: row.key,
691
- values: params,
1272
+ values,
692
1273
  row: copyRow(row),
693
- isAlias: found.template.isAlias,
694
- isExact: readRawParams(found) !== void 0
1274
+ isAliasMatch: found.template.isAlias,
1275
+ isExactMatch: rawRead !== void 0 && !isLenientMatch && !isSchemeRewritten,
1276
+ isLenientMatch
695
1277
  });
696
1278
  };
697
1279
  const readUrl = (url, readOptions) => {
698
1280
  if (readOptions?.base !== void 0 || readOptions?.isAnyHost) return readRooted(url, readOptions);
699
1281
  return readOwn(url);
700
1282
  };
1283
+ const isSameRead = (template, name, value, sourceValue) => {
1284
+ if ([...lenient.valueCase ?? [], ...template.hostNames].includes(name)) return isSameValue(value, sourceValue, isLooseMatch);
1285
+ return isSameValue(value, sourceValue, (left, right) => left === right);
1286
+ };
701
1287
  const writeMainUrl = (template, tableUrl, rawRead) => {
702
1288
  const { url } = tableUrl;
703
1289
  const [main] = compiledRows[template.rowIndex];
704
- const pairs = rawRead.pairs.filter((pair) => pair.text);
1290
+ const writtenRest = readWrittenRest(tableUrl);
1291
+ const { restName } = template;
1292
+ const hasReserved = restName !== void 0;
1293
+ const reservedRest = hasReserved && template.pipeNames.includes(restName) ? writtenRest.replace(escapedPipeRegex, "|") : writtenRest;
1294
+ const pairs = hasReserved ? [] : rawRead.pairs.filter((pair) => pair.text);
705
1295
  const isKept = (pair) => {
1296
+ if (main.passedName !== void 0) return true;
706
1297
  if (main.optionalNames.length > 0 || options.isQueryKept === false) return isNamed(pair, main.optionalNames);
707
1298
  return true;
708
1299
  };
709
- if (!template.isAlias) {
1300
+ if (!template.isAlias && !rawRead.isRespelled) {
710
1301
  const origin = url.port ? void 0 : main.getHttpsOrigin(rawRead.params);
711
- const stayingPairs = sortPairs(pairs.filter((pair) => isNamed(pair, main.ownNames) || isKept(pair)));
712
- const rest = writeQuery(stayingPairs) === writeQuery(pairs) ? `${writeQuery(rawRead.pairs)}${readQuery(tableUrl).hash}` : `${writeQuery(stayingPairs)}${url.hash}`;
1302
+ if (hasReserved) return `${origin ?? url.origin}${rawRead.pathname}${reservedRest}`;
1303
+ const mainPairs = pairs.filter((pair) => {
1304
+ return isNamed(pair, main.ownNames) || main.isFlagPair(pair, rawRead.values) || isKept(pair);
1305
+ });
1306
+ const stayingPairs = main.orderPairs(mainPairs, rawRead.values);
1307
+ const rest = writeQuery(stayingPairs) === writeQuery(pairs) ? `${writeQuery(rawRead.pairs)}${rawRead.hash ?? readQuery(tableUrl).hash}` : `${writeQuery(stayingPairs)}${rawRead.hash ?? url.hash}`;
713
1308
  return `${origin ?? url.origin}${rawRead.pathname}${rest}`;
714
1309
  }
715
- const ownNames = [...template.ownNames, ...main.ownNames];
716
- const keptPairs = pairs.filter((pair) => !isNamed(pair, ownNames) && isKept(pair));
717
- const rawUrl = main.getRawUrl(rawRead.params, keptPairs);
1310
+ const movedNames = template.optionalNames.filter((name) => main.checkNames.includes(name));
1311
+ const ownNames = [
1312
+ ...template.ownNames,
1313
+ ...main.ownNames,
1314
+ ...movedNames
1315
+ ];
1316
+ const isOwnFlag = (pair) => {
1317
+ return template.isFlagPair(pair, rawRead.values) || main.isFlagPair(pair, rawRead.values);
1318
+ };
1319
+ const keptPairs = pairs.filter((pair) => {
1320
+ return !isNamed(pair, ownNames) && !isOwnFlag(pair) && isKept(pair);
1321
+ });
1322
+ const rawUrl = main.getRawUrl(rawRead, keptPairs);
718
1323
  if (!rawUrl) return;
719
- const mainPairs = sortPairs(rawUrl.pairs);
720
- const mainUrl = `${rawUrl.base}${writeQuery(mainPairs)}`;
1324
+ const mainUrl = `${rawUrl.base}${writeQuery(rawUrl.pairs)}`;
721
1325
  if (url.port && parseUrl(mainUrl)?.port !== url.port) return;
722
1326
  if (url.protocol === "https:" && startsWithAnyOf(mainUrl, "http:")) return;
723
- const mainTexts = /* @__PURE__ */ new Set([...mainPairs.map((pair) => pair.text), ...main.flagTexts]);
724
1327
  if (pairs.some((pair) => {
725
- return isNamed(pair, main.ownNames) && !isNamed(pair, template.ownNames) && !mainTexts.has(main.getWrittenText(pair));
1328
+ const isMainPair = isNamed(pair, main.ownNames) && !isNamed(pair, template.ownNames);
1329
+ const isMainFlag = main.isFlagPair(pair, rawRead.values) && !template.isFlagPair(pair, rawRead.values);
1330
+ if (!isMainPair && !isMainFlag) return false;
1331
+ return !main.readOwnPair(pair, rawRead.values)?.every(([name, value]) => isSameRead(main, name, value, rawRead.values[name]));
1332
+ })) return;
1333
+ if (main.ownNames.some((name) => {
1334
+ return !isAnyOf(name, template.ownNames) && pairs.filter((pair) => isNamed(pair, name)).length > 1;
726
1335
  })) return;
727
- return `${mainUrl}${url.hash}`;
1336
+ if (hasReserved) return main.restName === void 0 ? `${mainUrl}${rawUrl.hash ?? ""}` : `${mainUrl}${reservedRest}`;
1337
+ const givenHash = template.hasFragment ? "" : url.hash;
1338
+ return `${mainUrl}${rawUrl.hash ?? givenHash}`;
728
1339
  };
729
1340
  const writeStrictMainUrl = (readBack, mainUrl) => {
730
1341
  const [main] = compiledRows[readBack.template.rowIndex];
731
- const values = { ...readBack.params };
732
- delete values[openTailName];
733
- const builtUrl = main.getUrl(values, "strict");
1342
+ const values = omit(readBack.params, [openTailName]);
1343
+ const templateUrl = main.getUrl(values, "strict").url;
734
1344
  const parsedMainUrl = parseUrl(mainUrl);
735
- if (!builtUrl || !parsedMainUrl) return;
736
- const queryStart = builtUrl.includes("?") ? builtUrl.indexOf("?") : builtUrl.length;
737
- const keptPairs = parseQuery(parsedMainUrl.search).filter((pair) => pair.text && !isNamed(pair, main.ownNames)).map(toStrictPair);
738
- const pairs = sortPairs([...parseQuery(builtUrl.slice(queryStart)), ...keptPairs]);
739
- return `${writeBase(builtUrl.slice(0, queryStart), pairs)}${writeQuery(pairs)}${parsedMainUrl.hash}`;
1345
+ if (!templateUrl || !parsedMainUrl) return;
1346
+ const builtUrl = templateUrl.replace(originRegex, parsedMainUrl.origin);
1347
+ if (main.restName !== void 0) return builtUrl;
1348
+ const hashStart = main.hasFragment ? builtUrl.indexOf("#") : builtUrl.length;
1349
+ const hash = main.hasFragment ? builtUrl.slice(hashStart) : parsedMainUrl.hash;
1350
+ const builtBody = builtUrl.slice(0, hashStart);
1351
+ const queryStart = builtBody.includes("?") ? builtBody.indexOf("?") : builtBody.length;
1352
+ const keptPairs = parseQuery(parsedMainUrl.search).filter((pair) => {
1353
+ return pair.text && !isNamed(pair, [...main.ownNames, ...main.optionalNames]) && !main.isFlagPair(pair, values) && main.passedName === void 0;
1354
+ }).map(toStrictPair);
1355
+ const pairs = [...parseQuery(builtBody.slice(queryStart)), ...keptPairs];
1356
+ return `${writeBase(builtBody.slice(0, queryStart), pairs)}${writeQuery(pairs)}${hash}`;
1357
+ };
1358
+ const readMainUrl = (mainUrl, source) => {
1359
+ const readBack = readTemplate(mainUrl);
1360
+ if (readBack?.template.rowIndex !== source.template.rowIndex) return;
1361
+ const { optionalNames, passedName } = readBack.template;
1362
+ if (!Object.entries(readBack.params).every(([name, value]) => {
1363
+ const sourceValue = source.params[name];
1364
+ if (sourceValue === void 0 && (optionalNames.includes(name) || name === passedName)) return true;
1365
+ return isSameRead(readBack.template, name, value, sourceValue);
1366
+ })) return;
1367
+ return readBack;
740
1368
  };
741
1369
  const getMainUrl = (url, writeOptions) => {
742
1370
  const found = readTemplate(url);
@@ -749,51 +1377,53 @@ const createTable = (givenRows, options = {}) => {
749
1377
  const mainUrl = writeMainUrl(found.template, found.tableUrl, rawRead);
750
1378
  if (!mainUrl) return;
751
1379
  const isStrict = writeOptions?.encoding === "strict";
752
- if (!isStrict && mainUrl === sourceUrl.href) return;
753
- const readBack = readTemplate(mainUrl);
754
- if (readBack?.template.rowIndex !== found.template.rowIndex) return;
755
- const caseNames = [...lenient.case ?? [], ...readBack.template.hostNames];
756
- if (!Object.entries(readBack.params).every(([name, value]) => {
757
- const sourceValue = found.params[name];
758
- if (caseNames.includes(name)) return isSameValue(value, sourceValue, isSameText);
759
- return isSameValue(value, sourceValue, (left, right) => left === right);
760
- })) return;
1380
+ if (!isStrict && mainUrl === sourceUrl.href) return mainUrl;
1381
+ const readBack = readMainUrl(mainUrl, found);
1382
+ if (!readBack) return;
1383
+ const mainRawRead = isStrict ? readRawParams(readBack) : void 0;
1384
+ if (mainRawRead && readBack.template.hasNonUtf8Value(mainRawRead)) return;
761
1385
  const writtenUrl = isStrict ? writeStrictMainUrl(readBack, mainUrl) : mainUrl;
762
- if (!writtenUrl || writtenUrl === sourceUrl.href) return;
763
- return writtenUrl;
1386
+ if (isStrict && (!writtenUrl || !readMainUrl(writtenUrl, readBack))) return;
1387
+ return parseUrl(writtenUrl)?.href;
764
1388
  };
765
1389
  const forSite = (url) => {
766
1390
  const parsedUrl = parseUrl(url);
767
1391
  if (!parsedUrl || !isHttpUrl(parsedUrl)) return;
768
- const urlParams = {
1392
+ const site = {
769
1393
  scheme: parsedUrl.protocol.slice(0, -1),
770
1394
  host: parsedUrl.host,
771
- domain: getTenantDomain(parsedUrl.hostname, options.hosts?.tenant)
772
- };
773
- const withUrlParams = (params = {}) => {
774
- return {
775
- ...urlParams,
776
- ...trimObject(params)
777
- };
1395
+ parent: getListedDomain(parsedUrl.hostname, options.hosts?.tenant)
778
1396
  };
779
1397
  return {
780
- buildUrl: (key, values, buildOptions) => buildUrl(key, withUrlParams(values), buildOptions),
781
- buildUrls: (key, values, buildOptions) => buildUrls(key, withUrlParams(values), buildOptions)
1398
+ buildUrl: (key, values, buildOptions) => buildUrl(key, values, buildOptions, site),
1399
+ buildUrls: (key, values, buildOptions) => buildUrls(key, values, buildOptions, site)
782
1400
  };
783
1401
  };
784
1402
  return {
785
1403
  table: {
786
1404
  rows: rows.map(copyRow),
787
- buildUrl,
788
- buildUrls,
1405
+ buildUrl: (key, values, buildOptions) => buildUrl(key, values, buildOptions),
1406
+ buildUrls: (key, values, buildOptions) => buildUrls(key, values, buildOptions),
789
1407
  readUrl,
790
1408
  getMainUrl,
791
1409
  forSite
792
1410
  },
793
- readStandIn: readOwn
1411
+ checkNames,
1412
+ readStandIn: readOwn,
1413
+ findHiddenRows
794
1414
  };
795
1415
  };
1416
+ const hiddenRowFinders = /* @__PURE__ */ new WeakMap();
796
1417
  const defineTable = (givenRows, options = {}) => {
797
- return createTable(givenRows, options).table;
1418
+ const parts = createTable({
1419
+ rows: givenRows,
1420
+ options
1421
+ });
1422
+ validateCheckNames(parts.checkNames);
1423
+ hiddenRowFinders.set(parts.table, parts.findHiddenRows);
1424
+ return parts.table;
1425
+ };
1426
+ const findHiddenRows = (table) => {
1427
+ return hiddenRowFinders.get(table)?.() ?? [];
798
1428
  };
799
- export { defineTable };
1429
+ export { defineTable, findHiddenRows };