-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqs.dart
More file actions
223 lines (192 loc) · 7.87 KB
/
qs.dart
File metadata and controls
223 lines (192 loc) · 7.87 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
import 'dart:convert' show latin1, utf8, Encoding;
import 'dart:typed_data' show ByteBuffer;
import 'package:qs_dart/src/enums/decode_kind.dart';
import 'package:qs_dart/src/enums/duplicates.dart';
import 'package:qs_dart/src/enums/format.dart';
import 'package:qs_dart/src/enums/list_format.dart';
import 'package:qs_dart/src/enums/sentinel.dart';
import 'package:qs_dart/src/extensions/extensions.dart';
import 'package:qs_dart/src/models/decode_options.dart';
import 'package:qs_dart/src/models/encode_options.dart';
import 'package:qs_dart/src/models/undefined.dart';
import 'package:qs_dart/src/utils.dart';
import 'package:weak_map/weak_map.dart';
// Re-export for public API: consumers can `import 'package:qs_dart/qs.dart'` and access DecodeKind
export 'package:qs_dart/src/enums/decode_kind.dart';
part 'extensions/decode.dart';
part 'extensions/encode.dart';
/// # QS (Dart)
///
/// Reference-style query‑string codec that mirrors the semantics of the
/// popular Node `qs` library. Provides two entry points: [decode] and
/// [encode].
///
/// Highlights
/// - RFC 3986 / RFC 1738 output formatting via [Format].
/// - Multiple list notations via [ListFormat].
/// - Duplicate handling on decode via [Duplicates].
/// - Pluggable encoder/decoder, custom key sorting and filtering hooks.
/// - Optional query prefix and charset sentinel emission.
final class QS {
/// Decode a query string or a pre-parsed map into a structured map.
///
/// - `input` may be:
/// * a query [String] (e.g. `"a=1&b[c]=2"`), or
/// * a pre-tokenized `Map<String, dynamic>` produced by a custom tokenizer.
/// - When `input` is `null` or the empty string, `{}` is returned.
/// - If [DecodeOptions.parseLists] is `true` and the number of top‑level
/// parameters exceeds [DecodeOptions.listLimit], list parsing is
/// temporarily disabled for this call to bound memory (mirrors Node `qs`).
/// - Throws [ArgumentError] if `input` is neither a `String` nor a
/// `Map<String, dynamic>`.
///
/// See [DecodeOptions] for delimiter, nesting depth, numeric-entity handling,
/// duplicates policy, and other knobs.
static Map<String, dynamic> decode(dynamic input, [DecodeOptions? options]) {
options ??= const DecodeOptions();
// Default to the library's safe, Node-`qs` compatible settings.
// Fail fast on unsupported input shapes to avoid ambiguous behavior.
if (!(input is String? || input is Map<String, dynamic>?)) {
throw ArgumentError.value(
input,
'input',
'The input must be a String or a Map<String, dynamic>',
);
}
// Normalize `null` / empty string to an empty map.
if (input?.isEmpty ?? true) {
return <String, dynamic>{};
}
final Map<String, dynamic>? tempObj = input is String
? _$Decode._parseQueryStringValues(input, options)
: input;
// Guardrail: if the top-level parameter count is large, temporarily disable
// list parsing to keep memory bounded (matches Node `qs`). Only apply for
// raw string inputs, not for pre-tokenized maps.
if (input is String &&
options.parseLists &&
options.listLimit > 0 &&
(tempObj?.length ?? 0) > options.listLimit) {
options = options.copyWith(parseLists: false);
}
Map<String, dynamic> obj = {};
// Merge each parsed key into the accumulator using the same rules as Node `qs`.
// Iterate over the keys and setup the new object
if (tempObj?.isNotEmpty ?? false) {
for (final MapEntry<String, dynamic> entry in tempObj!.entries) {
final parsed = _$Decode._parseKeys(
entry.key, entry.value, options, input is String);
if (obj.isEmpty && parsed is Map<String, dynamic>) {
obj = parsed; // direct assignment – no merge needed
} else {
obj = Utils.merge(obj, parsed, options) as Map<String, dynamic>;
}
}
}
// Drop undefined/empty leaves to match the reference behavior.
return Utils.compact(obj);
}
/// Encode a map/iterable into a query string.
///
/// - `object` may be:
/// * a `Map<String, dynamic>` (encoded as key/value pairs),
/// * an `Iterable` (encoded as an index‑keyed map: `0`, `1`, …), or
/// * `null` (returns the empty string).
/// - If [EncodeOptions.filter] is a function, it is invoked like the
/// Node `qs` filter; if it's an iterable, it specifies the exact
/// key order/selection.
/// - Keys are optionally sorted via [EncodeOptions.sort].
/// - [EncodeOptions.addQueryPrefix] and [EncodeOptions.charsetSentinel]
/// control the leading `?` and sentinel token emission.
///
/// See [EncodeOptions] for details about list formats, output format, and hooks.
static String encode(Object? object, [EncodeOptions? options]) {
options ??= const EncodeOptions();
// Use default encoding settings unless overridden by the caller.
// Normalize supported inputs into a mutable map we can traverse.
Map<String, dynamic> obj = switch (object) {
Map<String, dynamic> map => {...map},
Iterable iterable => Utils.createIndexMap(iterable),
_ => <String, dynamic>{},
};
final List<String> keys = [];
// Nothing to encode.
if (obj.isEmpty) {
return '';
}
List? objKeys;
// Support the two `qs` filter forms: function and whitelist iterable.
if (options.filter is Function) {
obj = options.filter?.call('', obj);
} else if (options.filter is Iterable) {
objKeys = List.of(options.filter);
}
objKeys ??= obj.keys.toList();
// Deterministic key order if a sorter is provided.
if (options.sort is Function) {
objKeys.sort(options.sort);
}
// Internal side-channel used by the encoder to detect cycles and share state.
final WeakMap sideChannel = WeakMap();
for (int i = 0; i < objKeys.length; i++) {
final key = objKeys[i];
if (key is! String || (obj[key] == null && options.skipNulls)) {
continue;
}
final ListFormatGenerator gen = options.listFormat.generator;
final bool crt = identical(gen, ListFormat.comma.generator) &&
options.commaRoundTrip == true;
final encoded = _$Encode._encode(
obj[key],
undefined: !obj.containsKey(key),
prefix: key,
generateArrayPrefix: gen,
commaRoundTrip: crt,
allowEmptyLists: options.allowEmptyLists,
strictNullHandling: options.strictNullHandling,
skipNulls: options.skipNulls,
encodeDotInKeys: options.encodeDotInKeys,
encoder: options.encode ? options.encoder : null,
serializeDate: options.serializeDate,
filter: options.filter,
sort: options.sort,
allowDots: options.allowDots,
format: options.format,
formatter: options.formatter,
encodeValuesOnly: options.encodeValuesOnly,
charset: options.charset,
addQueryPrefix: options.addQueryPrefix,
sideChannel: sideChannel,
);
if (encoded is Iterable) {
for (final e in encoded) {
if (e != null) keys.add(e as String);
}
} else if (encoded != null) {
keys.add(encoded as String);
}
}
// Join all encoded segments with the chosen delimiter.
final String joined = keys.join(options.delimiter);
final StringBuffer out = StringBuffer();
if (options.addQueryPrefix) {
out.write('?');
}
// Optionally emit the charset sentinel (mirrors Node `qs`).
if (options.charsetSentinel) {
out.write(switch (options.charset) {
/// encodeURIComponent('✓')
/// the "numeric entity" representation of a checkmark
latin1 => '${Sentinel.iso}&',
/// encodeURIComponent('✓')
utf8 => '${Sentinel.charset}&',
_ => '',
});
}
// Append the payload after any optional prefix/sentinel.
if (joined.isNotEmpty) {
out.write(joined);
}
return out.toString();
}
}