@cocreate/utils 1.42.0 → 1.42.2

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.
Files changed (65) hide show
  1. package/dist/cjs/ObjectId.js +54 -0
  2. package/dist/cjs/attributes.js +64 -0
  3. package/dist/cjs/checkValue.js +26 -0
  4. package/dist/cjs/clickedElement.js +48 -0
  5. package/dist/cjs/core.js +33 -0
  6. package/dist/cjs/createUpdate.js +188 -0
  7. package/dist/cjs/cssPath.js +60 -0
  8. package/dist/cjs/dataQuery.js +280 -0
  9. package/dist/cjs/dom.js +29 -0
  10. package/dist/cjs/domParser.js +44 -0
  11. package/dist/cjs/dotNotationToObject.js +103 -0
  12. package/dist/cjs/escapeHtml.js +25 -0
  13. package/dist/cjs/getRelativePath.js +39 -0
  14. package/dist/cjs/getValueFromObject.js +41 -0
  15. package/dist/cjs/index.js +112 -0
  16. package/dist/cjs/init-browser.js +4 -0
  17. package/dist/cjs/isValidDate.js +32 -0
  18. package/dist/cjs/objectToDotNotation.js +53 -0
  19. package/dist/cjs/objectToSearchParams.js +42 -0
  20. package/dist/cjs/operators copy.js +562 -0
  21. package/dist/cjs/operators.js +480 -0
  22. package/dist/cjs/parseTextToHtml.js +27 -0
  23. package/dist/cjs/queryElements.js +155 -0
  24. package/dist/cjs/safeParse.js +169 -0
  25. package/dist/cjs/uid.js +34 -0
  26. package/dist/esm/ObjectId.js +35 -0
  27. package/dist/esm/attributes.js +45 -0
  28. package/dist/esm/checkValue.js +7 -0
  29. package/dist/esm/clickedElement.js +29 -0
  30. package/dist/esm/core.js +14 -0
  31. package/dist/esm/createUpdate.js +185 -0
  32. package/dist/esm/cssPath.js +41 -0
  33. package/dist/esm/dataQuery.js +261 -0
  34. package/dist/esm/dom.js +10 -0
  35. package/dist/esm/domParser.js +25 -0
  36. package/dist/esm/dotNotationToObject.js +84 -0
  37. package/dist/esm/escapeHtml.js +6 -0
  38. package/dist/esm/getRelativePath.js +20 -0
  39. package/dist/esm/getValueFromObject.js +22 -0
  40. package/dist/esm/index.js +93 -0
  41. package/dist/esm/init-browser.js +4 -0
  42. package/dist/esm/isValidDate.js +13 -0
  43. package/dist/esm/objectToDotNotation.js +34 -0
  44. package/dist/esm/objectToSearchParams.js +23 -0
  45. package/dist/esm/operators copy.js +543 -0
  46. package/dist/esm/operators.js +461 -0
  47. package/dist/esm/package.json +3 -0
  48. package/dist/esm/parseTextToHtml.js +8 -0
  49. package/dist/esm/queryElements.js +136 -0
  50. package/dist/esm/safeParse.js +150 -0
  51. package/dist/esm/uid.js +15 -0
  52. package/package.json +9 -111
  53. package/src/index.js +3 -3
  54. package/src/operators copy.js +687 -0
  55. package/src/operators.js +407 -526
  56. package/.github/FUNDING.yml +0 -3
  57. package/.github/workflows/automated.yml +0 -44
  58. package/.github/workflows/manual.yml +0 -44
  59. package/CHANGELOG.md +0 -2075
  60. package/CoCreate.config.js +0 -23
  61. package/demo/index.html +0 -23
  62. package/docs/index.html +0 -331
  63. package/prettier.config.js +0 -16
  64. package/release.config.js +0 -22
  65. package/webpack.config.js +0 -65
@@ -0,0 +1,461 @@
1
+ import { ObjectId } from "./ObjectId.js";
2
+ import { uid } from "./uid.js";
3
+ import { queryElements } from "./queryElements.js";
4
+ import { getValueFromObject } from "./getValueFromObject.js";
5
+ const mathConstants = { PI: Math.PI, E: Math.E };
6
+ const mathFunctions = {
7
+ abs: Math.abs,
8
+ ceil: Math.ceil,
9
+ floor: Math.floor,
10
+ round: Math.round,
11
+ max: Math.max,
12
+ min: Math.min,
13
+ pow: Math.pow,
14
+ sqrt: Math.sqrt,
15
+ log: Math.log,
16
+ sin: Math.sin,
17
+ cos: Math.cos,
18
+ tan: Math.tan,
19
+ Number: (v) => Number(v)
20
+ // Explicit numeric casting
21
+ };
22
+ class Ref {
23
+ constructor(obj, prop) {
24
+ this.obj = obj;
25
+ this.prop = prop;
26
+ }
27
+ get() {
28
+ return this.obj ? this.obj[this.prop] : void 0;
29
+ }
30
+ set(val) {
31
+ if (this.obj) this.obj[this.prop] = val;
32
+ return val;
33
+ }
34
+ }
35
+ function unref(val) {
36
+ return val instanceof Ref ? val.get() : val;
37
+ }
38
+ function safeParse(expression, registry = /* @__PURE__ */ new Map()) {
39
+ if (typeof expression !== "string") return expression;
40
+ let currentExpr = expression.trim();
41
+ if (!currentExpr) return null;
42
+ const tokenizerRegex = /('[^']*'|"[^"]*"|\d+(?:\.\d+)?|>=|<=|===|!==|==|!=|&&|\|\||[a-zA-Z_][a-zA-Z0-9_\.]*|[\+\-\*\/\%\(\)\?\:\>\<\!\,\=])/g;
43
+ const tokens = currentExpr.match(tokenizerRegex) || [];
44
+ let pos = 0;
45
+ function peek() {
46
+ return tokens[pos];
47
+ }
48
+ function consume() {
49
+ return tokens[pos++];
50
+ }
51
+ function parse() {
52
+ return parseAssignment();
53
+ }
54
+ function parseAssignment() {
55
+ let left = parseTernary();
56
+ if (peek() === "=") {
57
+ consume();
58
+ let right = unref(parseAssignment());
59
+ if (left instanceof Ref) {
60
+ return left.set(right);
61
+ }
62
+ return right;
63
+ }
64
+ return left;
65
+ }
66
+ function parseTernary() {
67
+ let left = parseLogical();
68
+ if (peek() === "?") {
69
+ consume();
70
+ let trueExpr = parseTernary();
71
+ if (peek() === ":") {
72
+ consume();
73
+ let falseExpr = parseTernary();
74
+ return unref(left) ? unref(trueExpr) : unref(falseExpr);
75
+ }
76
+ }
77
+ return left;
78
+ }
79
+ function parseLogical() {
80
+ let left = parseComparison();
81
+ while (peek() === "&&" || peek() === "||") {
82
+ let op = consume();
83
+ let right = parseComparison();
84
+ if (op === "&&") left = unref(left) && unref(right);
85
+ if (op === "||") left = unref(left) || unref(right);
86
+ }
87
+ return left;
88
+ }
89
+ function parseComparison() {
90
+ let left = parseAdditive();
91
+ while ([">", "<", ">=", "<=", "===", "!==", "==", "!="].includes(peek())) {
92
+ let op = consume();
93
+ let right = parseAdditive();
94
+ let l = unref(left), r = unref(right);
95
+ if (op === ">") left = l > r;
96
+ if (op === "<") left = l < r;
97
+ if (op === ">=") left = l >= r;
98
+ if (op === "<=") left = l <= r;
99
+ if (op === "===") left = l === r;
100
+ if (op === "!==") left = l !== r;
101
+ if (op === "==") left = l == r;
102
+ if (op === "!=") left = l != r;
103
+ }
104
+ return left;
105
+ }
106
+ function parseAdditive() {
107
+ let left = parseMultiplicative();
108
+ while (["+", "-"].includes(peek())) {
109
+ let op = consume();
110
+ let right = parseMultiplicative();
111
+ if (op === "+") left = unref(left) + unref(right);
112
+ if (op === "-") left = unref(left) - unref(right);
113
+ }
114
+ return left;
115
+ }
116
+ function parseMultiplicative() {
117
+ let left = parsePrimary();
118
+ while (["*", "/", "%"].includes(peek())) {
119
+ let op = consume();
120
+ let right = parsePrimary();
121
+ if (op === "*") left = unref(left) * unref(right);
122
+ if (op === "/") left = unref(left) / unref(right);
123
+ if (op === "%") left = unref(left) % unref(right);
124
+ }
125
+ return left;
126
+ }
127
+ function parsePrimary() {
128
+ let token = consume();
129
+ if (!token) return void 0;
130
+ if (/^\d/.test(token)) return parseFloat(token);
131
+ if (token.startsWith("'") || token.startsWith('"')) {
132
+ return token.slice(1, -1);
133
+ }
134
+ if (token === "true") return true;
135
+ if (token === "false") return false;
136
+ if (token === "(") {
137
+ let expr = unref(parse());
138
+ if (peek() === ")") consume();
139
+ return expr;
140
+ }
141
+ if (token === "-") return -unref(parsePrimary());
142
+ if (token === "!") return !unref(parsePrimary());
143
+ if (mathConstants.hasOwnProperty(token)) return mathConstants[token];
144
+ if (peek() === "(" && mathFunctions.hasOwnProperty(token)) {
145
+ consume();
146
+ let args = [];
147
+ if (peek() !== ")") {
148
+ args.push(unref(parse()));
149
+ while (peek() === ",") {
150
+ consume();
151
+ args.push(unref(parse()));
152
+ }
153
+ }
154
+ if (peek() === ")") consume();
155
+ return mathFunctions[token](...args);
156
+ }
157
+ let path = token.split(".");
158
+ let baseToken = path[0];
159
+ let val;
160
+ if (registry.has(baseToken)) {
161
+ val = registry.get(baseToken);
162
+ } else if (typeof window !== "undefined" && window[baseToken]) {
163
+ val = window[baseToken];
164
+ } else {
165
+ val = void 0;
166
+ }
167
+ if (path.length === 1) return val;
168
+ for (let i = 1; i < path.length - 1; i++) {
169
+ if (val !== null && val !== void 0) {
170
+ val = val[path[i]];
171
+ } else {
172
+ return void 0;
173
+ }
174
+ }
175
+ return new Ref(val, path[path.length - 1]);
176
+ }
177
+ try {
178
+ const result = parse();
179
+ return unref(result);
180
+ } catch (error) {
181
+ console.warn(`safeParse error: ${error.message} (Expr: "${expression}")`, error);
182
+ return null;
183
+ }
184
+ }
185
+ const customOperators = new Map(
186
+ Object.entries({
187
+ $organization_id: () => localStorage.getItem("organization_id"),
188
+ $user_id: () => localStorage.getItem("user_id"),
189
+ $clientId: () => localStorage.getItem("clientId"),
190
+ $session_id: () => localStorage.getItem("session_id"),
191
+ $this: (element) => element,
192
+ $value: (element) => element.getValue() || "",
193
+ $innerWidth: () => window.innerWidth,
194
+ $innerHeight: () => window.innerHeight,
195
+ $href: () => window.location.href.replace(/\/$/, ""),
196
+ $origin: () => window.location.origin,
197
+ $protocol: () => window.location.protocol,
198
+ $hostname: () => window.location.hostname,
199
+ $host: () => window.location.host,
200
+ $port: () => window.location.port,
201
+ $pathname: () => window.location.pathname.replace(/\/$/, ""),
202
+ $hash: () => window.location.hash,
203
+ $subdomain: () => getSubdomain() || "",
204
+ $object_id: () => ObjectId().toString(),
205
+ "ObjectId()": () => ObjectId().toString(),
206
+ // Unwrap query results if only one element is found
207
+ $query: (element, args) => {
208
+ const results = queryElements({ element, selector: args });
209
+ return results.length === 1 ? results[0] : results;
210
+ },
211
+ $eval: (element, args, context) => safeParse(args, context.registry),
212
+ $relativePath: () => {
213
+ let currentPath = window.location.pathname.replace(/\/[^\/]*$/, "");
214
+ let depth = currentPath.split("/").filter(Boolean).length;
215
+ return depth > 0 ? "../".repeat(depth) : "./";
216
+ },
217
+ $path: () => {
218
+ let path = window.location.pathname;
219
+ if (path.split("/").pop().includes(".")) path = path.replace(/\/[^\/]+$/, "/");
220
+ return path === "/" ? "" : path;
221
+ },
222
+ $param: (element, args) => args,
223
+ $getObjectValue: (element, args) => {
224
+ if (Array.isArray(args) && args.length >= 2) return getValueFromObject(args[0], args[1]);
225
+ return "";
226
+ },
227
+ $setValue: (element, args) => element.setValue(...args) || "",
228
+ $true: () => true,
229
+ $false: () => false,
230
+ $parse: (element, args) => {
231
+ let value = args || "";
232
+ try {
233
+ return JSON.parse(value);
234
+ } catch (e) {
235
+ return value;
236
+ }
237
+ },
238
+ $numberFormat: (element, args) => {
239
+ let number = parseFloat(args[0]);
240
+ if (!Array.isArray(args)) args = [args];
241
+ const locale = args[0] || void 0;
242
+ const options = args[1] || {};
243
+ const numCandidate = args[2] !== void 0 ? args[2] : args[0];
244
+ number = parseFloat(numCandidate);
245
+ if (isNaN(number)) return String(numCandidate != null ? numCandidate : "");
246
+ return new Intl.NumberFormat(locale, options).format(number);
247
+ },
248
+ $uid: (element, args) => uid(args[0]) || ""
249
+ })
250
+ );
251
+ const isConstructor = (func, name) => {
252
+ try {
253
+ if (typeof func !== "function") return false;
254
+ if (/^\s*class\s+/.test(func.toString())) return true;
255
+ if (!func.prototype) return false;
256
+ const n = name || func.name;
257
+ if (n && /^[A-Z]/.test(n)) return true;
258
+ } catch (e) {
259
+ }
260
+ return false;
261
+ };
262
+ const findBareOperatorInPath = (path) => {
263
+ const trimmedPath = path.trim();
264
+ const match = trimmedPath.match(/^(\$[\w\-]+)/);
265
+ if (match) {
266
+ const key = match[1];
267
+ const remaining = trimmedPath.substring(key.length);
268
+ if (remaining.length === 0 || /^\s|\[|\./.test(remaining)) return key;
269
+ }
270
+ return null;
271
+ };
272
+ const findInnermostFunctionCall = (expression) => {
273
+ let balance = 0, deepestStart = -1, deepestEnd = -1, deepestBalance = -1;
274
+ let inSingleQuote = false, inDoubleQuote = false;
275
+ for (let i = 0; i < expression.length; i++) {
276
+ const char = expression[i];
277
+ if (char === '"' && !inSingleQuote) {
278
+ inDoubleQuote = !inDoubleQuote;
279
+ continue;
280
+ } else if (char === "'" && !inDoubleQuote) {
281
+ inSingleQuote = !inDoubleQuote;
282
+ continue;
283
+ }
284
+ if (inSingleQuote || inDoubleQuote) continue;
285
+ if (char === "(") {
286
+ balance++;
287
+ if (balance > deepestBalance) {
288
+ deepestBalance = balance;
289
+ deepestStart = i;
290
+ deepestEnd = -1;
291
+ }
292
+ } else if (char === ")") {
293
+ if (balance === deepestBalance) deepestEnd = i;
294
+ balance--;
295
+ }
296
+ }
297
+ if (deepestStart === -1 || deepestEnd === -1 || deepestEnd <= deepestStart) return null;
298
+ const rawArgs = expression.substring(deepestStart + 1, deepestEnd).trim();
299
+ let operatorStart = -1, nonWhitespaceFound = false;
300
+ for (let i = deepestStart - 1; i >= 0; i--) {
301
+ const char = expression[i];
302
+ if (!nonWhitespaceFound) {
303
+ if (/\s/.test(char)) continue;
304
+ nonWhitespaceFound = true;
305
+ }
306
+ if (!/[\w\-\$]/.test(char)) {
307
+ operatorStart = i + 1;
308
+ break;
309
+ }
310
+ operatorStart = i;
311
+ }
312
+ if (operatorStart === -1) operatorStart = 0;
313
+ const operatorNameCandidate = expression.substring(operatorStart, deepestStart).trim();
314
+ if (/^\$[\w\-]+$/.test(operatorNameCandidate) || customOperators.has(operatorNameCandidate)) {
315
+ return { operator: operatorNameCandidate, args: rawArgs, fullMatch: expression.substring(operatorStart, deepestEnd + 1) };
316
+ }
317
+ return null;
318
+ };
319
+ const findInnermostOperator = (expression) => {
320
+ function stripParentheses(str) {
321
+ let result = str;
322
+ if (result.startsWith("(")) result = result.substring(1);
323
+ if (result.endsWith(")")) result = result.substring(0, result.length - 1);
324
+ return result;
325
+ }
326
+ const functionCall = findInnermostFunctionCall(expression);
327
+ if (functionCall) return { operator: functionCall.operator, args: stripParentheses(functionCall.args), rawContent: functionCall.args, fullMatch: functionCall.fullMatch };
328
+ const rawContent = expression.trim(), innermostOperator = findBareOperatorInPath(rawContent);
329
+ if (innermostOperator) return { operator: innermostOperator, args: stripParentheses(rawContent.substring(innermostOperator.length).trim()), rawContent };
330
+ return { operator: null, args: stripParentheses(rawContent), rawContent };
331
+ };
332
+ function processOperators(element, value, exclude = [], parent, params = [], objectRegistry = /* @__PURE__ */ new Map()) {
333
+ if (typeof value !== "string" || !value.includes("$") && !value.includes("ObjectId()")) return value;
334
+ let processedValue = value, hasPromise = false, unresolvedTokens = /* @__PURE__ */ new Map();
335
+ while (processedValue.includes("$") || processedValue.includes("ObjectId()")) {
336
+ const paramMatch = processedValue.match(/^\$\$PARAM_(\d+)\$\$/);
337
+ if (paramMatch && Array.isArray(params) && params.length > 0) {
338
+ const index = parseInt(paramMatch[1], 10);
339
+ if (index < params.length) {
340
+ processedValue = processedValue.replace(paramMatch[0], params[index]);
341
+ continue;
342
+ }
343
+ }
344
+ const { operator, args, rawContent, fullMatch } = findInnermostOperator(processedValue);
345
+ if (!operator || operator === "$param" && !args) break;
346
+ const textToReplace = fullMatch || rawContent;
347
+ if (exclude.includes(operator)) {
348
+ const token = `__UNRESOLVED_${unresolvedTokens.size}__`;
349
+ unresolvedTokens.set(token, textToReplace);
350
+ processedValue = processedValue.replace(textToReplace, token);
351
+ continue;
352
+ }
353
+ let resolvedValue = resolveOperator(element, operator, args, parent, params, objectRegistry);
354
+ if (resolvedValue === void 0) {
355
+ const token = `__UNRESOLVED_${unresolvedTokens.size}__`;
356
+ unresolvedTokens.set(token, textToReplace);
357
+ processedValue = processedValue.replace(textToReplace, token);
358
+ continue;
359
+ }
360
+ if (resolvedValue instanceof Promise) {
361
+ const paramIndex = params.length;
362
+ params.push(resolvedValue);
363
+ processedValue = processedValue.replace(textToReplace, `$$PARAM_${paramIndex}$$`);
364
+ hasPromise = true;
365
+ break;
366
+ }
367
+ if (params.some((p) => p instanceof Promise)) {
368
+ hasPromise = true;
369
+ break;
370
+ }
371
+ let replacement = "";
372
+ if (operator === "$param") params.push(resolvedValue);
373
+ else if (resolvedValue !== null && (typeof resolvedValue === "object" || typeof resolvedValue === "function")) {
374
+ const token = `__OBJ_${objectRegistry.size}__`;
375
+ objectRegistry.set(token, resolvedValue);
376
+ replacement = token;
377
+ } else replacement = resolvedValue != null ? resolvedValue : "";
378
+ if (processedValue === textToReplace) {
379
+ processedValue = replacement;
380
+ break;
381
+ }
382
+ processedValue = processedValue.replace(textToReplace, replacement);
383
+ }
384
+ for (const [token, originalText] of unresolvedTokens.entries()) processedValue = processedValue.replace(token, originalText);
385
+ if (typeof processedValue === "string") {
386
+ const exactMatch = processedValue.match(/^__OBJ_(\d+)__$/);
387
+ if (exactMatch && objectRegistry.has(processedValue)) processedValue = objectRegistry.get(processedValue);
388
+ }
389
+ if (hasPromise) return { value: processedValue, params, objectRegistry };
390
+ return processedValue;
391
+ }
392
+ async function processOperatorsAsync(element, value, exclude = [], parent, params = [], objectRegistry = /* @__PURE__ */ new Map()) {
393
+ let result = processOperators(element, value, exclude, parent, params, objectRegistry);
394
+ while (typeof result === "object" && result.params) {
395
+ const resolvedParams = await Promise.all(result.params);
396
+ result = processOperators(element, result.value, exclude, parent, resolvedParams, result.objectRegistry || objectRegistry);
397
+ }
398
+ return result;
399
+ }
400
+ function resolveOperator(element, operator, args, parent, params, objectRegistry) {
401
+ if (params.some((p) => p instanceof Promise)) return "";
402
+ if (args && typeof args === "string" && args.includes("$")) {
403
+ args = processOperators(element, args, [], operator, params, objectRegistry);
404
+ }
405
+ let targetElements = element ? [element] : [];
406
+ if (args && typeof args === "string") {
407
+ const objMatch = args.match(/^__OBJ_(\d+)__$/);
408
+ if (objMatch && objectRegistry.has(args)) {
409
+ targetElements = [objectRegistry.get(args)];
410
+ } else if (!customOperators.has(operator)) {
411
+ targetElements = queryElements({ element, selector: args });
412
+ if (!targetElements.length) return void 0;
413
+ }
414
+ }
415
+ let value = processValues(targetElements, operator, args, parent, objectRegistry);
416
+ if (value && typeof value === "string" && value.includes("$")) {
417
+ value = processOperators(element, value, [], parent, params, objectRegistry);
418
+ }
419
+ return value;
420
+ }
421
+ function processValues(elements, operator, args, parent, objectRegistry) {
422
+ let customOp = customOperators.get(operator);
423
+ let aggregatedString = "";
424
+ let hasValidProperty = customOp ? true : false;
425
+ const context = { registry: objectRegistry, element: elements[0] };
426
+ for (const el of elements) {
427
+ if (!el) continue;
428
+ let rawValue = customOp;
429
+ const propName = customOp ? null : operator.substring(1);
430
+ if (!customOp) {
431
+ if (propName in el) {
432
+ hasValidProperty = true;
433
+ rawValue = el[propName];
434
+ } else continue;
435
+ }
436
+ if (typeof rawValue === "function") {
437
+ if (customOp) rawValue = Array.isArray(args) ? rawValue(el, ...args, context) : rawValue(el, args, context);
438
+ else {
439
+ if (isConstructor(rawValue, propName)) rawValue = Array.isArray(args) ? new rawValue(...args) : new rawValue(args);
440
+ else rawValue = Array.isArray(args) ? rawValue.apply(el, args) : rawValue.call(el, args);
441
+ }
442
+ }
443
+ if (parent === "$param") {
444
+ if (rawValue !== void 0 && rawValue !== null) return rawValue;
445
+ } else {
446
+ if (rawValue instanceof Promise || typeof rawValue === "object" && rawValue !== null || typeof rawValue === "function") return rawValue;
447
+ aggregatedString += String(rawValue != null ? rawValue : "");
448
+ }
449
+ }
450
+ return hasValidProperty ? aggregatedString : void 0;
451
+ }
452
+ function getSubdomain() {
453
+ const hostname = window.location.hostname, parts = hostname.split(".");
454
+ if (parts.length > 2 && isNaN(parseInt(parts[parts.length - 1]))) return parts.slice(0, parts.length - 2).join(".");
455
+ return null;
456
+ }
457
+ export {
458
+ customOperators,
459
+ processOperators,
460
+ processOperatorsAsync
461
+ };
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,8 @@
1
+ function parseTextToHtml(text) {
2
+ let doc = new DOMParser().parseFromString(text, "text/html");
3
+ if (doc.head.children[0]) return doc.head.children[0];
4
+ else return doc.body.children[0];
5
+ }
6
+ export {
7
+ parseTextToHtml
8
+ };
@@ -0,0 +1,136 @@
1
+ const queryTypes = [
2
+ "$closest",
3
+ "$parent",
4
+ "$next",
5
+ "$previous",
6
+ "$document",
7
+ "$frame",
8
+ "$top"
9
+ ];
10
+ const regexPatternString = `(?:${queryTypes.map((type) => type.replace("$", "\\$")).join("|")})`;
11
+ const queryTypesRegex = new RegExp(regexPatternString);
12
+ const mediaRanges = {
13
+ xs: [0, 575],
14
+ sm: [576, 768],
15
+ md: [769, 992],
16
+ lg: [993, 1200],
17
+ xl: [1201, 0]
18
+ };
19
+ function checkMediaQueries(selector) {
20
+ if (selector && selector.includes("@")) {
21
+ const viewportWidth = window.innerWidth;
22
+ let mediaViewport = false;
23
+ let screenSizes = selector.split("@");
24
+ selector = screenSizes.shift();
25
+ for (let screenSize of screenSizes) {
26
+ if (mediaRanges.hasOwnProperty(screenSize)) {
27
+ const [minWidth, maxWidth] = mediaRanges[screenSize];
28
+ if (viewportWidth >= minWidth && viewportWidth <= maxWidth) {
29
+ mediaViewport = true;
30
+ break;
31
+ }
32
+ }
33
+ }
34
+ if (!mediaViewport) return false;
35
+ }
36
+ return selector;
37
+ }
38
+ function queryType(element, type) {
39
+ if (!element) return null;
40
+ switch (type) {
41
+ case "$top":
42
+ return window.top.document;
43
+ case "$frame":
44
+ if (element.nodeType === 9) return window.frameElement;
45
+ return element;
46
+ case "$document":
47
+ return element.nodeType === 9 ? element : element.ownerDocument;
48
+ case "$closest":
49
+ return element.nodeType === 9 ? element : element.ownerDocument;
50
+ case "$parent":
51
+ if (element.nodeType === 9) {
52
+ return element.defaultView !== window.top ? element.defaultView.parent.document : null;
53
+ }
54
+ return element.parentElement;
55
+ case "$next":
56
+ return element.nextElementSibling;
57
+ case "$previous":
58
+ return element.previousElementSibling;
59
+ default:
60
+ return null;
61
+ }
62
+ }
63
+ function querySelector(element, selector) {
64
+ if (!element) return null;
65
+ return selector.endsWith("[]") ? element.querySelectorAll(selector.slice(0, -2)) : element.querySelector(selector);
66
+ }
67
+ function queryElements({ element = document, prefix, selector }) {
68
+ try {
69
+ let elements = /* @__PURE__ */ new Set();
70
+ if (!selector && element.nodeType === 1) {
71
+ if (!prefix) {
72
+ for (let attr of element.attributes) {
73
+ if (attr.name.endsWith("-query") || attr.name.endsWith(".query")) {
74
+ prefix = attr.name.slice(0, -6);
75
+ }
76
+ }
77
+ if (!prefix) return [];
78
+ }
79
+ selector = element.getAttribute(prefix + "-query") || element.getAttribute(prefix + ".query");
80
+ if (!selector) return [];
81
+ }
82
+ let selectors = selector.split(/,(?![^()\[\]]*[)\]])/g);
83
+ for (let i = 0; i < selectors.length; i++) {
84
+ if (!selectors[i]) continue;
85
+ let queriedElement = element;
86
+ if (selectors[i].includes("@")) {
87
+ selectors[i] = checkMediaQueries(selectors[i]);
88
+ if (selectors[i] === false) continue;
89
+ }
90
+ let remainingSelector = selectors[i].trim();
91
+ let match;
92
+ while ((match = queryTypesRegex.exec(remainingSelector)) !== null) {
93
+ const matchIndex = match.index;
94
+ const operator = match[0];
95
+ const part = remainingSelector.substring(0, matchIndex).trim().replace(/,$/, "");
96
+ if (part) {
97
+ queriedElement = querySelector(queriedElement, part);
98
+ if (!queriedElement) break;
99
+ }
100
+ remainingSelector = remainingSelector.substring(matchIndex + operator.length).trim();
101
+ if (operator === "$closest") {
102
+ let [closest, remaining = ""] = remainingSelector.split(/\s+/, 2);
103
+ queriedElement = queriedElement.closest(closest);
104
+ remainingSelector = remaining.trim();
105
+ } else {
106
+ queriedElement = queryType(queriedElement, operator);
107
+ }
108
+ if (!queriedElement) break;
109
+ }
110
+ if (!queriedElement) continue;
111
+ if (remainingSelector) {
112
+ queriedElement = querySelector(queriedElement, remainingSelector);
113
+ }
114
+ if (Array.isArray(queriedElement) || queriedElement instanceof HTMLCollection || queriedElement instanceof NodeList) {
115
+ for (let el of queriedElement) {
116
+ if (el instanceof Element) {
117
+ elements.add(el);
118
+ }
119
+ }
120
+ } else if (queriedElement instanceof Element) {
121
+ elements.add(queriedElement);
122
+ }
123
+ }
124
+ return Array.from(elements);
125
+ } catch (e) {
126
+ console.error(
127
+ `CoCreate: Error in queryElements with selector: "${selector}".`,
128
+ e
129
+ );
130
+ return [];
131
+ }
132
+ }
133
+ export {
134
+ checkMediaQueries,
135
+ queryElements
136
+ };