This repository was archived by the owner on Aug 1, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayload-parser-behavior.html
More file actions
424 lines (420 loc) · 12.5 KB
/
payload-parser-behavior.html
File metadata and controls
424 lines (420 loc) · 12.5 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
<!--
@license
Copyright 2018 The Advanced REST client authors <arc@mulesoft.com>
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
-->
<link rel="import" href="../polymer/lib/utils/mixin.html">
<script>
(function(global) {
'use strict';
if (!global.ArcBehaviors) {
/**
* @namespace ArcBehaviors
*/
global.ArcBehaviors = {};
}
/**
* A behavior to be implemented to elements that needs to parse
* request / response body.
* It contains functions to encode / decode form data and to escape HTML.
*
* @polymer
* @mixinFunction
* @memberof ArcBehaviors
*/
ArcBehaviors.PayloadParserBehavior = Polymer.dedupingMixin((base) => {
/**
* @polymer
* @mixinClass
*/
class PPBmixin extends base {
static get properties() {
return {
// Regexp to search for the `&` character
AMP_RE: {
type: RegExp,
readOnly: true,
value: function() {
return new RegExp(/&/g);
}
},
// Regexp to search for the `>` character
GT_RE: {
type: RegExp,
readOnly: true,
value: function() {
return new RegExp(/>/g);
}
},
// Regexp to search for the `<` character
LT_RE: {
type: RegExp,
readOnly: true,
value: function() {
return new RegExp(/</g);
}
},
// Regexp to search for the `'` character
SQUOT_RE: {
type: RegExp,
readOnly: true,
value: function() {
return new RegExp(/'/g);
}
},
// Regexp to search for the `"` character
QUOT_RE: {
type: RegExp,
readOnly: true,
value: function() {
return new RegExp(/"/g);
}
}
};
}
/**
* Escape HTML to save HTML text.
*
* @param {String} html A HTML string to be escaped.
* @return {String}
*/
htmlEscape(html) {
if (html.indexOf('&') !== -1) {
html = html.replace(this.AMP_RE, '&');
}
if (html.indexOf('<') !== -1) {
html = html.replace(this.LT_RE, '<');
}
if (html.indexOf('>') !== -1) {
html = html.replace(this.GT_RE, '>');
}
if (html.indexOf('"') !== -1) {
html = html.replace(this.QUOT_RE, '"');
}
if (html.indexOf('\'') !== -1) {
html = html.replace(this.SQUOT_RE, ''');
}
return html;
}
/**
* Parse input array to string x-www-form-urlencoded.
*
* Note that this function doesn't encodes the name and value. Use
* `this.formArrayToString(this.encodeUrlEncoded(arr))`
* to create a encoded string from the array.
*
* @param {Array<Object>} arr Input array. Each element must contain an
* object with `name` and `value` keys.
* @return {String} A parsed string of `name`=`value` pairs of the input objects.
*/
formArrayToString(arr) {
if (!arr) {
return [];
}
const result = [];
arr.forEach((item) => {
const data = this._modelItemToFormDataString(item);
if (data) {
result[result.length] = data;
}
});
return result.join('&');
}
/**
* Creates a form data string for a single item.
* @param {Object} model The model with `name` and `value` properties.
* @return {String} Generated value string for x-www-form-urlencoded form.
*/
_modelItemToFormDataString(model) {
if (model.schema && model.schema.enabled === false) {
return;
}
const name = this._paramValue(model.name);
let value = model.value;
if (value && value instanceof Array) {
return value.map((item) => name + '=' + this._paramValue(item))
.join('&');
}
value = this._paramValue(value);
if (!name && !value) {
return;
}
if (!value && model.required === false) {
return;
}
return name + '=' + value;
}
/**
* Parse input string to array of x-www-form-urlencoded form parameters.
*
* This function will not url-decode names and values. Please, use
* `this.decodeUrlEncoded(this.stringToArray(str))` to create an array
* of decoded parameters.
*
* @param {String} input A string of HTTP x-www-form-urlencoded parameters
* @return {Array<Object>} An array of params with `name` and `value` keys.
*/
stringToArray(input) {
if (typeof input !== 'string' || !input.trim()) {
return [];
}
// Chrome inspector has FormData output in format: `param-name`:`param-value`
// When copying from inspector the ':' must be replaced with '='
const htmlInputCheck = /^([^\\=]{1,})=(.*)$/m;
if (!htmlInputCheck.test(input)) {
// replace chome inspector data.
input = input.replace(/^([^\\:]{1,}):(.*)$/gm, '$1=$2&').replace(/\n/gm, '');
input = input.substr(0, input.length - 1);
}
return this._createParamsArray(input);
}
/**
* Converts a string to an array with objects containing name and value keys
* @param {String} input An input string
* @return {Array.<Object>} An array of params with `name` and `value` keys.
*/
_createParamsArray(input) {
let result = [];
if (!input) {
return result;
}
let state = 0; // 0 - reading name, 1 - reading value
let i = 0;
let _tmpName = '';
let _tmpValue = '';
while (true) {
const ch = input[i++];
if (ch === undefined) {
if (_tmpValue || _tmpName) {
result = this._appendArrayResult(result, _tmpName, _tmpValue);
}
break;
}
if (ch === '=') {
if (state !== 1) {
state = 1;
continue;
}
}
if (ch === '&') {
state = 0;
result = this._appendArrayResult(result, _tmpName, _tmpValue);
_tmpName = '';
_tmpValue = '';
continue;
}
if (state === 0) {
_tmpName += ch;
} else if (state === 1) {
_tmpValue += ch;
}
}
return result;
}
/**
* Appends form data parameter to an array.
* If the parameter already exists in the array it creates an array for
* the value onstead of appending the same parameter.
*
* @param {Array} array An array to append the parameter
* @param {String} name Name of the form data parameter
* @param {String} value Value of the form data parameter
* @return {Array} Updated array
*/
_appendArrayResult(array, name, value) {
for (let i = 0, len = array.length; i < len; i++) {
if (array[i].name === name) {
if (array[i].value instanceof Array) {
array[i].value.push(value);
} else {
array[i].value = [array[i].value, value];
}
return array;
}
}
array.push({
name: name,
value: value
});
return array;
}
/**
* Encode payload to x-www-form-urlencoded string.
*
* @param {Array<object>|String} input An input data.
* @return {Array<object>|String}
*/
encodeUrlEncoded(input) {
if (!input || !input.length) {
return input;
}
const isArray = input instanceof Array;
if (!isArray) {
input = this.stringToArray(input);
}
input.forEach((obj) => {
obj.name = this.encodeQueryString(obj.name);
obj.value = this._encodeValue(obj.value);
});
if (isArray) {
return input;
}
return this.formArrayToString(input);
}
/**
* URL encodes a value.
*
* @param {String|Array<String>} value Value to encode. Either string or
* array of strings.
* @return {String|Array<String>} Encoded value. The same type as the input.
*/
_encodeValue(value) {
if (value instanceof Array) {
for (let i = 0, len = value.length; i < len; i++) {
value[i] = this.encodeQueryString(value[i]);
}
return value;
}
return this.encodeQueryString(value);
}
/**
* Decode x-www-form-urlencoded data.
*
* @param {Array<object>|String} input An input data.
* @return {Array<object>|String}
*/
decodeUrlEncoded(input) {
if (!input || !input.length) {
return input;
}
const isArray = input instanceof Array;
if (!isArray) {
input = this.stringToArray(input);
}
input.forEach((obj) => {
obj.name = this.decodeQueryString(obj.name);
obj.value = this._decodeValue(obj.value);
});
if (isArray) {
return input;
}
return this.formArrayToString(input);
}
/**
* URL decodes a value.
*
* @param {String|Array<String>} value Value to decode. Either string or
* array of strings.
* @return {String|Array<String>} Decoded value. The same type as the input.
*/
_decodeValue(value) {
if (value instanceof Array) {
for (let i = 0, len = value.length; i < len; i++) {
value[i] = this.decodeQueryString(value[i]);
}
return value;
}
return this.decodeQueryString(value);
}
/**
* Parse input string as a payload param key or value.
*
* @param {String} input An input to parse.
* @return {String}
*/
_paramValue(input) {
if (!input) {
return String();
}
input = String(input);
input = input.trim();
return input;
}
/**
* Parse a line of key=value http params into an object with `name` and `value` keys.
*
* @param {String} input A input line of x-www-form-urlencoded text tike `param=value`
* @return {Object} A parsed object with `name` and `value` keys.
* @deprecated It's old parser. Use `_createParamsArray` instead.
*/
_paramLineToFormObject(input) {
if (!input) {
return;
}
const _tmp = input.split('=');
const name = _tmp[0].trim();
if (!name && _tmp.length === 1) {
return;
}
let value;
if (_tmp.length === 1) {
value = '';
} else {
value = _tmp[1].trim();
}
return {
name: name,
value: value
};
}
/**
* Returns a string where all characters that are not valid for a URL
* component have been escaped. The escaping of a character is done by
* converting it into its UTF-8 encoding and then encoding each of the
* resulting bytes as a %xx hexadecimal escape sequence.
*
* Note: this method will convert any space character into its escape
* short form, '+' rather than %20. It should therefore only be used for
* query-string parts.
*
* The following character sets are **not** escaped by this method:
* - ASCII digits or letters
* - ASCII punctuation characters: ```- _ . ! ~ * ' ( )</pre>```
*
* Notice that this method <em>does</em> encode the URL component delimiter
* characters:<blockquote>
*
* ```
* ; / ? : & = + $ , #
* ```
*
* @param {String} str A string containing invalid URL characters
* @return {String} a string with all invalid URL characters escaped
*/
encodeQueryString(str) {
if (!str) {
return str;
}
const regexp = /%20/g;
return encodeURIComponent(str).replace(regexp, '+');
}
/**
* Returns a string where all URL component escape sequences have been
* converted back to their original character representations.
*
* Note: this method will convert the space character escape short form, '+',
* into a space. It should therefore only be used for query-string parts.
*
* @param {String} str string containing encoded URL component sequences
* @return {String} string with no encoded URL component encoded sequences
*/
decodeQueryString(str) {
if (!str) {
return str;
}
const regexp = /\+/g;
return decodeURIComponent(str.replace(regexp, '%20'));
}
}
return PPBmixin;
});
})(window);
</script>