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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
export class MiniClassList {
  private values = new Set<string>();

  add(...tokens: string[]): void {
    tokens.forEach((token) => this.values.add(token));
  }

  remove(...tokens: string[]): void {
    tokens.forEach((token) => this.values.delete(token));
  }

  contains(token: string): boolean {
    return this.values.has(token);
  }

  toggle(token: string, force?: boolean): boolean {
    if (force === true) {
      this.values.add(token);
      return true;
    }
    if (force === false) {
      this.values.delete(token);
      return false;
    }
    if (this.values.has(token)) {
      this.values.delete(token);
      return false;
    }
    this.values.add(token);
    return true;
  }

  setFromString(value: string): void {
    this.values = new Set(String(value).split(/\s+/).filter(Boolean));
  }

  toString(): string {
    return Array.from(this.values).join(' ');
  }
}

export class MiniNode extends EventTarget {
  static readonly ELEMENT_NODE = 1;
  static readonly TEXT_NODE = 3;
  static readonly DOCUMENT_FRAGMENT_NODE = 11;

  childNodes: Array<MiniElement | MiniText | MiniDocumentFragment> = [];
  parentNode: MiniNode | null = null;
  parentElement: MiniElement | null = null;

  appendChild<T extends MiniElement | MiniText | MiniDocumentFragment>(child: T): T {
    if (child instanceof MiniDocumentFragment) {
      const children = [...child.childNodes];
      children.forEach((node) => this.appendChild(node));
      return child;
    }
    if (child.parentNode) {
      child.parentNode.removeChild(child);
    }
    child.parentNode = this;
    child.parentElement = this instanceof MiniElement ? this : null;
    this.childNodes.push(child);
    return child;
  }

  append(...children: Array<MiniElement | MiniText | MiniDocumentFragment | string | number | null | undefined>): void {
    children.forEach((child) => {
      if (child == null) return;
      if (typeof child === 'string' || typeof child === 'number') {
        this.appendChild(new MiniText(child));
        return;
      }
      this.appendChild(child);
    });
  }

  removeChild<T extends MiniElement | MiniText | MiniDocumentFragment>(child: T): T {
    const index = this.childNodes.indexOf(child);
    if (index >= 0) {
      this.childNodes.splice(index, 1);
      child.parentNode = null;
      child.parentElement = null;
    }
    return child;
  }

  insertBefore<T extends MiniElement | MiniText | MiniDocumentFragment>(child: T, referenceNode: MiniElement | MiniText | MiniDocumentFragment | null): T {
    if (referenceNode == null) {
      return this.appendChild(child);
    }
    if (child.parentNode) {
      child.parentNode.removeChild(child);
    }
    const index = this.childNodes.indexOf(referenceNode);
    if (index === -1) {
      return this.appendChild(child);
    }
    child.parentNode = this;
    child.parentElement = this instanceof MiniElement ? this : null;
    this.childNodes.splice(index, 0, child);
    return child;
  }

  get firstChild(): MiniElement | MiniText | MiniDocumentFragment | null {
    return this.childNodes[0] ?? null;
  }

  get lastChild(): MiniElement | MiniText | MiniDocumentFragment | null {
    return this.childNodes.at(-1) ?? null;
  }

  get firstElementChild(): MiniElement | null {
    return this.childNodes.find((child): child is MiniElement => child instanceof MiniElement) ?? null;
  }

  get lastElementChild(): MiniElement | null {
    return [...this.childNodes].reverse().find((child): child is MiniElement => child instanceof MiniElement) ?? null;
  }

  get childElementCount(): number {
    return this.childNodes.filter((child) => child instanceof MiniElement).length;
  }

  get textContent(): string {
    return this.childNodes.map((child) => child.textContent ?? '').join('');
  }

  set textContent(value: string | null) {
    this.childNodes = [new MiniText(value ?? '')];
  }

  replaceChildren(...children: Array<MiniElement | MiniText | MiniDocumentFragment | string | number>): void {
    this.childNodes = [];
    this.append(...children);
  }
}

export class MiniText extends MiniNode {
  readonly nodeType = MiniNode.TEXT_NODE;
  private value: string;

  constructor(value: string | number) {
    super();
    this.value = String(value);
  }

  override get textContent(): string {
    return this.value;
  }

  override set textContent(value: string | null) {
    this.value = String(value);
  }

  get outerHTML(): string {
    return this.value;
  }
}

export class MiniDocumentFragment extends MiniNode {
  readonly nodeType = MiniNode.DOCUMENT_FRAGMENT_NODE;

  get outerHTML(): string {
    return this.childNodes.map((child) => child.outerHTML ?? child.textContent ?? '').join('');
  }
}

interface MiniAttributeSelector {
  name: string;
  value: string | null;
}

type MiniStyleDeclaration = Record<string, string> & {
  getPropertyValue(name: string): string;
  removeProperty(name: string): string;
  setProperty(name: string, value: string): void;
};

function createMiniStyleDeclaration(): MiniStyleDeclaration {
  const style = {} as MiniStyleDeclaration;
  Object.defineProperties(style, {
    getPropertyValue: {
      value: (name: string) => style[name] ?? '',
    },
    removeProperty: {
      value: (name: string) => {
        const previous = style[name] ?? '';
        delete style[name];
        return previous;
      },
    },
    setProperty: {
      value: (name: string, value: string) => {
        style[name] = String(value);
      },
    },
  });
  return style;
}

export class MiniElement extends MiniNode {
  readonly nodeType = MiniNode.ELEMENT_NODE;
  readonly attributes = new Map<string, string>();
  readonly classList = new MiniClassList();
  readonly dataset: Record<string, string> = {};
  readonly style = createMiniStyleDeclaration();
  ownerDocument?: MiniDocument;
  private innerHtml = '';
  id = '';
  title = '';
  disabled = false;
  clientHeight = 0;
  clientWidth = 0;

  constructor(readonly tagName: string) {
    super();
    this.tagName = tagName.toUpperCase();
  }

  get className(): string {
    return this.classList.toString();
  }

  set className(value: string) {
    this.classList.setFromString(value);
  }

  get innerHTML(): string {
    if (this.innerHtml) return this.innerHtml;
    return this.childNodes.map((child) => child.outerHTML ?? child.textContent ?? '').join('');
  }

  set innerHTML(value: string) {
    this.innerHtml = String(value);
    this.childNodes = [];
  }

  override appendChild<T extends MiniElement | MiniText | MiniDocumentFragment>(child: T): T {
    this.innerHtml = '';
    return super.appendChild(child);
  }

  override insertBefore<T extends MiniElement | MiniText | MiniDocumentFragment>(child: T, referenceNode: MiniElement | MiniText | MiniDocumentFragment | null): T {
    this.innerHtml = '';
    return super.insertBefore(child, referenceNode);
  }

  override removeChild<T extends MiniElement | MiniText | MiniDocumentFragment>(child: T): T {
    this.innerHtml = '';
    return super.removeChild(child);
  }

  setAttribute(name: string, value: string): void {
    const stringValue = String(value);
    this.attributes.set(name, stringValue);
    if (name === 'class') {
      this.className = stringValue;
    } else if (name === 'id') {
      this.id = stringValue;
    } else if (name.startsWith('data-')) {
      const key = name
        .slice(5)
        .split('-')
        .map((part, index) => (index === 0 ? part : `${part[0]?.toUpperCase() ?? ''}${part.slice(1)}`))
        .join('');
      this.dataset[key] = stringValue;
    }
  }

  getAttribute(name: string): string | null {
    return this.attributes.get(name) ?? null;
  }

  hasAttribute(name: string): boolean {
    return this.attributes.has(name);
  }

  removeAttribute(name: string): void {
    this.attributes.delete(name);
    if (name === 'class') this.className = '';
  }

  matches(selector: string): boolean {
    return matchesSelector(this, selector);
  }

  querySelector(selector: string): MiniElement | null {
    return querySelectorAll(this, selector)[0] ?? null;
  }

  querySelectorAll(selector: string): MiniElement[] {
    return querySelectorAll(this, selector);
  }

  closest(selector: string): MiniElement | null {
    let current: MiniElement | null = this;
    while (current instanceof MiniElement) {
      if (current.matches(selector)) return current;
      current = current.parentElement;
    }
    return null;
  }

  remove(): void {
    if (this.parentNode) {
      this.parentNode.removeChild(this);
    }
  }

  getBoundingClientRect(): DOMRect {
    return { width: 1, height: 1, top: 0, left: 0, right: 1, bottom: 1, x: 0, y: 0, toJSON: () => ({}) };
  }

  focus(): void {
    const doc = this.ownerDocument ?? globalThis.document as unknown as MiniDocument | undefined;
    if (doc) doc.activeElement = this;
  }

  get nextElementSibling(): MiniElement | null {
    if (!this.parentNode) return null;
    const siblings = this.parentNode.childNodes.filter((child): child is MiniElement => child instanceof MiniElement);
    const index = siblings.indexOf(this);
    return index >= 0 ? siblings[index + 1] ?? null : null;
  }

  get isConnected(): boolean {
    let current = this.parentNode;
    while (current) {
      if (current === globalThis.document?.body || current === globalThis.document?.documentElement) {
        return true;
      }
      current = current.parentNode;
    }
    return false;
  }

  get outerHTML(): string {
    return `<${this.tagName.toLowerCase()}>${this.innerHTML}</${this.tagName.toLowerCase()}>`;
  }

  get children(): MiniElement[] {
    return this.childNodes.filter((child): child is MiniElement => child instanceof MiniElement);
  }

  get offsetParent(): MiniElement | null {
    return this.isConnected ? this.parentElement ?? null : null;
  }
}

export class MiniStorage {
  private values = new Map<string, string>();

  getItem(key: string): string | null {
    return this.values.has(key) ? this.values.get(key)! : null;
  }

  setItem(key: string, value: string): void {
    this.values.set(key, String(value));
  }

  removeItem(key: string): void {
    this.values.delete(key);
  }

  clear(): void {
    this.values.clear();
  }
}

export class MiniDocument extends EventTarget {
  readonly documentElement: MiniElement;
  readonly body: MiniElement;
  activeElement: MiniElement;

  constructor() {
    super();
    this.documentElement = new MiniElement('html');
    this.documentElement.clientHeight = 800;
    this.documentElement.clientWidth = 1200;
    this.body = new MiniElement('body');
    this.documentElement.ownerDocument = this;
    this.body.ownerDocument = this;
    this.documentElement.appendChild(this.body);
    this.activeElement = this.body;
  }

  createElement(tagName: string): MiniElement {
    const element = new MiniElement(tagName);
    element.ownerDocument = this;
    return element;
  }

  createElementNS(_namespace: string | null, qualifiedName: string): MiniElement {
    return this.createElement(qualifiedName);
  }

  createTextNode(value: string): MiniText {
    return new MiniText(value);
  }

  createDocumentFragment(): MiniDocumentFragment {
    return new MiniDocumentFragment();
  }

  getElementById(id: string): MiniElement | null {
    return querySelectorAll(this.documentElement, `#${id}`)[0] ?? null;
  }

  querySelector(selector: string): MiniElement | null {
    return this.documentElement.querySelector(selector);
  }

  querySelectorAll(selector: string): MiniElement[] {
    return this.documentElement.querySelectorAll(selector);
  }
}

function splitSelectorList(selector: string): string[] {
  return String(selector)
    .split(',')
    .map((part) => part.trim())
    .filter(Boolean);
}

function parseSimpleSelector(selector: string): {
  tag: string | null;
  id: string | null;
  classes: string[];
  attributes: MiniAttributeSelector[];
  notAttributes: MiniAttributeSelector[];
} {
  const trimmed = selector.trim();
  const result = {
    tag: null as string | null,
    id: null as string | null,
    classes: [] as string[],
    attributes: [] as MiniAttributeSelector[],
    notAttributes: [] as MiniAttributeSelector[],
  };
  let remaining = trimmed;

  const tagMatch = remaining.match(/^[a-zA-Z][a-zA-Z0-9-]*/);
  if (tagMatch) {
    result.tag = tagMatch[0].toUpperCase();
    remaining = remaining.slice(tagMatch[0].length);
  }

  while (remaining.length > 0) {
    if (remaining.startsWith('#')) {
      const match = remaining.match(/^#([A-Za-z0-9_-]+)/);
      if (!match) break;
      result.id = match[1]!;
      remaining = remaining.slice(match[0].length);
      continue;
    }

    if (remaining.startsWith('.')) {
      const match = remaining.match(/^\.([A-Za-z0-9_-]+)/);
      if (!match) break;
      result.classes.push(match[1]!);
      remaining = remaining.slice(match[0].length);
      continue;
    }

    if (remaining.startsWith(':not(')) {
      const match = remaining.match(/^:not\(\[([^\]=]+)(?:="([^"]*)")?\]\)/);
      if (!match) break;
      result.notAttributes.push({ name: match[1]!, value: match[2] ?? null });
      remaining = remaining.slice(match[0].length);
      continue;
    }

    if (remaining.startsWith('[')) {
      const match = remaining.match(/^\[([^\]=]+)(?:="([^"]*)")?\]/);
      if (!match) break;
      result.attributes.push({ name: match[1]!, value: match[2] ?? null });
      remaining = remaining.slice(match[0].length);
      continue;
    }

    break;
  }

  return result;
}

function matchesSelector(element: MiniElement, selector: string): boolean {
  return splitSelectorList(selector).some((part) => {
    const parsed = parseSimpleSelector(part);
    if (parsed.tag && element.tagName !== parsed.tag) return false;
    if (parsed.id && element.id !== parsed.id) return false;
    if (parsed.classes.some((name) => !element.classList.contains(name))) return false;
    if (parsed.attributes.some(({ name, value }) => {
      if (!element.hasAttribute(name)) return true;
      return value != null && element.getAttribute(name) !== value;
    })) return false;
    if (parsed.notAttributes.some(({ name, value }) => {
      if (!element.hasAttribute(name)) return false;
      return value == null ? true : element.getAttribute(name) === value;
    })) return false;
    return true;
  });
}

function querySelectorAll(root: MiniElement | MiniNode, selector: string): MiniElement[] {
  const matches: MiniElement[] = [];

  function visit(node: MiniElement | MiniText | MiniDocumentFragment): void {
    if (!(node instanceof MiniElement)) return;
    if (node.matches(selector)) {
      matches.push(node);
    }
    node.childNodes.forEach(visit);
  }

  if (root instanceof MiniElement) {
    root.childNodes.forEach(visit);
    return matches;
  }

  root.childNodes.forEach(visit);
  return matches;
}

export function createBrowserEnvironment() {
  const document = new MiniDocument();
  const localStorage = new MiniStorage();
  const window = {
    document,
    localStorage,
    innerHeight: 800,
    innerWidth: 1200,
    addEventListener() {},
    removeEventListener() {},
    open() {},
    location: {
      origin: 'https://worldmonitor.test',
      href: 'https://worldmonitor.test/',
    },
    navigator: {
      clipboard: {
        async writeText() {},
      },
    },
    getComputedStyle() {
      return {
        display: '',
        visibility: '',
        gridTemplateColumns: 'none',
        columnGap: '0',
      };
    },
  };

  return {
    document,
    localStorage,
    window,
    requestAnimationFrame(callback: FrameRequestCallback) {
      if (typeof callback === 'function') callback(0);
      return 1;
    },
    cancelAnimationFrame() {},
    HTMLElement: MiniElement,
    HTMLButtonElement: MiniElement,
  };
}