@ait-co/devtools 0.0.2 → 0.0.3

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.
@@ -1,14 +1,177 @@
1
- import {
2
- aitState,
3
- getDefaultPlaceholderImages
4
- } from "../chunk-6PPZTREF.js";
5
-
6
- // src/panel/styles.ts
7
- var PANEL_WIDTH = 360;
8
- var PANEL_HEIGHT = 480;
9
- var PANEL_STYLES = (
10
- /* css */
11
- `
1
+ //#region src/mock/state.ts
2
+ const DEFAULT_STATE = {
3
+ platform: "ios",
4
+ environment: "sandbox",
5
+ appVersion: "5.240.0",
6
+ locale: "ko-KR",
7
+ schemeUri: "/",
8
+ groupId: "mock-group-id",
9
+ deploymentId: "mock-deployment-id",
10
+ deviceId: "",
11
+ brand: {
12
+ displayName: "Mock App",
13
+ icon: "",
14
+ primaryColor: "#3182F6"
15
+ },
16
+ networkStatus: "WIFI",
17
+ permissions: {
18
+ clipboard: "allowed",
19
+ contacts: "allowed",
20
+ photos: "allowed",
21
+ geolocation: "allowed",
22
+ camera: "allowed",
23
+ microphone: "notDetermined"
24
+ },
25
+ location: {
26
+ coords: {
27
+ latitude: 37.5665,
28
+ longitude: 126.978,
29
+ altitude: 0,
30
+ accuracy: 10,
31
+ altitudeAccuracy: 0,
32
+ heading: 0
33
+ },
34
+ timestamp: Date.now(),
35
+ accessLocation: "FINE"
36
+ },
37
+ safeAreaInsets: {
38
+ top: 47,
39
+ bottom: 34,
40
+ left: 0,
41
+ right: 0
42
+ },
43
+ contacts: [{
44
+ name: "홍길동",
45
+ phoneNumber: "010-1234-5678"
46
+ }, {
47
+ name: "김토스",
48
+ phoneNumber: "010-9876-5432"
49
+ }],
50
+ iap: {
51
+ products: [{
52
+ sku: "mock-gem-100",
53
+ type: "CONSUMABLE",
54
+ displayName: "보석 100개",
55
+ displayAmount: "1,000원",
56
+ iconUrl: "",
57
+ description: "게임에서 사용할 수 있는 보석 100개"
58
+ }],
59
+ nextResult: "success",
60
+ pendingOrders: [],
61
+ completedOrders: []
62
+ },
63
+ payment: {
64
+ nextResult: "success",
65
+ failReason: ""
66
+ },
67
+ auth: {
68
+ isLoggedIn: true,
69
+ isTossLoginIntegrated: true,
70
+ userKeyHash: "mock-user-hash-abc123"
71
+ },
72
+ ads: {
73
+ isLoaded: false,
74
+ nextEvent: "loaded"
75
+ },
76
+ game: {
77
+ profile: {
78
+ nickname: "MockPlayer",
79
+ profileImageUri: ""
80
+ },
81
+ leaderboardScores: []
82
+ },
83
+ analyticsLog: [],
84
+ deviceModes: {
85
+ camera: "mock",
86
+ photos: "mock",
87
+ location: "mock",
88
+ network: "mock",
89
+ clipboard: "web"
90
+ },
91
+ mockData: {
92
+ images: [],
93
+ clipboardText: ""
94
+ },
95
+ panelEditable: true
96
+ };
97
+ function generateDeviceId() {
98
+ const stored = localStorage.getItem("__ait_device_id");
99
+ if (stored) return stored;
100
+ const id = crypto.randomUUID();
101
+ localStorage.setItem("__ait_device_id", id);
102
+ return id;
103
+ }
104
+ var AitStateManager = class {
105
+ _state;
106
+ _listeners = /* @__PURE__ */ new Set();
107
+ constructor() {
108
+ this._state = structuredClone(DEFAULT_STATE);
109
+ try {
110
+ this._state.deviceId = generateDeviceId();
111
+ } catch {
112
+ this._state.deviceId = "mock-device-" + Math.random().toString(36).slice(2);
113
+ }
114
+ }
115
+ get state() {
116
+ return this._state;
117
+ }
118
+ update(partial) {
119
+ this._state = {
120
+ ...this._state,
121
+ ...partial
122
+ };
123
+ this._notify();
124
+ }
125
+ /** 중첩 객체 업데이트용 */
126
+ patch(key, partial) {
127
+ const current = this._state[key];
128
+ if (typeof current === "object" && current !== null && !Array.isArray(current)) this._state = {
129
+ ...this._state,
130
+ [key]: {
131
+ ...current,
132
+ ...partial
133
+ }
134
+ };
135
+ else this._state = {
136
+ ...this._state,
137
+ [key]: partial
138
+ };
139
+ this._notify();
140
+ }
141
+ subscribe(listener) {
142
+ this._listeners.add(listener);
143
+ return () => this._listeners.delete(listener);
144
+ }
145
+ /** 분석 로그 추가 */
146
+ logAnalytics(entry) {
147
+ this._state = {
148
+ ...this._state,
149
+ analyticsLog: [...this._state.analyticsLog, {
150
+ ...entry,
151
+ timestamp: Date.now()
152
+ }]
153
+ };
154
+ this._notify();
155
+ }
156
+ /** 이벤트 트리거 (backEvent, homeEvent 등) */
157
+ trigger(event) {
158
+ window.dispatchEvent(new CustomEvent(`__ait:${event}`));
159
+ }
160
+ reset() {
161
+ const deviceId = this._state.deviceId;
162
+ this._state = {
163
+ ...structuredClone(DEFAULT_STATE),
164
+ deviceId
165
+ };
166
+ this._notify();
167
+ }
168
+ _notify() {
169
+ for (const listener of this._listeners) listener();
170
+ }
171
+ };
172
+ const aitState = new AitStateManager();
173
+ if (typeof window !== "undefined") window.__ait = aitState;
174
+ const PANEL_STYLES = `
12
175
  .ait-panel-toggle {
13
176
  position: fixed;
14
177
  z-index: 99999;
@@ -36,8 +199,8 @@ var PANEL_STYLES = (
36
199
  .ait-panel {
37
200
  position: fixed;
38
201
  z-index: 99998;
39
- width: ${PANEL_WIDTH}px;
40
- height: ${PANEL_HEIGHT}px;
202
+ width: 360px;
203
+ height: 480px;
41
204
  background: #1a1a2e;
42
205
  border-radius: 12px;
43
206
  box-shadow: 0 8px 32px rgba(0,0,0,0.4);
@@ -357,6 +520,11 @@ var PANEL_STYLES = (
357
520
  color: #fbbf24;
358
521
  }
359
522
 
523
+ .ait-panel-tab-error {
524
+ padding: 12px;
525
+ color: #e53e3e; /* readable on both light (#fff) and dark (#1a1a2e) panel backgrounds */
526
+ }
527
+
360
528
  @media (max-width: 480px) {
361
529
  .ait-panel.open {
362
530
  position: fixed;
@@ -376,709 +544,1083 @@ var PANEL_STYLES = (
376
544
  display: block;
377
545
  }
378
546
  }
379
- `
380
- );
381
-
382
- // src/panel/index.ts
383
- var TABS = [
384
- { id: "env", label: "Environment" },
385
- { id: "permissions", label: "Permissions" },
386
- { id: "location", label: "Location" },
387
- { id: "device", label: "Device" },
388
- { id: "iap", label: "IAP" },
389
- { id: "events", label: "Events" },
390
- { id: "analytics", label: "Analytics" },
391
- { id: "storage", label: "Storage" }
392
- ];
547
+ `;
548
+ //#endregion
549
+ //#region src/panel/helpers.ts
550
+ /**
551
+ * 공통 DOM 헬퍼 함수
552
+ */
393
553
  function h(tag, attrs, ...children) {
394
- const el = document.createElement(tag);
395
- if (attrs) {
396
- for (const [k, v] of Object.entries(attrs)) {
397
- if (k === "className") el.className = v;
398
- else el.setAttribute(k, v);
399
- }
400
- }
401
- for (const child of children) {
402
- el.append(typeof child === "string" ? document.createTextNode(child) : child);
403
- }
404
- return el;
554
+ const el = document.createElement(tag);
555
+ if (attrs) for (const [k, v] of Object.entries(attrs)) if (k === "className") el.className = v;
556
+ else el.setAttribute(k, v);
557
+ for (const child of children) el.append(typeof child === "string" ? document.createTextNode(child) : child);
558
+ return el;
405
559
  }
406
560
  function selectRow(label, options, value, onChange, disabled = false) {
407
- const select = h("select", { className: "ait-select" });
408
- if (disabled) select.disabled = true;
409
- for (const opt of options) {
410
- const option = h("option", { value: opt }, opt);
411
- if (opt === value) option.selected = true;
412
- select.appendChild(option);
413
- }
414
- select.addEventListener("change", () => onChange(select.value));
415
- return h("div", { className: "ait-row" }, h("label", {}, label), select);
561
+ const select = h("select", { className: "ait-select" });
562
+ if (disabled) select.disabled = true;
563
+ for (const opt of options) {
564
+ const option = h("option", { value: opt }, opt);
565
+ if (opt === value) option.selected = true;
566
+ select.appendChild(option);
567
+ }
568
+ select.addEventListener("change", () => onChange(select.value));
569
+ return h("div", { className: "ait-row" }, h("label", {}, label), select);
416
570
  }
417
571
  function inputRow(label, value, onChange, disabled = false) {
418
- const input = h("input", { className: "ait-input", value });
419
- if (disabled) input.disabled = true;
420
- input.addEventListener("change", () => onChange(input.value));
421
- return h("div", { className: "ait-row" }, h("label", {}, label), input);
572
+ const input = h("input", {
573
+ className: "ait-input",
574
+ value
575
+ });
576
+ if (disabled) input.disabled = true;
577
+ input.addEventListener("change", () => onChange(input.value));
578
+ return h("div", { className: "ait-row" }, h("label", {}, label), input);
422
579
  }
423
- function renderEnvTab() {
424
- const s = aitState.state;
425
- const disabled = !s.panelEditable;
426
- const container = h("div");
427
- if (disabled) container.appendChild(monitoringNotice());
428
- container.append(
429
- h(
430
- "div",
431
- { className: "ait-section" },
432
- h("div", { className: "ait-section-title" }, "Platform"),
433
- selectRow("OS", ["ios", "android"], s.platform, (v) => aitState.update({ platform: v }), disabled),
434
- inputRow("App Version", s.appVersion, (v) => aitState.update({ appVersion: v }), disabled),
435
- selectRow("Environment", ["toss", "sandbox"], s.environment, (v) => aitState.update({ environment: v }), disabled),
436
- inputRow("Locale", s.locale, (v) => aitState.update({ locale: v }), disabled)
437
- ),
438
- h(
439
- "div",
440
- { className: "ait-section" },
441
- h("div", { className: "ait-section-title" }, "Network"),
442
- selectRow("Status", ["WIFI", "4G", "5G", "3G", "2G", "OFFLINE", "WWAN", "UNKNOWN"], s.networkStatus, (v) => aitState.update({ networkStatus: v }), disabled)
443
- ),
444
- h(
445
- "div",
446
- { className: "ait-section" },
447
- h("div", { className: "ait-section-title" }, "Safe Area Insets"),
448
- inputRow("Top", String(s.safeAreaInsets.top), (v) => aitState.patch("safeAreaInsets", { top: Number(v) }), disabled),
449
- inputRow("Bottom", String(s.safeAreaInsets.bottom), (v) => aitState.patch("safeAreaInsets", { bottom: Number(v) }), disabled)
450
- )
451
- );
452
- return container;
580
+ function monitoringNotice() {
581
+ return h("div", { className: "ait-monitoring-notice" }, "Read-only — mock responses are controlled at build time.");
453
582
  }
583
+ //#endregion
584
+ //#region src/panel/tabs/environment.ts
585
+ function renderEnvironmentTab() {
586
+ const s = aitState.state;
587
+ const disabled = !s.panelEditable;
588
+ const container = h("div");
589
+ if (disabled) container.appendChild(monitoringNotice());
590
+ container.append(h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, "Platform"), selectRow("OS", ["ios", "android"], s.platform, (v) => aitState.update({ platform: v }), disabled), inputRow("App Version", s.appVersion, (v) => aitState.update({ appVersion: v }), disabled), selectRow("Environment", ["toss", "sandbox"], s.environment, (v) => aitState.update({ environment: v }), disabled), inputRow("Locale", s.locale, (v) => aitState.update({ locale: v }), disabled)), h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, "Network"), selectRow("Status", [
591
+ "WIFI",
592
+ "4G",
593
+ "5G",
594
+ "3G",
595
+ "2G",
596
+ "OFFLINE",
597
+ "WWAN",
598
+ "UNKNOWN"
599
+ ], s.networkStatus, (v) => aitState.update({ networkStatus: v }), disabled)), h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, "Safe Area Insets"), inputRow("Top", String(s.safeAreaInsets.top), (v) => aitState.patch("safeAreaInsets", { top: Number(v) }), disabled), inputRow("Bottom", String(s.safeAreaInsets.bottom), (v) => aitState.patch("safeAreaInsets", { bottom: Number(v) }), disabled)));
600
+ return container;
601
+ }
602
+ //#endregion
603
+ //#region src/panel/tabs/permissions.ts
454
604
  function renderPermissionsTab() {
455
- const s = aitState.state;
456
- const disabled = !s.panelEditable;
457
- const container = h("div");
458
- const names = ["camera", "photos", "geolocation", "clipboard", "contacts", "microphone"];
459
- const statuses = ["allowed", "denied", "notDetermined"];
460
- if (disabled) container.appendChild(monitoringNotice());
461
- container.append(
462
- h(
463
- "div",
464
- { className: "ait-section" },
465
- h("div", { className: "ait-section-title" }, "Device Permissions"),
466
- ...names.map(
467
- (name) => selectRow(name, statuses, s.permissions[name], (v) => {
468
- aitState.patch("permissions", { [name]: v });
469
- }, disabled)
470
- )
471
- )
472
- );
473
- return container;
605
+ const s = aitState.state;
606
+ const disabled = !s.panelEditable;
607
+ const container = h("div");
608
+ const names = [
609
+ "camera",
610
+ "photos",
611
+ "geolocation",
612
+ "clipboard",
613
+ "contacts",
614
+ "microphone"
615
+ ];
616
+ const statuses = [
617
+ "allowed",
618
+ "denied",
619
+ "notDetermined"
620
+ ];
621
+ if (disabled) container.appendChild(monitoringNotice());
622
+ container.append(h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, "Device Permissions"), ...names.map((name) => selectRow(name, statuses, s.permissions[name], (v) => {
623
+ aitState.patch("permissions", { [name]: v });
624
+ }, disabled))));
625
+ return container;
474
626
  }
627
+ //#endregion
628
+ //#region src/panel/tabs/location.ts
475
629
  function renderLocationTab() {
476
- const s = aitState.state;
477
- const disabled = !s.panelEditable;
478
- const container = h("div");
479
- if (disabled) container.appendChild(monitoringNotice());
480
- container.append(
481
- h(
482
- "div",
483
- { className: "ait-section" },
484
- h("div", { className: "ait-section-title" }, "Current Location"),
485
- inputRow("Latitude", String(s.location.coords.latitude), (v) => {
486
- const coords = { ...s.location.coords, latitude: Number(v) };
487
- aitState.patch("location", { coords });
488
- }, disabled),
489
- inputRow("Longitude", String(s.location.coords.longitude), (v) => {
490
- const coords = { ...s.location.coords, longitude: Number(v) };
491
- aitState.patch("location", { coords });
492
- }, disabled),
493
- inputRow("Accuracy", String(s.location.coords.accuracy), (v) => {
494
- const coords = { ...s.location.coords, accuracy: Number(v) };
495
- aitState.patch("location", { coords });
496
- }, disabled)
497
- )
498
- );
499
- return container;
630
+ const s = aitState.state;
631
+ const disabled = !s.panelEditable;
632
+ const container = h("div");
633
+ if (disabled) container.appendChild(monitoringNotice());
634
+ container.append(h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, "Current Location"), inputRow("Latitude", String(s.location.coords.latitude), (v) => {
635
+ const coords = {
636
+ ...s.location.coords,
637
+ latitude: Number(v)
638
+ };
639
+ aitState.patch("location", { coords });
640
+ }, disabled), inputRow("Longitude", String(s.location.coords.longitude), (v) => {
641
+ const coords = {
642
+ ...s.location.coords,
643
+ longitude: Number(v)
644
+ };
645
+ aitState.patch("location", { coords });
646
+ }, disabled), inputRow("Accuracy", String(s.location.coords.accuracy), (v) => {
647
+ const coords = {
648
+ ...s.location.coords,
649
+ accuracy: Number(v)
650
+ };
651
+ aitState.patch("location", { coords });
652
+ }, disabled)));
653
+ return container;
500
654
  }
501
- function renderIapTab() {
502
- const s = aitState.state;
503
- const disabled = !s.panelEditable;
504
- const container = h("div");
505
- const results = ["success", "USER_CANCELED", "INVALID_PRODUCT_ID", "PAYMENT_PENDING", "NETWORK_ERROR", "ITEM_ALREADY_OWNED", "INTERNAL_ERROR"];
506
- if (disabled) container.appendChild(monitoringNotice());
507
- container.append(
508
- h(
509
- "div",
510
- { className: "ait-section" },
511
- h("div", { className: "ait-section-title" }, "IAP Simulator"),
512
- selectRow("Next Purchase Result", results, s.iap.nextResult, (v) => {
513
- aitState.patch("iap", { nextResult: v });
514
- }, disabled)
515
- ),
516
- h(
517
- "div",
518
- { className: "ait-section" },
519
- h("div", { className: "ait-section-title" }, "TossPay"),
520
- selectRow("Next Payment Result", ["success", "fail"], s.payment.nextResult, (v) => {
521
- aitState.patch("payment", { nextResult: v });
522
- }, disabled)
523
- ),
524
- h(
525
- "div",
526
- { className: "ait-section" },
527
- h("div", { className: "ait-section-title" }, `Completed Orders (${s.iap.completedOrders.length})`),
528
- ...s.iap.completedOrders.slice(-5).map(
529
- (o) => h(
530
- "div",
531
- { className: "ait-log-entry" },
532
- h("span", { className: "ait-log-type" }, o.status),
533
- `${o.sku} (${o.orderId.slice(-8)})`
534
- )
535
- )
536
- )
537
- );
538
- return container;
655
+ //#endregion
656
+ //#region src/mock/device/_helpers.ts
657
+ /**
658
+ * 디바이스 모듈 내부 공유 헬퍼
659
+ */
660
+ function generatePlaceholderImage(width, height, text, color) {
661
+ const canvas = document.createElement("canvas");
662
+ canvas.width = width;
663
+ canvas.height = height;
664
+ const ctx = canvas.getContext("2d");
665
+ if (!ctx) {
666
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><rect fill="${color}" width="${width}" height="${height}"/><text x="50%" y="50%" fill="white" font-size="16" text-anchor="middle" dominant-baseline="middle">${text}</text></svg>`;
667
+ return "data:image/svg+xml;base64," + btoa(svg);
668
+ }
669
+ ctx.fillStyle = color;
670
+ ctx.fillRect(0, 0, width, height);
671
+ ctx.fillStyle = "white";
672
+ ctx.font = "16px sans-serif";
673
+ ctx.textAlign = "center";
674
+ ctx.textBaseline = "middle";
675
+ ctx.fillText(text, width / 2, height / 2);
676
+ return canvas.toDataURL("image/png");
539
677
  }
540
- function renderEventsTab() {
541
- const disabled = !aitState.state.panelEditable;
542
- const container = h("div");
543
- if (disabled) container.appendChild(monitoringNotice());
544
- const backBtn = h("button", { className: "ait-btn" }, "Trigger Back Event");
545
- backBtn.addEventListener("click", () => aitState.trigger("backEvent"));
546
- if (disabled) backBtn.disabled = true;
547
- const homeBtn = h("button", { className: "ait-btn" }, "Trigger Home Event");
548
- homeBtn.addEventListener("click", () => aitState.trigger("homeEvent"));
549
- if (disabled) homeBtn.disabled = true;
550
- container.append(
551
- h(
552
- "div",
553
- { className: "ait-section" },
554
- h("div", { className: "ait-section-title" }, "Navigation Events"),
555
- h("div", { className: "ait-row" }, backBtn, homeBtn)
556
- ),
557
- h(
558
- "div",
559
- { className: "ait-section" },
560
- h("div", { className: "ait-section-title" }, "Login"),
561
- selectRow("Logged In", ["true", "false"], String(aitState.state.auth.isLoggedIn), (v) => {
562
- aitState.patch("auth", { isLoggedIn: v === "true" });
563
- }, disabled),
564
- selectRow("Toss Login Integrated", ["true", "false"], String(aitState.state.auth.isTossLoginIntegrated), (v) => {
565
- aitState.patch("auth", { isTossLoginIntegrated: v === "true" });
566
- }, disabled)
567
- )
568
- );
569
- return container;
678
+ const DEFAULT_PLACEHOLDERS = [
679
+ {
680
+ text: "Mock Photo 1",
681
+ color: "#3182F6"
682
+ },
683
+ {
684
+ text: "Mock Photo 2",
685
+ color: "#27ae60"
686
+ },
687
+ {
688
+ text: "Mock Photo 3",
689
+ color: "#e67e22"
690
+ }
691
+ ];
692
+ let cachedPlaceholders = null;
693
+ function getDefaultPlaceholderImages() {
694
+ if (!cachedPlaceholders) cachedPlaceholders = DEFAULT_PLACEHOLDERS.map((p) => generatePlaceholderImage(320, 240, p.text, p.color));
695
+ return [...cachedPlaceholders];
570
696
  }
571
- function renderAnalyticsTab() {
572
- const disabled = !aitState.state.panelEditable;
573
- const container = h("div");
574
- if (disabled) container.appendChild(monitoringNotice());
575
- const logs = aitState.state.analyticsLog;
576
- const clearBtn = h("button", { className: "ait-btn ait-btn-sm ait-btn-danger" }, "Clear");
577
- if (disabled) clearBtn.disabled = true;
578
- clearBtn.addEventListener("click", () => {
579
- aitState.state.analyticsLog.length = 0;
580
- refreshPanel();
581
- });
582
- container.append(
583
- h(
584
- "div",
585
- { className: "ait-section" },
586
- h(
587
- "div",
588
- { className: "ait-row" },
589
- h("div", { className: "ait-section-title" }, `Analytics Log (${logs.length})`),
590
- clearBtn
591
- ),
592
- ...logs.slice(-30).reverse().map((entry) => {
593
- const time = new Date(entry.timestamp).toLocaleTimeString("ko-KR", { hour12: false });
594
- return h(
595
- "div",
596
- { className: "ait-log-entry" },
597
- h("span", { className: "ait-log-time" }, time),
598
- h("span", { className: "ait-log-type" }, entry.type),
599
- JSON.stringify(entry.params)
600
- );
601
- })
602
- )
603
- );
604
- return container;
697
+ /** @internal device 모듈 내부 전용 */
698
+ function getMockImages() {
699
+ const images = aitState.state.mockData.images;
700
+ if (images.length > 0) return images;
701
+ return getDefaultPlaceholderImages();
605
702
  }
606
- function renderStorageTab() {
607
- const disabled = !aitState.state.panelEditable;
608
- const container = h("div");
609
- if (disabled) container.appendChild(monitoringNotice());
610
- const prefix = "__ait_storage:";
611
- const entries = [];
612
- for (let i = 0; i < localStorage.length; i++) {
613
- const key = localStorage.key(i);
614
- if (key?.startsWith(prefix)) {
615
- entries.push([key.slice(prefix.length), localStorage.getItem(key) ?? ""]);
616
- }
617
- }
618
- const clearBtn = h("button", { className: "ait-btn ait-btn-sm ait-btn-danger" }, "Clear All");
619
- if (disabled) clearBtn.disabled = true;
620
- clearBtn.addEventListener("click", () => {
621
- entries.forEach(([key]) => localStorage.removeItem(prefix + key));
622
- refreshPanel();
623
- });
624
- container.append(
625
- h(
626
- "div",
627
- { className: "ait-section" },
628
- h(
629
- "div",
630
- { className: "ait-row" },
631
- h("div", { className: "ait-section-title" }, `Storage (${entries.length} items)`),
632
- clearBtn
633
- ),
634
- entries.length === 0 ? h("div", { style: "color:#555;font-size:12px" }, "No items in storage") : h(
635
- "div",
636
- {},
637
- ...entries.map(
638
- ([key, value]) => h(
639
- "div",
640
- { className: "ait-storage-row" },
641
- h("span", { className: "ait-storage-key" }, key),
642
- h("span", { className: "ait-storage-value" }, value.length > 100 ? value.slice(0, 100) + "..." : value)
643
- )
644
- )
645
- )
646
- )
647
- );
648
- return container;
703
+ const PROMPT_TIMEOUT_MS = 3e4;
704
+ /** @internal device 모듈 내부 전용 */
705
+ function waitForPromptResponse(type) {
706
+ return new Promise((resolve, reject) => {
707
+ const eventName = "__ait:prompt-response:" + type;
708
+ const cancelName = "__ait:prompt-cancel";
709
+ function cleanup() {
710
+ clearTimeout(timer);
711
+ window.removeEventListener(eventName, handler);
712
+ window.removeEventListener(cancelName, cancelHandler);
713
+ }
714
+ const timer = setTimeout(() => {
715
+ cleanup();
716
+ const hint = !!document.querySelector(".ait-panel") ? "Please provide input via the DevTools panel." : "Is @ait-co/devtools/panel imported?";
717
+ reject(/* @__PURE__ */ new Error(`[@ait-co/devtools] Prompt timeout for "${type}" after ${PROMPT_TIMEOUT_MS / 1e3}s. ${hint}`));
718
+ }, PROMPT_TIMEOUT_MS);
719
+ const handler = (e) => {
720
+ cleanup();
721
+ resolve(e.detail);
722
+ };
723
+ const cancelHandler = () => {
724
+ cleanup();
725
+ reject(/* @__PURE__ */ new Error(`[@ait-co/devtools] Prompt cancelled for "${type}"`));
726
+ };
727
+ window.addEventListener(eventName, handler);
728
+ window.addEventListener(cancelName, cancelHandler);
729
+ window.dispatchEvent(new CustomEvent("__ait:prompt-request", { detail: { type } }));
730
+ });
649
731
  }
650
- var pendingPrompt = null;
651
- if (typeof window !== "undefined") {
652
- window.addEventListener("__ait:prompt-request", (e) => {
653
- const detail = e.detail;
654
- pendingPrompt = { type: detail.type };
655
- currentTab = "device";
656
- if (panelEl && !panelEl.classList.contains("open")) {
657
- panelEl.classList.add("open");
658
- }
659
- refreshPanel();
660
- });
732
+ //#endregion
733
+ //#region src/mock/proxy.ts
734
+ /**
735
+ * 미구현 API용 Proxy 트립와이어.
736
+ *
737
+ * 미구현 프로퍼티에 접근하면 throw한다. 이는 "devtools에서는 멀쩡히 돌지만
738
+ * SDK에선 실제로 동작하는" 시나리오를 차단하기 위한 의도적 선택이다.
739
+ * mock이 미구현인 API는 실 SDK에서는 존재할 수 있고, 사용자가 이를 인지하지
740
+ * 못한 채 개발을 이어가면 배포 시점에 놀라게 된다. 에러 메시지에 이슈 URL을
741
+ * 포함해 사용자가 mock 누락을 제보할 수 있게 한다.
742
+ */
743
+ const ISSUES_URL = "https://github.com/apps-in-toss-community/devtools/issues";
744
+ function createMockProxy(moduleName, implementations) {
745
+ return new Proxy(implementations, { get(target, prop) {
746
+ if (typeof prop === "symbol") return void 0;
747
+ if (prop in target) return target[prop];
748
+ throw new Error(`[@ait-co/devtools] ${moduleName}.${prop} is not mocked. This API may exist in @apps-in-toss/web-framework, but devtools' mock does not cover it yet. Please file an issue: ${ISSUES_URL}`);
749
+ } });
750
+ }
751
+ createMockProxy("Storage", {
752
+ getItem: async (key) => {
753
+ return localStorage.getItem(`__ait_storage:${key}`);
754
+ },
755
+ setItem: async (key, value) => {
756
+ localStorage.setItem(`__ait_storage:${key}`, value);
757
+ },
758
+ removeItem: async (key) => {
759
+ localStorage.removeItem(`__ait_storage:${key}`);
760
+ },
761
+ clearItems: async () => {
762
+ Object.keys(localStorage).filter((k) => k.startsWith("__ait_storage:")).forEach((k) => localStorage.removeItem(k));
763
+ }
764
+ });
765
+ //#endregion
766
+ //#region src/mock/permissions.ts
767
+ /**
768
+ * 권한 시스템 mock
769
+ * 각 디바이스 API (.getPermission, .openPermissionDialog)에 부착된다.
770
+ */
771
+ async function getPermission(name) {
772
+ return aitState.state.permissions[name];
773
+ }
774
+ async function openPermissionDialog(name) {
775
+ if (aitState.state.permissions[name] === "allowed") return "allowed";
776
+ aitState.patch("permissions", { [name]: "allowed" });
777
+ return "allowed";
778
+ }
779
+ /** 권한이 필요한 함수에 .getPermission(), .openPermissionDialog()를 부착 */
780
+ function withPermission(fn, permissionName) {
781
+ const enhanced = fn;
782
+ enhanced.getPermission = () => getPermission(permissionName);
783
+ enhanced.openPermissionDialog = () => openPermissionDialog(permissionName);
784
+ return enhanced;
785
+ }
786
+ /** 권한 체크 후 denied면 에러 throw */
787
+ function checkPermission(name, fnName) {
788
+ if (aitState.state.permissions[name] === "denied") throw new Error(`[@ait-co/devtools] ${fnName}: Permission "${name}" is denied. Change it in the DevTools panel.`);
789
+ }
790
+ //#endregion
791
+ //#region src/mock/device/location.ts
792
+ /**
793
+ * Location mock (getCurrentLocation, startUpdateLocation)
794
+ * mock/web/prompt 모드 지원
795
+ */
796
+ function buildLocation() {
797
+ return {
798
+ coords: { ...aitState.state.location.coords },
799
+ timestamp: Date.now(),
800
+ accessLocation: aitState.state.location.accessLocation
801
+ };
802
+ }
803
+ async function getCurrentLocationMock() {
804
+ return buildLocation();
805
+ }
806
+ async function getCurrentLocationWeb() {
807
+ return new Promise((resolve) => {
808
+ if (!navigator.geolocation) {
809
+ console.warn("[@ait-co/devtools] Geolocation API not available, falling back to mock");
810
+ resolve(buildLocation());
811
+ return;
812
+ }
813
+ navigator.geolocation.getCurrentPosition((pos) => {
814
+ resolve({
815
+ coords: {
816
+ latitude: pos.coords.latitude,
817
+ longitude: pos.coords.longitude,
818
+ altitude: pos.coords.altitude ?? 0,
819
+ accuracy: pos.coords.accuracy,
820
+ altitudeAccuracy: pos.coords.altitudeAccuracy ?? 0,
821
+ heading: pos.coords.heading ?? 0
822
+ },
823
+ timestamp: pos.timestamp,
824
+ accessLocation: "FINE"
825
+ });
826
+ }, () => {
827
+ console.warn("[@ait-co/devtools] Geolocation failed, falling back to mock");
828
+ resolve(buildLocation());
829
+ });
830
+ });
831
+ }
832
+ async function getCurrentLocationPrompt() {
833
+ return waitForPromptResponse("location");
834
+ }
835
+ const _getCurrentLocation = async (_options) => {
836
+ checkPermission("geolocation", "getCurrentLocation");
837
+ const mode = aitState.state.deviceModes.location;
838
+ if (mode === "web") return getCurrentLocationWeb();
839
+ if (mode === "prompt") return getCurrentLocationPrompt();
840
+ return getCurrentLocationMock();
841
+ };
842
+ withPermission(_getCurrentLocation, "geolocation");
843
+ function startUpdateLocationMock(eventParams) {
844
+ const { onEvent, options } = eventParams;
845
+ const interval = Math.max(options.timeInterval, 500);
846
+ const id = setInterval(() => {
847
+ const loc = buildLocation();
848
+ loc.coords.latitude += (Math.random() - .5) * 1e-4;
849
+ loc.coords.longitude += (Math.random() - .5) * 1e-4;
850
+ onEvent(loc);
851
+ }, interval);
852
+ return () => clearInterval(id);
853
+ }
854
+ function startUpdateLocationWeb(eventParams) {
855
+ const { onEvent, onError } = eventParams;
856
+ if (!navigator.geolocation) {
857
+ console.warn("[@ait-co/devtools] Geolocation API not available, falling back to mock");
858
+ return startUpdateLocationMock(eventParams);
859
+ }
860
+ const watchId = navigator.geolocation.watchPosition((pos) => {
861
+ onEvent({
862
+ coords: {
863
+ latitude: pos.coords.latitude,
864
+ longitude: pos.coords.longitude,
865
+ altitude: pos.coords.altitude ?? 0,
866
+ accuracy: pos.coords.accuracy,
867
+ altitudeAccuracy: pos.coords.altitudeAccuracy ?? 0,
868
+ heading: pos.coords.heading ?? 0
869
+ },
870
+ timestamp: pos.timestamp,
871
+ accessLocation: "FINE"
872
+ });
873
+ }, (err) => onError(err));
874
+ return () => navigator.geolocation.clearWatch(watchId);
875
+ }
876
+ function startUpdateLocationPrompt(eventParams) {
877
+ const { onEvent } = eventParams;
878
+ const handler = (e) => {
879
+ onEvent(e.detail);
880
+ };
881
+ window.addEventListener("__ait:prompt-response:location-update", handler);
882
+ window.dispatchEvent(new CustomEvent("__ait:prompt-request", { detail: { type: "location-update" } }));
883
+ return () => window.removeEventListener("__ait:prompt-response:location-update", handler);
884
+ }
885
+ const _startUpdateLocation = (eventParams) => {
886
+ const mode = aitState.state.deviceModes.location;
887
+ if (mode === "web") return startUpdateLocationWeb(eventParams);
888
+ if (mode === "prompt") return startUpdateLocationPrompt(eventParams);
889
+ return startUpdateLocationMock(eventParams);
890
+ };
891
+ withPermission(_startUpdateLocation, "geolocation");
892
+ //#endregion
893
+ //#region src/mock/device/camera.ts
894
+ /**
895
+ * Camera & Album Photos mock
896
+ * mock/web/prompt 모드 지원
897
+ */
898
+ async function openCameraMock() {
899
+ const images = getMockImages();
900
+ return {
901
+ id: crypto.randomUUID(),
902
+ dataUri: images[0]
903
+ };
904
+ }
905
+ async function openCameraWeb() {
906
+ return new Promise((resolve, reject) => {
907
+ const input = document.createElement("input");
908
+ input.type = "file";
909
+ input.accept = "image/*";
910
+ input.capture = "environment";
911
+ let settled = false;
912
+ input.onchange = () => {
913
+ settled = true;
914
+ const file = input.files?.[0];
915
+ if (!file) {
916
+ reject(/* @__PURE__ */ new Error("No file selected"));
917
+ return;
918
+ }
919
+ const reader = new FileReader();
920
+ reader.onload = () => resolve({
921
+ id: crypto.randomUUID(),
922
+ dataUri: reader.result
923
+ });
924
+ reader.onerror = () => reject(/* @__PURE__ */ new Error("Failed to read file"));
925
+ reader.readAsDataURL(file);
926
+ };
927
+ const onFocus = () => {
928
+ setTimeout(() => {
929
+ if (!settled) reject(/* @__PURE__ */ new Error("File picker cancelled"));
930
+ window.removeEventListener("focus", onFocus);
931
+ }, 300);
932
+ };
933
+ window.addEventListener("focus", onFocus);
934
+ input.click();
935
+ });
936
+ }
937
+ async function openCameraPrompt() {
938
+ const dataUri = await waitForPromptResponse("camera");
939
+ return {
940
+ id: crypto.randomUUID(),
941
+ dataUri
942
+ };
661
943
  }
944
+ const _openCamera = async (_options) => {
945
+ checkPermission("camera", "openCamera");
946
+ const mode = aitState.state.deviceModes.camera;
947
+ if (mode === "web") return openCameraWeb();
948
+ if (mode === "prompt") return openCameraPrompt();
949
+ return openCameraMock();
950
+ };
951
+ withPermission(_openCamera, "camera");
952
+ async function fetchAlbumPhotosMock(maxCount) {
953
+ return getMockImages().slice(0, maxCount).map((dataUri) => ({
954
+ id: crypto.randomUUID(),
955
+ dataUri
956
+ }));
957
+ }
958
+ async function fetchAlbumPhotosWeb(maxCount) {
959
+ return new Promise((resolve, reject) => {
960
+ const input = document.createElement("input");
961
+ input.type = "file";
962
+ input.accept = "image/*";
963
+ input.multiple = true;
964
+ let settled = false;
965
+ input.onchange = async () => {
966
+ settled = true;
967
+ const files = Array.from(input.files ?? []).slice(0, maxCount);
968
+ if (files.length === 0) {
969
+ reject(/* @__PURE__ */ new Error("No files selected"));
970
+ return;
971
+ }
972
+ resolve(await Promise.all(files.map((file) => new Promise((res, rej) => {
973
+ const reader = new FileReader();
974
+ reader.onload = () => res({
975
+ id: crypto.randomUUID(),
976
+ dataUri: reader.result
977
+ });
978
+ reader.onerror = () => rej(/* @__PURE__ */ new Error("Failed to read file"));
979
+ reader.readAsDataURL(file);
980
+ }))));
981
+ };
982
+ const onFocus = () => {
983
+ setTimeout(() => {
984
+ if (!settled) reject(/* @__PURE__ */ new Error("File picker cancelled"));
985
+ window.removeEventListener("focus", onFocus);
986
+ }, 300);
987
+ };
988
+ window.addEventListener("focus", onFocus);
989
+ input.click();
990
+ });
991
+ }
992
+ async function fetchAlbumPhotosPrompt(maxCount) {
993
+ return (await waitForPromptResponse("photos")).slice(0, maxCount).map((dataUri) => ({
994
+ id: crypto.randomUUID(),
995
+ dataUri
996
+ }));
997
+ }
998
+ const _fetchAlbumPhotos = async (options) => {
999
+ checkPermission("photos", "fetchAlbumPhotos");
1000
+ const maxCount = options?.maxCount ?? 10;
1001
+ const mode = aitState.state.deviceModes.photos;
1002
+ if (mode === "web") return fetchAlbumPhotosWeb(maxCount);
1003
+ if (mode === "prompt") return fetchAlbumPhotosPrompt(maxCount);
1004
+ return fetchAlbumPhotosMock(maxCount);
1005
+ };
1006
+ withPermission(_fetchAlbumPhotos, "photos");
1007
+ //#endregion
1008
+ //#region src/mock/device/clipboard.ts
1009
+ /**
1010
+ * Clipboard mock
1011
+ * mock/web 모드 지원
1012
+ */
1013
+ const _getClipboardText = async () => {
1014
+ checkPermission("clipboard", "getClipboardText");
1015
+ if (aitState.state.deviceModes.clipboard === "mock") return aitState.state.mockData.clipboardText;
1016
+ try {
1017
+ return await navigator.clipboard.readText();
1018
+ } catch {
1019
+ return "";
1020
+ }
1021
+ };
1022
+ withPermission(_getClipboardText, "clipboard");
1023
+ const _setClipboardText = async (text) => {
1024
+ checkPermission("clipboard", "setClipboardText");
1025
+ if (aitState.state.deviceModes.clipboard === "mock") {
1026
+ aitState.patch("mockData", { clipboardText: text });
1027
+ return;
1028
+ }
1029
+ await navigator.clipboard.writeText(text);
1030
+ };
1031
+ withPermission(_setClipboardText, "clipboard");
1032
+ //#endregion
1033
+ //#region src/mock/device/contacts.ts
1034
+ /**
1035
+ * Contacts mock
1036
+ */
1037
+ const _fetchContacts = async (options) => {
1038
+ checkPermission("contacts", "fetchContacts");
1039
+ let contacts = aitState.state.contacts;
1040
+ if (options.query?.contains) {
1041
+ const q = options.query.contains.toLowerCase();
1042
+ contacts = contacts.filter((c) => c.name.toLowerCase().includes(q) || c.phoneNumber.includes(q));
1043
+ }
1044
+ const sliced = contacts.slice(options.offset, options.offset + options.size);
1045
+ const nextOffset = options.offset + options.size;
1046
+ return {
1047
+ result: sliced,
1048
+ nextOffset: nextOffset < contacts.length ? nextOffset : null,
1049
+ done: nextOffset >= contacts.length
1050
+ };
1051
+ };
1052
+ withPermission(_fetchContacts, "contacts");
1053
+ //#endregion
1054
+ //#region src/panel/tabs/device.ts
1055
+ let pendingPrompt = null;
1056
+ let refreshPanel$1 = () => {};
1057
+ function setDeviceRefreshPanel(fn) {
1058
+ refreshPanel$1 = fn;
1059
+ }
1060
+ if (typeof window !== "undefined") window.addEventListener("__ait:prompt-request", (e) => {
1061
+ pendingPrompt = { type: e.detail.type };
1062
+ window.dispatchEvent(new CustomEvent("__ait:panel-switch-tab", { detail: { tab: "device" } }));
1063
+ });
662
1064
  function resolvePrompt(type, data) {
663
- window.dispatchEvent(new CustomEvent("__ait:prompt-response:" + type, { detail: data }));
664
- pendingPrompt = null;
665
- refreshPanel();
1065
+ window.dispatchEvent(new CustomEvent("__ait:prompt-response:" + type, { detail: data }));
1066
+ pendingPrompt = null;
1067
+ refreshPanel$1();
666
1068
  }
667
1069
  function renderPromptBanner() {
668
- if (!pendingPrompt) return null;
669
- const banner = h("div", { className: "ait-prompt-banner" });
670
- if (pendingPrompt.type === "camera") {
671
- banner.append(
672
- h("div", { className: "ait-prompt-title" }, "Camera Prompt \u2014 Select an image")
673
- );
674
- const input = h("input", { type: "file", accept: "image/*", style: "font-size:11px;color:#aaa" });
675
- input.addEventListener("change", () => {
676
- const file = input.files?.[0];
677
- if (!file) return;
678
- const reader = new FileReader();
679
- reader.onload = () => resolvePrompt("camera", reader.result);
680
- reader.readAsDataURL(file);
681
- });
682
- banner.appendChild(input);
683
- } else if (pendingPrompt.type === "photos") {
684
- banner.append(
685
- h("div", { className: "ait-prompt-title" }, "Photos Prompt \u2014 Select images")
686
- );
687
- const input = h("input", { type: "file", accept: "image/*", multiple: "", style: "font-size:11px;color:#aaa" });
688
- input.addEventListener("change", () => {
689
- const files = Array.from(input.files ?? []);
690
- if (files.length === 0) return;
691
- Promise.all(files.map((file) => new Promise((res) => {
692
- const reader = new FileReader();
693
- reader.onload = () => res(reader.result);
694
- reader.readAsDataURL(file);
695
- }))).then((dataUris) => resolvePrompt("photos", dataUris));
696
- });
697
- banner.appendChild(input);
698
- } else if (pendingPrompt.type === "location" || pendingPrompt.type === "location-update") {
699
- banner.append(
700
- h(
701
- "div",
702
- { className: "ait-prompt-title" },
703
- pendingPrompt.type === "location" ? "Location Prompt \u2014 Enter coordinates" : "Location Update \u2014 Send coordinates"
704
- )
705
- );
706
- const latInput = h("input", { className: "ait-input", value: String(aitState.state.location.coords.latitude), style: "width:80px" });
707
- const lngInput = h("input", { className: "ait-input", value: String(aitState.state.location.coords.longitude), style: "width:80px" });
708
- const sendBtn = h("button", { className: "ait-btn ait-btn-sm" }, "Send");
709
- sendBtn.addEventListener("click", () => {
710
- const loc = {
711
- coords: {
712
- latitude: Number(latInput.value),
713
- longitude: Number(lngInput.value),
714
- altitude: 0,
715
- accuracy: 10,
716
- altitudeAccuracy: 0,
717
- heading: 0
718
- },
719
- timestamp: Date.now(),
720
- accessLocation: "FINE"
721
- };
722
- resolvePrompt(pendingPrompt.type, loc);
723
- });
724
- banner.append(
725
- h(
726
- "div",
727
- { className: "ait-prompt-input-row" },
728
- h("label", {}, "Lat"),
729
- latInput,
730
- h("label", {}, "Lng"),
731
- lngInput,
732
- sendBtn
733
- )
734
- );
735
- } else {
736
- banner.append(
737
- h("div", { className: "ait-prompt-title" }, `Prompt: ${pendingPrompt.type}`)
738
- );
739
- }
740
- const cancelBtn = h("button", { className: "ait-btn ait-btn-sm ait-btn-danger", style: "margin-top:8px" }, "Cancel");
741
- cancelBtn.addEventListener("click", () => {
742
- pendingPrompt = null;
743
- window.dispatchEvent(new CustomEvent("__ait:prompt-cancel"));
744
- refreshPanel();
745
- });
746
- banner.appendChild(cancelBtn);
747
- return banner;
1070
+ if (!pendingPrompt) return null;
1071
+ const banner = h("div", { className: "ait-prompt-banner" });
1072
+ if (pendingPrompt.type === "camera") {
1073
+ banner.append(h("div", { className: "ait-prompt-title" }, "Camera Prompt — Select an image"));
1074
+ const input = h("input", {
1075
+ type: "file",
1076
+ accept: "image/*",
1077
+ style: "font-size:11px;color:#aaa"
1078
+ });
1079
+ input.addEventListener("change", () => {
1080
+ const file = input.files?.[0];
1081
+ if (!file) return;
1082
+ const reader = new FileReader();
1083
+ reader.onload = () => resolvePrompt("camera", reader.result);
1084
+ reader.readAsDataURL(file);
1085
+ });
1086
+ banner.appendChild(input);
1087
+ } else if (pendingPrompt.type === "photos") {
1088
+ banner.append(h("div", { className: "ait-prompt-title" }, "Photos Prompt — Select images"));
1089
+ const input = h("input", {
1090
+ type: "file",
1091
+ accept: "image/*",
1092
+ multiple: "",
1093
+ style: "font-size:11px;color:#aaa"
1094
+ });
1095
+ input.addEventListener("change", () => {
1096
+ const files = Array.from(input.files ?? []);
1097
+ if (files.length === 0) return;
1098
+ Promise.all(files.map((file) => new Promise((res) => {
1099
+ const reader = new FileReader();
1100
+ reader.onload = () => res(reader.result);
1101
+ reader.readAsDataURL(file);
1102
+ }))).then((dataUris) => resolvePrompt("photos", dataUris));
1103
+ });
1104
+ banner.appendChild(input);
1105
+ } else if (pendingPrompt.type === "location" || pendingPrompt.type === "location-update") {
1106
+ banner.append(h("div", { className: "ait-prompt-title" }, pendingPrompt.type === "location" ? "Location Prompt — Enter coordinates" : "Location Update — Send coordinates"));
1107
+ const latInput = h("input", {
1108
+ className: "ait-input",
1109
+ value: String(aitState.state.location.coords.latitude),
1110
+ style: "width:80px"
1111
+ });
1112
+ const lngInput = h("input", {
1113
+ className: "ait-input",
1114
+ value: String(aitState.state.location.coords.longitude),
1115
+ style: "width:80px"
1116
+ });
1117
+ const sendBtn = h("button", { className: "ait-btn ait-btn-sm" }, "Send");
1118
+ sendBtn.addEventListener("click", () => {
1119
+ const loc = {
1120
+ coords: {
1121
+ latitude: Number(latInput.value),
1122
+ longitude: Number(lngInput.value),
1123
+ altitude: 0,
1124
+ accuracy: 10,
1125
+ altitudeAccuracy: 0,
1126
+ heading: 0
1127
+ },
1128
+ timestamp: Date.now(),
1129
+ accessLocation: "FINE"
1130
+ };
1131
+ resolvePrompt(pendingPrompt.type, loc);
1132
+ });
1133
+ banner.append(h("div", { className: "ait-prompt-input-row" }, h("label", {}, "Lat"), latInput, h("label", {}, "Lng"), lngInput, sendBtn));
1134
+ } else banner.append(h("div", { className: "ait-prompt-title" }, `Prompt: ${pendingPrompt.type}`));
1135
+ const cancelBtn = h("button", {
1136
+ className: "ait-btn ait-btn-sm ait-btn-danger",
1137
+ style: "margin-top:8px"
1138
+ }, "Cancel");
1139
+ cancelBtn.addEventListener("click", () => {
1140
+ pendingPrompt = null;
1141
+ window.dispatchEvent(new CustomEvent("__ait:prompt-cancel"));
1142
+ refreshPanel$1();
1143
+ });
1144
+ banner.appendChild(cancelBtn);
1145
+ return banner;
748
1146
  }
749
1147
  function renderDeviceTab() {
750
- const s = aitState.state;
751
- const disabled = !s.panelEditable;
752
- const container = h("div");
753
- if (disabled) container.appendChild(monitoringNotice());
754
- if (s.panelEditable) {
755
- const promptBanner = renderPromptBanner();
756
- if (promptBanner) container.appendChild(promptBanner);
757
- }
758
- const modeEntries = [
759
- { label: "Camera", key: "camera", options: ["mock", "web", "prompt"] },
760
- { label: "Photos", key: "photos", options: ["mock", "web", "prompt"] },
761
- { label: "Location", key: "location", options: ["mock", "web", "prompt"] },
762
- { label: "Network", key: "network", options: ["mock", "web"] },
763
- { label: "Clipboard", key: "clipboard", options: ["mock", "web"] }
764
- ];
765
- container.append(
766
- h(
767
- "div",
768
- { className: "ait-section" },
769
- h("div", { className: "ait-section-title" }, "Device API Modes"),
770
- ...modeEntries.map(
771
- (entry) => selectRow(entry.label, entry.options, s.deviceModes[entry.key], (v) => {
772
- aitState.patch("deviceModes", { [entry.key]: v });
773
- refreshPanel();
774
- }, disabled)
775
- )
776
- )
777
- );
778
- const images = s.mockData.images;
779
- const imageGrid = h("div", { className: "ait-image-grid" });
780
- images.forEach((dataUri, idx) => {
781
- const thumb = h("div", { className: "ait-image-thumb" });
782
- const img = h("img", { src: dataUri });
783
- const removeBtn = h("button", { className: "ait-image-remove" }, "x");
784
- removeBtn.addEventListener("click", () => {
785
- const newImages = [...aitState.state.mockData.images];
786
- newImages.splice(idx, 1);
787
- aitState.patch("mockData", { images: newImages });
788
- refreshPanel();
789
- });
790
- if (disabled) removeBtn.disabled = true;
791
- thumb.append(img, removeBtn);
792
- imageGrid.appendChild(thumb);
793
- });
794
- const addBtn = h("button", { className: "ait-btn-secondary" }, "+ Add");
795
- addBtn.addEventListener("click", () => {
796
- const input = document.createElement("input");
797
- input.type = "file";
798
- input.accept = "image/*";
799
- input.multiple = true;
800
- input.onchange = () => {
801
- const files = Array.from(input.files ?? []);
802
- Promise.all(files.map((file) => new Promise((res) => {
803
- const reader = new FileReader();
804
- reader.onload = () => res(reader.result);
805
- reader.readAsDataURL(file);
806
- }))).then((dataUris) => {
807
- aitState.patch("mockData", { images: [...aitState.state.mockData.images, ...dataUris] });
808
- refreshPanel();
809
- });
810
- };
811
- input.click();
812
- });
813
- if (disabled) addBtn.disabled = true;
814
- const defaultsBtn = h("button", { className: "ait-btn-secondary" }, "Use defaults");
815
- defaultsBtn.addEventListener("click", () => {
816
- aitState.patch("mockData", { images: [...getDefaultPlaceholderImages()] });
817
- refreshPanel();
818
- });
819
- if (disabled) defaultsBtn.disabled = true;
820
- const clearImagesBtn = h("button", { className: "ait-btn-secondary" }, "Clear");
821
- clearImagesBtn.addEventListener("click", () => {
822
- aitState.patch("mockData", { images: [] });
823
- refreshPanel();
824
- });
825
- if (disabled) clearImagesBtn.disabled = true;
826
- container.append(
827
- h(
828
- "div",
829
- { className: "ait-section" },
830
- h("div", { className: "ait-section-title" }, `Mock Images (${images.length})`),
831
- imageGrid,
832
- h("div", { className: "ait-btn-row" }, addBtn, defaultsBtn, clearImagesBtn)
833
- )
834
- );
835
- return container;
1148
+ const s = aitState.state;
1149
+ const disabled = !s.panelEditable;
1150
+ const container = h("div");
1151
+ if (disabled) container.appendChild(monitoringNotice());
1152
+ if (s.panelEditable) {
1153
+ const promptBanner = renderPromptBanner();
1154
+ if (promptBanner) container.appendChild(promptBanner);
1155
+ }
1156
+ container.append(h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, "Device API Modes"), ...[
1157
+ {
1158
+ label: "Camera",
1159
+ key: "camera",
1160
+ options: [
1161
+ "mock",
1162
+ "web",
1163
+ "prompt"
1164
+ ]
1165
+ },
1166
+ {
1167
+ label: "Photos",
1168
+ key: "photos",
1169
+ options: [
1170
+ "mock",
1171
+ "web",
1172
+ "prompt"
1173
+ ]
1174
+ },
1175
+ {
1176
+ label: "Location",
1177
+ key: "location",
1178
+ options: [
1179
+ "mock",
1180
+ "web",
1181
+ "prompt"
1182
+ ]
1183
+ },
1184
+ {
1185
+ label: "Network",
1186
+ key: "network",
1187
+ options: ["mock", "web"]
1188
+ },
1189
+ {
1190
+ label: "Clipboard",
1191
+ key: "clipboard",
1192
+ options: ["mock", "web"]
1193
+ }
1194
+ ].map((entry) => selectRow(entry.label, entry.options, s.deviceModes[entry.key], (v) => {
1195
+ aitState.patch("deviceModes", { [entry.key]: v });
1196
+ }, disabled))));
1197
+ const images = s.mockData.images;
1198
+ const imageGrid = h("div", { className: "ait-image-grid" });
1199
+ images.forEach((dataUri, idx) => {
1200
+ const thumb = h("div", { className: "ait-image-thumb" });
1201
+ const img = h("img", { src: dataUri });
1202
+ const removeBtn = h("button", { className: "ait-image-remove" }, "x");
1203
+ removeBtn.addEventListener("click", () => {
1204
+ const newImages = [...aitState.state.mockData.images];
1205
+ newImages.splice(idx, 1);
1206
+ aitState.patch("mockData", { images: newImages });
1207
+ });
1208
+ if (disabled) removeBtn.disabled = true;
1209
+ thumb.append(img, removeBtn);
1210
+ imageGrid.appendChild(thumb);
1211
+ });
1212
+ const addBtn = h("button", { className: "ait-btn-secondary" }, "+ Add");
1213
+ addBtn.addEventListener("click", () => {
1214
+ const input = document.createElement("input");
1215
+ input.type = "file";
1216
+ input.accept = "image/*";
1217
+ input.multiple = true;
1218
+ input.onchange = () => {
1219
+ const files = Array.from(input.files ?? []);
1220
+ Promise.all(files.map((file) => new Promise((res) => {
1221
+ const reader = new FileReader();
1222
+ reader.onload = () => res(reader.result);
1223
+ reader.readAsDataURL(file);
1224
+ }))).then((dataUris) => {
1225
+ aitState.patch("mockData", { images: [...aitState.state.mockData.images, ...dataUris] });
1226
+ });
1227
+ };
1228
+ input.click();
1229
+ });
1230
+ if (disabled) addBtn.disabled = true;
1231
+ const defaultsBtn = h("button", { className: "ait-btn-secondary" }, "Use defaults");
1232
+ defaultsBtn.addEventListener("click", () => {
1233
+ aitState.patch("mockData", { images: [...getDefaultPlaceholderImages()] });
1234
+ });
1235
+ if (disabled) defaultsBtn.disabled = true;
1236
+ const clearImagesBtn = h("button", { className: "ait-btn-secondary" }, "Clear");
1237
+ clearImagesBtn.addEventListener("click", () => {
1238
+ aitState.patch("mockData", { images: [] });
1239
+ });
1240
+ if (disabled) clearImagesBtn.disabled = true;
1241
+ container.append(h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, `Mock Images (${images.length})`), imageGrid, h("div", { className: "ait-btn-row" }, addBtn, defaultsBtn, clearImagesBtn)));
1242
+ return container;
836
1243
  }
837
- function monitoringNotice() {
838
- return h(
839
- "div",
840
- { className: "ait-monitoring-notice" },
841
- "Read-only \u2014 mock responses are controlled at build time."
842
- );
1244
+ //#endregion
1245
+ //#region src/panel/tabs/iap.ts
1246
+ function renderIapTab() {
1247
+ const s = aitState.state;
1248
+ const disabled = !s.panelEditable;
1249
+ const container = h("div");
1250
+ const results = [
1251
+ "success",
1252
+ "USER_CANCELED",
1253
+ "INVALID_PRODUCT_ID",
1254
+ "PAYMENT_PENDING",
1255
+ "NETWORK_ERROR",
1256
+ "ITEM_ALREADY_OWNED",
1257
+ "INTERNAL_ERROR"
1258
+ ];
1259
+ if (disabled) container.appendChild(monitoringNotice());
1260
+ container.append(h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, "IAP Simulator"), selectRow("Next Purchase Result", results, s.iap.nextResult, (v) => {
1261
+ aitState.patch("iap", { nextResult: v });
1262
+ }, disabled)), h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, "TossPay"), selectRow("Next Payment Result", ["success", "fail"], s.payment.nextResult, (v) => {
1263
+ aitState.patch("payment", { nextResult: v });
1264
+ }, disabled)), h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, `Completed Orders (${s.iap.completedOrders.length})`), ...s.iap.completedOrders.slice(-5).map((o) => h("div", { className: "ait-log-entry" }, h("span", { className: "ait-log-type" }, o.status), `${o.sku} (${o.orderId.slice(-8)})`))));
1265
+ return container;
843
1266
  }
844
- var TAB_RENDERERS = {
845
- env: renderEnvTab,
846
- permissions: renderPermissionsTab,
847
- location: renderLocationTab,
848
- device: renderDeviceTab,
849
- iap: renderIapTab,
850
- events: renderEventsTab,
851
- analytics: renderAnalyticsTab,
852
- storage: renderStorageTab
853
- };
1267
+ //#endregion
1268
+ //#region src/panel/tabs/events.ts
1269
+ function renderEventsTab() {
1270
+ const disabled = !aitState.state.panelEditable;
1271
+ const container = h("div");
1272
+ if (disabled) container.appendChild(monitoringNotice());
1273
+ const backBtn = h("button", { className: "ait-btn" }, "Trigger Back Event");
1274
+ backBtn.addEventListener("click", () => aitState.trigger("backEvent"));
1275
+ if (disabled) backBtn.disabled = true;
1276
+ const homeBtn = h("button", { className: "ait-btn" }, "Trigger Home Event");
1277
+ homeBtn.addEventListener("click", () => aitState.trigger("homeEvent"));
1278
+ if (disabled) homeBtn.disabled = true;
1279
+ container.append(h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, "Navigation Events"), h("div", { className: "ait-row" }, backBtn, homeBtn)), h("div", { className: "ait-section" }, h("div", { className: "ait-section-title" }, "Login"), selectRow("Logged In", ["true", "false"], String(aitState.state.auth.isLoggedIn), (v) => {
1280
+ aitState.patch("auth", { isLoggedIn: v === "true" });
1281
+ }, disabled), selectRow("Toss Login Integrated", ["true", "false"], String(aitState.state.auth.isTossLoginIntegrated), (v) => {
1282
+ aitState.patch("auth", { isTossLoginIntegrated: v === "true" });
1283
+ }, disabled)));
1284
+ return container;
1285
+ }
1286
+ //#endregion
1287
+ //#region src/panel/tabs/analytics.ts
1288
+ function renderAnalyticsTab() {
1289
+ const disabled = !aitState.state.panelEditable;
1290
+ const container = h("div");
1291
+ if (disabled) container.appendChild(monitoringNotice());
1292
+ const logs = aitState.state.analyticsLog;
1293
+ const clearBtn = h("button", { className: "ait-btn ait-btn-sm ait-btn-danger" }, "Clear");
1294
+ if (disabled) clearBtn.disabled = true;
1295
+ clearBtn.addEventListener("click", () => {
1296
+ aitState.update({ analyticsLog: [] });
1297
+ });
1298
+ container.append(h("div", { className: "ait-section" }, h("div", { className: "ait-row" }, h("div", { className: "ait-section-title" }, `Analytics Log (${logs.length})`), clearBtn), ...logs.slice(-30).reverse().map((entry) => {
1299
+ return h("div", { className: "ait-log-entry" }, h("span", { className: "ait-log-time" }, new Date(entry.timestamp).toLocaleTimeString("ko-KR", { hour12: false })), h("span", { className: "ait-log-type" }, entry.type), JSON.stringify(entry.params));
1300
+ })));
1301
+ return container;
1302
+ }
1303
+ //#endregion
1304
+ //#region src/panel/tabs/storage.ts
1305
+ function renderStorageTab(refreshPanel) {
1306
+ const disabled = !aitState.state.panelEditable;
1307
+ const container = h("div");
1308
+ if (disabled) container.appendChild(monitoringNotice());
1309
+ const prefix = "__ait_storage:";
1310
+ const entries = [];
1311
+ for (let i = 0; i < localStorage.length; i++) {
1312
+ const key = localStorage.key(i);
1313
+ if (key?.startsWith(prefix)) entries.push([key.slice(14), localStorage.getItem(key) ?? ""]);
1314
+ }
1315
+ const clearBtn = h("button", { className: "ait-btn ait-btn-sm ait-btn-danger" }, "Clear All");
1316
+ if (disabled) clearBtn.disabled = true;
1317
+ clearBtn.addEventListener("click", () => {
1318
+ entries.forEach(([key]) => localStorage.removeItem(prefix + key));
1319
+ refreshPanel();
1320
+ });
1321
+ container.append(h("div", { className: "ait-section" }, h("div", { className: "ait-row" }, h("div", { className: "ait-section-title" }, `Storage (${entries.length} items)`), clearBtn), entries.length === 0 ? h("div", { style: "color:#555;font-size:12px" }, "No items in storage") : h("div", {}, ...entries.map(([key, value]) => h("div", { className: "ait-storage-row" }, h("span", { className: "ait-storage-key" }, key), h("span", { className: "ait-storage-value" }, value.length > 100 ? value.slice(0, 100) + "..." : value))))));
1322
+ return container;
1323
+ }
1324
+ //#endregion
1325
+ //#region src/panel/tabs/index.ts
1326
+ const TABS = [
1327
+ {
1328
+ id: "env",
1329
+ label: "Environment"
1330
+ },
1331
+ {
1332
+ id: "permissions",
1333
+ label: "Permissions"
1334
+ },
1335
+ {
1336
+ id: "location",
1337
+ label: "Location"
1338
+ },
1339
+ {
1340
+ id: "device",
1341
+ label: "Device"
1342
+ },
1343
+ {
1344
+ id: "iap",
1345
+ label: "IAP"
1346
+ },
1347
+ {
1348
+ id: "events",
1349
+ label: "Events"
1350
+ },
1351
+ {
1352
+ id: "analytics",
1353
+ label: "Analytics"
1354
+ },
1355
+ {
1356
+ id: "storage",
1357
+ label: "Storage"
1358
+ }
1359
+ ];
1360
+ function createTabRenderers(refreshPanel) {
1361
+ return {
1362
+ env: renderEnvironmentTab,
1363
+ permissions: renderPermissionsTab,
1364
+ location: renderLocationTab,
1365
+ device: renderDeviceTab,
1366
+ iap: renderIapTab,
1367
+ events: renderEventsTab,
1368
+ analytics: renderAnalyticsTab,
1369
+ storage: () => renderStorageTab(refreshPanel)
1370
+ };
1371
+ }
1372
+ //#endregion
1373
+ //#region src/panel/index.ts
1374
+ /**
1375
+ * @ait-co/devtools Floating Panel
1376
+ *
1377
+ * import 하면 자동으로 페이지에 DevTools 패널을 마운트한다.
1378
+ * 외부 의존성 없이 vanilla DOM으로 구현.
1379
+ */
854
1380
  function makeDraggable(el, onClickOnly) {
855
- let isDragging = false;
856
- let startX = 0, startY = 0;
857
- let startLeft = 0, startTop = 0;
858
- let hasMoved = false;
859
- el.addEventListener("pointerdown", (e) => {
860
- isDragging = true;
861
- hasMoved = false;
862
- startX = e.clientX;
863
- startY = e.clientY;
864
- const rect = el.getBoundingClientRect();
865
- startLeft = rect.left;
866
- startTop = rect.top;
867
- el.setPointerCapture(e.pointerId);
868
- e.preventDefault();
869
- });
870
- el.addEventListener("pointermove", (e) => {
871
- if (!isDragging) return;
872
- const dx = e.clientX - startX;
873
- const dy = e.clientY - startY;
874
- if (Math.abs(dx) > 3 || Math.abs(dy) > 3) {
875
- hasMoved = true;
876
- el.classList.add("dragging");
877
- }
878
- if (!hasMoved) return;
879
- el.style.left = startLeft + dx + "px";
880
- el.style.top = startTop + dy + "px";
881
- el.style.right = "auto";
882
- el.style.bottom = "auto";
883
- });
884
- el.addEventListener("pointerup", (e) => {
885
- if (!isDragging) return;
886
- isDragging = false;
887
- el.classList.remove("dragging");
888
- el.releasePointerCapture(e.pointerId);
889
- if (hasMoved) {
890
- snapToEdge(el);
891
- updatePanelPosition(el);
892
- saveButtonPosition(el);
893
- } else {
894
- onClickOnly();
895
- }
896
- });
897
- el.addEventListener("pointercancel", (e) => {
898
- isDragging = false;
899
- el.classList.remove("dragging");
900
- el.releasePointerCapture(e.pointerId);
901
- if (hasMoved) {
902
- snapToEdge(el);
903
- updatePanelPosition(el);
904
- saveButtonPosition(el);
905
- }
906
- });
1381
+ let isDragging = false;
1382
+ let startX = 0, startY = 0;
1383
+ let startLeft = 0, startTop = 0;
1384
+ let hasMoved = false;
1385
+ el.addEventListener("pointerdown", (e) => {
1386
+ isDragging = true;
1387
+ hasMoved = false;
1388
+ startX = e.clientX;
1389
+ startY = e.clientY;
1390
+ const rect = el.getBoundingClientRect();
1391
+ startLeft = rect.left;
1392
+ startTop = rect.top;
1393
+ el.setPointerCapture(e.pointerId);
1394
+ e.preventDefault();
1395
+ });
1396
+ el.addEventListener("pointermove", (e) => {
1397
+ if (!isDragging) return;
1398
+ const dx = e.clientX - startX;
1399
+ const dy = e.clientY - startY;
1400
+ if (Math.abs(dx) > 3 || Math.abs(dy) > 3) {
1401
+ hasMoved = true;
1402
+ el.classList.add("dragging");
1403
+ }
1404
+ if (!hasMoved) return;
1405
+ el.style.left = startLeft + dx + "px";
1406
+ el.style.top = startTop + dy + "px";
1407
+ el.style.right = "auto";
1408
+ el.style.bottom = "auto";
1409
+ });
1410
+ el.addEventListener("pointerup", (e) => {
1411
+ if (!isDragging) return;
1412
+ isDragging = false;
1413
+ el.classList.remove("dragging");
1414
+ el.releasePointerCapture(e.pointerId);
1415
+ if (hasMoved) {
1416
+ snapToEdge(el);
1417
+ updatePanelPosition(el);
1418
+ saveButtonPosition(el);
1419
+ } else onClickOnly();
1420
+ });
1421
+ el.addEventListener("pointercancel", (e) => {
1422
+ isDragging = false;
1423
+ el.classList.remove("dragging");
1424
+ el.releasePointerCapture(e.pointerId);
1425
+ if (hasMoved) {
1426
+ snapToEdge(el);
1427
+ updatePanelPosition(el);
1428
+ saveButtonPosition(el);
1429
+ }
1430
+ });
907
1431
  }
908
1432
  function snapToEdge(el) {
909
- const rect = el.getBoundingClientRect();
910
- const vw = window.innerWidth;
911
- const vh = window.innerHeight;
912
- const cx = rect.left + rect.width / 2;
913
- const margin = 16;
914
- if (cx < vw / 2) {
915
- el.style.left = margin + "px";
916
- el.style.right = "auto";
917
- } else {
918
- el.style.left = "auto";
919
- el.style.right = margin + "px";
920
- }
921
- const top = Math.max(margin, Math.min(vh - rect.height - margin, rect.top));
922
- el.style.top = top + "px";
923
- el.style.bottom = "auto";
1433
+ const rect = el.getBoundingClientRect();
1434
+ const vw = window.innerWidth;
1435
+ const vh = window.innerHeight;
1436
+ const cx = rect.left + rect.width / 2;
1437
+ const margin = 16;
1438
+ if (cx < vw / 2) {
1439
+ el.style.left = margin + "px";
1440
+ el.style.right = "auto";
1441
+ } else {
1442
+ el.style.left = "auto";
1443
+ el.style.right = margin + "px";
1444
+ }
1445
+ const top = Math.max(margin, Math.min(vh - rect.height - margin, rect.top));
1446
+ el.style.top = top + "px";
1447
+ el.style.bottom = "auto";
924
1448
  }
925
1449
  function updatePanelPosition(toggleEl) {
926
- if (!panelEl) return;
927
- const vw = window.innerWidth;
928
- const vh = window.innerHeight;
929
- if (vw <= 480) {
930
- panelEl.style.top = "";
931
- panelEl.style.left = "";
932
- panelEl.style.right = "";
933
- panelEl.style.bottom = "";
934
- return;
935
- }
936
- const rect = toggleEl.getBoundingClientRect();
937
- const panelWidth = PANEL_WIDTH;
938
- const panelHeight = PANEL_HEIGHT;
939
- const margin = 16;
940
- if (rect.left < vw / 2) {
941
- panelEl.style.left = margin + "px";
942
- panelEl.style.right = "auto";
943
- } else {
944
- panelEl.style.left = "auto";
945
- panelEl.style.right = margin + "px";
946
- }
947
- if (rect.top < vh / 2) {
948
- const top = Math.min(rect.bottom + 8, vh - panelHeight - margin);
949
- panelEl.style.top = Math.max(margin, top) + "px";
950
- panelEl.style.bottom = "auto";
951
- } else {
952
- const bottom = Math.min(vh - rect.top + 8, vh - panelHeight - margin);
953
- panelEl.style.top = "auto";
954
- panelEl.style.bottom = Math.max(margin, bottom) + "px";
955
- }
1450
+ if (!panelEl) return;
1451
+ const vw = window.innerWidth;
1452
+ const vh = window.innerHeight;
1453
+ if (vw <= 480) {
1454
+ panelEl.style.top = "";
1455
+ panelEl.style.left = "";
1456
+ panelEl.style.right = "";
1457
+ panelEl.style.bottom = "";
1458
+ return;
1459
+ }
1460
+ const rect = toggleEl.getBoundingClientRect();
1461
+ const panelHeight = 480;
1462
+ const margin = 16;
1463
+ if (rect.left < vw / 2) {
1464
+ panelEl.style.left = margin + "px";
1465
+ panelEl.style.right = "auto";
1466
+ } else {
1467
+ panelEl.style.left = "auto";
1468
+ panelEl.style.right = margin + "px";
1469
+ }
1470
+ if (rect.top < vh / 2) {
1471
+ const top = Math.min(rect.bottom + 8, vh - panelHeight - margin);
1472
+ panelEl.style.top = Math.max(margin, top) + "px";
1473
+ panelEl.style.bottom = "auto";
1474
+ } else {
1475
+ const bottom = Math.min(vh - rect.top + 8, vh - panelHeight - margin);
1476
+ panelEl.style.top = "auto";
1477
+ panelEl.style.bottom = Math.max(margin, bottom) + "px";
1478
+ }
956
1479
  }
957
1480
  function saveButtonPosition(el) {
958
- localStorage.setItem("__ait_btn_pos", JSON.stringify({
959
- left: el.style.left,
960
- top: el.style.top,
961
- right: el.style.right,
962
- bottom: el.style.bottom
963
- }));
1481
+ localStorage.setItem("__ait_btn_pos", JSON.stringify({
1482
+ left: el.style.left,
1483
+ top: el.style.top,
1484
+ right: el.style.right,
1485
+ bottom: el.style.bottom
1486
+ }));
964
1487
  }
965
1488
  function restoreButtonPosition(el) {
966
- const saved = localStorage.getItem("__ait_btn_pos");
967
- if (saved) {
968
- try {
969
- const pos = JSON.parse(saved);
970
- if (typeof pos !== "object" || pos === null) return;
971
- const allowedKeys = ["left", "top", "right", "bottom"];
972
- const validCssValue = /^(\d+px|auto)$/;
973
- for (const key of allowedKeys) {
974
- if (key in pos && typeof pos[key] === "string" && validCssValue.test(pos[key])) {
975
- el.style[key] = pos[key];
976
- }
977
- }
978
- } catch {
979
- }
980
- } else {
981
- el.style.bottom = "16px";
982
- el.style.right = "16px";
983
- }
1489
+ const saved = localStorage.getItem("__ait_btn_pos");
1490
+ if (saved) try {
1491
+ const pos = JSON.parse(saved);
1492
+ if (typeof pos !== "object" || pos === null) return;
1493
+ const allowedKeys = [
1494
+ "left",
1495
+ "top",
1496
+ "right",
1497
+ "bottom"
1498
+ ];
1499
+ const validCssValue = /^(\d+px|auto)$/;
1500
+ for (const key of allowedKeys) if (key in pos && typeof pos[key] === "string" && validCssValue.test(pos[key])) el.style[key] = pos[key];
1501
+ } catch {}
1502
+ else {
1503
+ el.style.bottom = "16px";
1504
+ el.style.right = "16px";
1505
+ }
984
1506
  }
985
- var currentTab = "env";
986
- var panelEl = null;
987
- var bodyEl = null;
988
- var tabsEl = null;
1507
+ let currentTab = "env";
1508
+ let isOpen = false;
1509
+ let panelEl = null;
1510
+ let bodyEl = null;
1511
+ let tabsEl = null;
1512
+ let tabRenderers = null;
989
1513
  function refreshPanel() {
990
- if (!bodyEl || !tabsEl) return;
991
- bodyEl.innerHTML = "";
992
- bodyEl.appendChild(TAB_RENDERERS[currentTab]());
993
- tabsEl.querySelectorAll(".ait-panel-tab").forEach((el) => {
994
- el.classList.toggle("active", el.getAttribute("data-tab") === currentTab);
995
- });
1514
+ if (!bodyEl || !tabsEl) return;
1515
+ if (!tabRenderers) tabRenderers = createTabRenderers(refreshPanel);
1516
+ bodyEl.innerHTML = "";
1517
+ try {
1518
+ bodyEl.appendChild(tabRenderers[currentTab]());
1519
+ } catch (err) {
1520
+ console.error(`[@ait-co/devtools] Error rendering tab "${currentTab}":`, err);
1521
+ bodyEl.appendChild(h("div", { className: "ait-panel-tab-error" }, `Error rendering "${currentTab}" tab.`));
1522
+ }
1523
+ tabsEl.querySelectorAll(".ait-panel-tab").forEach((el) => {
1524
+ el.classList.toggle("active", el.getAttribute("data-tab") === currentTab);
1525
+ });
996
1526
  }
1527
+ if (typeof window !== "undefined") window.addEventListener("__ait:panel-switch-tab", (e) => {
1528
+ currentTab = e.detail.tab;
1529
+ if (panelEl && !panelEl.classList.contains("open")) {
1530
+ isOpen = true;
1531
+ panelEl.classList.add("open");
1532
+ }
1533
+ refreshPanel();
1534
+ });
997
1535
  function mount() {
998
- if (typeof document === "undefined") return;
999
- if (document.querySelector(".ait-panel-toggle")) return;
1000
- const style = document.createElement("style");
1001
- style.textContent = PANEL_STYLES;
1002
- document.head.appendChild(style);
1003
- const toggle = h("button", { className: "ait-panel-toggle", title: "AIT DevTools" }, "AIT");
1004
- let isOpen = false;
1005
- restoreButtonPosition(toggle);
1006
- panelEl = h("div", { className: "ait-panel" });
1007
- const closeBtn = h("button", { className: "ait-panel-close", title: "Close" }, "\xD7");
1008
- closeBtn.addEventListener("click", () => {
1009
- isOpen = false;
1010
- panelEl.classList.remove("open");
1011
- });
1012
- const mockBadge = h("span", {
1013
- className: `ait-mock-badge ${aitState.state.panelEditable ? "ait-mock-badge-on" : "ait-mock-badge-off"}`,
1014
- title: "Toggle panel edit mode"
1015
- }, aitState.state.panelEditable ? "EDIT" : "READ-ONLY");
1016
- mockBadge.addEventListener("click", () => {
1017
- aitState.update({ panelEditable: !aitState.state.panelEditable });
1018
- mockBadge.className = `ait-mock-badge ${aitState.state.panelEditable ? "ait-mock-badge-on" : "ait-mock-badge-off"}`;
1019
- mockBadge.textContent = aitState.state.panelEditable ? "EDIT" : "READ-ONLY";
1020
- refreshPanel();
1021
- });
1022
- const headerRight = h(
1023
- "span",
1024
- { style: "display:flex;align-items:center;gap:6px" },
1025
- mockBadge,
1026
- h("span", { style: "font-size:11px;color:#666;font-weight:400" }, `v${"0.0.2"}`),
1027
- closeBtn
1028
- );
1029
- const header = h(
1030
- "div",
1031
- { className: "ait-panel-header" },
1032
- h("span", {}, "AIT DevTools"),
1033
- headerRight
1034
- );
1035
- tabsEl = h("div", { className: "ait-panel-tabs" });
1036
- for (const tab of TABS) {
1037
- const tabEl = h("button", { className: "ait-panel-tab", "data-tab": tab.id }, tab.label);
1038
- tabEl.addEventListener("click", () => {
1039
- currentTab = tab.id;
1040
- refreshPanel();
1041
- });
1042
- tabsEl.appendChild(tabEl);
1043
- }
1044
- bodyEl = h("div", { className: "ait-panel-body" });
1045
- panelEl.append(header, tabsEl, bodyEl);
1046
- document.body.append(panelEl, toggle);
1047
- snapToEdge(toggle);
1048
- saveButtonPosition(toggle);
1049
- makeDraggable(toggle, () => {
1050
- isOpen = !isOpen;
1051
- panelEl.classList.toggle("open", isOpen);
1052
- if (isOpen) {
1053
- updatePanelPosition(toggle);
1054
- refreshPanel();
1055
- }
1056
- });
1057
- let resizeRaf = 0;
1058
- window.addEventListener("resize", () => {
1059
- if (resizeRaf) return;
1060
- resizeRaf = requestAnimationFrame(() => {
1061
- resizeRaf = 0;
1062
- snapToEdge(toggle);
1063
- saveButtonPosition(toggle);
1064
- if (isOpen) updatePanelPosition(toggle);
1065
- });
1066
- });
1067
- aitState.subscribe(() => {
1068
- if (isOpen && (currentTab === "analytics" || currentTab === "storage" || currentTab === "device")) {
1069
- refreshPanel();
1070
- }
1071
- });
1072
- refreshPanel();
1536
+ if (typeof document === "undefined") return;
1537
+ if (document.querySelector(".ait-panel-toggle")) return;
1538
+ setDeviceRefreshPanel(refreshPanel);
1539
+ const style = document.createElement("style");
1540
+ style.textContent = PANEL_STYLES;
1541
+ document.head.appendChild(style);
1542
+ const toggle = h("button", {
1543
+ className: "ait-panel-toggle",
1544
+ title: "AIT DevTools"
1545
+ }, "AIT");
1546
+ restoreButtonPosition(toggle);
1547
+ panelEl = h("div", { className: "ait-panel" });
1548
+ const closeBtn = h("button", {
1549
+ className: "ait-panel-close",
1550
+ title: "Close"
1551
+ }, "×");
1552
+ closeBtn.addEventListener("click", () => {
1553
+ isOpen = false;
1554
+ panelEl.classList.remove("open");
1555
+ });
1556
+ const mockBadge = h("span", {
1557
+ className: `ait-mock-badge ${aitState.state.panelEditable ? "ait-mock-badge-on" : "ait-mock-badge-off"}`,
1558
+ title: "Toggle panel edit mode"
1559
+ }, aitState.state.panelEditable ? "EDIT" : "READ-ONLY");
1560
+ mockBadge.addEventListener("click", () => {
1561
+ aitState.update({ panelEditable: !aitState.state.panelEditable });
1562
+ mockBadge.className = `ait-mock-badge ${aitState.state.panelEditable ? "ait-mock-badge-on" : "ait-mock-badge-off"}`;
1563
+ mockBadge.textContent = aitState.state.panelEditable ? "EDIT" : "READ-ONLY";
1564
+ refreshPanel();
1565
+ });
1566
+ const headerRight = h("span", { style: "display:flex;align-items:center;gap:6px" }, mockBadge, h("span", { style: "font-size:11px;color:#666;font-weight:400" }, `v0.0.3`), closeBtn);
1567
+ const header = h("div", { className: "ait-panel-header" }, h("span", {}, "AIT DevTools"), headerRight);
1568
+ tabsEl = h("div", { className: "ait-panel-tabs" });
1569
+ for (const tab of TABS) {
1570
+ const tabEl = h("button", {
1571
+ className: "ait-panel-tab",
1572
+ "data-tab": tab.id
1573
+ }, tab.label);
1574
+ tabEl.addEventListener("click", () => {
1575
+ currentTab = tab.id;
1576
+ refreshPanel();
1577
+ });
1578
+ tabsEl.appendChild(tabEl);
1579
+ }
1580
+ bodyEl = h("div", { className: "ait-panel-body" });
1581
+ panelEl.append(header, tabsEl, bodyEl);
1582
+ document.body.append(panelEl, toggle);
1583
+ snapToEdge(toggle);
1584
+ saveButtonPosition(toggle);
1585
+ makeDraggable(toggle, () => {
1586
+ isOpen = !isOpen;
1587
+ panelEl.classList.toggle("open", isOpen);
1588
+ if (isOpen) {
1589
+ updatePanelPosition(toggle);
1590
+ refreshPanel();
1591
+ }
1592
+ });
1593
+ let resizeRaf = 0;
1594
+ window.addEventListener("resize", () => {
1595
+ if (resizeRaf) return;
1596
+ resizeRaf = requestAnimationFrame(() => {
1597
+ resizeRaf = 0;
1598
+ snapToEdge(toggle);
1599
+ saveButtonPosition(toggle);
1600
+ if (isOpen) updatePanelPosition(toggle);
1601
+ });
1602
+ });
1603
+ aitState.subscribe(() => {
1604
+ try {
1605
+ if (isOpen && (currentTab === "analytics" || currentTab === "storage" || currentTab === "device")) refreshPanel();
1606
+ } catch (err) {
1607
+ console.error("[@ait-co/devtools] Error in subscribe callback:", err);
1608
+ }
1609
+ });
1610
+ refreshPanel();
1073
1611
  }
1074
1612
  if (typeof document !== "undefined") {
1075
- if (document.readyState === "loading") {
1076
- document.addEventListener("DOMContentLoaded", mount);
1077
- } else {
1078
- mount();
1079
- }
1613
+ const safeMount = () => {
1614
+ try {
1615
+ mount();
1616
+ } catch (err) {
1617
+ console.error("[@ait-co/devtools] Failed to mount panel:", err);
1618
+ }
1619
+ };
1620
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", safeMount);
1621
+ else safeMount();
1080
1622
  }
1081
- export {
1082
- mount
1083
- };
1623
+ //#endregion
1624
+ export { mount };
1625
+
1084
1626
  //# sourceMappingURL=index.js.map