urlmason 1.0.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/LICENSE +21 -0
- package/README.md +239 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.mjs +1 -0
- package/dist/locales.json.mjs +18 -0
- package/dist/node_modules/trousse/dist/arrays.mjs +9 -0
- package/dist/node_modules/trousse/dist/is.mjs +20 -0
- package/dist/node_modules/trousse/dist/locales.mjs +8 -0
- package/dist/node_modules/trousse/dist/matching.mjs +52 -0
- package/dist/node_modules/trousse/dist/objects.mjs +32 -0
- package/dist/node_modules/trousse/dist/urls.mjs +218 -0
- package/dist/queries.mjs +92 -0
- package/dist/tables.d.mts +2 -0
- package/dist/tables.mjs +799 -0
- package/dist/templates.mjs +407 -0
- package/dist/types.d.mts +77 -0
- package/package.json +50 -0
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
import { decodePercent, encodePathSegment, getQueryParamValues, isHttpUrl, parseUrl } from "./node_modules/trousse/dist/urls.mjs";
|
|
2
|
+
import { escapeRegex } from "./node_modules/trousse/dist/matching.mjs";
|
|
3
|
+
import { isPlainObject, isString } from "./node_modules/trousse/dist/is.mjs";
|
|
4
|
+
import { omitEmpty } from "./node_modules/trousse/dist/arrays.mjs";
|
|
5
|
+
import { t } from "./node_modules/trousse/dist/locales.mjs";
|
|
6
|
+
import { errors } from "./locales.json.mjs";
|
|
7
|
+
import { appendValue, encodeText, nonAsciiRegex, parseQuery, sortPairs, toPair, toSearchParams, writeQuery } from "./queries.mjs";
|
|
8
|
+
// src/templates.ts
|
|
9
|
+
const placeholderRegex = /\{\/?(\w+\*?)\}/g;
|
|
10
|
+
const trailingSlashRegex = /\/$/;
|
|
11
|
+
const templateRegex = /^(https?|\{scheme\}):\/\/((?:[^/?#{]|\{[^/{}]*\})+)((?:\/|\{\/)[^?#]*)?(\?(?!\?)[^#]*)?$/i;
|
|
12
|
+
const expressionRegex = /\{([^{}]*)\}/g;
|
|
13
|
+
const braceRegex = /[{}]/;
|
|
14
|
+
const oldListRegex = /(?<!\/)\/\{(\w*)\*\}/;
|
|
15
|
+
const oldTail = "{*}";
|
|
16
|
+
const oldQuery = "?{query}";
|
|
17
|
+
const plainExpressionRegex = /^(?:\w+|\/\w+\*)$/;
|
|
18
|
+
const queryExpressionRegex = /^\?\w+\*$/;
|
|
19
|
+
const optionalQueryExpressionRegex = /^[?&][\w-]+(?:,[\w-]+)*$/;
|
|
20
|
+
const optionalQueryRegex = /\{([?&])([\w-]+(?:,[\w-]+)*)\}$/;
|
|
21
|
+
const strayPercentRegex = /%(?![0-9a-f]{2})/gi;
|
|
22
|
+
const subDelimiterRegex = /[!'()*]/g;
|
|
23
|
+
const pathlessBaseRegex = /^[^/]+:\/\/[^/]+$/;
|
|
24
|
+
const ownGroupRegex = /^p\d+$/;
|
|
25
|
+
const dotSegmentRegex = /^(?:\.|%2e){1,2}$/i;
|
|
26
|
+
const hostDelimiterRegex = /[/?#@\\]/;
|
|
27
|
+
const schemePlaceholder = "{scheme}";
|
|
28
|
+
const basePlaceholder = "{/base*}";
|
|
29
|
+
const openTailName = "tail";
|
|
30
|
+
const openTailSuffix = "{/tail*}";
|
|
31
|
+
const emptyListNames = ["base*", `${openTailName}*`];
|
|
32
|
+
const captureGroupPrefix = "p";
|
|
33
|
+
const multiSegmentCapture = "[^/]+(?:/[^/]+)*";
|
|
34
|
+
const sharedPartMaxLength = 1e3;
|
|
35
|
+
const writtenPartMaxLength = sharedPartMaxLength * 9;
|
|
36
|
+
const toLengthGuard = (maxLength, stops) => {
|
|
37
|
+
if (!stops) return `(?=[^]{0,${maxLength}}$)`;
|
|
38
|
+
return `(?=[^${stops}]{0,${maxLength}}(?:[${stops}]|$))`;
|
|
39
|
+
};
|
|
40
|
+
const countValues = (pieces) => {
|
|
41
|
+
return Math.floor(pieces.length / 2);
|
|
42
|
+
};
|
|
43
|
+
const pathCapture = {
|
|
44
|
+
source: "[^/]+",
|
|
45
|
+
unit: "[^/]",
|
|
46
|
+
segmentMaxLength: sharedPartMaxLength
|
|
47
|
+
};
|
|
48
|
+
const writtenPathCapture = {
|
|
49
|
+
...pathCapture,
|
|
50
|
+
segmentMaxLength: writtenPartMaxLength
|
|
51
|
+
};
|
|
52
|
+
const queryCapture = {
|
|
53
|
+
source: "[^]+",
|
|
54
|
+
unit: "[^]"
|
|
55
|
+
};
|
|
56
|
+
const isMultiSegment = (placeholder) => {
|
|
57
|
+
return placeholder.endsWith("*");
|
|
58
|
+
};
|
|
59
|
+
const toBareName = (placeholder) => {
|
|
60
|
+
return isMultiSegment(placeholder) ? placeholder.slice(0, -1) : placeholder;
|
|
61
|
+
};
|
|
62
|
+
const isEmptyList = (placeholder) => {
|
|
63
|
+
return emptyListNames.includes(placeholder);
|
|
64
|
+
};
|
|
65
|
+
const toSegments = (value) => {
|
|
66
|
+
if (isPlainObject(value)) return [];
|
|
67
|
+
return (isString(value) ? value.split("/") : value ?? []).filter((segment) => segment);
|
|
68
|
+
};
|
|
69
|
+
const toMapItems = (map) => {
|
|
70
|
+
return Object.entries(map).flat();
|
|
71
|
+
};
|
|
72
|
+
const getPlaceholderValue = (params, placeholder) => {
|
|
73
|
+
const value = params[toBareName(placeholder)];
|
|
74
|
+
if (isPlainObject(value)) {
|
|
75
|
+
if (Object.keys(value).length === 0) return;
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
if (!isMultiSegment(placeholder)) return Array.isArray(value) ? omitEmpty(value) : value;
|
|
79
|
+
const segments = toSegments(value);
|
|
80
|
+
if (segments.length === 0 && !isEmptyList(placeholder)) return;
|
|
81
|
+
return segments;
|
|
82
|
+
};
|
|
83
|
+
const splitPath = (path) => {
|
|
84
|
+
return path.replaceAll("{/", "/{").split("/");
|
|
85
|
+
};
|
|
86
|
+
const toValueText = (value) => {
|
|
87
|
+
if (isPlainObject(value)) return toMapItems(value).join(",");
|
|
88
|
+
return Array.isArray(value) ? value.join("/") : value;
|
|
89
|
+
};
|
|
90
|
+
const decodeEscapes = (value) => {
|
|
91
|
+
return decodePercent(String(value));
|
|
92
|
+
};
|
|
93
|
+
const encodePathValue = (value) => {
|
|
94
|
+
return encodePathSegment(decodeEscapes(value).replaceAll("%", "%25")).replace(strayPercentRegex, "%25").replace(nonAsciiRegex, encodeURIComponent);
|
|
95
|
+
};
|
|
96
|
+
const encodeQueryValue = (value) => {
|
|
97
|
+
return encodeText(decodeEscapes(value));
|
|
98
|
+
};
|
|
99
|
+
const fillQueryValue = (template, values, encodeValue) => {
|
|
100
|
+
const runs = [];
|
|
101
|
+
const push = (text, kind) => {
|
|
102
|
+
const last = runs.at(-1);
|
|
103
|
+
if (last && last.kind === kind && kind !== "separator") {
|
|
104
|
+
last.text += text;
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
runs.push({
|
|
108
|
+
text,
|
|
109
|
+
kind
|
|
110
|
+
});
|
|
111
|
+
};
|
|
112
|
+
for (const [index, piece] of template.split(placeholderRegex).entries()) {
|
|
113
|
+
if (index % 2 === 0) {
|
|
114
|
+
if (piece) push(piece, "literal");
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const value = values[piece];
|
|
118
|
+
const items = isPlainObject(value) ? toMapItems(value) : value;
|
|
119
|
+
if (!Array.isArray(items)) {
|
|
120
|
+
push(String(items), "value");
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
for (const [itemIndex, item] of items.entries()) {
|
|
124
|
+
if (itemIndex > 0) push(",", "separator");
|
|
125
|
+
for (const [partIndex, part] of item.split(",").entries()) {
|
|
126
|
+
if (partIndex > 0) push("%2C", "separator");
|
|
127
|
+
push(part, "value");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return runs.map((run) => {
|
|
132
|
+
if (run.kind === "separator") return run.text;
|
|
133
|
+
return run.kind === "literal" ? encodeText(run.text) : encodeValue(run.text);
|
|
134
|
+
}).join("");
|
|
135
|
+
};
|
|
136
|
+
const encodeSlot = (value, encode) => {
|
|
137
|
+
const items = isPlainObject(value) ? toMapItems(value) : value;
|
|
138
|
+
if (!Array.isArray(items)) return encode(items);
|
|
139
|
+
return items.map((item) => encode(item).replaceAll(",", "%2C")).join(",");
|
|
140
|
+
};
|
|
141
|
+
const encodeMapSegments = (map, encode) => {
|
|
142
|
+
return Object.entries(map).map(([name, value]) => `${encode(name)}=${encode(value)}`).join("/");
|
|
143
|
+
};
|
|
144
|
+
const encodePath = (value) => {
|
|
145
|
+
return Array.isArray(value) ? value.map(encodePathValue).join("/") : encodePathValue(value);
|
|
146
|
+
};
|
|
147
|
+
const encodeLiteral = (text) => {
|
|
148
|
+
return text.replace(nonAsciiRegex, encodeURIComponent);
|
|
149
|
+
};
|
|
150
|
+
const toPercentEscape = (character) => {
|
|
151
|
+
return `%${character.charCodeAt(0).toString(16).toUpperCase()}`;
|
|
152
|
+
};
|
|
153
|
+
const encodeStrictValue = (value) => {
|
|
154
|
+
return encodeURIComponent(value).replace(subDelimiterRegex, toPercentEscape);
|
|
155
|
+
};
|
|
156
|
+
const encodeStrictQueryText = (text) => {
|
|
157
|
+
return text.split("+").map((piece) => encodeStrictValue(decodePercent(piece))).join("+");
|
|
158
|
+
};
|
|
159
|
+
const toStrictPair = (pair) => {
|
|
160
|
+
const separator = pair.text.indexOf("=");
|
|
161
|
+
if (separator === -1) return toPair(encodeStrictQueryText(pair.text));
|
|
162
|
+
const name = encodeStrictQueryText(pair.text.slice(0, separator));
|
|
163
|
+
const value = encodeStrictQueryText(pair.text.slice(separator + 1));
|
|
164
|
+
return toPair(`${name}=${value}`);
|
|
165
|
+
};
|
|
166
|
+
const encodeStrict = (value) => {
|
|
167
|
+
return Array.isArray(value) ? value.map(encodeStrictValue).join("/") : encodeStrictValue(value);
|
|
168
|
+
};
|
|
169
|
+
const decodePath = (path) => {
|
|
170
|
+
if (!path.includes("%")) return path;
|
|
171
|
+
return path.split("/").map((segment) => decodePercent(segment).replaceAll("%", "%25").replaceAll("/", "%2F")).join("/");
|
|
172
|
+
};
|
|
173
|
+
const writeBase = (base, pairs) => {
|
|
174
|
+
return pairs.length > 0 && pathlessBaseRegex.test(base) ? `${base}/` : base;
|
|
175
|
+
};
|
|
176
|
+
const mapTemplate = (text, mapPlaceholder, mapLiteral = (literal) => literal) => {
|
|
177
|
+
return text.split(placeholderRegex).map((piece, index) => {
|
|
178
|
+
if (index % 2 === 0) return mapLiteral(piece);
|
|
179
|
+
const value = mapPlaceholder(piece);
|
|
180
|
+
return isMultiSegment(piece) && value ? `/${value}` : value;
|
|
181
|
+
}).join("");
|
|
182
|
+
};
|
|
183
|
+
const toLaterSource = ({ unit }, separator) => {
|
|
184
|
+
if (!unit || !new RegExp(`^(?:${unit})+$`).test(separator)) return;
|
|
185
|
+
return `(?:(?!${escapeRegex(separator)})${unit})*${unit}{1,${separator.length}}`;
|
|
186
|
+
};
|
|
187
|
+
const toRegexSource = (text, wrapCapture, capture, captures = {}, mapLiteral = (literal) => literal, patterns = {}) => {
|
|
188
|
+
const pieces = text.split(placeholderRegex).map((piece, index) => index % 2 === 1 ? piece : mapLiteral(piece));
|
|
189
|
+
const countSegmentValues = (index) => {
|
|
190
|
+
const end = pieces.findIndex((piece, later) => {
|
|
191
|
+
return later > index && (later % 2 === 0 ? piece.includes("/") : isMultiSegment(piece));
|
|
192
|
+
});
|
|
193
|
+
return countValues(pieces.slice(index, end === -1 ? void 0 : end));
|
|
194
|
+
};
|
|
195
|
+
return pieces.map((piece, index) => {
|
|
196
|
+
if (index % 2 === 0) {
|
|
197
|
+
const slash = piece.lastIndexOf("/");
|
|
198
|
+
if (!capture.segmentMaxLength || slash === -1 || countSegmentValues(index) < 2) return escapeRegex(piece);
|
|
199
|
+
const head = escapeRegex(piece.slice(0, slash + 1));
|
|
200
|
+
const tail = escapeRegex(piece.slice(slash + 1));
|
|
201
|
+
return `${head}${toLengthGuard(capture.segmentMaxLength, "/")}${tail}`;
|
|
202
|
+
}
|
|
203
|
+
const frontPattern = index > 1 ? patterns[pieces[index - 2]] : void 0;
|
|
204
|
+
const isFreed = frontPattern !== void 0 && !new RegExp(`^${frontPattern}$`, "i").test(pieces[index - 1]);
|
|
205
|
+
const laterSource = index > 1 && !isFreed ? toLaterSource(capture, pieces[index - 1]) : void 0;
|
|
206
|
+
const source = wrapCapture(piece, captures[piece] ?? patterns[piece] ?? laterSource ?? capture.source);
|
|
207
|
+
if (!isMultiSegment(piece)) return source;
|
|
208
|
+
return isEmptyList(piece) ? `(?:/${source})?` : `/${source}`;
|
|
209
|
+
}).join("");
|
|
210
|
+
};
|
|
211
|
+
const checkExpressions = (template) => {
|
|
212
|
+
const throwOldSpelling = (expression, spelling) => {
|
|
213
|
+
throw new Error(t(errors.oldTemplateSpelling, {
|
|
214
|
+
template,
|
|
215
|
+
expression,
|
|
216
|
+
spelling
|
|
217
|
+
}));
|
|
218
|
+
};
|
|
219
|
+
const oldList = oldListRegex.exec(template);
|
|
220
|
+
if (oldList) throwOldSpelling(oldList[0], `{/${oldList[1] || "tail"}*}`);
|
|
221
|
+
if (template.includes(oldQuery)) throw new Error(t(errors.unsupportedPassedQuery, {
|
|
222
|
+
template,
|
|
223
|
+
expression: oldQuery
|
|
224
|
+
}));
|
|
225
|
+
if (braceRegex.test(template.replace(expressionRegex, ""))) throw new Error(t(errors.unbalancedBrace, { template }));
|
|
226
|
+
for (const [expression, body] of template.matchAll(expressionRegex)) {
|
|
227
|
+
if (expression === oldTail) throwOldSpelling(oldTail, openTailSuffix);
|
|
228
|
+
if (plainExpressionRegex.test(body) || optionalQueryExpressionRegex.test(body)) continue;
|
|
229
|
+
if (queryExpressionRegex.test(body)) throw new Error(t(errors.invalidTemplate, { template }));
|
|
230
|
+
throw new Error(t(errors.unsupportedTemplateExpression, {
|
|
231
|
+
template,
|
|
232
|
+
expression
|
|
233
|
+
}));
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
const parseTemplate = (template) => {
|
|
237
|
+
checkExpressions(template);
|
|
238
|
+
const optional = optionalQueryRegex.exec(template);
|
|
239
|
+
const base = optional ? template.slice(0, optional.index) : template;
|
|
240
|
+
const match = templateRegex.exec(base);
|
|
241
|
+
if (!match || base.includes("{?") || base.includes("{&")) throw new Error(t(errors.invalidTemplate, { template }));
|
|
242
|
+
const [, scheme, host, givenPath = "", search] = match;
|
|
243
|
+
if (optional && optional[1] === "?" === Boolean(search)) throw new Error(t(errors.invalidTemplate, { template }));
|
|
244
|
+
const optionalNames = optional ? optional[2].split(",") : [];
|
|
245
|
+
const isOpen = givenPath.endsWith(openTailSuffix);
|
|
246
|
+
const entries = search ? [...toSearchParams(parseQuery(search))] : [];
|
|
247
|
+
if (entries.some(([name]) => name.includes("{"))) throw new Error(t(errors.invalidTemplate, { template }));
|
|
248
|
+
const flagNames = entries.filter(([, value]) => !value).map(([name]) => name);
|
|
249
|
+
const params = entries.map(([name, value]) => {
|
|
250
|
+
const isFlag = flagNames.includes(name);
|
|
251
|
+
const isFilled = !isFlag && value.includes("{");
|
|
252
|
+
const writtenName = encodeText(name);
|
|
253
|
+
const writtenValue = isFilled ? "" : encodeText(value);
|
|
254
|
+
return {
|
|
255
|
+
name,
|
|
256
|
+
value,
|
|
257
|
+
isFlag,
|
|
258
|
+
writtenName,
|
|
259
|
+
pair: toPair(isFlag ? writtenName : `${writtenName}=${writtenValue}`),
|
|
260
|
+
isFilled
|
|
261
|
+
};
|
|
262
|
+
});
|
|
263
|
+
const paramNames = [...params.map((param) => param.name), ...optionalNames];
|
|
264
|
+
const placeholderNames = [...base.matchAll(placeholderRegex)].map(([, name]) => toBareName(name));
|
|
265
|
+
if (optionalNames.some((name) => placeholderNames.includes(name))) throw new Error(t(errors.invalidTemplate, { template }));
|
|
266
|
+
if (paramNames.some((name, index) => paramNames.indexOf(name) !== index)) throw new Error(t(errors.invalidTemplate, { template }));
|
|
267
|
+
const path = isOpen ? givenPath.slice(0, -8) : givenPath;
|
|
268
|
+
return {
|
|
269
|
+
text: template,
|
|
270
|
+
scheme,
|
|
271
|
+
host,
|
|
272
|
+
path,
|
|
273
|
+
search,
|
|
274
|
+
isOpen,
|
|
275
|
+
names: [...`${scheme}${host}${path}${search ?? ""}`.matchAll(placeholderRegex)].map(([, name]) => name),
|
|
276
|
+
params,
|
|
277
|
+
optionalNames
|
|
278
|
+
};
|
|
279
|
+
};
|
|
280
|
+
const compileTemplate = (parsed, pathPatterns = {}, writtenPathPatterns = pathPatterns) => {
|
|
281
|
+
const { scheme, host, path, isOpen, names } = parsed;
|
|
282
|
+
const captured = [];
|
|
283
|
+
const captureIn = (part) => {
|
|
284
|
+
return (name, source) => {
|
|
285
|
+
captured.push({
|
|
286
|
+
name: toBareName(name),
|
|
287
|
+
part,
|
|
288
|
+
isList: part === "path" && isMultiSegment(name)
|
|
289
|
+
});
|
|
290
|
+
return `(?<${captureGroupPrefix}${captured.length - 1}>${source})`;
|
|
291
|
+
};
|
|
292
|
+
};
|
|
293
|
+
const getCaptured = (group) => {
|
|
294
|
+
if (!ownGroupRegex.test(group)) return;
|
|
295
|
+
return captured[Number(group.slice(1))];
|
|
296
|
+
};
|
|
297
|
+
const params = parsed.params.map((param) => {
|
|
298
|
+
const source = toRegexSource(param.value, captureIn("query"), queryCapture);
|
|
299
|
+
const rawSource = toRegexSource(param.value, captureIn("query"), queryCapture, {}, encodeText);
|
|
300
|
+
const isShared = countValues(param.value.split(placeholderRegex)) > 1;
|
|
301
|
+
const guard = isShared ? toLengthGuard(sharedPartMaxLength) : "";
|
|
302
|
+
const rawGuard = isShared ? toLengthGuard(writtenPartMaxLength) : "";
|
|
303
|
+
return {
|
|
304
|
+
...param,
|
|
305
|
+
regex: new RegExp(`^${guard}${source}$`, "i"),
|
|
306
|
+
rawRegex: new RegExp(`^${rawGuard}${rawSource}$`, "d")
|
|
307
|
+
};
|
|
308
|
+
});
|
|
309
|
+
const multiSegmentCaptures = Object.fromEntries(names.filter(isMultiSegment).map((name) => [name, multiSegmentCapture]));
|
|
310
|
+
const hasTwoLists = names.filter(isMultiSegment).length > 1;
|
|
311
|
+
const pathGuard = hasTwoLists ? toLengthGuard(sharedPartMaxLength) : "";
|
|
312
|
+
const rawPathGuard = hasTwoLists ? toLengthGuard(writtenPartMaxLength) : "";
|
|
313
|
+
const pathSource = toRegexSource(path.replace(trailingSlashRegex, ""), captureIn("path"), pathCapture, multiSegmentCaptures, decodePath, pathPatterns);
|
|
314
|
+
const rawPathSource = path ? toRegexSource(path, captureIn("path"), writtenPathCapture, multiSegmentCaptures, encodeLiteral, writtenPathPatterns) : "/?";
|
|
315
|
+
const readPathSource = isOpen ? `${pathGuard}${pathSource}(?:/${captureIn("path")(`${openTailName}*`, ".*")})?` : `${pathGuard}${pathSource}`;
|
|
316
|
+
const readGroups = (values, groups = {}) => {
|
|
317
|
+
for (const [group, value] of Object.entries(groups)) {
|
|
318
|
+
const groupCaptured = getCaptured(group);
|
|
319
|
+
if (!groupCaptured || value === void 0 || values[groupCaptured.name] !== void 0) continue;
|
|
320
|
+
if (groupCaptured.part !== "path") {
|
|
321
|
+
values[groupCaptured.name] = value;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
values[groupCaptured.name] = groupCaptured.isList ? value.split("/").filter((segment) => segment).map(decodePercent) : decodePercent(value);
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
const read = (groups, getSearchParams) => {
|
|
328
|
+
const values = {};
|
|
329
|
+
readGroups(values, groups);
|
|
330
|
+
if (isOpen && !values["tail"]?.length) delete values[openTailName];
|
|
331
|
+
for (const { name, isFlag, regex } of params) {
|
|
332
|
+
const [value] = getQueryParamValues(getSearchParams(), name, { preserveEmptyValues: isFlag });
|
|
333
|
+
if (value === void 0) return;
|
|
334
|
+
const queryMatch = regex.exec(value);
|
|
335
|
+
if (!queryMatch) return;
|
|
336
|
+
readGroups(values, queryMatch.groups);
|
|
337
|
+
}
|
|
338
|
+
for (const name of parsed.optionalNames) {
|
|
339
|
+
const [value] = getQueryParamValues(getSearchParams(), name);
|
|
340
|
+
if (value !== void 0) values[name] = value;
|
|
341
|
+
}
|
|
342
|
+
return values;
|
|
343
|
+
};
|
|
344
|
+
const getValues = (givenParams) => {
|
|
345
|
+
const values = {};
|
|
346
|
+
for (const name of names) {
|
|
347
|
+
const value = getPlaceholderValue(givenParams, name);
|
|
348
|
+
if (!value) return;
|
|
349
|
+
values[name] = value;
|
|
350
|
+
}
|
|
351
|
+
for (const name of parsed.optionalNames) {
|
|
352
|
+
const value = getPlaceholderValue(givenParams, name);
|
|
353
|
+
if (value !== void 0) values[name] = value;
|
|
354
|
+
}
|
|
355
|
+
return values;
|
|
356
|
+
};
|
|
357
|
+
const writtenPath = encodeLiteral(path);
|
|
358
|
+
const fill = (values, encoding = "pretty") => {
|
|
359
|
+
const isStrict = encoding === "strict";
|
|
360
|
+
const fillPlaceholders = (text, encode = toValueText) => {
|
|
361
|
+
return text.replace(placeholderRegex, (_placeholder, name) => {
|
|
362
|
+
const value = values[name];
|
|
363
|
+
if (!isMultiSegment(name)) return encodeSlot(value, encode);
|
|
364
|
+
if (isPlainObject(value)) return `/${encodeMapSegments(value, isStrict ? encodeStrictValue : encodePathValue)}`;
|
|
365
|
+
return value.length > 0 ? `/${encode(value)}` : "";
|
|
366
|
+
});
|
|
367
|
+
};
|
|
368
|
+
const pairs = [];
|
|
369
|
+
for (const own of params) {
|
|
370
|
+
if (!own.isFilled) {
|
|
371
|
+
pairs.push(own.pair);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
const text = fillQueryValue(own.value, values, isStrict ? encodeStrictValue : encodeQueryValue);
|
|
375
|
+
pairs.push(appendValue(own.pair, text));
|
|
376
|
+
}
|
|
377
|
+
for (const name of parsed.optionalNames) {
|
|
378
|
+
const value = values[name];
|
|
379
|
+
if (value === void 0) continue;
|
|
380
|
+
const writtenName = isStrict ? encodeStrictValue(name) : encodeText(name);
|
|
381
|
+
const writtenValue = encodeSlot(value, isStrict ? encodeStrictValue : encodeQueryValue);
|
|
382
|
+
pairs.push(toPair(`${writtenName}=${writtenValue}`));
|
|
383
|
+
}
|
|
384
|
+
const filledHost = fillPlaceholders(host).toLowerCase();
|
|
385
|
+
if (hostDelimiterRegex.test(filledHost)) return;
|
|
386
|
+
const filledScheme = fillPlaceholders(scheme);
|
|
387
|
+
const filledPath = fillPlaceholders(writtenPath, isStrict ? encodeStrict : encodePath);
|
|
388
|
+
if (filledPath.split("/").some((segment) => dotSegmentRegex.test(segment))) return;
|
|
389
|
+
const url = `${writeBase(`${filledScheme}://${filledHost}${filledPath}`, pairs)}${writeQuery(sortPairs(pairs))}`;
|
|
390
|
+
const parsedUrl = parseUrl(url);
|
|
391
|
+
if (!parsedUrl || !isHttpUrl(parsedUrl) || parsedUrl.host !== filledHost) return;
|
|
392
|
+
if (parsedUrl.protocol !== `${filledScheme.toLowerCase()}:`) return;
|
|
393
|
+
return url;
|
|
394
|
+
};
|
|
395
|
+
return {
|
|
396
|
+
...parsed,
|
|
397
|
+
params,
|
|
398
|
+
readPathSource,
|
|
399
|
+
rawPathSource: `${rawPathGuard}${rawPathSource}`,
|
|
400
|
+
captureIn,
|
|
401
|
+
getCaptured,
|
|
402
|
+
read,
|
|
403
|
+
getValues,
|
|
404
|
+
fill
|
|
405
|
+
};
|
|
406
|
+
};
|
|
407
|
+
export { basePlaceholder, compileTemplate, decodePath, dotSegmentRegex, encodeLiteral, isMultiSegment, mapTemplate, openTailName, openTailSuffix, parseTemplate, placeholderRegex, schemePlaceholder, sharedPartMaxLength, splitPath, toBareName, toLengthGuard, toRegexSource, toSegments, toStrictPair, toValueText, trailingSlashRegex, writeBase };
|
package/dist/types.d.mts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
export type UrlLenient = {
|
|
2
|
+
case?: Array<string>;
|
|
3
|
+
ampersandEntity?: boolean;
|
|
4
|
+
};
|
|
5
|
+
export type UrlRow<Key extends string = string> = {
|
|
6
|
+
key: Key;
|
|
7
|
+
main: string;
|
|
8
|
+
aliases?: Array<string>;
|
|
9
|
+
isBuildOnly?: boolean;
|
|
10
|
+
variant?: string;
|
|
11
|
+
checks?: Record<string, UrlRowCheck | undefined>;
|
|
12
|
+
};
|
|
13
|
+
export type UrlMap = Record<string, string>;
|
|
14
|
+
export type UrlValue = string | Array<string> | UrlMap;
|
|
15
|
+
export type UrlValues = Record<string, UrlValue | undefined>;
|
|
16
|
+
export type UrlHostCheck = (host: string) => boolean;
|
|
17
|
+
export type UrlHosts = {
|
|
18
|
+
exact?: Array<string | RegExp | UrlHostCheck>;
|
|
19
|
+
tenant?: Array<string | RegExp | UrlHostCheck>;
|
|
20
|
+
};
|
|
21
|
+
export type UrlCheck = ((value: string) => boolean) | RegExp;
|
|
22
|
+
export type UrlRowCheck = ((value: string, values: Record<string, string>) => boolean) | RegExp;
|
|
23
|
+
export type UrlTableOptions = {
|
|
24
|
+
hosts?: UrlHosts;
|
|
25
|
+
isWwwTenant?: boolean;
|
|
26
|
+
isWwwTenantPrefix?: boolean;
|
|
27
|
+
checks?: Record<string, UrlCheck>;
|
|
28
|
+
isQueryKept?: boolean;
|
|
29
|
+
lenient?: UrlLenient;
|
|
30
|
+
isFallThrough?: boolean;
|
|
31
|
+
};
|
|
32
|
+
export type UrlReadOptions = {
|
|
33
|
+
base?: UrlValue;
|
|
34
|
+
isAnyHost?: boolean;
|
|
35
|
+
};
|
|
36
|
+
type TemplateNames<Template extends string> = Template extends `${string}{${infer Name}}${infer Rest}` ? Name | TemplateNames<Rest> : never;
|
|
37
|
+
type RowTemplates<Row> = Row extends {
|
|
38
|
+
main: infer Main extends string;
|
|
39
|
+
} ? Main | (Row extends {
|
|
40
|
+
aliases: ReadonlyArray<infer Alias extends string>;
|
|
41
|
+
} ? Alias : never) : never;
|
|
42
|
+
type CommonNames<Template extends string> = (Template extends string ? (names: TemplateNames<Template>) => void : never) extends ((names: infer Names) => void) ? Names : never;
|
|
43
|
+
type TailName = '/tail*';
|
|
44
|
+
type BaseName = '/base*';
|
|
45
|
+
type ValueName<Name> = Name extends `/${infer Bare extends string}*` ? Bare : Name extends string ? Name : never;
|
|
46
|
+
type NameValue<Name> = Name extends `${string}*` ? Array<string> : string;
|
|
47
|
+
type TemplateValues<Template extends string> = string extends Template ? Record<string, UrlValue | undefined> : { [Name in Exclude<CommonNames<Template>, TailName | BaseName> as ValueName<Name>]: NameValue<Name>; } & { [Name in Exclude<TemplateNames<Template>, TailName | Exclude<CommonNames<Template>, BaseName>> as ValueName<Name>]?: NameValue<Name>; };
|
|
48
|
+
type KeyRows<Key, Row> = [Extract<Row, {
|
|
49
|
+
key: Key;
|
|
50
|
+
}>] extends [never] ? Row : Extract<Row, {
|
|
51
|
+
key: Key;
|
|
52
|
+
}>;
|
|
53
|
+
type KeyValues<Key, Row> = TemplateValues<RowTemplates<KeyRows<Key, Row>>>;
|
|
54
|
+
export type UrlMatch<Key extends string, Row> = Key extends Key ? UrlKeyMatch<Key, Row> : never;
|
|
55
|
+
export type UrlKeyMatch<Key extends string, Row> = {
|
|
56
|
+
key: Key;
|
|
57
|
+
values: KeyValues<Key, Row>;
|
|
58
|
+
row: Row;
|
|
59
|
+
isAlias: boolean;
|
|
60
|
+
isExact: boolean;
|
|
61
|
+
};
|
|
62
|
+
export type UrlEncoding = 'pretty' | 'strict';
|
|
63
|
+
export type UrlWriteOptions = {
|
|
64
|
+
encoding?: UrlEncoding;
|
|
65
|
+
};
|
|
66
|
+
export type UrlBuildOptions<Row> = UrlWriteOptions & {
|
|
67
|
+
select?: (row: Row) => boolean;
|
|
68
|
+
};
|
|
69
|
+
export type UrlTable<Key extends string, Row> = {
|
|
70
|
+
rows: Array<Row>;
|
|
71
|
+
buildUrl: (key: Key, values?: UrlValues, options?: UrlBuildOptions<Row>) => string | undefined;
|
|
72
|
+
buildUrls: (key: Key, values?: UrlValues, options?: UrlBuildOptions<Row>) => Array<string>;
|
|
73
|
+
readUrl: (url: string, options?: UrlReadOptions) => UrlMatch<Key, Row> | undefined;
|
|
74
|
+
getMainUrl: (url: string, options?: UrlWriteOptions) => string | undefined;
|
|
75
|
+
forSite: (url: string) => Pick<UrlTable<Key, Row>, 'buildUrl' | 'buildUrls'> | undefined;
|
|
76
|
+
};
|
|
77
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "urlmason",
|
|
3
|
+
"description": "Turn URLs into values and values back into URLs, from one list of URL patterns. Based on URI Templates.",
|
|
4
|
+
"repository": {
|
|
5
|
+
"type": "git",
|
|
6
|
+
"url": "https://github.com/macieklamberski/urlmason.git"
|
|
7
|
+
},
|
|
8
|
+
"bugs": {
|
|
9
|
+
"url": "https://github.com/macieklamberski/urlmason/issues"
|
|
10
|
+
},
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"author": "Maciej Lamberski",
|
|
13
|
+
"sideEffects": false,
|
|
14
|
+
"keywords": [
|
|
15
|
+
"url",
|
|
16
|
+
"uri-template",
|
|
17
|
+
"rfc6570",
|
|
18
|
+
"parse",
|
|
19
|
+
"build",
|
|
20
|
+
"match",
|
|
21
|
+
"alias"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.mts",
|
|
27
|
+
"default": "./dist/index.mjs"
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist"
|
|
33
|
+
],
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=18"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"prepare": "lefthook install",
|
|
39
|
+
"build": "tsdown src/index.ts --format esm --dts --clean --unbundle"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@types/bun": "^1.4.4",
|
|
43
|
+
"kvalita": "^1.41.0",
|
|
44
|
+
"trousse": "3.17.0",
|
|
45
|
+
"tsdown": "0.23.7",
|
|
46
|
+
"uritemplate-test": "github:uri-templates/uritemplate-test#4171dac22aa6",
|
|
47
|
+
"url-template": "github:bramstein/url-template#e5edf15bfc86"
|
|
48
|
+
},
|
|
49
|
+
"version": "1.0.0"
|
|
50
|
+
}
|