-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode.dart
More file actions
458 lines (410 loc) · 16.3 KB
/
decode.dart
File metadata and controls
458 lines (410 loc) · 16.3 KB
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
part of '../qs.dart';
/// Decoder: query-string → nested Dart maps/lists (Node `qs` parity)
///
/// This module mirrors the semantics of the original `qs` (https://github.com/ljharb/qs):
/// - Bracket notation drives structure (e.g. `a[b][0]=1`).
/// - Optional dot-notation can be accepted and normalized to brackets when
/// `DecodeOptions.allowDots` is true (e.g. `a.b` → `a[b]`).
/// - Depth limiting (`depth`) behaves like `qs`: depth=0 disables splitting;
/// `strictDepth=true` throws when nesting exceeds the limit; otherwise the
/// remainder is kept as a single segment.
/// - Charset sentinel (`utf8=`) handling matches `qs`.
/// - Duplicate key handling (`duplicates`) and list parsing (`parseLists`,
/// `allowEmptyLists`, `allowSparseLists`, `listLimit`) follow the reference.
///
/// Implementation notes:
/// - We decode key parts lazily and then "reduce" right-to-left to build the
/// final structure in `_parseObject`.
/// - We never mutate caller-provided containers; fresh maps/lists are created.
/// - No behavioral changes are introduced here; comments only.
/// Split operation result used by the decoder helpers.
/// - `parts`: collected key segments.
/// - `exceeded`: indicates whether a configured limit was exceeded during split.
typedef SplitResult = ({List<String> parts, bool exceeded});
/// Normalizes simple dot notation to bracket notation (e.g. `a.b` → `a[b]`).
/// Only matches \nondotted, non-bracketed tokens so `a.b.c` becomes `a[b][c]`.
final RegExp _dotToBracket = RegExp(r'\.([^.\[]+)');
/// Internal decoding surface grouped under the `QS` extension.
///
/// These static helpers are private to the library and orchestrate the
/// string → structure pipeline used by `QS.decode`.
extension _$Decode on QS {
/// Interprets a single scalar value as a list element when the `comma`
/// option is enabled and a comma is present, and enforces `listLimit`.
///
/// If `throwOnLimitExceeded` is true, exceeding `listLimit` will throw a
/// `RangeError`; otherwise the caller can decide how to degrade.
///
/// The `currentListLength` is used to guard incremental growth when we are
/// already building a list for a given key path.
static dynamic _parseListValue(
dynamic val,
DecodeOptions options,
int currentListLength,
) {
// Fast-path: split comma-separated scalars into a list when requested.
if (val is String && val.isNotEmpty && options.comma && val.contains(',')) {
final List<String> splitVal = val.split(',');
if (options.throwOnLimitExceeded &&
currentListLength + splitVal.length > options.listLimit) {
throw RangeError(
'List limit exceeded. '
'Only ${options.listLimit} element${options.listLimit == 1 ? '' : 's'} allowed in a list.',
);
}
return splitVal;
}
// Guard incremental growth of an existing list as we parse additional items.
if (options.throwOnLimitExceeded &&
currentListLength + 1 > options.listLimit) {
throw RangeError(
'List limit exceeded. '
'Only ${options.listLimit} element${options.listLimit == 1 ? '' : 's'} allowed in a list.',
);
}
return val;
}
/// Tokenizes the raw query-string into a flat key→value map before any
/// structural reconstruction. Handles:
/// - query prefix removal (`?`), percent-decoding via `options.decoder`
/// - charset sentinel detection (`utf8=`) per `qs`
/// - duplicate key policy (combine/first/last)
/// - parameter and list limits with optional throwing behavior
static Map<String, dynamic> _parseQueryStringValues(
String str, [
DecodeOptions options = const DecodeOptions(),
]) {
// 1) Normalize the incoming string (drop `?`, normalize %5B/%5D to brackets).
final String cleanStr =
_cleanQueryString(str, ignoreQueryPrefix: options.ignoreQueryPrefix);
// 2) Resolve the parameter limit; `double.infinity` denotes no limit.
final int? limit = options.parameterLimit == double.infinity
? null
: options.parameterLimit.toInt();
// `qs` treats non-positive limits as programmer error when enforced.
if (limit != null && limit <= 0) {
throw ArgumentError('Parameter limit must be a positive integer.');
}
// 3) Split by delimiter once; optionally truncate, optionally throw on overflow.
final List<String> allParts = cleanStr.split(options.delimiter);
late final List<String> parts;
if (limit != null && limit > 0) {
final int takeCount = options.throwOnLimitExceeded ? limit + 1 : limit;
final int count =
allParts.length < takeCount ? allParts.length : takeCount;
parts = allParts.sublist(0, count);
if (options.throwOnLimitExceeded && allParts.length > limit) {
throw RangeError(
'Parameter limit exceeded. Only $limit parameter${limit == 1 ? '' : 's'} allowed.',
);
}
} else {
parts = allParts;
}
// Charset probing (utf8=✓ / utf8=X). Skip the sentinel pair later.
int skipIndex = -1; // Keep track of where the utf8 sentinel was found
int i;
Encoding charset = options.charset;
// 4) Scan once for a charset sentinel and adjust decoder charset accordingly.
if (options.charsetSentinel) {
for (i = 0; i < parts.length; ++i) {
final String p = parts[i];
if (p.startsWith('utf8=')) {
if (p == Sentinel.charset.toString()) {
charset = utf8;
} else if (p == Sentinel.iso.toString()) {
charset = latin1;
}
skipIndex = i;
break;
}
}
}
// 5) Parse each `key=value` pair, honoring bracket-`]=` short-circuit for speed.
final Map<String, dynamic> obj = {};
for (i = 0; i < parts.length; ++i) {
if (i == skipIndex) continue;
final String part = parts[i];
final int bracketEqualsPos = part.indexOf(']=');
final int pos =
bracketEqualsPos == -1 ? part.indexOf('=') : bracketEqualsPos + 1;
late final String key;
dynamic val;
// Decode key/value using key-aware decoder, no %2E protection shim.
if (pos == -1) {
// Decode bare key (no '=') using key-aware decoder
key = options.decoder(part, charset: charset, kind: DecodeKind.key);
val = options.strictNullHandling ? null : '';
} else {
// Decode key slice using key-aware decoder; values decode as value kind
key = options.decoder(part.slice(0, pos),
charset: charset, kind: DecodeKind.key);
// Decode the substring *after* '=', applying list parsing and the configured decoder.
val = Utils.apply<dynamic>(
_parseListValue(
part.slice(pos + 1),
options,
obj.containsKey(key) && obj[key] is List
? (obj[key] as List).length
: 0,
),
(dynamic v) =>
options.decoder(v, charset: charset, kind: DecodeKind.value),
);
}
// Optional HTML numeric entity interpretation (legacy Latin-1 queries).
if (val != null &&
!Utils.isEmpty(val) &&
options.interpretNumericEntities &&
charset == latin1) {
if (val is Iterable) {
val = Utils.interpretNumericEntities(_joinIterableToCommaString(val));
} else {
val = Utils.interpretNumericEntities(val.toString());
}
}
// Quirk: a literal `[]=` suffix forces an array container (qs behavior).
if (options.parseLists && part.contains('[]=')) {
val = [val];
}
// Duplicate key policy: combine/first/last (default: combine).
final bool existing = obj.containsKey(key);
if (existing && options.duplicates == Duplicates.combine) {
obj[key] = Utils.combine(obj[key], val);
} else if (!existing || options.duplicates == Duplicates.last) {
obj[key] = val;
}
}
return obj;
}
/// Reduces a list of key segments (e.g. `["a", "[b]", "[0]"]`) and a
/// leaf value into a nested structure. Operates right-to-left, constructing
/// maps or lists based on segment content and `DecodeOptions`.
///
/// Notes:
/// - When `parseLists` is false, numeric segments are treated as string keys.
/// - When `allowEmptyLists` is true, an empty string (or `null` under
/// `strictNullHandling`) under a `[]` segment yields an empty list.
/// - `listLimit` applies to explicit numeric indices as an upper bound.
static dynamic _parseObject(
List<String> chain,
dynamic val,
DecodeOptions options,
bool valuesParsed,
) {
// Determine the current list length if we are appending into `[]`.
late final int currentListLength;
if (chain.length >= 2 && chain.last == '[]') {
final String prev = chain[chain.length - 2];
final bool bracketed = prev.startsWith('[') && prev.endsWith(']');
final int? parentIndex =
bracketed ? int.tryParse(prev.substring(1, prev.length - 1)) : null;
if (parentIndex != null &&
parentIndex >= 0 &&
val is List &&
parentIndex < val.length) {
final dynamic parent = val[parentIndex];
currentListLength = parent is List ? parent.length : 0;
} else {
currentListLength = 0;
}
} else {
currentListLength = 0;
}
// Lazily parse comma-lists once per leaf unless the caller already did.
dynamic leaf = valuesParsed
? val
: _parseListValue(
val,
options,
currentListLength,
);
for (int i = chain.length - 1; i >= 0; --i) {
dynamic obj;
final String root = chain[i];
// Anonymous list segment `[]` — either an empty list (when allowed) or a
// single-element list with the leaf combined in.
if (root == '[]' && options.parseLists) {
obj = options.allowEmptyLists &&
(leaf == '' || (options.strictNullHandling && leaf == null))
? List<dynamic>.empty(growable: true)
: Utils.combine([], leaf);
} else {
obj = <String, dynamic>{};
// Normalize bracketed segments ("[k]") and optionally decode `%2E` → '.'
// when `decodeDotInKeys` is enabled.
final String cleanRoot = root.startsWith('[') && root.endsWith(']')
? root.slice(1, root.length - 1)
: root;
final String decodedRoot = options.decodeDotInKeys
? cleanRoot.replaceAll('%2E', '.').replaceAll('%2e', '.')
: cleanRoot;
final int? index = int.tryParse(decodedRoot);
if (!options.parseLists && decodedRoot == '') {
obj = <String, dynamic>{'0': leaf};
} else if (index != null &&
index >= 0 &&
root != decodedRoot &&
index.toString() == decodedRoot &&
options.parseLists &&
index <= options.listLimit) {
// Numeric segment treated as list index when lists are enabled and the
// token was actually bracketed (to disambiguate bare numeric keys).
obj = List<dynamic>.filled(
index + 1,
const Undefined(),
growable: true,
);
obj[index] = leaf;
} else {
obj[index?.toString() ?? decodedRoot] = leaf;
}
}
leaf = obj;
}
return leaf;
}
/// Splits a raw key into bracket segments (respecting dot-notation and
/// depth constraints) and delegates to `_parseObject` to build the value.
/// Returns `null` for empty keys.
static dynamic _parseKeys(
String? givenKey,
dynamic val,
DecodeOptions options, [
bool valuesParsed = false,
]) {
if (givenKey == null || givenKey.isEmpty) return null;
final segments = _splitKeyIntoSegments(
originalKey: givenKey,
allowDots: options.allowDots,
maxDepth: options.depth,
strictDepth: options.strictDepth,
);
return _parseObject(segments, val, options, valuesParsed);
}
/// Splits a key like `a[b][0][c]` into `['a', '[b]', '[0]', '[c]']` with:
/// - dot-notation normalization (`a.b` → `a[b]`) when `allowDots` is true
/// - depth limiting (depth=0 returns the whole key as a single segment)
/// - bracket group balancing, preserving unterminated tails as a single
/// remainder segment unless `strictDepth` is enabled (then it throws)
static List<String> _splitKeyIntoSegments({
required String originalKey,
required bool allowDots,
required int maxDepth,
required bool strictDepth,
}) {
// Optionally normalize `a.b` to `a[b]` before splitting.
final String key = allowDots
? originalKey.replaceAllMapped(_dotToBracket, (m) => '[${m[1]}]')
: originalKey;
// Depth==0 → do not split at all (reference `qs` behavior).
if (maxDepth <= 0) {
return <String>[key];
}
final List<String> segments = [];
// Extract the parent token (before the first '['), if any.
final int first = key.indexOf('[');
final String parent = first >= 0 ? key.substring(0, first) : key;
if (parent.isNotEmpty) segments.add(parent);
final int n = key.length;
int open = first;
int depth = 0;
while (open >= 0 && depth < maxDepth) {
// Balance nested brackets inside this group: "[ ... possibly [] ... ]"
int level = 1;
int i = open + 1;
int close = -1;
while (i < n) {
final int ch = key.codeUnitAt(i);
if (ch == 0x5B) {
// '['
level++;
} else if (ch == 0x5D) {
// ']'
level--;
if (level == 0) {
close = i;
break;
}
}
// Advance inside the current bracket group until it balances.
i++;
}
if (close < 0) {
// Unterminated group, stop collecting groups
break;
}
segments.add(key.substring(open, close + 1)); // includes enclosing [ ]
depth++;
// find next group, starting after this one
open = key.indexOf('[', close + 1);
}
// If additional groups remain beyond the allowed depth, either throw or
// stash the remainder as a single segment, per `strictDepth`.
if (open >= 0) {
// We still have remainder starting with '['
if (strictDepth) {
throw RangeError(
'Input depth exceeded $maxDepth and strictDepth is true');
}
// Stash the remainder as a single segment (qs behavior)
segments.add('[${key.substring(open)}]');
}
return segments;
}
/// Normalizes the raw query-string prior to tokenization:
/// - Optionally drops a single leading `?` (when `ignoreQueryPrefix` is set).
/// - Rewrites percent-encoded bracket characters (%5B/%5b → '[', %5D/%5d → ']')
/// in a single pass for faster downstream bracket parsing.
static String _cleanQueryString(
String str, {
required bool ignoreQueryPrefix,
}) {
// Drop exactly one leading '?' (qs semantics) — not all leading question marks.
if (ignoreQueryPrefix &&
str.isNotEmpty &&
str.codeUnitAt(0) == 0x3F /* '?' */) {
// Remove leading '?' only once (qs semantics)
str = str.substring(1);
}
if (str.length < 3) return str;
// Single-pass scan; we avoid full percent-decoding and only normalize
// bracket tokens that matter for key splitting.
final StringBuffer sb = StringBuffer();
final int n = str.length;
int i = 0;
while (i < n) {
final int c = str.codeUnitAt(i);
// Match "%5B" / "%5b" -> '[' and "%5D" / "%5d" -> ']'
if (c == 0x25 /* '%' */ && i + 2 < n) {
final c1 = str.codeUnitAt(i + 1);
if (c1 == 0x35 /* '5' */) {
final c2 = str.codeUnitAt(i + 2);
if (c2 == 0x42 /* 'B' */ || c2 == 0x62 /* 'b' */) {
sb.writeCharCode(0x5B); // '['
i += 3;
continue;
} else if (c2 == 0x44 /* 'D' */ || c2 == 0x64 /* 'd' */) {
sb.writeCharCode(0x5D); // ']'
i += 3;
continue;
}
}
}
sb.writeCharCode(c);
i++;
}
return sb.toString();
}
/// Joins an iterable of objects into a comma-separated string.
static String _joinIterableToCommaString(Iterable it) {
final StringBuffer sb = StringBuffer();
bool first = true;
for (final e in it) {
if (!first) sb.write(',');
sb.write(e == null ? '' : e.toString());
first = false;
}
return sb.toString();
}
}