@cocreate/element-prototype 1.27.0 → 1.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/getValue.js CHANGED
@@ -1,418 +1,419 @@
1
- const storage = new Map()
1
+ import utility from "./utility";
2
2
 
3
- HTMLElement.prototype.getValue = function () {
4
- let value = getValue(this)
5
- return value;
6
- };
7
-
8
- HTMLInputElement.prototype.getValue = function () {
9
- let value = getValue(this)
10
- return value;
11
- };
3
+ const storage = new Map();
12
4
 
13
- HTMLHeadingElement.prototype.getValue = function () {
14
- let value = getValue(this)
15
- return value;
5
+ HTMLElement.prototype.getValue = function () {
6
+ let value = getValue(this);
7
+ return value;
16
8
  };
17
9
 
18
10
  // TODO: check if using a a switch case will provide better performance
11
+ // return blobs for element.src and for link.href
12
+ // pass value type as a param
19
13
  const getValue = (element) => {
20
- let value = element.value || element.getAttribute('value') || "";
21
- if (element.hasAttribute('component') || element.hasAttribute('plugin') || element.type === 'file' || element.getAttribute('type') === 'file') {
22
- value = storage.get(element)
23
- storage.delete(element)
24
- return value
25
- }
26
-
27
- let prefix = element.getAttribute('value-prefix') || "";
28
- let suffix = element.getAttribute('value-suffix') || "";
29
- let valueType = element.getAttribute('value-type') || "";
30
-
31
- if (element.type === "checkbox") {
32
- let inputs = [element]
33
- let key = element.getAttribute('key');
34
- if (key)
35
- inputs = document.querySelectorAll(`input[type="${element.type}"][key="${key}"]`);
36
-
37
-
38
- if (inputs.length > 1) {
39
- value = [];
40
- inputs.forEach(el => {
41
- if (el.checked) {
42
- let checkedValue = el.value
43
- if (prefix || suffix)
44
- checkedValue = prefix + checkedValue + suffix;
45
-
46
- value.push(checkedValue);
47
- }
48
- });
49
- } else {
50
- if (element.checked) {
51
- if (element.hasAttribute('value'))
52
- value = element.value || true
53
- else
54
- value = true
55
- } else
56
- value = false
57
-
58
- }
59
- } else if (element.type === 'radio') {
60
- let key = element.getAttribute('key');
61
- value = document.querySelector(`input[key="${key}"]:checked`).value
62
- } else if (element.type === "number") {
63
- value = Number(value);
64
- } else if (element.type === 'range') {
65
- value = [Number(element.min), Number(element.value)];
66
- } else if (element.type === "password") {
67
- value = btoa(value || '');
68
- } else if (element.type === "email") {
69
- value = value.toLowerCase();
70
- } else if (element.type === "url") {
71
- // TODO: define attributes to return url parts
72
- // return as a string or an object of url parts
73
- } else if (element.tagName == "SELECT" && element.hasAttribute('multiple')) {
74
- let options = element.selectedOptions;
75
- value = [];
76
- for (let i = 0; i < options.length; i++) {
77
- let optionValue = options[i].value
78
- if (prefix || suffix)
79
- optionValue = prefix + optionValue + suffix;
80
- value.push(optionValue);
81
- }
82
- } else if (["time", "date", "datetime", "datetime-local"].includes(element.getAttribute('type'))) {
83
- if (value === '$now')
84
- value = new Date()
85
- else if (value)
86
- value = new Date(value)
87
-
88
- if (value) {
89
- if (!valueType)
90
- value = value.toISOString()
91
-
92
- if (element.type === 'time')
93
- // value = value.substring(11, 8) + 'Z';
94
- value = value.substring(11, 19) + 'Z';
95
-
96
- switch (valueType) {
97
- case 'getDayName':
98
- const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
99
- value = days[value.getDay()];
100
- break;
101
- case 'getMonthName':
102
- const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
103
- value = months[value.getMonth()];
104
- break;
105
- case 'toUnixTimestamp':
106
- value = Math.floor(value.getTime() / 1000);
107
- break;
108
- case 'toLocaleString':
109
- let locale = element.getAttribute('locale') || 'en-US'
110
- value = value[valueType](locale);
111
- break;
112
- default:
113
- if (typeof value[valueType] === 'function') {
114
- value = value[valueType]();
115
- } else {
116
- console.warn(`The method ${valueType} is not a function of Date object.`);
117
- }
118
- }
119
- }
120
- } else if (element.tagName == 'INPUT' || element.tagName == 'SELECT') {
121
- value = element.value;
122
- } else if (element.tagName == 'TEXTAREA') {
123
- if (element.hasAttribute('value'))
124
- value = element.getAttribute('value');
125
- else
126
- value = element.value;
127
- } else if (element.tagName === 'IFRAME') {
128
- value = element.srcdoc;
129
- } else if (element.hasAttribute('value')) {
130
- value = element.getAttribute('value');
131
- } else {
132
- let targetElement = element;
133
-
134
- // If value-exclude-selector exists, clone the element and remove the specified selectors
135
- const excludeSelector = element.getAttribute('value-remove-selector');
136
- if (excludeSelector) {
137
- targetElement = element.cloneNode(true);
138
-
139
- // Remove matching elements from the cloned element
140
- targetElement.querySelectorAll(excludeSelector).forEach(el => el.remove());
141
- }
142
-
143
- // Determine whether to use outerHTML, innerHTML, or innerText based on valueType
144
- if (valueType === 'text') {
145
- value = targetElement.innerText;
146
- } else if (valueType === 'outerHTML') {
147
- value = targetElement.outerHTML;
148
- } else {
149
- value = targetElement.innerHTML;
150
- }
151
- }
152
-
153
- if (valueType === 'boolean') {
154
- if (!value || value === 'fasle')
155
- return false
156
- else
157
- return true
158
- }
159
-
160
- if (value === '$organization_id')
161
- value = localStorage.getItem('organization_id')
162
- else if (value === '$user_id')
163
- value = localStorage.getItem('user_id')
164
- else if (value === '$clientId')
165
- value = localStorage.getItem('clientId')
166
- else if (value === '$session_id')
167
- value = localStorage.getItem('session_id')
168
- else if (typeof value === 'string') {
169
- if (value.startsWith('$search')) {
170
- const searchParams = new URLSearchParams(window.location.search);
171
- if (value.includes('.')) {
172
- value = searchParams.get(value.split('.')[1]);
173
- } else {
174
- const paramsObject = {};
175
-
176
- // Iterate over all key-value pairs and add them to the object
177
- for (const [key, value] of searchParams) {
178
- paramsObject[key] = value;
179
- }
180
- value = paramsObject
181
- }
182
-
183
- } else if ([
184
- '$href',
185
- '$origin',
186
- '$protocol',
187
- '$host',
188
- '$hostname',
189
- '$port',
190
- '$pathname',
191
- '$hash'
192
- ].includes(value)) {
193
- value = window.location[value.substring(1)]
194
- }
195
- }
196
-
197
- try {
198
-
199
- const attributes = element.attributes; // Get all attributes of the element
200
- const regexAttribute = [
201
- 'value-replace',
202
- 'value-replaceall',
203
- 'value-test',
204
- 'value-match',
205
- 'value-split',
206
- 'value-lastindex',
207
- 'value-search',
208
- 'value-exec'
209
- ];
210
- // Process each attribute in order
211
- for (let i = 0; i < attributes.length; i++) {
212
- if (value === null || value === undefined)
213
- break
214
-
215
- if (!regexAttribute.includes(attributes[i].name))
216
- continue
217
-
218
- let regexAttributeValue = attributes[i].value
219
-
220
- if (!regexAttributeValue)
221
- continue
222
-
223
- let { regex, replacement } = regexParser(regexAttributeValue);
224
-
225
- if (regex)
226
- regexAttributeValue = regex
227
-
228
- replacement = replacement || element.getAttribute('value-replacement') || "";
229
-
230
- switch (attributes[i].name) {
231
- case 'value-replace':
232
- value = value.replace(regexAttributeValue, replacement);
233
- break;
234
-
235
- case 'value-replaceall':
236
- value = value.replaceAll(regexAttributeValue, replacement);
237
- break;
238
-
239
- case 'value-test':
240
- value = regex.test(value);
241
- break;
242
-
243
- case 'value-match':
244
- const matches = value.match(regexAttributeValue);
245
- if (matches) {
246
- value = matches[1] || matches[0]; // Prioritize capturing group if available
247
- }
248
- break;
249
-
250
- case 'value-split':
251
- value = value.split(regexAttributeValue);
252
- break;
253
-
254
- case 'value-lastindex':
255
- regex.lastIndex = 0; // Ensure starting index is 0
256
- regex.test(value);
257
- value = regex.lastIndex;
258
- break;
259
-
260
- case 'value-search':
261
- value = value.search(regexAttributeValue);
262
- break;
263
-
264
- case 'value-exec':
265
- const execResult = regex.exec(value);
266
- if (execResult) {
267
- value = execResult[1] || execResult[2] || execResult[0]; // Prioritize capturing group if available
268
- } else {
269
- // value = null;
270
- }
271
- break;
272
-
273
- default:
274
- // Ignore other attributes
275
- break;
276
- }
277
- }
278
-
279
- } catch (error) {
280
- console.error('getValue() error:', error, element);
281
- }
282
-
283
- // TODO: encode and decode needs a method to prevent multiple encode of an already encoded value
284
- let encode = element.getAttribute('value-encode')
285
- if (encode)
286
- value = encodeValue(value, encode)
287
-
288
- let decode = element.getAttribute('value-decode')
289
- if (decode)
290
- value = decodeValue(value, decode)
291
-
292
- let lowercase = element.getAttribute('value-lowercase')
293
- if (lowercase || lowercase === '')
294
- value = value.toLowerCase()
295
- let uppercase = element.getAttribute('value-uppercase');
296
- if (uppercase || uppercase === '')
297
- value = value.toUpperCase()
298
-
299
- // Apply prefix and suffix first, before JSON parsing
300
- if (typeof value === 'string' || typeof value === 'number') {
301
- if (prefix || suffix) {
302
- value = prefix + value + suffix;
303
- }
304
- }
305
-
306
- // Handle JSON parsing for objects, arrays, or when valueType starts with 'array'
307
- if (value && (valueType === 'object' || valueType === 'json' || valueType.startsWith('array'))) {
308
- try {
309
- value = JSON.parse(value);
310
- } catch (error) {
311
- const jsonRegex = /(\{[\s\S]*\}|\[[\s\S]*\])/;
312
- const match = value.match(jsonRegex);
313
-
314
- if (match) {
315
- try {
316
- value = JSON.parse(match[0]);
317
- } catch (e) {
318
- console.error('Failed to parse JSON after regex extraction:', e);
319
- }
320
- } else {
321
- console.error('No valid JSON structure found in the string.');
322
- }
323
- }
324
- }
325
-
326
- // Now handle array-specific logic if valueType starts with 'array'
327
- if (valueType.startsWith('array')) {
328
- if (!Array.isArray(value)) {
329
- // If the parsed value is an object, apply array conversion based on operators
330
- if (typeof value === 'object') {
331
- if (valueType === 'array.$keys') {
332
- value = Object.keys(value);
333
- } else if (valueType === 'array.$values') {
334
- value = Object.values(value);
335
- } else if (valueType === 'array.$entries') {
336
- value = Object.entries(value);
337
- } else {
338
- // Default behavior: wrap the object in an array
339
- value = [value];
340
- }
341
- } else {
342
- // If it's not an object (i.e., a primitive), wrap the value in an array
343
- value = [value];
344
- }
345
- }
346
- }
347
-
348
- return value;
349
-
14
+ let value = element.value || element.getAttribute("value") || "";
15
+ if (
16
+ element.hasAttribute("component") ||
17
+ element.hasAttribute("plugin") ||
18
+ element.type === "file" ||
19
+ element.getAttribute("type") === "file"
20
+ ) {
21
+ value = storage.get(element);
22
+ storage.delete(element);
23
+ return value;
24
+ }
25
+
26
+ let prefix = element.getAttribute("value-prefix") || "";
27
+ let suffix = element.getAttribute("value-suffix") || "";
28
+ let valueType = element.getAttribute("value-type") || "";
29
+
30
+ if (element.type === "checkbox") {
31
+ let inputs = [element];
32
+ let key = element.getAttribute("key");
33
+ if (key)
34
+ inputs = document.querySelectorAll(
35
+ `input[type="${element.type}"][key="${key}"]`
36
+ );
37
+
38
+ if (inputs.length > 1) {
39
+ value = [];
40
+ inputs.forEach((el) => {
41
+ if (el.checked) {
42
+ let checkedValue = el.value;
43
+ if (prefix || suffix)
44
+ checkedValue = prefix + checkedValue + suffix;
45
+
46
+ value.push(checkedValue);
47
+ }
48
+ });
49
+ } else {
50
+ if (element.checked) {
51
+ if (element.hasAttribute("value"))
52
+ value = element.value || true;
53
+ else value = true;
54
+ } else value = false;
55
+ }
56
+ } else if (element.type === "radio") {
57
+ let key = element.getAttribute("key");
58
+ value = document.querySelector(`input[key="${key}"]:checked`).value;
59
+ } else if (element.type === "number") {
60
+ value = Number(value);
61
+ } else if (element.type === "range") {
62
+ if (Number(element.min))
63
+ value = [Number(element.min), Number(element.value)];
64
+ else value = Number(element.value);
65
+ } else if (element.type === "password") {
66
+ value = btoa(value || "");
67
+ } else if (element.type === "email") {
68
+ value = value.toLowerCase();
69
+ } else if (element.type === "url") {
70
+ // TODO: define attributes to return url parts
71
+ // return as a string or an object of url parts
72
+ } else if (
73
+ element.tagName == "SELECT" &&
74
+ element.hasAttribute("multiple")
75
+ ) {
76
+ let options = element.selectedOptions;
77
+ value = [];
78
+ for (let i = 0; i < options.length; i++) {
79
+ let optionValue = options[i].value;
80
+ if (prefix || suffix) optionValue = prefix + optionValue + suffix;
81
+ value.push(optionValue);
82
+ }
83
+ } else if (
84
+ ["time", "date", "datetime", "datetime-local"].includes(
85
+ element.getAttribute("type")
86
+ )
87
+ ) {
88
+ if (value === "$now") value = new Date();
89
+ else if (value) value = new Date(value);
90
+
91
+ if (value) {
92
+ if (!valueType) value = value.toISOString();
93
+
94
+ if (element.type === "time")
95
+ // value = value.substring(11, 8) + 'Z';
96
+ value = value.substring(11, 19) + "Z";
97
+
98
+ switch (valueType) {
99
+ case "getDayName":
100
+ const days = [
101
+ "Sunday",
102
+ "Monday",
103
+ "Tuesday",
104
+ "Wednesday",
105
+ "Thursday",
106
+ "Friday",
107
+ "Saturday"
108
+ ];
109
+ value = days[value.getDay()];
110
+ break;
111
+ case "getMonthName":
112
+ const months = [
113
+ "January",
114
+ "February",
115
+ "March",
116
+ "April",
117
+ "May",
118
+ "June",
119
+ "July",
120
+ "August",
121
+ "September",
122
+ "October",
123
+ "November",
124
+ "December"
125
+ ];
126
+ value = months[value.getMonth()];
127
+ break;
128
+ case "toUnixTimestamp":
129
+ value = Math.floor(value.getTime() / 1000);
130
+ break;
131
+ case "toLocaleString":
132
+ let locale = element.getAttribute("locale") || "en-US";
133
+ value = value[valueType](locale);
134
+ break;
135
+ default:
136
+ if (typeof value[valueType] === "function") {
137
+ value = value[valueType]();
138
+ } else {
139
+ console.warn(
140
+ `The method ${valueType} is not a function of Date object.`
141
+ );
142
+ }
143
+ }
144
+ }
145
+ } else if (element.tagName == "INPUT" || element.tagName == "SELECT") {
146
+ value = element.value;
147
+ } else if (element.tagName == "TEXTAREA") {
148
+ if (element.hasAttribute("value"))
149
+ value = element.getAttribute("value");
150
+ else value = element.value;
151
+ } else if (element.tagName === "IFRAME") {
152
+ value = element.srcdoc;
153
+ } else if (element.hasAttribute("value")) {
154
+ value = element.getAttribute("value");
155
+ } else {
156
+ let targetElement = element;
157
+
158
+ // If value-exclude-selector exists, clone the element and remove the specified selectors
159
+ const excludeSelector = element.getAttribute("value-remove-selector");
160
+ if (excludeSelector) {
161
+ targetElement = element.cloneNode(true);
162
+
163
+ // Remove matching elements from the cloned element
164
+ targetElement
165
+ .querySelectorAll(excludeSelector)
166
+ .forEach((el) => el.remove());
167
+ }
168
+
169
+ // Determine whether to use outerHTML, innerHTML, or innerText based on valueType
170
+ if (valueType === "text") {
171
+ value = targetElement.innerText;
172
+ } else if (valueType === "outerHTML") {
173
+ value = targetElement.outerHTML;
174
+ } else {
175
+ value = targetElement.innerHTML;
176
+ }
177
+ }
178
+
179
+ if (valueType === "boolean") {
180
+ if (!value || value === "fasle") return false;
181
+ else return true;
182
+ }
183
+
184
+ if (value === "$organization_id")
185
+ value = localStorage.getItem("organization_id");
186
+ else if (value === "$user_id") value = localStorage.getItem("user_id");
187
+ else if (value === "$clientId") value = localStorage.getItem("clientId");
188
+ else if (value === "$session_id")
189
+ value = localStorage.getItem("session_id");
190
+ else if (typeof value === "string" && value.includes("$")) {
191
+ value = utility.urlOperators(value);
192
+ }
193
+
194
+ try {
195
+ const attributes = element.attributes; // Get all attributes of the element
196
+ const regexAttribute = [
197
+ "value-replace",
198
+ "value-replaceall",
199
+ "value-test",
200
+ "value-match",
201
+ "value-split",
202
+ "value-lastindex",
203
+ "value-search",
204
+ "value-exec"
205
+ ];
206
+ // Process each attribute in order
207
+ for (let i = 0; i < attributes.length; i++) {
208
+ if (value === null || value === undefined) break;
209
+
210
+ if (!regexAttribute.includes(attributes[i].name)) continue;
211
+
212
+ let regexAttributeValue = attributes[i].value;
213
+
214
+ if (!regexAttributeValue) continue;
215
+
216
+ let { regex, replacement } = regexParser(regexAttributeValue);
217
+
218
+ if (regex) regexAttributeValue = regex;
219
+
220
+ replacement =
221
+ replacement || element.getAttribute("value-replacement") || "";
222
+
223
+ switch (attributes[i].name) {
224
+ case "value-replace":
225
+ value = value.replace(regexAttributeValue, replacement);
226
+ break;
227
+
228
+ case "value-replaceall":
229
+ value = value.replaceAll(regexAttributeValue, replacement);
230
+ break;
231
+
232
+ case "value-test":
233
+ value = regex.test(value);
234
+ break;
235
+
236
+ case "value-match":
237
+ const matches = value.match(regexAttributeValue);
238
+ if (matches) {
239
+ value = matches[1] || matches[0]; // Prioritize capturing group if available
240
+ }
241
+ break;
242
+
243
+ case "value-split":
244
+ value = value.split(regexAttributeValue);
245
+ break;
246
+
247
+ case "value-lastindex":
248
+ regex.lastIndex = 0; // Ensure starting index is 0
249
+ regex.test(value);
250
+ value = regex.lastIndex;
251
+ break;
252
+
253
+ case "value-search":
254
+ value = value.search(regexAttributeValue);
255
+ break;
256
+
257
+ case "value-exec":
258
+ const execResult = regex.exec(value);
259
+ if (execResult) {
260
+ value = execResult[1] || execResult[2] || execResult[0]; // Prioritize capturing group if available
261
+ } else {
262
+ // value = null;
263
+ }
264
+ break;
265
+
266
+ default:
267
+ // Ignore other attributes
268
+ break;
269
+ }
270
+ }
271
+ } catch (error) {
272
+ console.error("getValue() error:", error, element);
273
+ }
274
+
275
+ // TODO: encode and decode needs a method to prevent multiple encode of an already encoded value
276
+ let encode = element.getAttribute("value-encode");
277
+ if (encode) value = encodeValue(value, encode);
278
+
279
+ let decode = element.getAttribute("value-decode");
280
+ if (decode) value = decodeValue(value, decode);
281
+
282
+ let lowercase = element.getAttribute("value-lowercase");
283
+ if (lowercase || lowercase === "") value = value.toLowerCase();
284
+ let uppercase = element.getAttribute("value-uppercase");
285
+ if (uppercase || uppercase === "") value = value.toUpperCase();
286
+
287
+ // Apply prefix and suffix first, before JSON parsing
288
+ if (typeof value === "string" || typeof value === "number") {
289
+ if (prefix || suffix) {
290
+ value = prefix + value + suffix;
291
+ }
292
+ }
293
+
294
+ // Handle JSON parsing for objects, arrays, or when valueType starts with 'array'
295
+ if (
296
+ value &&
297
+ (valueType === "object" ||
298
+ valueType === "json" ||
299
+ valueType.startsWith("array"))
300
+ ) {
301
+ try {
302
+ value = JSON.parse(value);
303
+ } catch (error) {
304
+ const jsonRegex = /(\{[\s\S]*\}|\[[\s\S]*\])/;
305
+ const match = value.match(jsonRegex);
306
+
307
+ if (match) {
308
+ try {
309
+ value = JSON.parse(match[0]);
310
+ } catch (e) {
311
+ console.error(
312
+ "Failed to parse JSON after regex extraction:",
313
+ e
314
+ );
315
+ }
316
+ } else {
317
+ console.error("No valid JSON structure found in the string.");
318
+ }
319
+ }
320
+ }
321
+
322
+ // Now handle array-specific logic if valueType starts with 'array'
323
+ if (valueType.startsWith("array")) {
324
+ if (!Array.isArray(value)) {
325
+ // If the parsed value is an object, apply array conversion based on operators
326
+ if (typeof value === "object") {
327
+ if (valueType === "array.$keys") {
328
+ value = Object.keys(value);
329
+ } else if (valueType === "array.$values") {
330
+ value = Object.values(value);
331
+ } else if (valueType === "array.$entries") {
332
+ value = Object.entries(value);
333
+ } else {
334
+ // Default behavior: wrap the object in an array
335
+ value = [value];
336
+ }
337
+ } else {
338
+ // If it's not an object (i.e., a primitive), wrap the value in an array
339
+ value = [value];
340
+ }
341
+ }
342
+ }
343
+
344
+ return value;
350
345
  };
351
346
 
352
347
  function regexParser(string) {
353
- let regex, replacement;
354
- let regexMatch = string.match(/\/(.+)\/([gimuy]*)/);
355
- if (regexMatch) {
356
- regex = new RegExp(regexMatch[1], regexMatch[2]);
357
- const splitReplace = string.split(', ');
358
- replacement = splitReplace.length > 1 ? splitReplace[1].slice(1, -1) : "";
359
- }
360
-
361
- return { regex, replacement }
348
+ let regex, replacement;
349
+ // Match a regex pattern enclosed by delimiters or a bare regex string
350
+ // let regexMatch = string.match(/^\/(.+)\/([gimuy]*)$/) || [null, string, ""];
351
+
352
+ let regexMatch = string.match(/\/(.+)\/([gimuy]*)/);
353
+ if (regexMatch) {
354
+ regex = new RegExp(regexMatch[1], regexMatch[2]);
355
+ const splitReplace = string.split(", ");
356
+ replacement =
357
+ splitReplace.length > 1 ? splitReplace[1].slice(1, -1) : "";
358
+ }
359
+
360
+ return { regex, replacement };
362
361
  }
363
362
 
364
363
  function encodeValue(value, encodingType) {
365
- switch (encodingType.toLowerCase()) {
366
- case 'url':
367
- case 'uri':
368
- return encodeURI(value.replace(/ /g, "%20"));
369
- case 'uri-component':
370
- return encodeURIComponent(value.replace(/ /g, "%20"));
371
- case 'base64':
372
- case 'atob':
373
- const encoder = new TextEncoder();
374
- const uint8Array = encoder.encode(value);
375
- return btoa(String.fromCharCode(...uint8Array));
376
- case 'html-entities':
377
- return value.replace(/[\u00A0-\u9999<>\&]/g, (i) => {
378
- return `&#${i.charCodeAt(0)};`;
379
- });
380
- case 'json':
381
- return JSON.stringify(value);
382
- default:
383
- throw new Error(`Unsupported encoding type: ${encodingType}`);
384
- }
364
+ switch (encodingType.toLowerCase()) {
365
+ case "url":
366
+ case "uri":
367
+ return encodeURI(value.replace(/ /g, "%20"));
368
+ case "uri-component":
369
+ return encodeURIComponent(value.replace(/ /g, "%20"));
370
+ case "base64":
371
+ case "atob":
372
+ const encoder = new TextEncoder();
373
+ const uint8Array = encoder.encode(value);
374
+ return btoa(String.fromCharCode(...uint8Array));
375
+ case "html-entities":
376
+ return value.replace(/[\u00A0-\u9999<>\&]/g, (i) => {
377
+ return `&#${i.charCodeAt(0)};`;
378
+ });
379
+ case "json":
380
+ return JSON.stringify(value);
381
+ default:
382
+ throw new Error(`Unsupported encoding type: ${encodingType}`);
383
+ }
385
384
  }
386
385
 
387
386
  function decodeValue(value, decodingType) {
388
- switch (decodingType.toLowerCase()) {
389
- case 'url':
390
- case 'uri':
391
- return decodeURI(value);
392
- case 'uri-component':
393
- return decodeURIComponent(value);
394
- case 'base64':
395
- case 'btoa': // New case for Base64 decoding (alias for 'base64')
396
- try {
397
- const decodedArray = Uint8Array.from(atob(value), (c) => c.charCodeAt(0));
398
- const decoder = new TextDecoder();
399
- return decoder.decode(decodedArray);
400
- } catch (error) {
401
- throw new Error(`Invalid Base64 string: ${error.message}`);
402
- }
403
- case 'html-entities':
404
- const tempElement = document.createElement('div');
405
- tempElement.innerHTML = value;
406
- return tempElement.textContent;
407
- case 'json':
408
- try {
409
- return JSON.parse(value);
410
- } catch (error) {
411
- throw new Error(`Invalid JSON string: ${error.message}`);
412
- }
413
- default:
414
- throw new Error(`Unsupported decoding type: ${decodingType}`);
415
- }
387
+ switch (decodingType.toLowerCase()) {
388
+ case "url":
389
+ case "uri":
390
+ return decodeURI(value);
391
+ case "uri-component":
392
+ return decodeURIComponent(value);
393
+ case "base64":
394
+ case "btoa": // New case for Base64 decoding (alias for 'base64')
395
+ try {
396
+ const decodedArray = Uint8Array.from(atob(value), (c) =>
397
+ c.charCodeAt(0)
398
+ );
399
+ const decoder = new TextDecoder();
400
+ return decoder.decode(decodedArray);
401
+ } catch (error) {
402
+ throw new Error(`Invalid Base64 string: ${error.message}`);
403
+ }
404
+ case "html-entities":
405
+ const tempElement = document.createElement("div");
406
+ tempElement.innerHTML = value;
407
+ return tempElement.textContent;
408
+ case "json":
409
+ try {
410
+ return JSON.parse(value);
411
+ } catch (error) {
412
+ throw new Error(`Invalid JSON string: ${error.message}`);
413
+ }
414
+ default:
415
+ throw new Error(`Unsupported decoding type: ${decodingType}`);
416
+ }
416
417
  }
417
418
 
418
419
  export { getValue, storage };