deno.land / x / uriware@v0.1.0 / RegExpUri.ts

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import { escapeStringRegexp } from "https://deno.land/x/escape_string_regexp@v0.0.1/mod.ts"import tlds from "./tlds.ts"
// <https://datatracker.ietf.org/doc/html/rfc3986#appendix-A>
const ALPHA = `a-zA-Z`const DIGIT = `0-9`const HEXDIG = `0-9a-fA-F`
const subDelims = `[!$&'()*+,;=]`// const genDelims = `[:/?#\\[\\]@]`// const reserved = `(?:${genDelims}|${subDelims})`const unreserved = `(?:[${ALPHA}]|[${DIGIT}]|-|\\.|_|~)`const pctEncoded = `%[${HEXDIG}][${HEXDIG}]`const pchar = `(?:${unreserved}|${pctEncoded}|${subDelims}|:|@)`
// const segmentNzNc = `(?:${unreserved}|${pctEncoded}|${subDelims}|@)+`const segmentNz = `(?:${pchar})+`const segment = `(?:${pchar})*`
const pathEmpty = ``const pathRootless = `${segmentNz}(?:/${segment})*`// const pathNoscheme = `${segmentNzNc}(?:/${segment})*`const pathAbsolute = `/(?:${segmentNz}(?:/${segment})*)?`// const pathAbempty = `(?:/${segment})*`// const pathNoauthority = `(?:${pathAbsolute}|${pathRootless}|${pathEmpty})`// const path = `(?:${pathAbempty}|${pathAbsolute}|${pathNoscheme}|${pathRootless}|${pathEmpty})`
const regName = `(?:${unreserved}|${pctEncoded}|${subDelims})*`
const decOctet = `(?:[${DIGIT}]|[1-9][${DIGIT}]|1[${DIGIT}]{2}|2[0-4][${DIGIT}]|25[0-5])`const ipv4Address = `${decOctet}.${decOctet}.${decOctet}.${decOctet}`const h16 = `[${HEXDIG}]{1,4}`const ls32 = `(?:${h16}:${h16}|${ipv4Address})`const ipv6Address = `(?:` + `(?:${h16}:){6}${ls32}|` + `::(?:${h16}:){5}${ls32}|` + `(?:${h16})?::(?:${h16}:){4}${ls32}|` + `(?:(?:${h16}:){,1}${h16})?::(?:${h16}:){3}${ls32}|` + `(?:(?:${h16}:){,2}${h16})?::(?:${h16}:){2}${ls32}|` + `(?:(?:${h16}:){,3}${h16})?::${h16}:${ls32}|` + `(?:(?:${h16}:){,4}${h16})?::${ls32}|` + `(?:(?:${h16}:){,5}${h16})?::${h16}|` + `(?:(?:${h16}:){,6}${h16})?::` + `)`const ipvFuture = `v[${HEXDIG}]+.(?:${unreserved}|${subDelims}|:)+`const ipLiteral = `\\[(?:${ipv6Address}|${ipvFuture})\\]`
// RFC1034 3.5. Preferred name syntaxconst letDig = `[${ALPHA}${DIGIT}]`const letDigHyp = `[${ALPHA}${DIGIT}-]`const ldhStr = `(?:${letDigHyp})+`const label = `[${ALPHA}](?:${ldhStr}(?:${letDig})?)?`const regNamePreferred = `(?:${label}\\.)+${label}`const regNamePreferredWithKnownTlds = `(?:${label}\\.)+(?:${tlds.join("|")})`
const normalizeOptions = ( options?: Partial< { preset: keyof typeof RegExpUri.presets } & RegExpUri.Options >,): RegExpUri.Options => { const preset = options?.preset ?? "canonical" const exact = options?.exact ?? false const groups = options?.groups ?? (exact ? "all" : "outmost") return { ...RegExpUri.presets[preset], ...options, exact, groups }}
const generatePatternScheme = (options: RegExpUri.Options): string => { let pattern = `[${ALPHA}][${ALPHA}${DIGIT}+-.]*` const { allow, disallow } = options.schemes const syntax = new RegExp(`^${pattern}$`) if (allow && !disallow) { const invalid = allow.filter(scheme => !syntax.test(scheme)) if (0 < invalid.length) throw new Error( `Some items in the scheme whitelist are in invalid syntax: ${invalid .map(scheme => `"${scheme}"`) .join(", ")}`, ) pattern = `(?:${allow.map(escapeStringRegexp).join("|")})` } else if (!allow && disallow) { // If zero, it allows everything if (disallow.length !== 0) { const invalid = disallow.filter(scheme => !syntax.test(scheme)) if (0 < invalid.length) throw new Error( `Some items in the scheme blacklist are in invalid syntax: ${invalid .map(scheme => `"${scheme}"`) .join(", ")}`, ) const negation = `(?:${disallow.map(escapeStringRegexp).join("|")})` pattern = `(?:(?!${negation})${pattern}|${pattern}(?<!${negation}))` } } else { throw new Error( "The scheme whitelisting/blacklisting option cannot contain the both `allow` and `disallow` properties at the same time.", ) } if (options.groups === "all") pattern = `(?<scheme>${pattern})` return pattern}
const generateRegName = (options: RegExpUri.Options): string => { let pattern = regName if (options.usePreferredDomainNameSyntax) { pattern = regNamePreferred if (options.allowKnownTldsOnly) { pattern = regNamePreferredWithKnownTlds } } const { allow, disallow } = options.domains const syntax = new RegExp(`^${pattern}$`) if (allow && !disallow) { const invalid = allow.filter(domain => !syntax.test(domain)) if (0 < invalid.length) throw new Error( `Some items in the domain whitelist are in invalid syntax: ${invalid .map(domain => `"${domain}"`) .join(", ")}`, ) pattern = `(?:${allow.map(escapeStringRegexp).join("|")})` } else if (!allow && disallow) { // If zero, it allows everything if (disallow.length !== 0) { const invalid = disallow.filter(domain => !syntax.test(domain)) if (0 < invalid.length) throw new Error( `Some items in the domain blacklist are in invalid syntax: ${invalid .map(domain => `"${domain}"`) .join(", ")}`, ) const negation = `(?:${disallow.map(escapeStringRegexp).join("|")})` pattern = `(?:(?!${negation})${pattern}|${pattern}(?<!${negation}))` } } else { throw new Error( "The domain whitelisting/blacklisting option cannot contain the both `allow` and `disallow` properties at the same time.", ) } return pattern}
const generatePatternHost = (options: RegExpUri.Options): string => { const regName = generateRegName(options) let pattern = `(?:${ipLiteral}|${ipv4Address}|${regName})` if (options.groups === "all") pattern = `(?<host>${pattern})` return pattern}
const generatePatternPort = (options: RegExpUri.Options): string => { let pattern = `[${DIGIT}]*` if (options.groups === "all") pattern = `(?<port>${pattern})` return pattern}
const generatePatternUserinfo = (options: RegExpUri.Options): string => { let pattern = `(?:${unreserved}|${pctEncoded}|${subDelims}|:)*` if (options.groups === "all") pattern = `(?<userinfo>${pattern})` return pattern}
const generatePatternAuthority = (options: RegExpUri.Options): string => { const host = generatePatternHost(options) const port = generatePatternPort(options) const userinfo = generatePatternUserinfo(options) let pattern = `(?:${userinfo}@)?${host}(?::${port})?` if (options.groups === "all") pattern = `(?<authority>${pattern})` return pattern}
const generatePatternPathAbempty = (options: RegExpUri.Options): string => { let pattern = `(?:/${segment})*` if (options.groups === "all") pattern = `(?<pathAbempty>${pattern})` return pattern}
const generatePatternPathNoauthority = (options: RegExpUri.Options): string => { let pattern = `(?:${pathAbsolute}|${pathRootless}|${pathEmpty})` if (options.groups === "all") pattern = `(?<pathNoauthority>${pattern})` return pattern}
const generatePatternSchemeHierPart = (options: RegExpUri.Options): string => { const scheme = generatePatternScheme(options) const authority = generatePatternAuthority(options) const pathAbempty = generatePatternPathAbempty(options) const pathNoauthority = generatePatternPathNoauthority(options) const { requireScheme, requireDoubleSlash, requireAuthority } = options switch (requireAuthority) { case "always": // authority switch (requireScheme) { case "always": // scheme return `${scheme}://${authority}${pathAbempty}` case "never": // scheme switch (requireDoubleSlash) { case "always": // double slash return `//${authority}${pathAbempty}` case "never": // double slash return `${authority}${pathAbempty}` default: // double slash return `(?://)?${authority}${pathAbempty}` } default: // scheme switch (requireDoubleSlash) { case "always": // double slash return `(?:${scheme}:)?//${authority}${pathAbempty}` case "never": // double slash return `(?:${scheme}://)?${authority}${pathAbempty}` default: // double slash return `(?:(?:${scheme}:)?//)?${authority}${pathAbempty}` } } case "never": // authority switch (requireScheme) { case "always": // scheme return `${scheme}:${pathNoauthority}` case "never": // scheme return `${pathNoauthority}` default: // scheme return `(?:${scheme}:)?${pathNoauthority}` } default: // authority switch (requireScheme) { case "always": // scheme return `${scheme}:(?://${authority}${pathAbempty}|${pathNoauthority})` case "never": // scheme switch (requireDoubleSlash) { case "always": // double slash return `(?://${authority}${pathAbempty}|${pathNoauthority})` case "never": // double slash return `(?:${authority}${pathAbempty}|${pathNoauthority})` default: // double slash return `(?:(?://)?${authority}${pathAbempty}|${pathNoauthority})` } default: // scheme switch (requireDoubleSlash) { case "always": // double slash return `(?:${scheme}:)?(?://${authority}${pathAbempty}|${pathNoauthority})` case "never": // double slash return `(?:${scheme}://)?(?:${authority}${pathAbempty}|${pathNoauthority})` default: // double slash return `(?:${scheme}://|//)?(?:${authority}${pathAbempty}|${pathNoauthority})` } } }}
const generatePatternQuery = (options: RegExpUri.Options): string => { let pattern = `(?:${pchar}|/|\\?)+` if (options.allowEmptyQuery) pattern = `(?:${pattern})?` if (options.groups === "all") pattern = `(?<query>${pattern})` return `(?:\\?${pattern})?`}
const generatePatternFragment = (options: RegExpUri.Options): string => { let pattern = `(?:${pchar}|/|\\?)+` if (options.allowEmptyFragment) pattern = `(?:${pattern})?` if (options.groups === "all") pattern = `(?<fragment>${pattern})` return `(?:#${pattern})?`}
const generatePatternUri = (options: RegExpUri.Options): string => { const schemeHierPart = generatePatternSchemeHierPart(options) const query = generatePatternQuery(options) const fragment = generatePatternFragment(options) let pattern = `${schemeHierPart}${query}${fragment}` if (options.groups !== "none") pattern = `(?<uri>${pattern})` return pattern}
const generatePattern = (options: RegExpUri.Options): string => { let pattern = generatePatternUri(options) if (options.exact) pattern = `^${pattern}$` return pattern}
class RegExpUri extends RegExp { options: RegExpUri.Options constructor( options?: | Partial<{ preset: keyof typeof RegExpUri.presets } & RegExpUri.Options> | RegExpUri, flags?: string, ) { const optionsDetailed = options instanceof RegExpUri ? options.options : normalizeOptions(options) super(generatePattern(optionsDetailed), flags) this.options = optionsDetailed } exec(string: string): RegExpExecArray | null { const result = RegExp.prototype.exec.call(this, string) if (result?.groups) { if (!this.options.allowEmpty && result[0] === "") return null if ( "pathAbempty" in result.groups || "pathNoauthority" in result.groups ) { const path = result.groups.pathAbempty ?? result.groups.pathNoauthority const query = result.groups.query const fragment = result.groups.fragment delete result.groups.pathAbempty delete result.groups.pathNoauthority delete result.groups.query delete result.groups.fragment result.groups.path = path result.groups.query = query result.groups.fragment = fragment } } return result }}
namespace RegExpUri { export type Options = { /** * A whitelist or a blacklist of schemes. * * Default: `{ disallow: [] }`. */ schemes: Whitelist<string> | Blacklist<string>
/** * A whitelist or a blacklist of domains. * * Default: `{ disallow: [] }`. */ domains: Whitelist<string> | Blacklist<string>
/** * Whether the scheme part must be present. `undefined` allows both cases. * * [RFC3986 ***does*** require](https://datatracker.ietf.org/doc/html/rfc3986#section-3), so setting this option to `"never"` or `undefined` shall get you out of the legal syntax of URI. * * Default: `"always"`. */ requireScheme: "always" | "never" | undefined
/** * Whether the double slash must be present, when the scheme part is missing but the authority part is present. `undefined` allows both cases. This setting is only meaningful when `requireScheme` is `"never"` or `undefined. * * [RFC3986 ***does*** require it as long as the authority part is present](https://datatracker.ietf.org/doc/html/rfc3986#section-3), so setting this option to `"never"` or `undefined` shall get you out of the legal syntax of URI. * * Default: `"always"`. */ requireDoubleSlash: "always" | "never" | undefined
/** * Whether the authority part must be present. `undefined` allows both cases. * * Default: `undefined`. */ requireAuthority: "always" | "never" | undefined
/** * Whether to use [RFC1034 3.5. Preferred name syntax](https://datatracker.ietf.org/doc/html/rfc1034#section-3.5). * * Default: `false`. */ usePreferredDomainNameSyntax: boolean
/** * Whether to verify given domain name has a well-known TLD in the IANA's list. Only meaningful when `usePreferredDomainNameSyntax` is `true`. * * Default: `false`. */ allowKnownTldsOnly: boolean
/** * Whether URIs can be relative reference. * * Default: `true`. */ allowRelative: boolean
/** * Whether to allow the query part to be without its content. * * Default: `true`. */ allowEmptyQuery: boolean
/** * Whether to allow the fragment part to be without its content. * * Default: `true`. */ allowEmptyFragment: boolean
/** * Allows matching to empty string. * * Default: `false`. */ allowEmpty: boolean
/** * Enables exact match pattern. It wraps the `RegExp` pattern with `^` and `$`. * * Default: `false`. */ exact: boolean
/** * Enables named capture groups. See {@link NamedCaptureGroups `RegExpUri.NamedCaptureGroups`} to know what's in the box. * * `"outmost"` should fit for some usage e.g. splitting a plaintext by URIs using [`String.prototype.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split). * * Default: `"all"` if `exact` is `true`, `"outmost"` otherwise. */ groups: "all" | "outmost" | "none" }
export type NamedCaptureGroups = { uri: string scheme: string | undefined authority: string | undefined userinfo: string | undefined host: string | undefined port: string | undefined path: string | undefined query: string | undefined fragment: string | undefined }
export type Whitelist<T> = { allow: T[]; disallow?: never } export type Blacklist<T> = { allow?: never; disallow: T[] }
export const presets = { canonical: { schemes: { disallow: [] }, domains: { disallow: [] }, requireScheme: "always", requireDoubleSlash: "always", requireAuthority: undefined, usePreferredDomainNameSyntax: false, allowKnownTldsOnly: false, allowRelative: true, allowEmptyQuery: true, allowEmptyFragment: true, allowEmpty: false, } as Omit<Options, "exact" | "groups">, convenient: { schemes: { allow: ["https", "http"] }, domains: { disallow: [] }, requireScheme: undefined, requireDoubleSlash: "never", requireAuthority: "always", usePreferredDomainNameSyntax: true, allowKnownTldsOnly: true, allowRelative: false, allowEmptyQuery: false, allowEmptyFragment: false, allowEmpty: false, } as Omit<Options, "exact" | "groups">, } as const}
export default RegExpUri
uriware

Version Info

Tagged at
a year ago