-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
uri.dart
5065 lines (4725 loc) · 181 KB
/
uri.dart
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
part of dart.core;
// Frequently used character codes.
const int _SPACE = 0x20;
const int _PERCENT = 0x25;
const int _AMPERSAND = 0x26;
const int _PLUS = 0x2B;
const int _DOT = 0x2E;
const int _SLASH = 0x2F;
const int _COLON = 0x3A;
const int _EQUALS = 0x3d;
const int _UPPER_CASE_A = 0x41;
const int _UPPER_CASE_Z = 0x5A;
const int _LEFT_BRACKET = 0x5B;
const int _BACKSLASH = 0x5C;
const int _RIGHT_BRACKET = 0x5D;
const int _LOWER_CASE_A = 0x61;
const int _LOWER_CASE_F = 0x66;
const int _LOWER_CASE_Z = 0x7A;
const String _hexDigits = "0123456789ABCDEF";
/// A parsed URI, such as a URL.
///
/// To create a URI with specific components, use [Uri.new]:
/// ```dart
/// var httpsUri = Uri(
/// scheme: 'https',
/// host: 'dart.dev',
/// path: '/guides/libraries/library-tour',
/// fragment: 'numbers');
/// print(httpsUri); // https://dart.dev/guides/libraries/library-tour#numbers
///
/// httpsUri = Uri(
/// scheme: 'https',
/// host: 'example.com',
/// path: '/page/',
/// queryParameters: {'search': 'blue', 'limit': '10'});
/// print(httpsUri); // https://example.com/page/?search=blue&limit=10
///
/// final mailtoUri = Uri(
/// scheme: 'mailto',
/// path: 'John.Doe@example.com',
/// queryParameters: {'subject': 'Example'});
/// print(mailtoUri); // mailto:John.Doe@example.com?subject=Example
/// ```
///
/// ## HTTP and HTTPS URI
/// To create a URI with https scheme, use [Uri.https] or [Uri.http]:
/// ```dart
/// final httpsUri = Uri.https('example.com', 'api/fetch', {'limit': '10'});
/// print(httpsUri); // https://example.com/api/fetch?limit=10
/// ```
/// ## File URI
/// To create a URI from file path, use [Uri.file]:
/// ```dart
/// final fileUriUnix =
/// Uri.file(r'/home/myself/images/image.png', windows: false);
/// print(fileUriUnix); // file:///home/myself/images/image.png
///
/// final fileUriWindows =
/// Uri.file(r'C:\Users\myself\Documents\image.png', windows: true);
/// print(fileUriWindows); // file:///C:/Users/myself/Documents/image.png
/// ```
/// If the URI is not a file URI, calling this throws [UnsupportedError].
///
/// ## Directory URI
/// Like [Uri.file] except that a non-empty URI path ends in a slash.
/// ```dart
/// final fileDirectory =
/// Uri.directory('/home/myself/data/image', windows: false);
/// print(fileDirectory); // file:///home/myself/data/image/
///
/// final fileDirectoryWindows = Uri.directory('/data/images', windows: true);
/// print(fileDirectoryWindows); // file:///data/images/
/// ```
///
/// ## URI from string
/// To create a URI from string, use [Uri.parse] or [Uri.tryParse]:
/// ```dart
/// final uri = Uri.parse(
/// 'https://dart.dev/guides/libraries/library-tour#utility-classes');
/// print(uri); // https://dart.dev
/// print(uri.isScheme('https')); // true
/// print(uri.origin); // https://dart.dev
/// print(uri.host); // dart.dev
/// print(uri.authority); // dart.dev
/// print(uri.port); // 443
/// print(uri.path); // guides/libraries/library-tour
/// print(uri.pathSegments); // [guides, libraries, library-tour]
/// print(uri.fragment); // utility-classes
/// print(uri.hasQuery); // false
/// print(uri.data); // null
/// ```
///
/// **See also:**
/// * [URIs][uris] in the [library tour][libtour]
/// * [RFC-3986](https://tools.ietf.org/html/rfc3986)
/// * [RFC-2396](https://tools.ietf.org/html/rfc2396)
/// * [RFC-2045](https://tools.ietf.org/html/rfc2045)
///
/// [uris]: https://dart.dev/guides/libraries/library-tour#uris
/// [libtour]: https://dart.dev/guides/libraries/library-tour
abstract interface class Uri {
/// The natural base URI for the current platform.
///
/// When running in a browser, this is the current URL of the current page
/// (from `window.location.href`).
///
/// When not running in a browser, this is the file URI referencing
/// the current working directory.
external static Uri get base;
/// Creates a new URI from its components.
///
/// Each component is set through a named argument. Any number of
/// components can be provided. The [path] and [query] components can be set
/// using either of two different named arguments.
///
/// The scheme component is set through [scheme]. The scheme is
/// normalized to all lowercase letters. If the scheme is omitted or empty,
/// the URI will not have a scheme part.
///
/// The user info part of the authority component is set through
/// [userInfo]. It defaults to the empty string, which will be omitted
/// from the string representation of the URI.
///
/// The host part of the authority component is set through
/// [host]. The host can either be a hostname, an IPv4 address or an
/// IPv6 address, contained in `'['` and `']'`. If the host contains a
/// ':' character, the `'['` and `']'` are added if not already provided.
/// The host is normalized to all lowercase letters.
///
/// The port part of the authority component is set through
/// [port].
/// If [port] is omitted or `null`, it implies the default port for
/// the URI's scheme, and is equivalent to passing that port explicitly.
/// The recognized schemes, and their default ports, are "http" (80) and
/// "https" (443). All other schemes are considered as having zero as the
/// default port.
///
/// If any of `userInfo`, `host` or `port` are provided,
/// the URI has an authority according to [hasAuthority].
///
/// The path component is set through either [path] or
/// [pathSegments].
/// When [path] is used, it should be a valid URI path,
/// but invalid characters, except the general delimiters ':/@[]?#',
/// will be escaped if necessary. A backslash, `\`, will be converted
/// to a slash `/`.
/// When [pathSegments] is used, each of the provided segments
/// is first percent-encoded and then joined using the forward slash
/// separator.
///
/// The percent-encoding of the path segments encodes all
/// characters except for the unreserved characters and the following
/// list of characters: `!$&'()*+,;=:@`. If the other components
/// necessitate an absolute path, a leading slash `/` is prepended if
/// not already there.
///
/// The query component is set through either [query] or [queryParameters].
/// When [query] is used, the provided string should be a valid URI query,
/// but invalid characters, other than general delimiters,
/// will be escaped if necessary.
/// When [queryParameters] is used, the query is built from the
/// provided map. Each key and value in the map is percent-encoded
/// and joined using equal and ampersand characters.
/// A value in the map must be either `null`, a string, or an [Iterable] of
/// strings. An iterable corresponds to multiple values for the same key,
/// and an empty iterable or `null` corresponds to no value for the key.
///
/// The percent-encoding of the keys and values encodes all characters
/// except for the unreserved characters, and replaces spaces with `+`.
/// If [query] is the empty string, it is equivalent to omitting it.
/// To have an actual empty query part,
/// use an empty map for [queryParameters].
///
/// If both [query] and [queryParameters] are omitted or `null`,
/// the URI has no query part.
///
/// The fragment component is set through [fragment].
/// It should be a valid URI fragment, but invalid characters other than
/// general delimiters are escaped if necessary.
/// If [fragment] is omitted or `null`, the URI has no fragment part.
///
/// Example:
/// ```dart
/// final httpsUri = Uri(
/// scheme: 'https',
/// host: 'dart.dev',
/// path: 'guides/libraries/library-tour',
/// fragment: 'numbers');
/// print(httpsUri); // https://dart.dev/guides/libraries/library-tour#numbers
///
/// final mailtoUri = Uri(
/// scheme: 'mailto',
/// path: 'John.Doe@example.com',
/// queryParameters: {'subject': 'Example'});
/// print(mailtoUri); // mailto:John.Doe@example.com?subject=Example
/// ```
factory Uri(
{String? scheme,
String? userInfo,
String? host,
int? port,
String? path,
Iterable<String>? pathSegments,
String? query,
Map<String, dynamic /*String?|Iterable<String>*/ >? queryParameters,
String? fragment}) = _Uri;
/// Creates a new `http` URI from authority, path and query.
///
/// Example:
/// ```dart
/// var uri = Uri.http('example.org', '/path', { 'q' : 'dart' });
/// print(uri); // http://example.org/path?q=dart
///
/// uri = Uri.http('user:password@localhost:8080', '');
/// print(uri); // http://user:password@localhost:8080
///
/// uri = Uri.http('example.org', 'a b');
/// print(uri); // http://example.org/a%20b
///
/// uri = Uri.http('example.org', '/a%2F');
/// print(uri); // http://example.org/a%252F
/// ```
///
/// The `scheme` is always set to `http`.
///
/// The `userInfo`, `host` and `port` components are set from the
/// [authority] argument. If `authority` is `null` or empty,
/// the created `Uri` has no authority, and isn't directly usable
/// as an HTTP URL, which must have a non-empty host.
///
/// The `path` component is set from the [unencodedPath]
/// argument. The path passed must not be encoded as this constructor
/// encodes the path. Only `/` is recognized as path separator.
/// If omitted, the path defaults to being empty.
///
/// The `query` component is set from the optional [queryParameters]
/// argument.
factory Uri.http(
String authority, [
String unencodedPath,
Map<String, dynamic /*String?|Iterable<String>*/ >? queryParameters,
]) = _Uri.http;
/// Creates a new `https` URI from authority, path and query.
///
/// This constructor is the same as [Uri.http] except for the scheme
/// which is set to `https`.
///
/// Example:
/// ```dart
/// var uri = Uri.https('example.org', '/path', {'q': 'dart'});
/// print(uri); // https://example.org/path?q=dart
///
/// uri = Uri.https('user:password@localhost:8080', '');
/// print(uri); // https://user:password@localhost:8080
///
/// uri = Uri.https('example.org', 'a b');
/// print(uri); // https://example.org/a%20b
///
/// uri = Uri.https('example.org', '/a%2F');
/// print(uri); // https://example.org/a%252F
/// ```
factory Uri.https(String authority,
[String unencodedPath,
Map<String, dynamic>? queryParameters]) = _Uri.https;
/// Creates a new file URI from an absolute or relative file path.
///
/// The file path is passed in [path].
///
/// This path is interpreted using either Windows or non-Windows
/// semantics.
///
/// With non-Windows semantics, the slash (`/`) is used to separate
/// path segments in the input [path].
///
/// With Windows semantics, backslash (`\`) and forward-slash (`/`)
/// are used to separate path segments in the input [path],
/// except if the path starts with `\\?\` in which case
/// only backslash (`\`) separates path segments in [path].
///
/// If the path starts with a path separator, an absolute URI (with the
/// `file` scheme and an empty authority) is created.
/// Otherwise a relative URI reference with no scheme or authority is created.
/// One exception to this rule is that when Windows semantics is used
/// and the path starts with a drive letter followed by a colon (":") and a
/// path separator, then an absolute URI is created.
///
/// The default for whether to use Windows or non-Windows semantics
/// is determined from the platform Dart is running on. When running in
/// the standalone VM, this is detected by the VM based on the
/// operating system. When running in a browser, non-Windows semantics
/// is always used.
///
/// To override the automatic detection of which semantics to use pass
/// a value for [windows]. Passing `true` will use Windows
/// semantics and passing `false` will use non-Windows semantics.
///
/// Examples using non-Windows semantics:
/// ```dart
/// // xxx/yyy
/// Uri.file('xxx/yyy', windows: false);
///
/// // xxx/yyy/
/// Uri.file('xxx/yyy/', windows: false);
///
/// // file:///xxx/yyy
/// Uri.file('/xxx/yyy', windows: false);
///
/// // file:///xxx/yyy/
/// Uri.file('/xxx/yyy/', windows: false);
///
/// // C%3A
/// Uri.file('C:', windows: false);
/// ```
///
/// Examples using Windows semantics:
/// ```dart
/// // xxx/yyy
/// Uri.file(r'xxx\yyy', windows: true);
///
/// // xxx/yyy/
/// Uri.file(r'xxx\yyy\', windows: true);
///
/// file:///xxx/yyy
/// Uri.file(r'\xxx\yyy', windows: true);
///
/// file:///xxx/yyy/
/// Uri.file(r'\xxx\yyy/', windows: true);
///
/// // file:///C:/xxx/yyy
/// Uri.file(r'C:\xxx\yyy', windows: true);
///
/// // This throws an error. A path with a drive letter, but no following
/// // path, is not allowed.
/// Uri.file(r'C:', windows: true);
///
/// // This throws an error. A path with a drive letter is not absolute.
/// Uri.file(r'C:xxx\yyy', windows: true);
///
/// // file://server/share/file
/// Uri.file(r'\\server\share\file', windows: true);
/// ```
///
/// If the path passed is not a valid file path, an error is thrown.
factory Uri.file(String path, {bool? windows}) = _Uri.file;
/// Like [Uri.file] except that a non-empty URI path ends in a slash.
///
/// If [path] is not empty, and it doesn't end in a directory separator,
/// then a slash is added to the returned URI's path.
/// In all other cases, the result is the same as returned by `Uri.file`.
///
/// Example:
/// ```dart
/// final fileDirectory = Uri.directory('data/images', windows: false);
/// print(fileDirectory); // data/images/
///
/// final fileDirectoryWindows =
/// Uri.directory(r'C:\data\images', windows: true);
/// print(fileDirectoryWindows); // file:///C:/data/images/
/// ```
factory Uri.directory(String path, {bool? windows}) = _Uri.directory;
/// Creates a `data:` URI containing the [content] string.
///
/// Converts the content to bytes using [encoding] or the charset specified
/// in [parameters] (defaulting to US-ASCII if not specified or unrecognized),
/// then encodes the bytes into the resulting data URI.
///
/// Defaults to encoding using percent-encoding (any non-ASCII or
/// non-URI-valid bytes is replaced by a percent encoding). If [base64] is
/// true, the bytes are instead encoded using [base64].
///
/// If [encoding] is not provided and [parameters] has a `charset` entry,
/// that name is looked up using [Encoding.getByName],
/// and if the lookup returns an encoding, that encoding is used to convert
/// [content] to bytes.
/// If providing both an [encoding] and a charset in [parameters], they should
/// agree, otherwise decoding won't be able to use the charset parameter
/// to determine the encoding.
///
/// If [mimeType] and/or [parameters] are supplied, they are added to the
/// created URI. If any of these contain characters that are not allowed
/// in the data URI, the character is percent-escaped. If the character is
/// non-ASCII, it is first UTF-8 encoded and then the bytes are percent
/// encoded. An omitted [mimeType] in a data URI means `text/plain`, just
/// as an omitted `charset` parameter defaults to meaning `US-ASCII`.
///
/// To read the content back, use [UriData.contentAsString].
///
/// Example:
/// ```dart
/// final uri = Uri.dataFromString(
/// 'example content',
/// mimeType: 'text/plain',
/// parameters: <String, String>{'search': 'file', 'max': '10'},
/// );
/// print(uri); // data:;search=name;max=10,example%20content
/// ```
factory Uri.dataFromString(String content,
{String? mimeType,
Encoding? encoding,
Map<String, String>? parameters,
bool base64 = false}) {
UriData data = UriData.fromString(content,
mimeType: mimeType,
encoding: encoding,
parameters: parameters,
base64: base64);
return data.uri;
}
/// Creates a `data:` URI containing an encoding of [bytes].
///
/// Defaults to Base64 encoding the bytes, but if [percentEncoded]
/// is `true`, the bytes will instead be percent encoded (any non-ASCII
/// or non-valid-ASCII-character byte is replaced by a percent encoding).
///
/// To read the bytes back, use [UriData.contentAsBytes].
///
/// It defaults to having the mime-type `application/octet-stream`.
/// The [mimeType] and [parameters] are added to the created URI.
/// If any of these contain characters that are not allowed
/// in the data URI, the character is percent-escaped. If the character is
/// non-ASCII, it is first UTF-8 encoded and then the bytes are percent
/// encoded.
///
/// Example:
/// ```dart
/// final uri = Uri.dataFromBytes([68, 97, 114, 116]);
/// print(uri); // data:application/octet-stream;base64,RGFydA==
/// ```
factory Uri.dataFromBytes(List<int> bytes,
{String mimeType = "application/octet-stream",
Map<String, String>? parameters,
bool percentEncoded = false}) {
UriData data = UriData.fromBytes(bytes,
mimeType: mimeType,
parameters: parameters,
percentEncoded: percentEncoded);
return data.uri;
}
/// The scheme component of the URI.
///
/// The value is the empty string if there is no scheme component.
///
/// A URI scheme is case insensitive.
/// The returned scheme is canonicalized to lowercase letters.
String get scheme;
/// The authority component.
///
/// The authority is formatted from the [userInfo], [host] and [port]
/// parts.
///
/// The value is the empty string if there is no authority component.
String get authority;
/// The user info part of the authority component.
///
/// The value is the empty string if there is no user info in the
/// authority component.
String get userInfo;
/// The host part of the authority component.
///
/// The value is the empty string if there is no authority component and
/// hence no host.
///
/// If the host is an IP version 6 address, the surrounding `[` and `]` is
/// removed.
///
/// The host string is case-insensitive.
/// The returned host name is canonicalized to lower-case
/// with upper-case percent-escapes.
String get host;
/// The port part of the authority component.
///
/// The value is the default port if there is no port number in the authority
/// component. That's 80 for http, 443 for https, and 0 for everything else.
int get port;
/// The path component.
///
/// The path is the actual substring of the URI representing the path,
/// and it is encoded where necessary. To get direct access to the decoded
/// path, use [pathSegments].
///
/// The path value is the empty string if there is no path component.
String get path;
/// The query component.
///
/// The value is the actual substring of the URI representing the query part,
/// and it is encoded where necessary.
/// To get direct access to the decoded query, use [queryParameters].
///
/// The value is the empty string if there is no query component.
String get query;
/// The fragment identifier component.
///
/// The value is the empty string if there is no fragment identifier
/// component.
String get fragment;
/// The URI path split into its segments.
///
/// Each of the segments in the list has been decoded.
/// If the path is empty, the empty list will
/// be returned. A leading slash `/` does not affect the segments returned.
///
/// The list is unmodifiable and will throw [UnsupportedError] on any
/// calls that would mutate it.
List<String> get pathSegments;
/// The URI query split into a map according to the rules
/// specified for FORM post in the [HTML 4.01 specification section
/// 17.13.4](https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4
/// "HTML 4.01 section 17.13.4").
///
/// Each key and value in the resulting map has been decoded.
/// If there is no query, the empty map is returned.
///
/// Keys in the query string that have no value are mapped to the
/// empty string.
/// If a key occurs more than once in the query string, it is mapped to
/// an arbitrary choice of possible value.
/// The [queryParametersAll] getter can provide a map
/// that maps keys to all of their values.
///
/// Example:
/// ```dart import:convert
/// final uri =
/// Uri.parse('https://example.com/api/fetch?limit=10,20,30&max=100');
/// print(jsonEncode(uri.queryParameters));
/// // {"limit":"10,20,30","max":"100"}
/// ```
///
/// The map is unmodifiable.
Map<String, String> get queryParameters;
/// Returns the URI query split into a map according to the rules
/// specified for FORM post in the [HTML 4.01 specification section
/// 17.13.4](https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4
/// "HTML 4.01 section 17.13.4").
///
/// Each key and value in the resulting map has been decoded. If there is no
/// query, the map is empty.
///
/// Keys are mapped to lists of their values. If a key occurs only once,
/// its value is a singleton list. If a key occurs with no value, the
/// empty string is used as the value for that occurrence.
///
/// Example:
/// ```dart import:convert
/// final uri =
/// Uri.parse('https://example.com/api/fetch?limit=10&limit=20&limit=30&max=100');
/// print(jsonEncode(uri.queryParametersAll)); // {"limit":["10","20","30"],"max":["100"]}
/// ```
///
/// The map and the lists it contains are unmodifiable.
Map<String, List<String>> get queryParametersAll;
/// Whether the URI is absolute.
///
/// A URI is an absolute URI in the sense of RFC 3986 if it has a scheme
/// and no fragment.
bool get isAbsolute;
/// Whether the URI has a [scheme] component.
bool get hasScheme => scheme.isNotEmpty;
/// Whether the URI has an [authority] component.
bool get hasAuthority;
/// Whether the URI has an explicit port.
///
/// If the port number is the default port number
/// (zero for unrecognized schemes, with http (80) and https (443) being
/// recognized),
/// then the port is made implicit and omitted from the URI.
bool get hasPort;
/// Whether the URI has a query part.
bool get hasQuery;
/// Whether the URI has a fragment part.
bool get hasFragment;
/// Whether the URI has an empty path.
bool get hasEmptyPath;
/// Whether the URI has an absolute path (starting with '/').
bool get hasAbsolutePath;
/// Returns the origin of the URI in the form scheme://host:port for the
/// schemes http and https.
///
/// It is an error if the scheme is not "http" or "https", or if the host name
/// is missing or empty.
///
/// See: https://www.w3.org/TR/2011/WD-html5-20110405/origin-0.html#origin
String get origin;
/// Whether the scheme of this [Uri] is [scheme].
///
/// The [scheme] should be the same as the one returned by [Uri.scheme],
/// but doesn't have to be case-normalized to lower-case characters.
///
/// Example:
/// ```dart
/// var uri = Uri.parse('http://example.com');
/// print(uri.isScheme('HTTP')); // true
///
/// final uriNoScheme = Uri(host: 'example.com');
/// print(uriNoScheme.isScheme('HTTP')); // false
/// ```
///
/// An empty [scheme] string matches a URI with no scheme
/// (one where [hasScheme] returns false).
bool isScheme(String scheme);
/// Creates a file path from a file URI.
///
/// The returned path has either Windows or non-Windows
/// semantics.
///
/// For non-Windows semantics, the slash ("/") is used to separate
/// path segments.
///
/// For Windows semantics, the backslash ("\\") separator is used to
/// separate path segments.
///
/// If the URI is absolute, the path starts with a path separator
/// unless Windows semantics is used and the first path segment is a
/// drive letter. When Windows semantics is used, a host component in
/// the uri in interpreted as a file server and a UNC path is
/// returned.
///
/// The default for whether to use Windows or non-Windows semantics
/// is determined from the platform Dart is running on. When running in
/// the standalone VM, this is detected by the VM based on the
/// operating system. When running in a browser, non-Windows semantics
/// is always used.
///
/// To override the automatic detection of which semantics to use pass
/// a value for [windows]. Passing `true` will use Windows
/// semantics and passing `false` will use non-Windows semantics.
///
/// If the URI ends with a slash (i.e. the last path component is
/// empty), the returned file path will also end with a slash.
///
/// With Windows semantics, URIs starting with a drive letter cannot
/// be relative to the current drive on the designated drive. That is,
/// for the URI `file:///c:abc` calling `toFilePath` will throw as a
/// path segment cannot contain colon on Windows.
///
/// Examples using non-Windows semantics (resulting of calling
/// toFilePath in comment):
/// ```dart
/// Uri.parse("xxx/yyy"); // xxx/yyy
/// Uri.parse("xxx/yyy/"); // xxx/yyy/
/// Uri.parse("file:///xxx/yyy"); // /xxx/yyy
/// Uri.parse("file:///xxx/yyy/"); // /xxx/yyy/
/// Uri.parse("file:///C:"); // /C:
/// Uri.parse("file:///C:a"); // /C:a
/// ```
/// Examples using Windows semantics (resulting URI in comment):
/// ```dart
/// Uri.parse("xxx/yyy"); // xxx\yyy
/// Uri.parse("xxx/yyy/"); // xxx\yyy\
/// Uri.parse("file:///xxx/yyy"); // \xxx\yyy
/// Uri.parse("file:///xxx/yyy/"); // \xxx\yyy\
/// Uri.parse("file:///C:/xxx/yyy"); // C:\xxx\yyy
/// Uri.parse("file:C:xxx/yyy"); // Throws as a path segment
/// // cannot contain colon on Windows.
/// Uri.parse("file://server/share/file"); // \\server\share\file
/// ```
/// If the URI is not a file URI, calling this throws
/// [UnsupportedError].
///
/// If the URI cannot be converted to a file path, calling this throws
/// [UnsupportedError].
// TODO(lrn): Deprecate and move functionality to File class or similar.
// The core libraries should not worry about the platform.
String toFilePath({bool? windows});
/// Access the structure of a `data:` URI.
///
/// Returns a [UriData] object for `data:` URIs and `null` for all other
/// URIs.
/// The [UriData] object can be used to access the media type and data
/// of a `data:` URI.
UriData? get data;
/// Returns a hash code computed as `toString().hashCode`.
///
/// This guarantees that URIs with the same normalized string representation
/// have the same hash code.
int get hashCode;
/// A URI is equal to another URI with the same normalized representation.
bool operator ==(Object other);
/// The normalized string representation of the URI.
String toString();
/// Creates a new `Uri` based on this one, but with some parts replaced.
///
/// This method takes the same parameters as the [Uri] constructor,
/// and they have the same meaning.
///
/// At most one of [path] and [pathSegments] must be provided.
/// Likewise, at most one of [query] and [queryParameters] must be provided.
///
/// Each part that is not provided will default to the corresponding
/// value from this `Uri` instead.
///
/// This method is different from [Uri.resolve], which overrides in a
/// hierarchical manner,
/// and can instead replace each part of a `Uri` individually.
///
/// Example:
/// ```dart
/// final uri1 = Uri.parse(
/// 'http://dart.dev/guides/libraries/library-tour#utility-classes');
///
/// final uri2 = uri1.replace(
/// scheme: 'https',
/// path: 'guides/libraries/library-tour',
/// fragment: 'uris');
/// print(uri2); // https://dart.dev/guides/libraries/library-tour#uris
/// ```
/// This method acts similarly to using the `Uri` constructor with
/// some of the arguments taken from this `Uri`. Example:
/// ``` dart continued
/// final Uri uri3 = Uri(
/// scheme: 'https',
/// userInfo: uri1.userInfo,
/// host: uri1.host,
/// port: uri2.port,
/// path: '/guides/language/language-tour',
/// query: uri1.query,
/// fragment: null);
/// print(uri3); // https://dart.dev/guides/language/language-tour
/// ```
/// Using this method can be seen as shorthand for the `Uri` constructor
/// call above, but may also be slightly faster because the parts taken
/// from this `Uri` need not be checked for validity again.
Uri replace(
{String? scheme,
String? userInfo,
String? host,
int? port,
String? path,
Iterable<String>? pathSegments,
String? query,
Map<String, dynamic /*String?|Iterable<String>*/ >? queryParameters,
String? fragment});
/// Creates a `Uri` that differs from this only in not having a fragment.
///
/// If this `Uri` does not have a fragment, it is itself returned.
///
/// Example:
/// ```dart
/// final uri =
/// Uri.parse('https://example.org:8080/foo/bar#frag').removeFragment();
/// print(uri); // https://example.org:8080/foo/bar
/// ```
Uri removeFragment();
/// Resolve [reference] as an URI relative to `this`.
///
/// First turn [reference] into a URI using [Uri.parse]. Then resolve the
/// resulting URI relative to `this`.
///
/// Returns the resolved URI.
///
/// See [resolveUri] for details.
Uri resolve(String reference);
/// Resolve [reference] as a URI relative to `this`.
///
/// Returns the resolved URI.
///
/// The algorithm "Transform Reference" for resolving a reference is described
/// in [RFC-3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5
/// "RFC-1123").
///
/// Updated to handle the case where the base URI is just a relative path -
/// that is: when it has no scheme and no authority and the path does not
/// start with a slash.
/// In that case, the paths are combined without removing leading "..", and
/// an empty path is not converted to "/".
Uri resolveUri(Uri reference);
/// Returns a URI where the path has been normalized.
///
/// A normalized path does not contain `.` segments or non-leading `..`
/// segments.
/// Only a relative path with no scheme or authority may contain
/// leading `..` segments;
/// a path that starts with `/` will also drop any leading `..` segments.
///
/// This uses the same normalization strategy as `Uri().resolve(this)`.
///
/// Does not change any part of the URI except the path.
///
/// The default implementation of `Uri` always normalizes paths, so calling
/// this function has no effect.
Uri normalizePath();
/// Creates a new `Uri` object by parsing a URI string.
///
/// If [start] and [end] are provided, they must specify a valid substring
/// of [uri], and only the substring from `start` to `end` is parsed as a URI.
///
/// If the [uri] string is not valid as a URI or URI reference,
/// a [FormatException] is thrown.
///
/// Example:
/// ```dart
/// final uri =
/// Uri.parse('https://example.com/api/fetch?limit=10,20,30&max=100');
/// print(uri); // https://example.com/api/fetch?limit=10,20,30&max=100
///
/// Uri.parse('::Not valid URI::'); // Throws FormatException.
/// ```
static Uri parse(String uri, [int start = 0, int? end]) {
// This parsing will not validate percent-encoding, IPv6, etc.
// When done splitting into parts, it will call, e.g., [_makeFragment]
// to do the final parsing.
//
// Important parts of the RFC 3986 used here:
// URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
//
// hier-part = "//" authority path-abempty
// / path-absolute
// / path-rootless
// / path-empty
//
// URI-reference = URI / relative-ref
//
// absolute-URI = scheme ":" hier-part [ "?" query ]
//
// relative-ref = relative-part [ "?" query ] [ "#" fragment ]
//
// relative-part = "//" authority path-abempty
// / path-absolute
// / path-noscheme
// / path-empty
//
// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
//
// authority = [ userinfo "@" ] host [ ":" port ]
// userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
// host = IP-literal / IPv4address / reg-name
// IP-literal = "[" ( IPv6address / IPv6addrz / IPvFuture ) "]"
// IPv6addrz = IPv6address "%25" ZoneID
// ZoneID = 1*( unreserved / pct-encoded )
// port = *DIGIT
// reg-name = *( unreserved / pct-encoded / sub-delims )
//
// path = path-abempty ; begins with "/" or is empty
// / path-absolute ; begins with "/" but not "//"
// / path-noscheme ; begins with a non-colon segment
// / path-rootless ; begins with a segment
// / path-empty ; zero characters
//
// path-abempty = *( "/" segment )
// path-absolute = "/" [ segment-nz *( "/" segment ) ]
// path-noscheme = segment-nz-nc *( "/" segment )
// path-rootless = segment-nz *( "/" segment )
// path-empty = 0<pchar>
//
// segment = *pchar
// segment-nz = 1*pchar
// segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
// ; non-zero-length segment without any colon ":"
//
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
//
// query = *( pchar / "/" / "?" )
//
// fragment = *( pchar / "/" / "?" )
end ??= uri.length;
// Special case data:URIs. Ignore case when testing.
if (end >= start + 5) {
int dataDelta = _startsWithData(uri, start);
if (dataDelta == 0) {
// The case is right.
if (start > 0 || end < uri.length) uri = uri.substring(start, end);
return UriData._parse(uri, 5, null).uri;
} else if (dataDelta == 0x20) {
return UriData._parse(uri.substring(start + 5, end), 0, null).uri;
}
// Otherwise the URI doesn't start with "data:" or any case variant of it.
}
// The following index-normalization belongs with the scanning, but is
// easier to do here because we already have extracted variables from the
// indices list.
var indices = List<int>.filled(8, 0, growable: false);
// Set default values for each position.
// The value will either be correct in some cases where it isn't set
// by the scanner, or it is clearly recognizable as an unset value.
indices
..[0] = 0
..[_schemeEndIndex] = start - 1
..[_hostStartIndex] = start - 1
..[_notSimpleIndex] = start - 1
..[_portStartIndex] = start
..[_pathStartIndex] = start
..[_queryStartIndex] = end
..[_fragmentStartIndex] = end;
var state = _scan(uri, start, end, _uriStart, indices);
// Some states that should be non-simple, but the URI ended early.
// Paths that end at a ".." must be normalized to end in "../".
if (state >= _nonSimpleEndStates) {
indices[_notSimpleIndex] = end;
}
int schemeEnd = indices[_schemeEndIndex];
if (schemeEnd >= start) {
// Rescan the scheme part now that we know it's not a path.
state = _scan(uri, start, schemeEnd, _schemeStart, indices);
if (state == _schemeStart) {
// Empty scheme.
indices[_notSimpleIndex] = schemeEnd;
}
}
// The returned positions are limited by the scanners ability to write only
// one position per character, and only the current position.
// Scanning from left to right, we only know whether something is a scheme
// or a path when we see a `:` or `/`, and likewise we only know if the first
// `/` is part of the path or is leading an authority component when we see
// the next character.
int hostStart = indices[_hostStartIndex] + 1;
int portStart = indices[_portStartIndex];
int pathStart = indices[_pathStartIndex];
int queryStart = indices[_queryStartIndex];
int fragmentStart = indices[_fragmentStartIndex];
// We may discover the scheme while handling special cases.
String? scheme;
// Derive some positions that weren't set to normalize the indices.
if (fragmentStart < queryStart) queryStart = fragmentStart;
// If pathStart isn't set (it's before scheme end or host start), then
// the path is empty, or there is no authority part and the path
// starts with a non-simple character.
if (pathStart < hostStart) {
// There is an authority, but no path. The path would start with `/`
// if it was there.
pathStart = queryStart;
} else if (pathStart <= schemeEnd) {
// There is a scheme, but no authority.
pathStart = schemeEnd + 1;
}
// If there is an authority with no port, set the port position
// to be at the end of the authority (equal to pathStart).
// This also handles a ":" in a user-info component incorrectly setting
// the port start position.
if (portStart < hostStart) portStart = pathStart;
assert(hostStart == start || schemeEnd <= hostStart);
assert(hostStart <= portStart);
assert(schemeEnd <= pathStart);
assert(portStart <= pathStart);
assert(pathStart <= queryStart);
assert(queryStart <= fragmentStart);
bool isSimple = indices[_notSimpleIndex] < start;
if (isSimple) {
// Check/do normalizations that weren't detected by the scanner.
// This includes removal of empty port or userInfo,
// or scheme specific port and path normalizations.
if (hostStart > schemeEnd + 3) {
// Always be non-simple if URI contains user-info.
// The scanner doesn't set the not-simple position in this case because
// it's setting the host-start position instead.
isSimple = false;
} else if (portStart > start && portStart + 1 == pathStart) {