@howone/sdk 0.2.1 → 0.2.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.
package/dist/index.mjs CHANGED
@@ -697,17 +697,13 @@ var LoginForm = ({
697
697
  const [codeSent, setCodeSent] = useState2(false);
698
698
  const [loginError, setLoginError] = useState2(null);
699
699
  const googleLogin = async () => {
700
- console.log("Google login clicked");
701
700
  };
702
701
  const githubLogin = async () => {
703
- console.log("GitHub login clicked");
704
702
  };
705
703
  const sendEmailCode = async (email2) => {
706
- console.log("Send code to:", email2, "for app:", appName);
707
704
  setCodeSent(true);
708
705
  };
709
706
  const loginWithEmail = async (email2, code2) => {
710
- console.log("Login with email:", email2, "code:", code2);
711
707
  if (onLoginSuccess) onLoginSuccess();
712
708
  };
713
709
  const clearError = () => {
@@ -1154,11 +1150,9 @@ var ElementSelectorProvider = ({ children }) => {
1154
1150
  type: "ELEMENT_SELECTION_CANCELLED"
1155
1151
  }, "*");
1156
1152
  }
1157
- console.log("\u{1F6AB} \u5143\u7D20\u9009\u62E9\u5DF2\u53D6\u6D88 (ESC)");
1158
1153
  }, []);
1159
1154
  const handleSelect = useCallback3((data) => {
1160
1155
  sendElementSelectionToParent(data);
1161
- console.log("\u{1F3AF} \u5143\u7D20\u5DF2\u9009\u4E2D:", data.element.tagName, data.sourceLocation?.file);
1162
1156
  }, []);
1163
1157
  useEffect5(() => {
1164
1158
  const handleStartSelection = () => {
@@ -1210,14 +1204,12 @@ var ERROR_CONFIG = {
1210
1204
  LOW: ["info", "debug", "trace", "notice"]
1211
1205
  },
1212
1206
  CATEGORY_KEYWORDS: {
1213
- SYNTAX: ["syntaxerror", "unexpected token", "parse error", "invalid syntax"],
1207
+ SYNTAX: ["syntaxerror", "unexpected token", "parse error", "invalid syntax", "expected", "transform failed"],
1214
1208
  NETWORK: ["fetch", "xhr", "network", "cors", "timeout", "connection"],
1215
1209
  RUNTIME: ["referenceerror", "typeerror", "rangeerror", "undefined"],
1216
1210
  SECURITY: ["csp", "xss", "csrf", "security", "unauthorized"],
1217
1211
  PERFORMANCE: ["slow", "memory", "leak", "performance", "timeout"],
1218
- DEVELOPMENT: ["vite", "hmr", "hot reload", "dev server", "webpack"],
1219
- REACT: ["react", "jsx", "component", "hook", "render"],
1220
- VITE: ["vite", "[vite]", "vite:react", "transform failed"]
1212
+ DEVELOPMENT: ["vite", "hmr", "hot reload", "dev server", "webpack", "esbuild", "plugin:vite:esbuild"]
1221
1213
  }
1222
1214
  };
1223
1215
  var GLOBAL_CONFIG = {
@@ -1558,9 +1550,13 @@ var ViteHMRDetector = class {
1558
1550
  setupHMREventListeners() {
1559
1551
  if (typeof window !== "undefined" && window.import?.meta?.hot) {
1560
1552
  const hot = window.import.meta.hot;
1561
- hot.on("vite:error", () => {
1553
+ hot.on("vite:error", (data) => {
1554
+ this.handleViteError(data);
1562
1555
  requestAnimationFrame(() => this.checkForViteErrorOverlay());
1563
1556
  });
1557
+ hot.on("vite:invalidate", (data) => {
1558
+ setTimeout(() => this.checkForCompileErrors(), 500);
1559
+ });
1564
1560
  hot.on("vite:beforeUpdate", () => {
1565
1561
  console.log("[ViteHMRDetector] HMR \u66F4\u65B0\u5F00\u59CB");
1566
1562
  });
@@ -1737,6 +1733,90 @@ File: ${errorInfo.fileText}`;
1737
1733
  }
1738
1734
  }
1739
1735
  }
1736
+ /**
1737
+ * 处理 Vite 错误事件
1738
+ */
1739
+ handleViteError(errorData) {
1740
+ try {
1741
+ const errorPayload = {
1742
+ id: `vite-error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1743
+ type: "vite_hmr",
1744
+ error: {
1745
+ name: "ViteError",
1746
+ message: errorData?.message || "Vite error",
1747
+ stack: errorData?.stack || ""
1748
+ },
1749
+ source: "vite:error",
1750
+ timestamp: Date.now(),
1751
+ severity: "error",
1752
+ context: {
1753
+ viteErrorData: errorData,
1754
+ url: window.location.href,
1755
+ userAgent: navigator.userAgent
1756
+ }
1757
+ };
1758
+ if (window.__AUTO_ENGINEER_ERRORS__) {
1759
+ window.__AUTO_ENGINEER_ERRORS__.push(errorPayload);
1760
+ }
1761
+ this.sendMessage({
1762
+ type: "SYSTEM_EVENT",
1763
+ payload: errorPayload,
1764
+ timestamp: Date.now()
1765
+ });
1766
+ } catch (error) {
1767
+ console.error("[ViteHMRDetector] \u5904\u7406 Vite \u9519\u8BEF\u5931\u8D25:", error);
1768
+ }
1769
+ }
1770
+ /**
1771
+ * 检查编译错误
1772
+ */
1773
+ async checkForCompileErrors() {
1774
+ try {
1775
+ if (document.querySelector("vite-error-overlay")) {
1776
+ this.checkForViteErrorOverlay();
1777
+ return;
1778
+ }
1779
+ const response = await fetch(window.location.href, {
1780
+ method: "HEAD",
1781
+ cache: "no-cache"
1782
+ });
1783
+ if (!response.ok) {
1784
+ this.handleCompileError(`HTTP ${response.status}: ${response.statusText}`);
1785
+ }
1786
+ } catch (error) {
1787
+ this.handleCompileError(`Error: ${error.message}`);
1788
+ }
1789
+ }
1790
+ /**
1791
+ * 处理编译错误
1792
+ */
1793
+ handleCompileError(errorMessage) {
1794
+ const errorPayload = {
1795
+ id: `compile-error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1796
+ type: "compile_error",
1797
+ error: {
1798
+ name: "CompileError",
1799
+ message: `Compile error: ${errorMessage}`,
1800
+ stack: ""
1801
+ },
1802
+ source: "vite:compile",
1803
+ timestamp: Date.now(),
1804
+ severity: "error",
1805
+ context: {
1806
+ url: window.location.href,
1807
+ userAgent: navigator.userAgent,
1808
+ compilationFailed: true
1809
+ }
1810
+ };
1811
+ if (window.__AUTO_ENGINEER_ERRORS__) {
1812
+ window.__AUTO_ENGINEER_ERRORS__.push(errorPayload);
1813
+ }
1814
+ this.sendMessage({
1815
+ type: "SYSTEM_EVENT",
1816
+ payload: errorPayload,
1817
+ timestamp: Date.now()
1818
+ });
1819
+ }
1740
1820
  /**
1741
1821
  * 检查当前环境是否支持 Vite HMR
1742
1822
  */
@@ -3093,6 +3173,20 @@ var ErrorTracking = class {
3093
3173
  const fileInfo = this.extractFileInfoFromStack(fullStack);
3094
3174
  const serializedArgs = args.map((arg) => DeepSerializer.quickSerialize(arg));
3095
3175
  const message = serializedArgs.map((arg) => typeof arg === "string" ? arg : JSON.stringify(arg, null, 2)).join(" ") + (stack ? "\n" + stack : "");
3176
+ const lowerMessage = message.toLowerCase();
3177
+ const isFromVite = (fileInfo.filename || "").toLowerCase().includes("vite") || lowerMessage.includes("@vite") || lowerMessage.includes("vite") || lowerMessage.includes("hmr");
3178
+ const ignoreVitePatterns = [
3179
+ /\[vite\]\s*hot updated/i,
3180
+ /\[vite\]\s*connected/i,
3181
+ /\[vite\]\s*connecting/i,
3182
+ /\bhot updated\b/i,
3183
+ /\bhmr\b.*\bupdated\b/i
3184
+ ];
3185
+ if (isFromVite && ignoreVitePatterns.some((re) => re.test(lowerMessage))) {
3186
+ return;
3187
+ }
3188
+ const hasErrorKeywords = /\b(error|failed|overlay|compile|exception)\b/.test(lowerMessage);
3189
+ const isViteHMRNonError = isFromVite && !hasErrorKeywords;
3096
3190
  if (method === "error") {
3097
3191
  const globalError = {
3098
3192
  id: `console-error-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
@@ -3109,9 +3203,11 @@ var ErrorTracking = class {
3109
3203
  pagePath: window.location.pathname + window.location.search + window.location.hash,
3110
3204
  interactionTrail: [...window.__AUTO_ENGINEER_INTERACTION_TRAIL__ || []]
3111
3205
  };
3112
- window.__AUTO_ENGINEER_ERRORS__ = window.__AUTO_ENGINEER_ERRORS__ || [];
3113
- window.__AUTO_ENGINEER_ERRORS__.push(globalError);
3114
- this.manageArrayLength(window.__AUTO_ENGINEER_ERRORS__, ERROR_CONFIG.MAX_ERRORS);
3206
+ if (!isViteHMRNonError) {
3207
+ window.__AUTO_ENGINEER_ERRORS__ = window.__AUTO_ENGINEER_ERRORS__ || [];
3208
+ window.__AUTO_ENGINEER_ERRORS__.push(globalError);
3209
+ this.manageArrayLength(window.__AUTO_ENGINEER_ERRORS__, ERROR_CONFIG.MAX_ERRORS);
3210
+ }
3115
3211
  }
3116
3212
  const consoleLevelMap = {
3117
3213
  log: "info",
@@ -3123,7 +3219,7 @@ var ErrorTracking = class {
3123
3219
  this.sendMessage({
3124
3220
  type: "CONSOLE_EVENT",
3125
3221
  payload: {
3126
- type: consoleLevelMap[method] === "info" ? "info" : consoleLevelMap[method] === "warning" ? "warning" : "error",
3222
+ type: consoleLevelMap[method] === "info" ? "info" : consoleLevelMap[method] === "warning" ? "warning" : consoleLevelMap[method] === "debug" ? "debug" : "error",
3127
3223
  message,
3128
3224
  logged_at: (/* @__PURE__ */ new Date()).toISOString(),
3129
3225
  filename: fileInfo.filename,
@@ -3144,15 +3240,44 @@ var ErrorTracking = class {
3144
3240
  * 设置网络监控
3145
3241
  */
3146
3242
  setupNetworkMonitoring() {
3243
+ const self = this;
3147
3244
  const originalFetch = window.fetch;
3148
3245
  window.fetch = async (...args) => {
3149
3246
  const startTime = Date.now();
3150
3247
  try {
3151
3248
  const response = await originalFetch(...args);
3152
- this.logNetworkRequest(args, response, Date.now() - startTime);
3249
+ self.logNetworkRequest(args, response, Date.now() - startTime);
3153
3250
  return response;
3154
3251
  } catch (error) {
3155
- this.logNetworkError(args, error, Date.now() - startTime);
3252
+ const duration = Date.now() - startTime;
3253
+ const message = error && (error.message || String(error));
3254
+ const match = typeof message === "string" ? message.match(/^HTTP\s+(\d+):\s*(.*)$/i) : null;
3255
+ if (match) {
3256
+ const status = Number(match[1]);
3257
+ const statusText = match[2] || "";
3258
+ const stack = new Error().stack;
3259
+ const fileInfo = self.extractFileInfoFromStack(stack);
3260
+ self.sendMessage({
3261
+ type: "NETWORK_EVENT",
3262
+ payload: {
3263
+ type: "request_error",
3264
+ url: args[0],
3265
+ method: args[1]?.method || "GET",
3266
+ status,
3267
+ statusText,
3268
+ filename: fileInfo.filename,
3269
+ lineno: fileInfo.lineno,
3270
+ colno: fileInfo.colno,
3271
+ duration,
3272
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3273
+ pageUrl: window.location.href,
3274
+ interactionTrail: self.getRecentInteractions()
3275
+ },
3276
+ timestamp: Date.now()
3277
+ });
3278
+ } else {
3279
+ self.logNetworkError(args, error, duration);
3280
+ }
3156
3281
  throw error;
3157
3282
  }
3158
3283
  };
@@ -3345,12 +3470,6 @@ var ErrorTracking = class {
3345
3470
  if (ERROR_CONFIG.CATEGORY_KEYWORDS.DEVELOPMENT.some((keyword) => lowerMessage.includes(keyword))) {
3346
3471
  return "DEVELOPMENT";
3347
3472
  }
3348
- if (ERROR_CONFIG.CATEGORY_KEYWORDS.REACT.some((keyword) => lowerMessage.includes(keyword))) {
3349
- return "REACT";
3350
- }
3351
- if (ERROR_CONFIG.CATEGORY_KEYWORDS.VITE.some((keyword) => lowerMessage.includes(keyword))) {
3352
- return "VITE";
3353
- }
3354
3473
  return "UNKNOWN";
3355
3474
  }
3356
3475
  /**
@@ -3984,7 +4103,6 @@ var ElementSelector2 = class {
3984
4103
  this.waitForRootElement();
3985
4104
  this.createTooltip();
3986
4105
  this.createStyles();
3987
- console.log("[ElementSelector] \u5143\u7D20\u9009\u62E9\u5668\u521D\u59CB\u5316\u5B8C\u6210");
3988
4106
  }
3989
4107
  /**
3990
4108
  * 等待根元素加载
@@ -4122,7 +4240,6 @@ var ElementSelector2 = class {
4122
4240
  document.body.classList.add("element-selector-active");
4123
4241
  this.setupEventListeners();
4124
4242
  this.manageButtonStates(true);
4125
- console.log("[ElementSelector] \u9009\u62E9\u5668\u5DF2\u542F\u7528");
4126
4243
  this.sendMessage({
4127
4244
  type: "SELECTOR_ENABLED",
4128
4245
  payload: { isActive: true }
@@ -4140,7 +4257,6 @@ var ElementSelector2 = class {
4140
4257
  this.clearSelection();
4141
4258
  this.manageButtonStates(false);
4142
4259
  this.hideTooltip();
4143
- console.log("[ElementSelector] \u9009\u62E9\u5668\u5DF2\u7981\u7528");
4144
4260
  this.sendMessage({
4145
4261
  type: "SELECTOR_DISABLED",
4146
4262
  payload: { isActive: false }
@@ -4814,7 +4930,6 @@ var ElementSelector2 = class {
4814
4930
  this.styleElement.remove();
4815
4931
  this.styleElement = null;
4816
4932
  }
4817
- console.log("[ElementSelector] \u5143\u7D20\u9009\u62E9\u5668\u5DF2\u9500\u6BC1");
4818
4933
  }
4819
4934
  };
4820
4935
 
@@ -5477,7 +5592,6 @@ var ErrorHandler = class {
5477
5592
  enableInteractionTracking: true
5478
5593
  };
5479
5594
  this.config = { ...this.config, ...options };
5480
- console.log("[ErrorHandler] \u5F00\u59CB\u521D\u59CB\u5316\u7EDF\u4E00\u9519\u8BEF\u5904\u7406\u5668...");
5481
5595
  this.messageSender = createDefaultMessageSender({
5482
5596
  addTimestamp: true,
5483
5597
  enableDebugLog: false
@@ -5492,9 +5606,7 @@ var ErrorHandler = class {
5492
5606
  this.componentTreeGenerator = new ComponentTreeGenerator();
5493
5607
  if (this.config.enableViteHMR && ViteHMRDetector.isViteEnvironment()) {
5494
5608
  this.viteHMRDetector = new ViteHMRDetector(sendMessage);
5495
- console.log("[ErrorHandler] Vite HMR \u68C0\u6D4B\u5668\u5DF2\u521D\u59CB\u5316");
5496
5609
  }
5497
- console.log("[ErrorHandler] \u6A21\u5757\u521D\u59CB\u5316\u5B8C\u6210");
5498
5610
  }
5499
5611
  /** ----------------- 主要初始化方法 ----------------- */
5500
5612
  /**
@@ -5506,12 +5618,10 @@ var ErrorHandler = class {
5506
5618
  return;
5507
5619
  }
5508
5620
  try {
5509
- console.log("[ErrorHandler] \u5F00\u59CB\u521D\u59CB\u5316\u5404\u4E2A\u6A21\u5757...");
5510
5621
  this.initializeCore();
5511
5622
  this.setupModuleIntegration();
5512
5623
  this.enableFeatures();
5513
5624
  this.initialized = true;
5514
- console.log("[ErrorHandler] \u521D\u59CB\u5316\u5B8C\u6210");
5515
5625
  } catch (error) {
5516
5626
  console.error("[ErrorHandler] \u521D\u59CB\u5316\u5931\u8D25:", error);
5517
5627
  throw error;
@@ -5524,7 +5634,6 @@ var ErrorHandler = class {
5524
5634
  this.initializeGlobalState();
5525
5635
  this.setupDebugEndpoint();
5526
5636
  this.errorTracking.initialize();
5527
- console.log("[ErrorHandler] \u6838\u5FC3\u529F\u80FD\u521D\u59CB\u5316\u5B8C\u6210");
5528
5637
  }
5529
5638
  /**
5530
5639
  * 初始化全局状态
@@ -5536,7 +5645,6 @@ var ErrorHandler = class {
5536
5645
  if (!window.__AUTO_ENGINEER_INTERACTION_TRAIL__) {
5537
5646
  window.__AUTO_ENGINEER_INTERACTION_TRAIL__ = [];
5538
5647
  }
5539
- console.log("[ErrorHandler] \u5168\u5C40\u72B6\u6001\u521D\u59CB\u5316\u5B8C\u6210");
5540
5648
  }
5541
5649
  /**
5542
5650
  * 设置调试端点
@@ -5560,24 +5668,19 @@ var ErrorHandler = class {
5560
5668
  this.messageBridge.setComponentTreeGenerator(this.componentTreeGenerator);
5561
5669
  this.errorTracking.setViewDetector(this.viewDetector);
5562
5670
  this.errorTracking.setInteractionTracking(this.interactionTracking);
5563
- console.log("[ErrorHandler] \u6A21\u5757\u96C6\u6210\u8BBE\u7F6E\u5B8C\u6210");
5564
5671
  }
5565
5672
  /**
5566
5673
  * 启用功能模块
5567
5674
  */
5568
5675
  enableFeatures() {
5569
- console.log("[ErrorHandler] \u542F\u7528\u529F\u80FD\u6A21\u5757...");
5570
5676
  if (this.config.enableInteractionTracking) {
5571
5677
  this.interactionTracking.startTracking();
5572
- console.log("[ErrorHandler] \u4EA4\u4E92\u8FFD\u8E2A\u5DF2\u542F\u7528");
5573
5678
  }
5574
5679
  if (this.viteHMRDetector) {
5575
5680
  this.viteHMRDetector.initialize();
5576
- console.log("[ErrorHandler] Vite HMR \u68C0\u6D4B\u5668\u5DF2\u542F\u7528");
5577
5681
  }
5578
5682
  this.handleHardRefreshLogic();
5579
5683
  this.setupViewDetection();
5580
- console.log("[ErrorHandler] \u529F\u80FD\u6A21\u5757\u542F\u7528\u5B8C\u6210");
5581
5684
  }
5582
5685
  /**
5583
5686
  * 处理硬刷新逻辑
@@ -5586,7 +5689,6 @@ var ErrorHandler = class {
5586
5689
  HardRefreshManager.cleanupRefreshParams();
5587
5690
  const refreshStats = HardRefreshManager.getRefreshStats();
5588
5691
  if (refreshStats.isHardRefresh) {
5589
- console.log("[ErrorHandler] \u68C0\u6D4B\u5230\u786C\u5237\u65B0:", refreshStats);
5590
5692
  this.messageSender.send({
5591
5693
  type: "SYSTEM_EVENT",
5592
5694
  payload: {
@@ -5607,7 +5709,6 @@ var ErrorHandler = class {
5607
5709
  const currentView = this.viewDetector.getCurrentViewInfo();
5608
5710
  if (currentView.title !== lastViewTitle) {
5609
5711
  lastViewTitle = currentView.title;
5610
- console.log("[ErrorHandler] \u89C6\u56FE\u53D8\u5316:", currentView);
5611
5712
  }
5612
5713
  };
5613
5714
  setInterval(checkViewChange, 1e3);
@@ -5702,7 +5803,6 @@ var ErrorHandler = class {
5702
5803
  */
5703
5804
  updateConfig(newConfig) {
5704
5805
  this.config = { ...this.config, ...newConfig };
5705
- console.log("[ErrorHandler] \u914D\u7F6E\u5DF2\u66F4\u65B0:", this.config);
5706
5806
  }
5707
5807
  /**
5708
5808
  * 销毁错误处理器
@@ -5721,7 +5821,6 @@ var ErrorHandler = class {
5721
5821
  this.viewDetector.clearCache();
5722
5822
  }
5723
5823
  this.initialized = false;
5724
- console.log("[ErrorHandler] \u5DF2\u9500\u6BC1");
5725
5824
  } catch (error) {
5726
5825
  const originalConsole = getOriginalConsole3();
5727
5826
  originalConsole.error("[ErrorHandler] \u9500\u6BC1\u65F6\u53D1\u751F\u9519\u8BEF:", error);
@@ -5762,1708 +5861,1702 @@ var ErrorHandler = class {
5762
5861
  }
5763
5862
  };
5764
5863
 
5765
- // src/utils/iframe-navigation.ts
5766
- function getNavState() {
5767
- if (typeof window === "undefined") {
5768
- return {
5769
- navigationHistory: [],
5770
- currentHistoryIndex: -1,
5771
- initialized: false
5772
- };
5864
+ // src/components/auth/HowoneProvider.tsx
5865
+ import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
5866
+ var globalErrorHandler = null;
5867
+ var initializeErrorHandler = () => {
5868
+ if (!globalErrorHandler) {
5869
+ globalErrorHandler = new ErrorHandler({
5870
+ enableViteHMR: true,
5871
+ enableElementSelector: true,
5872
+ enableInteractionTracking: true
5873
+ });
5874
+ globalErrorHandler.init();
5875
+ window.__ERROR_HANDLER__ = globalErrorHandler;
5773
5876
  }
5774
- if (!window.customNavigationState) {
5775
- window.customNavigationState = {
5776
- navigationHistory: [],
5777
- currentHistoryIndex: -1,
5778
- initialized: false
5877
+ return globalErrorHandler;
5878
+ };
5879
+ initializeErrorHandler();
5880
+ var HowoneContext = createContext2(null);
5881
+ var HowOneProvider = ({
5882
+ children,
5883
+ showFloatingButton = true,
5884
+ projectId,
5885
+ defaultTheme = "system",
5886
+ themeStorageKey = "howone-theme",
5887
+ forceDefaultTheme = false,
5888
+ authUrl = "https://howone.dev/auth",
5889
+ redirectOnUnauthenticated = true
5890
+ }) => {
5891
+ const [user, setUser] = useState7(() => parseUserFromToken(getToken()));
5892
+ const [token, setTokenState] = useState7(() => getToken());
5893
+ const [hasCheckedUrlToken, setHasCheckedUrlToken] = useState7(false);
5894
+ useEffect6(() => {
5895
+ try {
5896
+ const params = new URLSearchParams(window.location.search);
5897
+ let urlToken = params.get("access_token") || params.get("token");
5898
+ if (!urlToken && window.location.hash) {
5899
+ const hashParams = new URLSearchParams(window.location.hash.slice(1));
5900
+ urlToken = hashParams.get("access_token") || hashParams.get("token");
5901
+ }
5902
+ if (urlToken) {
5903
+ setToken(urlToken);
5904
+ setTokenState(urlToken);
5905
+ setUser(parseUserFromToken(urlToken));
5906
+ params.delete("access_token");
5907
+ params.delete("token");
5908
+ params.delete("project_id");
5909
+ const newSearch = params.toString();
5910
+ const newUrl = window.location.pathname + (newSearch ? "?" + newSearch : "");
5911
+ window.history.replaceState({}, "", newUrl);
5912
+ }
5913
+ } catch (e) {
5914
+ console.error("[HowOneProvider] Failed to capture token from URL:", e);
5915
+ } finally {
5916
+ setHasCheckedUrlToken(true);
5917
+ }
5918
+ }, []);
5919
+ useEffect6(() => {
5920
+ if (!hasCheckedUrlToken) {
5921
+ return;
5922
+ }
5923
+ if (redirectOnUnauthenticated && !token && !user) {
5924
+ const currentUrl = new URL(window.location.href);
5925
+ if (!currentUrl.pathname.includes("/auth")) {
5926
+ try {
5927
+ const authUrlObj = new URL(authUrl);
5928
+ const redirectUri = window.location.href;
5929
+ authUrlObj.searchParams.set("redirect_uri", redirectUri);
5930
+ if (projectId) {
5931
+ authUrlObj.searchParams.set("project_id", projectId);
5932
+ }
5933
+ window.location.href = authUrlObj.toString();
5934
+ } catch (error) {
5935
+ console.error("[HowOneProvider] Failed to build auth URL:", error);
5936
+ window.location.href = authUrl;
5937
+ }
5938
+ }
5939
+ }
5940
+ }, [token, user, redirectOnUnauthenticated, authUrl, projectId, hasCheckedUrlToken]);
5941
+ const logout = () => {
5942
+ try {
5943
+ setToken(null);
5944
+ } catch {
5945
+ }
5946
+ setTokenState(null);
5947
+ setUser(null);
5948
+ };
5949
+ const value = {
5950
+ user,
5951
+ token,
5952
+ isAuthenticated: hasCheckedUrlToken && !!token,
5953
+ logout
5954
+ };
5955
+ return /* @__PURE__ */ jsxs5(
5956
+ ThemeProvider,
5957
+ {
5958
+ defaultTheme,
5959
+ storageKey: themeStorageKey,
5960
+ forceDefault: forceDefaultTheme,
5961
+ children: [
5962
+ /* @__PURE__ */ jsx7(ElementSelectorProvider, { children: /* @__PURE__ */ jsxs5(HowoneContext.Provider, { value, children: [
5963
+ children,
5964
+ showFloatingButton && /* @__PURE__ */ jsx7(FloatingButton, { onClick: () => window.open("https://howone.ai", "_blank") })
5965
+ ] }) }),
5966
+ /* @__PURE__ */ jsx7(GlobalToastContainer, {})
5967
+ ]
5968
+ }
5969
+ );
5970
+ };
5971
+ function useHowoneContext() {
5972
+ const ctx = useContext2(HowoneContext);
5973
+ if (!ctx) {
5974
+ const t = getToken();
5975
+ return {
5976
+ user: parseUserFromToken(t),
5977
+ token: t,
5978
+ isAuthenticated: !!t,
5979
+ logout: () => {
5980
+ try {
5981
+ setToken(null);
5982
+ } catch {
5983
+ }
5984
+ }
5779
5985
  };
5780
5986
  }
5781
- return window.customNavigationState;
5987
+ return ctx;
5782
5988
  }
5783
- function getElementSelectorState() {
5784
- if (typeof window === "undefined") {
5785
- return { active: false, callback: null };
5989
+
5990
+ // src/components/index.ts
5991
+ init_auth();
5992
+
5993
+ // src/howone/client.ts
5994
+ init_auth();
5995
+ init_config();
5996
+ var HowoneAuthClient = class {
5997
+ constructor() {
5998
+ this.listeners = /* @__PURE__ */ new Set();
5999
+ this.loading = false;
5786
6000
  }
5787
- if (!window.elementSelectorState) {
5788
- window.elementSelectorState = {
5789
- active: false,
5790
- callback: null
6001
+ emit() {
6002
+ const state = {
6003
+ user: parseUserFromToken(getToken()),
6004
+ isLoading: this.loading
5791
6005
  };
5792
- }
5793
- return window.elementSelectorState;
5794
- }
5795
- function sendNavigationState(targetWindow, targetOrigin) {
5796
- const navState = getNavState();
5797
- const canGoBack = navState.currentHistoryIndex > 0;
5798
- const canGoForward = navState.currentHistoryIndex < navState.navigationHistory.length - 1;
5799
- const state = {
5800
- type: "NAVIGATION_STATE",
5801
- payload: {
5802
- canGoBack,
5803
- canGoForward,
5804
- historyLength: navState.navigationHistory.length,
5805
- currentIndex: navState.currentHistoryIndex,
5806
- maxIndex: navState.navigationHistory.length - 1
6006
+ for (const l of this.listeners) {
6007
+ try {
6008
+ l(state);
6009
+ } catch (e) {
6010
+ void e;
6011
+ }
5807
6012
  }
5808
- };
5809
- if (targetWindow && targetOrigin) {
6013
+ }
6014
+ onAuthStateChanged(listener) {
6015
+ this.listeners.add(listener);
5810
6016
  try {
5811
- targetWindow.postMessage(state, targetOrigin);
6017
+ listener({ user: parseUserFromToken(getToken()), isLoading: this.loading });
5812
6018
  } catch (e) {
5813
- if (typeof console !== "undefined" && console.warn) {
5814
- console.warn("Failed to send navigation state:", e.message);
5815
- }
6019
+ void e;
5816
6020
  }
6021
+ return () => {
6022
+ this.listeners.delete(listener);
6023
+ };
5817
6024
  }
5818
- }
5819
- function addToNavigationHistory(url, title) {
5820
- const navState = getNavState();
5821
- if (navState.currentHistoryIndex < navState.navigationHistory.length - 1) {
5822
- navState.navigationHistory = navState.navigationHistory.slice(
5823
- 0,
5824
- navState.currentHistoryIndex + 1
5825
- );
5826
- }
5827
- const currentPage = navState.navigationHistory[navState.currentHistoryIndex];
5828
- if (currentPage && currentPage.url === url) {
5829
- return;
5830
- }
5831
- const pageInfo = {
5832
- url,
5833
- title: title || (typeof document !== "undefined" ? document.title : "") || url,
5834
- timestamp: Date.now()
6025
+ // Simple redirect-based login trigger (consumer can override)
6026
+ login() {
6027
+ const root = getEnvs().AUTH_ROOT_VALUE;
6028
+ try {
6029
+ const loc = window.location.href;
6030
+ const authUrl = new URL("/auth", String(root));
6031
+ authUrl.searchParams.set("redirect_uri", String(loc));
6032
+ try {
6033
+ const cfg = (init_config(), __toCommonJS(config_exports));
6034
+ const pid = cfg.getDefaultProjectId && cfg.getDefaultProjectId();
6035
+ if (pid) authUrl.searchParams.set("project_id", String(pid));
6036
+ } catch {
6037
+ }
6038
+ try {
6039
+ if (window.top && window.top !== window) {
6040
+ window.top.location.replace(authUrl.toString());
6041
+ } else {
6042
+ window.location.replace(authUrl.toString());
6043
+ }
6044
+ } catch {
6045
+ try {
6046
+ window.location.replace(String(root));
6047
+ } catch {
6048
+ }
6049
+ }
6050
+ } catch {
6051
+ try {
6052
+ window.location.replace(String(root));
6053
+ } catch {
6054
+ }
6055
+ }
6056
+ }
6057
+ logout() {
6058
+ setToken(null);
6059
+ this.emit();
6060
+ }
6061
+ getUser() {
6062
+ return parseUserFromToken(getToken());
6063
+ }
6064
+ // helper to programmatically set token (e.g., after callback handling)
6065
+ setToken(token) {
6066
+ setToken(token);
6067
+ this.emit();
6068
+ }
6069
+ };
6070
+ var howone = {
6071
+ auth: new HowoneAuthClient()
6072
+ };
6073
+ var client_default = howone;
6074
+
6075
+ // src/components/ui/Loading.tsx
6076
+ import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
6077
+ var Loading = ({
6078
+ size = "md",
6079
+ text = "Loading...",
6080
+ className = "",
6081
+ fullScreen = false
6082
+ }) => {
6083
+ const sizeClasses = {
6084
+ sm: "h-4 w-4",
6085
+ md: "h-8 w-8",
6086
+ lg: "h-12 w-12"
5835
6087
  };
5836
- navState.navigationHistory.push(pageInfo);
5837
- navState.currentHistoryIndex = navState.navigationHistory.length - 1;
5838
- if (typeof window !== "undefined" && window.parent && window.parent !== window) {
5839
- sendNavigationState(window.parent, "*");
6088
+ const containerClasses = fullScreen ? "fixed inset-0 flex items-center justify-center bg-white/80 backdrop-blur-sm z-50" : "flex items-center justify-center p-4";
6089
+ return /* @__PURE__ */ jsx8("div", { className: `${containerClasses} ${className}`, children: /* @__PURE__ */ jsxs6("div", { className: "text-center", children: [
6090
+ /* @__PURE__ */ jsx8(
6091
+ "div",
6092
+ {
6093
+ className: `animate-spin rounded-full border-2 border-gray-300 border-t-blue-600 mx-auto ${sizeClasses[size]}`
6094
+ }
6095
+ ),
6096
+ text && /* @__PURE__ */ jsx8("p", { className: "mt-2 text-sm text-gray-600", children: text })
6097
+ ] }) });
6098
+ };
6099
+ var LoadingSpinner = ({
6100
+ size = "md",
6101
+ className = ""
6102
+ }) => {
6103
+ const sizeClasses = {
6104
+ sm: "h-4 w-4",
6105
+ md: "h-8 w-8",
6106
+ lg: "h-12 w-12"
6107
+ };
6108
+ return /* @__PURE__ */ jsx8(
6109
+ "div",
6110
+ {
6111
+ className: `animate-spin rounded-full border-2 border-gray-300 border-t-blue-600 ${sizeClasses[size]} ${className}`
6112
+ }
6113
+ );
6114
+ };
6115
+
6116
+ // src/components/ui/ErrorBoundary.tsx
6117
+ import { Component } from "react";
6118
+ import { jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
6119
+ var ErrorBoundary = class extends Component {
6120
+ constructor(props) {
6121
+ super(props);
6122
+ this.handleRetry = () => {
6123
+ this.setState({ hasError: false, error: void 0, errorInfo: void 0 });
6124
+ };
6125
+ this.state = { hasError: false };
5840
6126
  }
5841
- }
5842
- function customGoBack() {
5843
- const navState = getNavState();
5844
- if (navState.currentHistoryIndex > 0) {
5845
- navState.currentHistoryIndex--;
5846
- if (typeof window !== "undefined" && window.parent && window.parent !== window) {
5847
- sendNavigationState(window.parent, "*");
6127
+ static getDerivedStateFromError(error) {
6128
+ return { hasError: true, error };
6129
+ }
6130
+ componentDidCatch(error, errorInfo) {
6131
+ this.setState({
6132
+ error,
6133
+ errorInfo
6134
+ });
6135
+ this.props.onError?.(error, errorInfo);
6136
+ }
6137
+ render() {
6138
+ if (this.state.hasError) {
6139
+ if (this.props.fallback) {
6140
+ const FallbackComponent = this.props.fallback;
6141
+ return /* @__PURE__ */ jsx9(FallbackComponent, { error: this.state.error, retry: this.handleRetry });
6142
+ }
6143
+ return /* @__PURE__ */ jsx9("div", { className: "min-h-[400px] flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs7("div", { className: "text-center max-w-md", children: [
6144
+ /* @__PURE__ */ jsx9("div", { className: "text-red-500 text-6xl mb-4", children: "\u26A0\uFE0F" }),
6145
+ /* @__PURE__ */ jsx9("h2", { className: "text-xl font-semibold text-gray-900 mb-2", children: "Something went wrong" }),
6146
+ /* @__PURE__ */ jsx9("p", { className: "text-gray-600 mb-4", children: "An unexpected error occurred. Please try refreshing the page." }),
6147
+ /* @__PURE__ */ jsx9(
6148
+ "button",
6149
+ {
6150
+ onClick: this.handleRetry,
6151
+ className: "px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors",
6152
+ children: "Try Again"
6153
+ }
6154
+ ),
6155
+ false
6156
+ ] }) });
5848
6157
  }
5849
- return true;
6158
+ return this.props.children;
5850
6159
  }
5851
- return false;
5852
- }
5853
- function customGoForward() {
5854
- const navState = getNavState();
5855
- if (navState.currentHistoryIndex < navState.navigationHistory.length - 1) {
5856
- navState.currentHistoryIndex++;
5857
- if (typeof window !== "undefined" && window.parent && window.parent !== window) {
5858
- sendNavigationState(window.parent, "*");
6160
+ };
6161
+ var DefaultErrorFallback = ({ retry }) => /* @__PURE__ */ jsx9("div", { className: "min-h-[200px] flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs7("div", { className: "text-center", children: [
6162
+ /* @__PURE__ */ jsx9("div", { className: "text-red-500 text-4xl mb-2", children: "\u26A0\uFE0F" }),
6163
+ /* @__PURE__ */ jsx9("p", { className: "text-gray-600 mb-2", children: "Something went wrong" }),
6164
+ retry && /* @__PURE__ */ jsx9(
6165
+ "button",
6166
+ {
6167
+ onClick: retry,
6168
+ className: "px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors",
6169
+ children: "Retry"
6170
+ }
6171
+ )
6172
+ ] }) });
6173
+
6174
+ // src/components/ui/ClayxButton.tsx
6175
+ import { jsx as jsx10 } from "react/jsx-runtime";
6176
+ var getSizeClasses = (size, isIconOnly) => {
6177
+ if (isIconOnly) {
6178
+ switch (size) {
6179
+ case "sm":
6180
+ return "h-8 w-8 min-w-8 p-0";
6181
+ case "md":
6182
+ return "h-10 w-10 min-w-10 p-0";
6183
+ case "lg":
6184
+ return "h-12 w-12 min-w-12 p-0";
6185
+ default:
6186
+ return "h-10 w-10 min-w-10 p-0";
5859
6187
  }
5860
- return true;
5861
6188
  }
5862
- return false;
5863
- }
5864
- function triggerElementSelection() {
5865
- if (typeof window === "undefined") return;
5866
- const event = new CustomEvent("howone:start-element-selection");
5867
- window.dispatchEvent(event);
5868
- getElementSelectorState().active = true;
5869
- }
5870
- function cancelElementSelection() {
5871
- if (typeof window === "undefined") return;
5872
- const event = new CustomEvent("howone:cancel-element-selection");
5873
- window.dispatchEvent(event);
5874
- getElementSelectorState().active = false;
5875
- }
5876
- function handlePageChange() {
5877
- if (typeof window === "undefined") return;
5878
- const currentUrl = window.location.href;
5879
- const currentTitle = document.title;
5880
- addToNavigationHistory(currentUrl, currentTitle);
5881
- }
5882
- function initIframeNavigation() {
5883
- if (typeof window === "undefined") return;
5884
- const navState = getNavState();
5885
- window.addEventListener("keydown", function(e) {
5886
- if (e.key === "Escape" && getElementSelectorState().active) {
5887
- cancelElementSelection();
6189
+ switch (size) {
6190
+ case "sm":
6191
+ return "h-8 px-3 text-sm";
6192
+ case "md":
6193
+ return "h-10 px-4 text-base";
6194
+ case "lg":
6195
+ return "h-12 px-6 text-lg";
6196
+ default:
6197
+ return "h-10 px-4 text-base";
6198
+ }
6199
+ };
6200
+ var getVariantClasses = (variant) => {
6201
+ switch (variant) {
6202
+ case "solid":
6203
+ return "bg-primary text-white hover:bg-primary/90";
6204
+ case "ghost":
6205
+ return "bg-transparent hover:bg-white/10";
6206
+ case "flat":
6207
+ return "bg-white/5 hover:bg-white/10";
6208
+ default:
6209
+ return "";
6210
+ }
6211
+ };
6212
+ var ClayxButton = ({
6213
+ isIconOnly = false,
6214
+ size = "md",
6215
+ variant = "solid",
6216
+ className = "",
6217
+ children,
6218
+ disabled = false,
6219
+ ...props
6220
+ }) => {
6221
+ const sizeClasses = getSizeClasses(size, isIconOnly);
6222
+ const variantClasses = getVariantClasses(variant);
6223
+ const baseClasses = `
6224
+ inline-flex items-center justify-center
6225
+ rounded-md font-medium
6226
+ transition-all duration-200
6227
+ focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-transparent
6228
+ disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none
6229
+ `.replace(/\s+/g, " ").trim();
6230
+ const combinedClasses = `${baseClasses} ${sizeClasses} ${variantClasses} ${className}`.trim();
6231
+ return /* @__PURE__ */ jsx10(
6232
+ "button",
6233
+ {
6234
+ className: combinedClasses,
6235
+ disabled,
6236
+ ...props,
6237
+ children
5888
6238
  }
5889
- });
5890
- window.addEventListener("message", (event) => {
5891
- try {
5892
- const { type, payload } = event.data;
5893
- switch (type) {
5894
- case "NAVIGATE_BACK":
5895
- case "GO_BACK":
5896
- customGoBack();
5897
- break;
5898
- case "NAVIGATE_FORWARD":
5899
- case "GO_FORWARD":
5900
- customGoForward();
5901
- break;
5902
- case "REQUEST_NAVIGATION_STATE":
5903
- case "CHECK_NAVIGATION_STATE":
5904
- sendNavigationState(event.source, event.origin);
5905
- break;
5906
- case "START_ELEMENT_SELECTION":
5907
- triggerElementSelection();
5908
- break;
5909
- case "ELEMENT_SELECTED":
5910
- if (event.source && event.source !== window) {
5911
- window.parent.postMessage(
5912
- {
5913
- type: "ELEMENT_SELECTED",
5914
- payload
5915
- },
5916
- "*"
5917
- );
6239
+ );
6240
+ };
6241
+
6242
+ // src/components/ui/LimitUpgradeToast.tsx
6243
+ import { Icon as Icon5 } from "@iconify/react";
6244
+
6245
+ // src/components/ui/Toast/ClayxToast.tsx
6246
+ import React7, { useCallback as useCallback4 } from "react";
6247
+ import { Bounce, toast } from "react-toastify";
6248
+ import { Icon as Icon4 } from "@iconify/react";
6249
+
6250
+ // src/components/theme/ThemeToggle.tsx
6251
+ import * as React6 from "react";
6252
+ import { Icon as Icon3 } from "@iconify/react";
6253
+ import { jsx as jsx11, jsxs as jsxs8 } from "react/jsx-runtime";
6254
+ function ThemeToggle({ className }) {
6255
+ const { setTheme, theme } = useTheme();
6256
+ const [mounted, setMounted] = React6.useState(false);
6257
+ React6.useEffect(() => {
6258
+ setMounted(true);
6259
+ }, []);
6260
+ const handleToggle = () => {
6261
+ if (theme === "dark") {
6262
+ setTheme("light");
6263
+ } else {
6264
+ setTheme("dark");
6265
+ }
6266
+ };
6267
+ if (!mounted) {
6268
+ return /* @__PURE__ */ jsxs8(
6269
+ "button",
6270
+ {
6271
+ className: `relative inline-flex h-10 w-12 items-center justify-center rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground ${className || ""}`,
6272
+ disabled: true,
6273
+ children: [
6274
+ /* @__PURE__ */ jsx11(Icon3, { icon: "solar:sun-bold", width: 20, height: 20 }),
6275
+ /* @__PURE__ */ jsx11("span", { className: "sr-only", children: "\u5207\u6362\u4E3B\u9898" })
6276
+ ]
6277
+ }
6278
+ );
6279
+ }
6280
+ return /* @__PURE__ */ jsxs8(
6281
+ "button",
6282
+ {
6283
+ className: `inline-flex h-10 w-12 items-center justify-center rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground transition-colors ${className || ""}`,
6284
+ onClick: handleToggle,
6285
+ children: [
6286
+ theme === "light" ? /* @__PURE__ */ jsx11(Icon3, { icon: "solar:sun-bold", width: 20, height: 20 }) : /* @__PURE__ */ jsx11(Icon3, { icon: "solar:moon-linear", width: 20, height: 20 }),
6287
+ /* @__PURE__ */ jsx11("span", { className: "sr-only", children: "\u5207\u6362\u4E3B\u9898" })
6288
+ ]
6289
+ }
6290
+ );
6291
+ }
6292
+
6293
+ // src/components/ui/Toast/ClayxToast.tsx
6294
+ import { jsx as jsx12, jsxs as jsxs9 } from "react/jsx-runtime";
6295
+ var TOAST_ICONS = {
6296
+ success: {
6297
+ icon: "mdi:success",
6298
+ color: "text-green-400",
6299
+ className: "text-green-400",
6300
+ // 深色主题配置
6301
+ dark: {
6302
+ bgGradient: "bg-[#14181d]",
6303
+ // 移除透明度 f2
6304
+ gradientColor: "#389726",
6305
+ borderGradient: "border-[#389726]",
6306
+ borderGradientColor: "#389726"
6307
+ },
6308
+ // 浅色主题配置
6309
+ light: {
6310
+ bgGradient: "bg-[#fafafa]",
6311
+ // 移除透明度 ff
6312
+ gradientColor: "#22c55e",
6313
+ borderGradient: "border-[#22c55e]",
6314
+ borderGradientColor: "#22c55e"
6315
+ }
6316
+ },
6317
+ error: {
6318
+ icon: "ic:outline-close",
6319
+ color: "text-red-400",
6320
+ className: "text-red-400",
6321
+ dark: {
6322
+ bgGradient: "bg-[#14181d]",
6323
+ // 移除透明度 f2
6324
+ gradientColor: "#ef4444",
6325
+ borderGradient: "border-[#ef4444]",
6326
+ borderGradientColor: "#ef4444"
6327
+ },
6328
+ light: {
6329
+ bgGradient: "bg-[#fafafa]",
6330
+ // 移除透明度 ff
6331
+ gradientColor: "#f87171",
6332
+ borderGradient: "border-[#f87171]",
6333
+ borderGradientColor: "#f87171"
6334
+ }
6335
+ },
6336
+ warning: {
6337
+ icon: "mi:warning",
6338
+ color: "text-yellow-400",
6339
+ className: "text-yellow-400",
6340
+ dark: {
6341
+ bgGradient: "bg-[#14181d]",
6342
+ // 移除透明度 f2
6343
+ gradientColor: "#facc15",
6344
+ borderGradient: "border-[#facc15]",
6345
+ borderGradientColor: "#facc15"
6346
+ },
6347
+ light: {
6348
+ bgGradient: "bg-[#fafafa]",
6349
+ // 移除透明度 ff
6350
+ gradientColor: "#f59e0b",
6351
+ borderGradient: "border-[#f59e0b]",
6352
+ borderGradientColor: "#f59e0b"
6353
+ }
6354
+ },
6355
+ info: {
6356
+ icon: "ic:outline-info",
6357
+ color: "text-blue-400",
6358
+ className: "text-blue-400",
6359
+ dark: {
6360
+ bgGradient: "bg-[#14181d]",
6361
+ // 移除透明度 f2
6362
+ gradientColor: "#60a5fa",
6363
+ borderGradient: "border-[#60a5fa]",
6364
+ borderGradientColor: "#f0f0f0"
6365
+ },
6366
+ light: {
6367
+ bgGradient: "bg-[#fafafa]",
6368
+ // 移除透明度 ff
6369
+ gradientColor: "#3b82f6",
6370
+ borderGradient: "border-[#3b82f6]",
6371
+ borderGradientColor: "#3b82f6"
6372
+ }
6373
+ },
6374
+ default: {
6375
+ icon: "ic:round-notifications",
6376
+ color: "text-gray-400",
6377
+ className: "text-gray-400",
6378
+ dark: {
6379
+ bgGradient: "bg-[#14181d]",
6380
+ // 移除透明度 f2
6381
+ gradientColor: "#9ca3af",
6382
+ borderGradient: "border-[#9ca3af]",
6383
+ borderGradientColor: "#9ca3af"
6384
+ },
6385
+ light: {
6386
+ bgGradient: "bg-[#fafafa]",
6387
+ // 移除透明度 ff
6388
+ gradientColor: "#6b7280",
6389
+ borderGradient: "border-[#6b7280]",
6390
+ borderGradientColor: "#6b7280"
6391
+ }
6392
+ }
6393
+ };
6394
+ var CloseButton = React7.memo(({ closeToast }) => {
6395
+ const { theme } = useTheme();
6396
+ const handleClick = useCallback4((e) => {
6397
+ e.preventDefault();
6398
+ e.stopPropagation();
6399
+ closeToast?.();
6400
+ }, [closeToast]);
6401
+ const getCloseButtonColor = () => {
6402
+ const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6403
+ return actualTheme === "dark" ? "#b4b4b4" : "#6b7280";
6404
+ };
6405
+ const getCloseButtonHoverColor = () => {
6406
+ const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6407
+ return actualTheme === "dark" ? "white" : "#374151";
6408
+ };
6409
+ return /* @__PURE__ */ jsx12(
6410
+ Icon4,
6411
+ {
6412
+ icon: "vaadin:close",
6413
+ className: "flex items-center justify-center rounded-full relative z-10 flex-shrink-0 cursor-pointer \n transition-colors duration-200 drop-shadow-sm",
6414
+ onClick: handleClick,
6415
+ width: 14,
6416
+ height: 14,
6417
+ style: {
6418
+ color: getCloseButtonColor()
6419
+ },
6420
+ onMouseEnter: (e) => {
6421
+ e.currentTarget.style.color = getCloseButtonHoverColor();
6422
+ },
6423
+ onMouseLeave: (e) => {
6424
+ e.currentTarget.style.color = getCloseButtonColor();
6425
+ }
6426
+ }
6427
+ );
6428
+ });
6429
+ CloseButton.displayName = "CloseButton";
6430
+ var ToastContent = ({ type, title, message, component, closeToast }) => {
6431
+ const iconConfig = TOAST_ICONS[type];
6432
+ const { theme } = useTheme();
6433
+ const handleClose = useCallback4(() => {
6434
+ closeToast?.();
6435
+ }, [closeToast]);
6436
+ const getTextColor = () => {
6437
+ const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6438
+ return actualTheme === "dark" ? "white" : "#1f2937";
6439
+ };
6440
+ const getThemeConfig = () => {
6441
+ const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6442
+ return actualTheme === "dark" ? iconConfig.dark : iconConfig.light;
6443
+ };
6444
+ const themeConfig = getThemeConfig();
6445
+ if (component) {
6446
+ return /* @__PURE__ */ jsxs9("div", { className: `flex items-start gap-3 !min-h-[90px] w-full backdrop-blur-md p-4 shadow-2xl relative overflow-hidden ${themeConfig.bgGradient}`, children: [
6447
+ /* @__PURE__ */ jsx12("div", { className: "flex-1 relative z-10", children: component }),
6448
+ /* @__PURE__ */ jsx12("div", { className: "relative z-10", children: /* @__PURE__ */ jsx12(CloseButton, { closeToast: handleClose }) })
6449
+ ] });
6450
+ }
6451
+ return /* @__PURE__ */ jsxs9("div", { className: `flex items-start gap-3 !min-h-[90px] w-full backdrop-blur-md p-4 shadow-2xl relative overflow-hidden ${themeConfig.bgGradient}`, children: [
6452
+ /* @__PURE__ */ jsx12(
6453
+ "div",
6454
+ {
6455
+ className: "absolute left-0 top-0 w-full h-full rounded-xl",
6456
+ style: {
6457
+ background: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "#0f1419" : "#ffffff",
6458
+ zIndex: -2
6459
+ }
6460
+ }
6461
+ ),
6462
+ /* @__PURE__ */ jsx12(
6463
+ "div",
6464
+ {
6465
+ className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-xl",
6466
+ style: {
6467
+ background: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? `linear-gradient(135deg, ${themeConfig.gradientColor}30 0%, ${themeConfig.gradientColor}20 15%, #14181df2 30%)` : `linear-gradient(135deg, ${themeConfig.gradientColor}15 0%, ${themeConfig.gradientColor}08 15%, #fafafaff 30%)`,
6468
+ zIndex: -1
6469
+ }
6470
+ }
6471
+ ),
6472
+ /* @__PURE__ */ jsx12(
6473
+ "div",
6474
+ {
6475
+ className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-xl",
6476
+ style: {
6477
+ border: "2px solid transparent",
6478
+ backgroundImage: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? `linear-gradient(135deg, ${themeConfig.borderGradientColor}60 0%, ${themeConfig.borderGradientColor}40 5%, transparent 22%)` : `linear-gradient(135deg, ${themeConfig.borderGradientColor}40 0%, ${themeConfig.borderGradientColor}25 5%, transparent 22%)`,
6479
+ backgroundOrigin: "border-box",
6480
+ backgroundClip: "border-box",
6481
+ WebkitMask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6482
+ WebkitMaskComposite: "xor",
6483
+ mask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6484
+ maskComposite: "exclude"
6485
+ }
6486
+ }
6487
+ ),
6488
+ /* @__PURE__ */ jsx12("div", { className: "flex-shrink-0 mt-0.5 relative z-10", children: /* @__PURE__ */ jsx12("div", { className: `w-7 h-7 backdrop-blur-sm rounded-full flex items-center justify-center ${theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "bg-white/10" : "bg-black/5"}`, children: /* @__PURE__ */ jsx12(
6489
+ Icon4,
6490
+ {
6491
+ icon: iconConfig.icon,
6492
+ width: 16,
6493
+ height: 16,
6494
+ className: iconConfig.color,
6495
+ style: {
6496
+ color: themeConfig.gradientColor
6497
+ }
6498
+ }
6499
+ ) }) }),
6500
+ /* @__PURE__ */ jsxs9("div", { className: "flex flex-col gap-1 flex-1 relative z-10", children: [
6501
+ title && /* @__PURE__ */ jsx12(
6502
+ "div",
6503
+ {
6504
+ className: "text-[16px] font-semibold leading-tight drop-shadow-sm",
6505
+ style: {
6506
+ color: getTextColor(),
6507
+ backgroundClip: "text"
6508
+ },
6509
+ children: title
6510
+ }
6511
+ ),
6512
+ message && /* @__PURE__ */ jsx12(
6513
+ "div",
6514
+ {
6515
+ className: "text-[13px] font-normal leading-relaxed drop-shadow-sm",
6516
+ style: {
6517
+ color: getTextColor(),
6518
+ backgroundClip: "text"
6519
+ },
6520
+ children: message
6521
+ }
6522
+ )
6523
+ ] }),
6524
+ /* @__PURE__ */ jsx12("div", { className: "relative z-10", children: /* @__PURE__ */ jsx12(CloseButton, { closeToast: handleClose }) })
6525
+ ] });
6526
+ };
6527
+ var defaultToastOptions = {
6528
+ position: "bottom-right",
6529
+ autoClose: 3e3,
6530
+ hideProgressBar: true,
6531
+ closeOnClick: false,
6532
+ pauseOnHover: true,
6533
+ draggable: true,
6534
+ pauseOnFocusLoss: false,
6535
+ theme: "dark",
6536
+ transition: Bounce
6537
+ };
6538
+ var createToast = (type) => {
6539
+ return (params) => {
6540
+ const { title, message, component, options } = params;
6541
+ toast(
6542
+ ({ closeToast }) => {
6543
+ if (params.render) return params.render(closeToast);
6544
+ return /* @__PURE__ */ jsx12(
6545
+ ToastContent,
6546
+ {
6547
+ type,
6548
+ title,
6549
+ message: message || "",
6550
+ component,
6551
+ closeToast
5918
6552
  }
5919
- break;
5920
- case "CANCEL_ELEMENT_SELECTION":
5921
- cancelElementSelection();
5922
- break;
5923
- }
5924
- } catch (e) {
5925
- }
5926
- });
5927
- window.addEventListener("popstate", () => {
5928
- setTimeout(() => {
5929
- if (window.parent && window.parent !== window) {
5930
- sendNavigationState(window.parent, "*");
5931
- }
5932
- }, 50);
5933
- });
5934
- window.addEventListener("hashchange", () => {
5935
- handlePageChange();
5936
- });
5937
- window.addEventListener("load", () => {
5938
- if (!navState.initialized) {
5939
- addToNavigationHistory(window.location.href, document.title);
5940
- navState.initialized = true;
5941
- }
5942
- setTimeout(() => {
5943
- if (window.parent && window.parent !== window) {
5944
- sendNavigationState(window.parent, "*");
5945
- }
5946
- }, 500);
5947
- });
5948
- if (document.readyState === "loading") {
5949
- document.addEventListener("DOMContentLoaded", () => {
5950
- if (!navState.initialized) {
5951
- addToNavigationHistory(window.location.href, document.title);
5952
- navState.initialized = true;
5953
- }
5954
- });
5955
- } else if (!navState.initialized) {
5956
- addToNavigationHistory(window.location.href, document.title);
5957
- navState.initialized = true;
5958
- }
5959
- window.iframeElementSelector = {
5960
- startSelection: function() {
5961
- triggerElementSelection();
5962
- }
5963
- };
5964
- window.iframeNavigation = {
5965
- addPage: function(url, title) {
5966
- addToNavigationHistory(
5967
- url || window.location.href,
5968
- title || document.title
5969
- );
5970
- },
5971
- getState: function() {
5972
- return {
5973
- canGoBack: navState.currentHistoryIndex > 0,
5974
- canGoForward: navState.currentHistoryIndex < navState.navigationHistory.length - 1,
5975
- historyLength: navState.navigationHistory.length,
5976
- currentIndex: navState.currentHistoryIndex,
5977
- currentPage: navState.navigationHistory[navState.currentHistoryIndex]
5978
- };
5979
- },
5980
- updateState: function() {
5981
- if (window.parent && window.parent !== window) {
5982
- sendNavigationState(window.parent, "*");
6553
+ );
6554
+ },
6555
+ {
6556
+ ...defaultToastOptions,
6557
+ ...options,
6558
+ // 确保圆角样式不被覆盖,添加 rounded-xl
6559
+ className: "!p-0 !shadow-none !rounded-xl",
6560
+ style: { padding: 0, borderRadius: "0.75rem" }
5983
6561
  }
5984
- }
5985
- };
5986
- }
5987
- var iframeNavigation = {
5988
- /**
5989
- * Initialize the navigation system
5990
- */
5991
- init: initIframeNavigation,
5992
- /**
5993
- * Add a page to navigation history
5994
- */
5995
- addPage: (url, title) => {
5996
- if (typeof window === "undefined") return;
5997
- addToNavigationHistory(
5998
- url || window.location.href,
5999
- title || (typeof document !== "undefined" ? document.title : "")
6000
6562
  );
6001
- },
6002
- /**
6003
- * Get current navigation state
6004
- */
6005
- getState: () => {
6006
- const navState = getNavState();
6007
- return {
6008
- canGoBack: navState.currentHistoryIndex > 0,
6009
- canGoForward: navState.currentHistoryIndex < navState.navigationHistory.length - 1,
6010
- historyLength: navState.navigationHistory.length,
6011
- currentIndex: navState.currentHistoryIndex,
6012
- currentPage: navState.navigationHistory[navState.currentHistoryIndex]
6013
- };
6014
- },
6015
- /**
6016
- * Update navigation state (send to parent)
6017
- */
6018
- updateState: () => {
6019
- if (typeof window !== "undefined" && window.parent && window.parent !== window) {
6020
- sendNavigationState(window.parent, "*");
6021
- }
6022
- },
6023
- /**
6024
- * Go back in history
6025
- */
6026
- goBack: customGoBack,
6027
- /**
6028
- * Go forward in history
6029
- */
6030
- goForward: customGoForward
6563
+ };
6031
6564
  };
6032
- var elementSelector = {
6033
- /**
6034
- * Start element selection mode
6035
- */
6036
- startSelection: triggerElementSelection,
6037
- /**
6038
- * Cancel element selection mode
6039
- */
6040
- cancel: cancelElementSelection,
6041
- /**
6042
- * Check if selector is active
6043
- */
6044
- isActive: () => getElementSelectorState().active
6565
+ var ClayxToast = {
6566
+ success: createToast("success"),
6567
+ error: createToast("error"),
6568
+ warning: createToast("warning"),
6569
+ info: createToast("info"),
6570
+ default: createToast("default")
6045
6571
  };
6046
6572
 
6047
- // src/components/auth/HowoneProvider.tsx
6048
- import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
6049
- var HowoneContext = createContext2(null);
6050
- var HowOneProvider = ({
6051
- children,
6052
- showFloatingButton = true,
6053
- projectId,
6054
- defaultTheme = "system",
6055
- themeStorageKey = "howone-theme",
6056
- forceDefaultTheme = false,
6057
- authUrl = "https://howone.dev/auth",
6058
- redirectOnUnauthenticated = true
6059
- }) => {
6060
- const [user, setUser] = useState7(() => parseUserFromToken(getToken()));
6061
- const [token, setTokenState] = useState7(() => getToken());
6062
- const [hasCheckedUrlToken, setHasCheckedUrlToken] = useState7(false);
6063
- useEffect6(() => {
6064
- const errorHandler = new ErrorHandler({
6065
- enableViteHMR: true,
6066
- enableElementSelector: true,
6067
- enableInteractionTracking: true
6068
- // enableConsoleCapture: true,
6069
- // enableNetworkCapture: true,
6070
- // maxErrors: 100,
6071
- // maxInteractions: 50,
6072
- // debounceTime: 100,
6073
- // reportToParent: true,
6074
- // reportToConsole: true
6075
- });
6076
- errorHandler.init();
6077
- window.__ERROR_HANDLER__ = errorHandler;
6078
- initIframeNavigation();
6079
- try {
6080
- const params = new URLSearchParams(window.location.search);
6081
- let urlToken = params.get("access_token") || params.get("token");
6082
- if (!urlToken && window.location.hash) {
6083
- const hashParams = new URLSearchParams(window.location.hash.slice(1));
6084
- urlToken = hashParams.get("access_token") || hashParams.get("token");
6573
+ // src/components/ui/LimitUpgradeToast.tsx
6574
+ import { jsx as jsx13, jsxs as jsxs10 } from "react/jsx-runtime";
6575
+ var LimitToastContainer = ({ message, onUpgrade, closeToast }) => {
6576
+ return /* @__PURE__ */ jsxs10("div", { className: "relative w-full max-w-[420px] overflow-hidden rounded-md bg-gradient-to-br from-[#1A1A1A] via-[#151515] to-[#1A1A1A] shadow-[0_20px_60px_rgba(168,85,247,0.2)] backdrop-blur-sm", children: [
6577
+ /* @__PURE__ */ jsx13(
6578
+ "div",
6579
+ {
6580
+ className: "absolute left-0 top-0 w-full h-full rounded-md",
6581
+ style: {
6582
+ background: "#0f1419",
6583
+ zIndex: -2
6584
+ }
6085
6585
  }
6086
- if (urlToken) {
6087
- console.log("[HowOneProvider] Token captured from URL, storing to localStorage...");
6088
- setToken(urlToken);
6089
- setTokenState(urlToken);
6090
- setUser(parseUserFromToken(urlToken));
6091
- params.delete("access_token");
6092
- params.delete("token");
6093
- params.delete("project_id");
6094
- const newSearch = params.toString();
6095
- const newUrl = window.location.pathname + (newSearch ? "?" + newSearch : "");
6096
- window.history.replaceState({}, "", newUrl);
6097
- console.log("[HowOneProvider] Token stored successfully, URL cleaned");
6586
+ ),
6587
+ /* @__PURE__ */ jsx13(
6588
+ "div",
6589
+ {
6590
+ className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-md",
6591
+ style: {
6592
+ background: `linear-gradient(135deg, rgba(168,85,247,0.3) 0%, rgba(168,85,247,0.2) 15%, #1A1A1A 30%)`,
6593
+ zIndex: -1
6594
+ }
6098
6595
  }
6099
- } catch (e) {
6100
- console.error("[HowOneProvider] Failed to capture token from URL:", e);
6101
- } finally {
6102
- setHasCheckedUrlToken(true);
6103
- }
6104
- }, []);
6105
- useEffect6(() => {
6106
- if (!hasCheckedUrlToken) {
6107
- return;
6108
- }
6109
- if (redirectOnUnauthenticated && !token && !user) {
6110
- const currentUrl = new URL(window.location.href);
6111
- if (!currentUrl.pathname.includes("/auth")) {
6112
- console.log("[HowOneProvider] No token found, redirecting to auth page...");
6113
- try {
6114
- const authUrlObj = new URL(authUrl);
6115
- const redirectUri = window.location.href;
6116
- authUrlObj.searchParams.set("redirect_uri", redirectUri);
6117
- if (projectId) {
6118
- authUrlObj.searchParams.set("project_id", projectId);
6596
+ ),
6597
+ /* @__PURE__ */ jsx13(
6598
+ "div",
6599
+ {
6600
+ className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-md",
6601
+ style: {
6602
+ border: "2px solid transparent",
6603
+ backgroundImage: `linear-gradient(135deg, rgba(168,85,247,0.6) 0%, rgba(168,85,247,0.4) 5%, transparent 22%)`,
6604
+ backgroundOrigin: "border-box",
6605
+ backgroundClip: "border-box",
6606
+ WebkitMask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6607
+ WebkitMaskComposite: "xor",
6608
+ mask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6609
+ maskComposite: "exclude"
6610
+ }
6611
+ }
6612
+ ),
6613
+ /* @__PURE__ */ jsx13("div", { className: "absolute -top-16 -right-16 h-32 w-32 rounded-full bg-gradient-to-br from-purple-500/20 via-pink-500/10 to-transparent blur-3xl animate-pulse" }),
6614
+ /* @__PURE__ */ jsx13("div", { className: "absolute -bottom-16 -left-16 h-32 w-32 rounded-full bg-gradient-to-tr from-blue-500/10 to-transparent blur-2xl animate-pulse", style: { animationDelay: "1s" } }),
6615
+ /* @__PURE__ */ jsx13("div", { className: "relative z-10 flex items-start gap-4 p-4", children: /* @__PURE__ */ jsxs10("div", { className: "flex flex-1 flex-col gap-3", children: [
6616
+ /* @__PURE__ */ jsxs10("div", { className: "flex items-center justify-between", children: [
6617
+ /* @__PURE__ */ jsxs10("div", { className: "flex items-center gap-2", children: [
6618
+ /* @__PURE__ */ jsx13("div", { className: "text-lg font-bold bg-gradient-to-r from-white to-gray-400 bg-clip-text text-transparent", children: "Upgrade Required" }),
6619
+ /* @__PURE__ */ jsx13("div", { className: "px-2 py-0.5 text-xs font-bold bg-purple-500/20 text-purple-400 rounded-md border border-purple-500/30", children: "Premium" })
6620
+ ] }),
6621
+ /* @__PURE__ */ jsx13(
6622
+ ClayxButton,
6623
+ {
6624
+ onClick: closeToast,
6625
+ isIconOnly: true,
6626
+ size: "sm",
6627
+ className: "h-6 w-6 min-w-6 rounded-full bg-white/5 hover:bg-white/10 transition-colors",
6628
+ children: /* @__PURE__ */ jsx13(Icon5, { icon: "iconamoon:close", className: "w-4 h-4 text-gray-400" })
6119
6629
  }
6120
- console.log("[HowOneProvider] Redirecting to:", authUrlObj.toString());
6121
- window.location.href = authUrlObj.toString();
6122
- } catch (error) {
6123
- console.error("[HowOneProvider] Failed to build auth URL:", error);
6124
- window.location.href = authUrl;
6630
+ )
6631
+ ] }),
6632
+ /* @__PURE__ */ jsx13("p", { className: "text-sm text-gray-300 leading-relaxed", children: message }),
6633
+ /* @__PURE__ */ jsx13("div", { className: "mt-1 flex items-center gap-3", children: /* @__PURE__ */ jsx13(
6634
+ ClayxButton,
6635
+ {
6636
+ onClick: () => {
6637
+ onUpgrade();
6638
+ closeToast?.();
6639
+ },
6640
+ className: "flex-1 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-semibold transition-all duration-300 hover:shadow-lg hover:shadow-purple-500/30 cursor-pointer",
6641
+ style: { cursor: "pointer" },
6642
+ children: /* @__PURE__ */ jsxs10("span", { className: "flex items-center gap-2", children: [
6643
+ /* @__PURE__ */ jsx13(Icon5, { icon: "solar:rocket-2-bold", className: "w-4 h-4" }),
6644
+ "Upgrade Now"
6645
+ ] })
6125
6646
  }
6126
- }
6127
- }
6128
- }, [token, user, redirectOnUnauthenticated, authUrl, projectId, hasCheckedUrlToken]);
6129
- const logout = () => {
6130
- try {
6131
- setToken(null);
6132
- } catch {
6133
- }
6134
- setTokenState(null);
6135
- setUser(null);
6136
- };
6137
- const value = {
6138
- user,
6139
- token,
6140
- isAuthenticated: hasCheckedUrlToken && !!token,
6141
- logout
6142
- };
6143
- return /* @__PURE__ */ jsxs5(
6144
- ThemeProvider,
6145
- {
6146
- defaultTheme,
6147
- storageKey: themeStorageKey,
6148
- forceDefault: forceDefaultTheme,
6149
- children: [
6150
- /* @__PURE__ */ jsx7(ElementSelectorProvider, { children: /* @__PURE__ */ jsxs5(HowoneContext.Provider, { value, children: [
6151
- children,
6152
- showFloatingButton && /* @__PURE__ */ jsx7(FloatingButton, { onClick: () => window.open("https://howone.ai", "_blank") })
6153
- ] }) }),
6154
- /* @__PURE__ */ jsx7(GlobalToastContainer, {})
6155
- ]
6156
- }
6157
- );
6647
+ ) })
6648
+ ] }) })
6649
+ ] });
6158
6650
  };
6159
- function useHowoneContext() {
6160
- const ctx = useContext2(HowoneContext);
6161
- if (!ctx) {
6162
- const t = getToken();
6163
- return {
6164
- user: parseUserFromToken(t),
6165
- token: t,
6166
- isAuthenticated: !!t,
6167
- logout: () => {
6168
- try {
6169
- setToken(null);
6170
- } catch {
6171
- }
6651
+ function showLimitUpgradeToast(message, onUpgrade) {
6652
+ ClayxToast.default({
6653
+ render: (closeToast) => /* @__PURE__ */ jsx13(LimitToastContainer, { message, onUpgrade, closeToast }),
6654
+ options: {
6655
+ position: "bottom-right",
6656
+ closeOnClick: false,
6657
+ autoClose: false,
6658
+ hideProgressBar: true,
6659
+ draggable: false,
6660
+ pauseOnHover: true,
6661
+ className: "!bg-transparent !shadow-none",
6662
+ style: {
6663
+ background: "transparent",
6664
+ padding: 0,
6665
+ width: "auto",
6666
+ maxWidth: "420px"
6172
6667
  }
6173
- };
6174
- }
6175
- return ctx;
6668
+ }
6669
+ });
6176
6670
  }
6177
6671
 
6178
- // src/components/index.ts
6179
- init_auth();
6180
-
6181
- // src/howone/client.ts
6182
- init_auth();
6183
- init_config();
6184
- var HowoneAuthClient = class {
6185
- constructor() {
6186
- this.listeners = /* @__PURE__ */ new Set();
6187
- this.loading = false;
6672
+ // src/services/ai-workflow.ts
6673
+ var AIWorkflowClient = class {
6674
+ constructor(options = {}) {
6675
+ this.baseUrl = options.baseUrl?.replace(/\/+$/, "") || "";
6676
+ this.apiKey = options.apiKey;
6677
+ this.headers = { "Content-Type": "application/json", ...options.headers || {} };
6678
+ this.fetchImpl = options.fetchImpl || fetch.bind(globalThis);
6188
6679
  }
6189
- emit() {
6190
- const state = {
6191
- user: parseUserFromToken(getToken()),
6192
- isLoading: this.loading
6193
- };
6194
- for (const l of this.listeners) {
6195
- try {
6196
- l(state);
6197
- } catch (e) {
6198
- void e;
6199
- }
6680
+ buildHeaders(extra) {
6681
+ const h = { ...this.headers, ...extra || {} };
6682
+ if (this.apiKey && !h["Authorization"]) {
6683
+ h["Authorization"] = `Bearer ${this.apiKey}`;
6200
6684
  }
6685
+ return h;
6201
6686
  }
6202
- onAuthStateChanged(listener) {
6203
- this.listeners.add(listener);
6687
+ async safeJson(resp) {
6204
6688
  try {
6205
- listener({ user: parseUserFromToken(getToken()), isLoading: this.loading });
6206
- } catch (e) {
6207
- void e;
6689
+ return await resp.json();
6690
+ } catch (_e) {
6691
+ return null;
6208
6692
  }
6209
- return () => {
6210
- this.listeners.delete(listener);
6211
- };
6212
6693
  }
6213
- // Simple redirect-based login trigger (consumer can override)
6214
- login() {
6215
- const root = getEnvs().AUTH_ROOT_VALUE;
6694
+ /**
6695
+ * 按 ID 执行工作流:POST {baseUrl}/workflow/{workflowId}/execute
6696
+ * body: { input, options }
6697
+ */
6698
+ async executeWorkflow(workflowId, inputs, options) {
6699
+ if (!this.baseUrl) {
6700
+ throw new Error("AI workflow client requires a baseUrl (e.g. https://evoagentx-server.fly.dev)");
6701
+ }
6702
+ const url = `${this.baseUrl}/workflow/${workflowId}/execute`;
6216
6703
  try {
6217
- const loc = window.location.href;
6218
- const authUrl = new URL("/auth", String(root));
6219
- authUrl.searchParams.set("redirect_uri", String(loc));
6220
- try {
6221
- const cfg = (init_config(), __toCommonJS(config_exports));
6222
- const pid = cfg.getDefaultProjectId && cfg.getDefaultProjectId();
6223
- if (pid) authUrl.searchParams.set("project_id", String(pid));
6224
- } catch {
6225
- }
6226
- try {
6227
- if (window.top && window.top !== window) {
6228
- window.top.location.replace(authUrl.toString());
6229
- } else {
6230
- window.location.replace(authUrl.toString());
6231
- }
6232
- } catch {
6233
- try {
6234
- window.location.replace(String(root));
6235
- } catch {
6236
- }
6704
+ const res = await this.fetchImpl(url, {
6705
+ method: "POST",
6706
+ headers: this.buildHeaders(),
6707
+ body: JSON.stringify({ inputs, options })
6708
+ });
6709
+ const data = await this.safeJson(res);
6710
+ if (!res.ok) {
6711
+ return { success: false, error: data?.error || `HTTP ${res.status}` };
6237
6712
  }
6238
- } catch {
6239
- try {
6240
- window.location.replace(String(root));
6241
- } catch {
6713
+ if (data && data.status && data.status === 4003) {
6714
+ showLimitUpgradeToast(
6715
+ "Your credits are exhausted. Please upgrade your plan to continue generating projects.",
6716
+ () => window.open("https://clayx.ai/pricing", "_blank")
6717
+ );
6718
+ return null;
6242
6719
  }
6720
+ return data || { success: true };
6721
+ } catch (error) {
6722
+ return { success: false, error: error instanceof Error ? error.message : "Network error" };
6243
6723
  }
6244
6724
  }
6245
- logout() {
6246
- setToken(null);
6247
- this.emit();
6248
- }
6249
- getUser() {
6250
- return parseUserFromToken(getToken());
6251
- }
6252
- // helper to programmatically set token (e.g., after callback handling)
6253
- setToken(token) {
6254
- setToken(token);
6255
- this.emit();
6256
- }
6257
6725
  };
6258
- var howone = {
6259
- auth: new HowoneAuthClient()
6260
- };
6261
- var client_default = howone;
6726
+ function createAIWorkflowClient(options = {}) {
6727
+ return new AIWorkflowClient(options);
6728
+ }
6729
+ var aiWorkflow = createAIWorkflowClient({ baseUrl: "https://evoagentx-server" });
6262
6730
 
6263
- // src/components/ui/Loading.tsx
6264
- import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
6265
- var Loading = ({
6266
- size = "md",
6267
- text = "Loading...",
6268
- className = "",
6269
- fullScreen = false
6270
- }) => {
6271
- const sizeClasses = {
6272
- sm: "h-4 w-4",
6273
- md: "h-8 w-8",
6274
- lg: "h-12 w-12"
6275
- };
6276
- const containerClasses = fullScreen ? "fixed inset-0 flex items-center justify-center bg-white/80 backdrop-blur-sm z-50" : "flex items-center justify-center p-4";
6277
- return /* @__PURE__ */ jsx8("div", { className: `${containerClasses} ${className}`, children: /* @__PURE__ */ jsxs6("div", { className: "text-center", children: [
6278
- /* @__PURE__ */ jsx8(
6279
- "div",
6280
- {
6281
- className: `animate-spin rounded-full border-2 border-gray-300 border-t-blue-600 mx-auto ${sizeClasses[size]}`
6731
+ // src/services/request/index.ts
6732
+ import axios from "axios";
6733
+ var Request = class {
6734
+ constructor(config) {
6735
+ this.abortControllers = /* @__PURE__ */ new Map();
6736
+ this.instance = axios.create({
6737
+ ...config,
6738
+ validateStatus: (status) => {
6739
+ return status >= 200 && status < 300;
6740
+ }
6741
+ });
6742
+ this.interceptors = config.interceptors;
6743
+ this.instance.interceptors.request.use(
6744
+ this.interceptors?.requestInterceptor,
6745
+ this.interceptors?.requestInterceptorCatch
6746
+ );
6747
+ this.instance.interceptors.response.use(
6748
+ this.interceptors?.responseInterceptor,
6749
+ this.interceptors?.responseInterceptorCatch
6750
+ );
6751
+ this.instance.interceptors.request.use(
6752
+ (config2) => {
6753
+ return config2;
6754
+ },
6755
+ (err) => {
6756
+ return Promise.reject(err);
6757
+ }
6758
+ );
6759
+ this.instance.interceptors.response.use(
6760
+ (res) => {
6761
+ return res.data;
6762
+ },
6763
+ (err) => {
6764
+ if (axios.isCancel(err)) {
6765
+ return Promise.reject({
6766
+ isCanceled: true,
6767
+ message: "request canceled",
6768
+ originalError: err
6769
+ });
6770
+ }
6771
+ if (err.response?.data?.error) {
6772
+ return Promise.reject(err.response.data.error);
6773
+ }
6774
+ return Promise.reject(err);
6282
6775
  }
6283
- ),
6284
- text && /* @__PURE__ */ jsx8("p", { className: "mt-2 text-sm text-gray-600", children: text })
6285
- ] }) });
6286
- };
6287
- var LoadingSpinner = ({
6288
- size = "md",
6289
- className = ""
6290
- }) => {
6291
- const sizeClasses = {
6292
- sm: "h-4 w-4",
6293
- md: "h-8 w-8",
6294
- lg: "h-12 w-12"
6295
- };
6296
- return /* @__PURE__ */ jsx8(
6297
- "div",
6298
- {
6299
- className: `animate-spin rounded-full border-2 border-gray-300 border-t-blue-600 ${sizeClasses[size]} ${className}`
6300
- }
6301
- );
6302
- };
6303
-
6304
- // src/components/ui/ErrorBoundary.tsx
6305
- import { Component } from "react";
6306
- import { jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
6307
- var ErrorBoundary = class extends Component {
6308
- constructor(props) {
6309
- super(props);
6310
- this.handleRetry = () => {
6311
- this.setState({ hasError: false, error: void 0, errorInfo: void 0 });
6312
- };
6313
- this.state = { hasError: false };
6776
+ );
6314
6777
  }
6315
- static getDerivedStateFromError(error) {
6316
- return { hasError: true, error };
6778
+ cancelRequest(url) {
6779
+ this.abortControllers.forEach((controller, key) => {
6780
+ if (key.includes(url)) {
6781
+ controller.abort();
6782
+ this.abortControllers.delete(key);
6783
+ }
6784
+ });
6317
6785
  }
6318
- componentDidCatch(error, errorInfo) {
6319
- this.setState({
6320
- error,
6321
- errorInfo
6786
+ cancelAllRequests() {
6787
+ this.abortControllers.forEach((controller) => {
6788
+ controller.abort();
6322
6789
  });
6323
- this.props.onError?.(error, errorInfo);
6790
+ this.abortControllers.clear();
6324
6791
  }
6325
- render() {
6326
- if (this.state.hasError) {
6327
- if (this.props.fallback) {
6328
- const FallbackComponent = this.props.fallback;
6329
- return /* @__PURE__ */ jsx9(FallbackComponent, { error: this.state.error, retry: this.handleRetry });
6792
+ request(config) {
6793
+ const controller = new AbortController();
6794
+ const url = config.url || "";
6795
+ const method = config.method || "GET";
6796
+ const key = `${method}:${url}`;
6797
+ this.abortControllers.set(key, controller);
6798
+ config.signal = controller.signal;
6799
+ return new Promise((resolve, reject) => {
6800
+ if (config.interceptors?.requestInterceptor) {
6801
+ config = config.interceptors.requestInterceptor(config);
6330
6802
  }
6331
- return /* @__PURE__ */ jsx9("div", { className: "min-h-[400px] flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs7("div", { className: "text-center max-w-md", children: [
6332
- /* @__PURE__ */ jsx9("div", { className: "text-red-500 text-6xl mb-4", children: "\u26A0\uFE0F" }),
6333
- /* @__PURE__ */ jsx9("h2", { className: "text-xl font-semibold text-gray-900 mb-2", children: "Something went wrong" }),
6334
- /* @__PURE__ */ jsx9("p", { className: "text-gray-600 mb-4", children: "An unexpected error occurred. Please try refreshing the page." }),
6335
- /* @__PURE__ */ jsx9(
6336
- "button",
6337
- {
6338
- onClick: this.handleRetry,
6339
- className: "px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors",
6340
- children: "Try Again"
6341
- }
6342
- ),
6343
- false
6344
- ] }) });
6345
- }
6346
- return this.props.children;
6803
+ this.instance.request(config).then((res) => {
6804
+ this.abortControllers.delete(key);
6805
+ if (config.interceptors?.responseInterceptor) {
6806
+ res = config.interceptors.responseInterceptor(res);
6807
+ }
6808
+ resolve(res);
6809
+ }).catch((err) => {
6810
+ this.abortControllers.delete(key);
6811
+ reject(err);
6812
+ });
6813
+ });
6347
6814
  }
6348
- };
6349
- var DefaultErrorFallback = ({ retry }) => /* @__PURE__ */ jsx9("div", { className: "min-h-[200px] flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs7("div", { className: "text-center", children: [
6350
- /* @__PURE__ */ jsx9("div", { className: "text-red-500 text-4xl mb-2", children: "\u26A0\uFE0F" }),
6351
- /* @__PURE__ */ jsx9("p", { className: "text-gray-600 mb-2", children: "Something went wrong" }),
6352
- retry && /* @__PURE__ */ jsx9(
6353
- "button",
6354
- {
6355
- onClick: retry,
6356
- className: "px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors",
6357
- children: "Retry"
6358
- }
6359
- )
6360
- ] }) });
6361
-
6362
- // src/components/ui/ClayxButton.tsx
6363
- import { jsx as jsx10 } from "react/jsx-runtime";
6364
- var getSizeClasses = (size, isIconOnly) => {
6365
- if (isIconOnly) {
6366
- switch (size) {
6367
- case "sm":
6368
- return "h-8 w-8 min-w-8 p-0";
6369
- case "md":
6370
- return "h-10 w-10 min-w-10 p-0";
6371
- case "lg":
6372
- return "h-12 w-12 min-w-12 p-0";
6373
- default:
6374
- return "h-10 w-10 min-w-10 p-0";
6375
- }
6815
+ get(config) {
6816
+ return this.request({ ...config, method: "GET" });
6376
6817
  }
6377
- switch (size) {
6378
- case "sm":
6379
- return "h-8 px-3 text-sm";
6380
- case "md":
6381
- return "h-10 px-4 text-base";
6382
- case "lg":
6383
- return "h-12 px-6 text-lg";
6384
- default:
6385
- return "h-10 px-4 text-base";
6818
+ post(config) {
6819
+ return this.request({ ...config, method: "POST" });
6386
6820
  }
6387
- };
6388
- var getVariantClasses = (variant) => {
6389
- switch (variant) {
6390
- case "solid":
6391
- return "bg-primary text-white hover:bg-primary/90";
6392
- case "ghost":
6393
- return "bg-transparent hover:bg-white/10";
6394
- case "flat":
6395
- return "bg-white/5 hover:bg-white/10";
6396
- default:
6397
- return "";
6821
+ delete(config) {
6822
+ return this.request({ ...config, method: "DELETE" });
6823
+ }
6824
+ put(config) {
6825
+ return this.request({ ...config, method: "PUT" });
6826
+ }
6827
+ patch(config) {
6828
+ return this.request({ ...config, method: "PATCH" });
6398
6829
  }
6399
6830
  };
6400
- var ClayxButton = ({
6401
- isIconOnly = false,
6402
- size = "md",
6403
- variant = "solid",
6404
- className = "",
6405
- children,
6406
- disabled = false,
6407
- ...props
6408
- }) => {
6409
- const sizeClasses = getSizeClasses(size, isIconOnly);
6410
- const variantClasses = getVariantClasses(variant);
6411
- const baseClasses = `
6412
- inline-flex items-center justify-center
6413
- rounded-md font-medium
6414
- transition-all duration-200
6415
- focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-transparent
6416
- disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none
6417
- `.replace(/\s+/g, " ").trim();
6418
- const combinedClasses = `${baseClasses} ${sizeClasses} ${variantClasses} ${className}`.trim();
6419
- return /* @__PURE__ */ jsx10(
6420
- "button",
6421
- {
6422
- className: combinedClasses,
6423
- disabled,
6424
- ...props,
6425
- children
6426
- }
6427
- );
6428
- };
6429
-
6430
- // src/components/ui/LimitUpgradeToast.tsx
6431
- import { Icon as Icon5 } from "@iconify/react";
6432
-
6433
- // src/components/ui/Toast/ClayxToast.tsx
6434
- import React7, { useCallback as useCallback4 } from "react";
6435
- import { Bounce, toast } from "react-toastify";
6436
- import { Icon as Icon4 } from "@iconify/react";
6831
+ var request_default = Request;
6437
6832
 
6438
- // src/components/theme/ThemeToggle.tsx
6439
- import * as React6 from "react";
6440
- import { Icon as Icon3 } from "@iconify/react";
6441
- import { jsx as jsx11, jsxs as jsxs8 } from "react/jsx-runtime";
6442
- function ThemeToggle({ className }) {
6443
- const { setTheme, theme } = useTheme();
6444
- const [mounted, setMounted] = React6.useState(false);
6445
- React6.useEffect(() => {
6446
- setMounted(true);
6447
- }, []);
6448
- const handleToggle = () => {
6449
- if (theme === "dark") {
6450
- setTheme("light");
6451
- } else {
6452
- setTheme("dark");
6453
- }
6454
- };
6455
- if (!mounted) {
6456
- return /* @__PURE__ */ jsxs8(
6457
- "button",
6458
- {
6459
- className: `relative inline-flex h-10 w-12 items-center justify-center rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground ${className || ""}`,
6460
- disabled: true,
6461
- children: [
6462
- /* @__PURE__ */ jsx11(Icon3, { icon: "solar:sun-bold", width: 20, height: 20 }),
6463
- /* @__PURE__ */ jsx11("span", { className: "sr-only", children: "\u5207\u6362\u4E3B\u9898" })
6464
- ]
6465
- }
6466
- );
6467
- }
6468
- return /* @__PURE__ */ jsxs8(
6469
- "button",
6470
- {
6471
- className: `inline-flex h-10 w-12 items-center justify-center rounded-md border border-input bg-background hover:bg-accent hover:text-accent-foreground transition-colors ${className || ""}`,
6472
- onClick: handleToggle,
6473
- children: [
6474
- theme === "light" ? /* @__PURE__ */ jsx11(Icon3, { icon: "solar:sun-bold", width: 20, height: 20 }) : /* @__PURE__ */ jsx11(Icon3, { icon: "solar:moon-linear", width: 20, height: 20 }),
6475
- /* @__PURE__ */ jsx11("span", { className: "sr-only", children: "\u5207\u6362\u4E3B\u9898" })
6476
- ]
6833
+ // src/services/ai-workflow-axios.ts
6834
+ function createAIWorkflowClientAxios(options = {}) {
6835
+ const basePath = options.basePath ?? "/api";
6836
+ const baseUrl = (options.baseUrl || "https://evoagentx-server.fly.dev").replace(/\/+$/, "");
6837
+ const baseAPI = `${baseUrl}${basePath.startsWith("/") ? "" : "/"}${basePath}`.replace(/\/+$/, "");
6838
+ const client = options.requestInstance || new request_default({
6839
+ baseURL: baseAPI,
6840
+ timeout: options.timeout ?? 6e4,
6841
+ interceptors: {
6842
+ requestInterceptor: (config) => {
6843
+ config.headers = config.headers || {};
6844
+ if (options.apiKey && !config.headers["Authorization"]) {
6845
+ config.headers["Authorization"] = `Bearer ${options.apiKey}`;
6846
+ }
6847
+ if (options.headers) {
6848
+ config.headers = { ...config.headers || {}, ...options.headers };
6849
+ }
6850
+ return config;
6851
+ },
6852
+ requestInterceptorCatch: (err) => Promise.reject(err),
6853
+ responseInterceptor: (res) => res,
6854
+ responseInterceptorCatch: (err) => Promise.reject(err)
6477
6855
  }
6478
- );
6856
+ });
6857
+ return {
6858
+ async executeWorkflow(workflowId, inputs, opts) {
6859
+ const url = `${baseUrl}/workflow/${workflowId}/execute`;
6860
+ const data = await client.post({ url, data: { inputs, options: opts } });
6861
+ return data;
6862
+ }
6863
+ };
6479
6864
  }
6480
6865
 
6481
- // src/components/ui/Toast/ClayxToast.tsx
6482
- import { jsx as jsx12, jsxs as jsxs9 } from "react/jsx-runtime";
6483
- var TOAST_ICONS = {
6484
- success: {
6485
- icon: "mdi:success",
6486
- color: "text-green-400",
6487
- className: "text-green-400",
6488
- // 深色主题配置
6489
- dark: {
6490
- bgGradient: "bg-[#14181d]",
6491
- // 移除透明度 f2
6492
- gradientColor: "#389726",
6493
- borderGradient: "border-[#389726]",
6494
- borderGradientColor: "#389726"
6866
+ // src/services/artifact-types.ts
6867
+ function canAccessArtifact(a, ctx = {}) {
6868
+ if (!a) return false;
6869
+ if (a.visibility === "public") return true;
6870
+ if (a.visibility === "project") {
6871
+ if (ctx.projectId && a.projectId && ctx.projectId === a.projectId) return true;
6872
+ if (ctx.tokenScopes && ctx.tokenScopes.includes("project:read")) return true;
6873
+ return false;
6874
+ }
6875
+ if (a.visibility === "private") {
6876
+ if (ctx.userId && a.ownerId && ctx.userId === a.ownerId) return true;
6877
+ if (ctx.tokenScopes && (ctx.tokenScopes.includes("artifact:read:all") || ctx.tokenScopes.includes("admin"))) return true;
6878
+ return false;
6879
+ }
6880
+ if (a.visibility === "shared") {
6881
+ if (ctx.userId && a.sharedWith && a.sharedWith.includes(ctx.userId)) return true;
6882
+ if (ctx.tokenScopes && (ctx.tokenScopes.includes("artifact:read:all") || ctx.tokenScopes.includes("admin"))) return true;
6883
+ return false;
6884
+ }
6885
+ return false;
6886
+ }
6887
+
6888
+ // src/services/artifacts-client.ts
6889
+ function createArtifactsClient(req) {
6890
+ return {
6891
+ async create(input) {
6892
+ return await req.post({ url: "/artifacts", data: input });
6495
6893
  },
6496
- // 浅色主题配置
6497
- light: {
6498
- bgGradient: "bg-[#fafafa]",
6499
- // 移除透明度 ff
6500
- gradientColor: "#22c55e",
6501
- borderGradient: "border-[#22c55e]",
6502
- borderGradientColor: "#22c55e"
6503
- }
6504
- },
6505
- error: {
6506
- icon: "ic:outline-close",
6507
- color: "text-red-400",
6508
- className: "text-red-400",
6509
- dark: {
6510
- bgGradient: "bg-[#14181d]",
6511
- // 移除透明度 f2
6512
- gradientColor: "#ef4444",
6513
- borderGradient: "border-[#ef4444]",
6514
- borderGradientColor: "#ef4444"
6894
+ async list(query) {
6895
+ return await req.get({ url: "/artifacts", params: query });
6515
6896
  },
6516
- light: {
6517
- bgGradient: "bg-[#fafafa]",
6518
- // 移除透明度 ff
6519
- gradientColor: "#f87171",
6520
- borderGradient: "border-[#f87171]",
6521
- borderGradientColor: "#f87171"
6522
- }
6523
- },
6524
- warning: {
6525
- icon: "mi:warning",
6526
- color: "text-yellow-400",
6527
- className: "text-yellow-400",
6528
- dark: {
6529
- bgGradient: "bg-[#14181d]",
6530
- // 移除透明度 f2
6531
- gradientColor: "#facc15",
6532
- borderGradient: "border-[#facc15]",
6533
- borderGradientColor: "#facc15"
6897
+ async get(id) {
6898
+ return await req.get({ url: `/artifacts/${encodeURIComponent(id)}` });
6534
6899
  },
6535
- light: {
6536
- bgGradient: "bg-[#fafafa]",
6537
- // 移除透明度 ff
6538
- gradientColor: "#f59e0b",
6539
- borderGradient: "border-[#f59e0b]",
6540
- borderGradientColor: "#f59e0b"
6541
- }
6542
- },
6543
- info: {
6544
- icon: "ic:outline-info",
6545
- color: "text-blue-400",
6546
- className: "text-blue-400",
6547
- dark: {
6548
- bgGradient: "bg-[#14181d]",
6549
- // 移除透明度 f2
6550
- gradientColor: "#60a5fa",
6551
- borderGradient: "border-[#60a5fa]",
6552
- borderGradientColor: "#f0f0f0"
6900
+ async setVisibility(id, visibility) {
6901
+ await req.patch({ url: `/artifacts/${encodeURIComponent(id)}/visibility`, data: { visibility } });
6553
6902
  },
6554
- light: {
6555
- bgGradient: "bg-[#fafafa]",
6556
- // 移除透明度 ff
6557
- gradientColor: "#3b82f6",
6558
- borderGradient: "border-[#3b82f6]",
6559
- borderGradientColor: "#3b82f6"
6560
- }
6561
- },
6562
- default: {
6563
- icon: "ic:round-notifications",
6564
- color: "text-gray-400",
6565
- className: "text-gray-400",
6566
- dark: {
6567
- bgGradient: "bg-[#14181d]",
6568
- // 移除透明度 f2
6569
- gradientColor: "#9ca3af",
6570
- borderGradient: "border-[#9ca3af]",
6571
- borderGradientColor: "#9ca3af"
6903
+ async delete(id) {
6904
+ await req.delete({ url: `/artifacts/${encodeURIComponent(id)}` });
6572
6905
  },
6573
- light: {
6574
- bgGradient: "bg-[#fafafa]",
6575
- // 移除透明度 ff
6576
- gradientColor: "#6b7280",
6577
- borderGradient: "border-[#6b7280]",
6578
- borderGradientColor: "#6b7280"
6579
- }
6580
- }
6581
- };
6582
- var CloseButton = React7.memo(({ closeToast }) => {
6583
- const { theme } = useTheme();
6584
- const handleClick = useCallback4((e) => {
6585
- e.preventDefault();
6586
- e.stopPropagation();
6587
- closeToast?.();
6588
- }, [closeToast]);
6589
- const getCloseButtonColor = () => {
6590
- const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6591
- return actualTheme === "dark" ? "#b4b4b4" : "#6b7280";
6592
- };
6593
- const getCloseButtonHoverColor = () => {
6594
- const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6595
- return actualTheme === "dark" ? "white" : "#374151";
6596
- };
6597
- return /* @__PURE__ */ jsx12(
6598
- Icon4,
6599
- {
6600
- icon: "vaadin:close",
6601
- className: "flex items-center justify-center rounded-full relative z-10 flex-shrink-0 cursor-pointer \n transition-colors duration-200 drop-shadow-sm",
6602
- onClick: handleClick,
6603
- width: 14,
6604
- height: 14,
6605
- style: {
6606
- color: getCloseButtonColor()
6607
- },
6608
- onMouseEnter: (e) => {
6609
- e.currentTarget.style.color = getCloseButtonHoverColor();
6610
- },
6611
- onMouseLeave: (e) => {
6612
- e.currentTarget.style.color = getCloseButtonColor();
6613
- }
6906
+ // convenience local check (server is authoritative)
6907
+ canAccessLocal(a, ctx) {
6908
+ if (!a) return false;
6909
+ if (a.visibility === "public") return true;
6910
+ if (a.visibility === "project") return Boolean(ctx.projectId && a.projectId && ctx.projectId === a.projectId);
6911
+ if (a.visibility === "private") return Boolean(ctx.userId && a.ownerId && ctx.userId === a.ownerId);
6912
+ if (a.visibility === "shared") return Boolean(ctx.userId && a.sharedWith && a.sharedWith.includes(ctx.userId));
6913
+ return false;
6614
6914
  }
6615
- );
6616
- });
6617
- CloseButton.displayName = "CloseButton";
6618
- var ToastContent = ({ type, title, message, component, closeToast }) => {
6619
- const iconConfig = TOAST_ICONS[type];
6620
- const { theme } = useTheme();
6621
- const handleClose = useCallback4(() => {
6622
- closeToast?.();
6623
- }, [closeToast]);
6624
- const getTextColor = () => {
6625
- const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6626
- return actualTheme === "dark" ? "white" : "#1f2937";
6627
- };
6628
- const getThemeConfig = () => {
6629
- const actualTheme = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme;
6630
- return actualTheme === "dark" ? iconConfig.dark : iconConfig.light;
6631
6915
  };
6632
- const themeConfig = getThemeConfig();
6633
- if (component) {
6634
- return /* @__PURE__ */ jsxs9("div", { className: `flex items-start gap-3 !min-h-[90px] w-full backdrop-blur-md p-4 shadow-2xl relative overflow-hidden ${themeConfig.bgGradient}`, children: [
6635
- /* @__PURE__ */ jsx12("div", { className: "flex-1 relative z-10", children: component }),
6636
- /* @__PURE__ */ jsx12("div", { className: "relative z-10", children: /* @__PURE__ */ jsx12(CloseButton, { closeToast: handleClose }) })
6637
- ] });
6638
- }
6639
- return /* @__PURE__ */ jsxs9("div", { className: `flex items-start gap-3 !min-h-[90px] w-full backdrop-blur-md p-4 shadow-2xl relative overflow-hidden ${themeConfig.bgGradient}`, children: [
6640
- /* @__PURE__ */ jsx12(
6641
- "div",
6642
- {
6643
- className: "absolute left-0 top-0 w-full h-full rounded-xl",
6644
- style: {
6645
- background: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "#0f1419" : "#ffffff",
6646
- zIndex: -2
6647
- }
6648
- }
6649
- ),
6650
- /* @__PURE__ */ jsx12(
6651
- "div",
6652
- {
6653
- className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-xl",
6654
- style: {
6655
- background: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? `linear-gradient(135deg, ${themeConfig.gradientColor}30 0%, ${themeConfig.gradientColor}20 15%, #14181df2 30%)` : `linear-gradient(135deg, ${themeConfig.gradientColor}15 0%, ${themeConfig.gradientColor}08 15%, #fafafaff 30%)`,
6656
- zIndex: -1
6657
- }
6658
- }
6659
- ),
6660
- /* @__PURE__ */ jsx12(
6661
- "div",
6662
- {
6663
- className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-xl",
6664
- style: {
6665
- border: "2px solid transparent",
6666
- backgroundImage: theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? `linear-gradient(135deg, ${themeConfig.borderGradientColor}60 0%, ${themeConfig.borderGradientColor}40 5%, transparent 22%)` : `linear-gradient(135deg, ${themeConfig.borderGradientColor}40 0%, ${themeConfig.borderGradientColor}25 5%, transparent 22%)`,
6667
- backgroundOrigin: "border-box",
6668
- backgroundClip: "border-box",
6669
- WebkitMask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6670
- WebkitMaskComposite: "xor",
6671
- mask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6672
- maskComposite: "exclude"
6916
+ }
6917
+
6918
+ // src/services/index.ts
6919
+ init_auth();
6920
+ init_config();
6921
+ init_config();
6922
+ init_auth();
6923
+
6924
+ // src/utils/urlSanitizer.ts
6925
+ var DEFAULT_SENSITIVE = ["token", "access_token", "auth", "auth_token"];
6926
+ function removeSensitiveParamsFromUrl(opts) {
6927
+ if (typeof window === "undefined") return;
6928
+ try {
6929
+ const { clearAll, sensitiveParams, includeHash = true, onChanged } = opts || {};
6930
+ const sens = (sensitiveParams && sensitiveParams.length > 0 ? sensitiveParams : DEFAULT_SENSITIVE).map((s) => s.toLowerCase());
6931
+ const before = window.location.href;
6932
+ const url = new URL(before);
6933
+ if (clearAll) {
6934
+ url.search = "";
6935
+ } else if (url.search) {
6936
+ let changed = false;
6937
+ for (const [k] of url.searchParams) {
6938
+ if (sens.includes(k.toLowerCase())) {
6939
+ url.searchParams.delete(k);
6940
+ changed = true;
6673
6941
  }
6674
6942
  }
6675
- ),
6676
- /* @__PURE__ */ jsx12("div", { className: "flex-shrink-0 mt-0.5 relative z-10", children: /* @__PURE__ */ jsx12("div", { className: `w-7 h-7 backdrop-blur-sm rounded-full flex items-center justify-center ${theme === "dark" || theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "bg-white/10" : "bg-black/5"}`, children: /* @__PURE__ */ jsx12(
6677
- Icon4,
6678
- {
6679
- icon: iconConfig.icon,
6680
- width: 16,
6681
- height: 16,
6682
- className: iconConfig.color,
6683
- style: {
6684
- color: themeConfig.gradientColor
6685
- }
6943
+ if (changed) {
6944
+ const qs = url.searchParams.toString();
6945
+ url.search = qs ? `?${qs}` : "";
6686
6946
  }
6687
- ) }) }),
6688
- /* @__PURE__ */ jsxs9("div", { className: "flex flex-col gap-1 flex-1 relative z-10", children: [
6689
- title && /* @__PURE__ */ jsx12(
6690
- "div",
6691
- {
6692
- className: "text-[16px] font-semibold leading-tight drop-shadow-sm",
6693
- style: {
6694
- color: getTextColor(),
6695
- backgroundClip: "text"
6696
- },
6697
- children: title
6698
- }
6699
- ),
6700
- message && /* @__PURE__ */ jsx12(
6701
- "div",
6702
- {
6703
- className: "text-[13px] font-normal leading-relaxed drop-shadow-sm",
6704
- style: {
6705
- color: getTextColor(),
6706
- backgroundClip: "text"
6707
- },
6708
- children: message
6709
- }
6710
- )
6711
- ] }),
6712
- /* @__PURE__ */ jsx12("div", { className: "relative z-10", children: /* @__PURE__ */ jsx12(CloseButton, { closeToast: handleClose }) })
6713
- ] });
6714
- };
6715
- var defaultToastOptions = {
6716
- position: "bottom-right",
6717
- autoClose: 3e3,
6718
- hideProgressBar: true,
6719
- closeOnClick: false,
6720
- pauseOnHover: true,
6721
- draggable: true,
6722
- pauseOnFocusLoss: false,
6723
- theme: "dark",
6724
- transition: Bounce
6725
- };
6726
- var createToast = (type) => {
6727
- return (params) => {
6728
- const { title, message, component, options } = params;
6729
- toast(
6730
- ({ closeToast }) => {
6731
- if (params.render) return params.render(closeToast);
6732
- return /* @__PURE__ */ jsx12(
6733
- ToastContent,
6734
- {
6735
- type,
6736
- title,
6737
- message: message || "",
6738
- component,
6739
- closeToast
6947
+ }
6948
+ if (includeHash && url.hash) {
6949
+ const raw = url.hash.slice(1);
6950
+ if (raw.includes("=")) {
6951
+ const hp = new URLSearchParams(raw);
6952
+ let changed = false;
6953
+ for (const [k] of hp) {
6954
+ if (clearAll || sens.includes(k.toLowerCase())) {
6955
+ hp.delete(k);
6956
+ changed = true;
6740
6957
  }
6741
- );
6742
- },
6743
- {
6744
- ...defaultToastOptions,
6745
- ...options,
6746
- // 确保圆角样式不被覆盖,添加 rounded-xl 类
6747
- className: "!p-0 !shadow-none !rounded-xl",
6748
- style: { padding: 0, borderRadius: "0.75rem" }
6749
- }
6750
- );
6751
- };
6752
- };
6753
- var ClayxToast = {
6754
- success: createToast("success"),
6755
- error: createToast("error"),
6756
- warning: createToast("warning"),
6757
- info: createToast("info"),
6758
- default: createToast("default")
6759
- };
6760
-
6761
- // src/components/ui/LimitUpgradeToast.tsx
6762
- import { jsx as jsx13, jsxs as jsxs10 } from "react/jsx-runtime";
6763
- var LimitToastContainer = ({ message, onUpgrade, closeToast }) => {
6764
- return /* @__PURE__ */ jsxs10("div", { className: "relative w-full max-w-[420px] overflow-hidden rounded-md bg-gradient-to-br from-[#1A1A1A] via-[#151515] to-[#1A1A1A] shadow-[0_20px_60px_rgba(168,85,247,0.2)] backdrop-blur-sm", children: [
6765
- /* @__PURE__ */ jsx13(
6766
- "div",
6767
- {
6768
- className: "absolute left-0 top-0 w-full h-full rounded-md",
6769
- style: {
6770
- background: "#0f1419",
6771
- zIndex: -2
6772
6958
  }
6773
- }
6774
- ),
6775
- /* @__PURE__ */ jsx13(
6776
- "div",
6777
- {
6778
- className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-md",
6779
- style: {
6780
- background: `linear-gradient(135deg, rgba(168,85,247,0.3) 0%, rgba(168,85,247,0.2) 15%, #1A1A1A 30%)`,
6781
- zIndex: -1
6959
+ if (changed) {
6960
+ const hs = hp.toString();
6961
+ url.hash = hs ? `#${hs}` : "";
6782
6962
  }
6783
- }
6784
- ),
6785
- /* @__PURE__ */ jsx13(
6786
- "div",
6787
- {
6788
- className: "absolute left-0 top-0 w-full h-full pointer-events-none rounded-md",
6789
- style: {
6790
- border: "2px solid transparent",
6791
- backgroundImage: `linear-gradient(135deg, rgba(168,85,247,0.6) 0%, rgba(168,85,247,0.4) 5%, transparent 22%)`,
6792
- backgroundOrigin: "border-box",
6793
- backgroundClip: "border-box",
6794
- WebkitMask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6795
- WebkitMaskComposite: "xor",
6796
- mask: "linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0)",
6797
- maskComposite: "exclude"
6963
+ } else {
6964
+ if (!clearAll && sens.some((p) => raw.toLowerCase().startsWith(p))) {
6965
+ url.hash = "";
6966
+ } else if (clearAll) {
6967
+ url.hash = "";
6798
6968
  }
6799
6969
  }
6800
- ),
6801
- /* @__PURE__ */ jsx13("div", { className: "absolute -top-16 -right-16 h-32 w-32 rounded-full bg-gradient-to-br from-purple-500/20 via-pink-500/10 to-transparent blur-3xl animate-pulse" }),
6802
- /* @__PURE__ */ jsx13("div", { className: "absolute -bottom-16 -left-16 h-32 w-32 rounded-full bg-gradient-to-tr from-blue-500/10 to-transparent blur-2xl animate-pulse", style: { animationDelay: "1s" } }),
6803
- /* @__PURE__ */ jsx13("div", { className: "relative z-10 flex items-start gap-4 p-4", children: /* @__PURE__ */ jsxs10("div", { className: "flex flex-1 flex-col gap-3", children: [
6804
- /* @__PURE__ */ jsxs10("div", { className: "flex items-center justify-between", children: [
6805
- /* @__PURE__ */ jsxs10("div", { className: "flex items-center gap-2", children: [
6806
- /* @__PURE__ */ jsx13("div", { className: "text-lg font-bold bg-gradient-to-r from-white to-gray-400 bg-clip-text text-transparent", children: "Upgrade Required" }),
6807
- /* @__PURE__ */ jsx13("div", { className: "px-2 py-0.5 text-xs font-bold bg-purple-500/20 text-purple-400 rounded-md border border-purple-500/30", children: "Premium" })
6808
- ] }),
6809
- /* @__PURE__ */ jsx13(
6810
- ClayxButton,
6811
- {
6812
- onClick: closeToast,
6813
- isIconOnly: true,
6814
- size: "sm",
6815
- className: "h-6 w-6 min-w-6 rounded-full bg-white/5 hover:bg-white/10 transition-colors",
6816
- children: /* @__PURE__ */ jsx13(Icon5, { icon: "iconamoon:close", className: "w-4 h-4 text-gray-400" })
6817
- }
6818
- )
6819
- ] }),
6820
- /* @__PURE__ */ jsx13("p", { className: "text-sm text-gray-300 leading-relaxed", children: message }),
6821
- /* @__PURE__ */ jsx13("div", { className: "mt-1 flex items-center gap-3", children: /* @__PURE__ */ jsx13(
6822
- ClayxButton,
6823
- {
6824
- onClick: () => {
6825
- onUpgrade();
6826
- closeToast?.();
6827
- },
6828
- className: "flex-1 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 text-white font-semibold transition-all duration-300 hover:shadow-lg hover:shadow-purple-500/30 cursor-pointer",
6829
- style: { cursor: "pointer" },
6830
- children: /* @__PURE__ */ jsxs10("span", { className: "flex items-center gap-2", children: [
6831
- /* @__PURE__ */ jsx13(Icon5, { icon: "solar:rocket-2-bold", className: "w-4 h-4" }),
6832
- "Upgrade Now"
6833
- ] })
6970
+ }
6971
+ const next = url.pathname + url.search + url.hash;
6972
+ if (next !== window.location.pathname + window.location.search + window.location.hash) {
6973
+ window.history.replaceState(window.history.state, document.title, next);
6974
+ onChanged && onChanged(next);
6975
+ }
6976
+ } catch (e) {
6977
+ console.warn("[howone][urlSanitizer] failed", e);
6978
+ }
6979
+ }
6980
+
6981
+ // src/services/index.ts
6982
+ function getGlobalAvailableToken() {
6983
+ try {
6984
+ return getToken() || null;
6985
+ } catch {
6986
+ return null;
6987
+ }
6988
+ }
6989
+ function wrapRequestWithProjectPrefix(biz, projectId) {
6990
+ if (!projectId) return biz;
6991
+ const prefix = `/entities/apps/${String(projectId)}`;
6992
+ function shouldPrefix(url) {
6993
+ if (!url) return false;
6994
+ const u = String(url);
6995
+ if (u.startsWith(prefix)) return false;
6996
+ if (/^https?:\/\//.test(u) || u.startsWith("//")) return false;
6997
+ if (u.startsWith("/data")) return true;
6998
+ return false;
6999
+ }
7000
+ const wrapped = {
7001
+ instance: biz.instance,
7002
+ request: (config) => {
7003
+ try {
7004
+ if (config && typeof config.url === "string" && shouldPrefix(config.url)) {
7005
+ config = { ...config, url: `${prefix}${config.url}` };
6834
7006
  }
6835
- ) })
6836
- ] }) })
6837
- ] });
6838
- };
6839
- function showLimitUpgradeToast(message, onUpgrade) {
6840
- ClayxToast.default({
6841
- render: (closeToast) => /* @__PURE__ */ jsx13(LimitToastContainer, { message, onUpgrade, closeToast }),
6842
- options: {
6843
- position: "bottom-right",
6844
- closeOnClick: false,
6845
- autoClose: false,
6846
- hideProgressBar: true,
6847
- draggable: false,
6848
- pauseOnHover: true,
6849
- className: "!bg-transparent !shadow-none",
6850
- style: {
6851
- background: "transparent",
6852
- padding: 0,
6853
- width: "auto",
6854
- maxWidth: "420px"
7007
+ } catch (_e) {
6855
7008
  }
6856
- }
6857
- });
7009
+ return biz.request(config);
7010
+ },
7011
+ get: (config) => wrapped.request({ ...config, method: "GET" }),
7012
+ post: (config) => wrapped.request({ ...config, method: "POST" }),
7013
+ put: (config) => wrapped.request({ ...config, method: "PUT" }),
7014
+ patch: (config) => wrapped.request({ ...config, method: "PATCH" }),
7015
+ delete: (config) => wrapped.request({ ...config, method: "DELETE" }),
7016
+ cancelRequest: (url) => biz.cancelRequest(url),
7017
+ cancelAllRequests: () => biz.cancelAllRequests()
7018
+ };
7019
+ return wrapped;
6858
7020
  }
6859
-
6860
- // src/services/ai-workflow.ts
6861
- var AIWorkflowClient = class {
6862
- constructor(options = {}) {
6863
- this.baseUrl = options.baseUrl?.replace(/\/+$/, "") || "";
6864
- this.apiKey = options.apiKey;
6865
- this.headers = { "Content-Type": "application/json", ...options.headers || {} };
6866
- this.fetchImpl = options.fetchImpl || fetch.bind(globalThis);
7021
+ function createClient(opts) {
7022
+ const envValue = opts.env || getGlobalEnvironment() || "prod";
7023
+ const env2 = setEnvironment(envValue);
7024
+ function makeRequestFromBase(base) {
7025
+ return new request_default({
7026
+ baseURL: base,
7027
+ timeout: 6e4,
7028
+ interceptors: {
7029
+ requestInterceptor: (config) => {
7030
+ config.headers = config.headers || {};
7031
+ if (!config.headers["Authorization"]) {
7032
+ const availableToken = getAvailableToken();
7033
+ if (availableToken) {
7034
+ config.headers["Authorization"] = `Bearer ${availableToken}`;
7035
+ }
7036
+ }
7037
+ return config;
7038
+ },
7039
+ requestInterceptorCatch: (err) => Promise.reject(err),
7040
+ responseInterceptor: (res) => {
7041
+ const data = res.data;
7042
+ if (data && data.status && data.status === 4003) {
7043
+ showLimitUpgradeToast(
7044
+ "Your credits are exhausted. Please upgrade your plan to continue generating projects.",
7045
+ () => window.open(`${getEnvs().AUTH_ROOT_VALUE}/price`, "_blank")
7046
+ );
7047
+ return res;
7048
+ }
7049
+ return res;
7050
+ },
7051
+ responseInterceptorCatch: (err) => Promise.reject(err)
7052
+ }
7053
+ });
6867
7054
  }
6868
- buildHeaders(extra) {
6869
- const h = { ...this.headers, ...extra || {} };
6870
- if (this.apiKey && !h["Authorization"]) {
6871
- h["Authorization"] = `Bearer ${this.apiKey}`;
6872
- }
6873
- return h;
7055
+ const biz = makeRequestFromBase(env2.baseUrl);
7056
+ const ai = makeRequestFromBase(env2.aiBaseUrl);
7057
+ const bizWrapped = wrapRequestWithProjectPrefix(biz, opts?.projectId);
7058
+ let token = null;
7059
+ function getAvailableToken() {
7060
+ return token || getGlobalAvailableToken();
6874
7061
  }
6875
- async safeJson(resp) {
6876
- try {
6877
- return await resp.json();
6878
- } catch (_e) {
6879
- return null;
7062
+ try {
7063
+ if (opts?.projectId) {
7064
+ setDefaultProjectId(String(opts.projectId));
6880
7065
  }
7066
+ } catch {
6881
7067
  }
6882
- /**
6883
- * 按 ID 执行工作流:POST {baseUrl}/workflow/{workflowId}/execute
6884
- * body: { input, options }
6885
- */
6886
- async executeWorkflow(workflowId, inputs, options) {
6887
- if (!this.baseUrl) {
6888
- throw new Error("AI workflow client requires a baseUrl (e.g. https://evoagentx-server.fly.dev)");
6889
- }
6890
- const url = `${this.baseUrl}/workflow/${workflowId}/execute`;
7068
+ function applyToken(t) {
6891
7069
  try {
6892
- const res = await this.fetchImpl(url, {
6893
- method: "POST",
6894
- headers: this.buildHeaders(),
6895
- body: JSON.stringify({ inputs, options })
6896
- });
6897
- const data = await this.safeJson(res);
6898
- if (!res.ok) {
6899
- return { success: false, error: data?.error || `HTTP ${res.status}` };
6900
- }
6901
- if (data && data.status && data.status === 4003) {
6902
- showLimitUpgradeToast(
6903
- "Your credits are exhausted. Please upgrade your plan to continue generating projects.",
6904
- () => window.open("https://clayx.ai/pricing", "_blank")
6905
- );
6906
- return null;
7070
+ try {
7071
+ if (biz && biz.instance) {
7072
+ if (t) biz.instance.defaults.headers.common["Authorization"] = `Bearer ${t}`;
7073
+ else delete biz.instance.defaults.headers.common["Authorization"];
7074
+ }
7075
+ if (ai && ai.instance) {
7076
+ if (t) ai.instance.defaults.headers.common["Authorization"] = `Bearer ${t}`;
7077
+ else delete ai.instance.defaults.headers.common["Authorization"];
7078
+ }
7079
+ } catch (_e) {
6907
7080
  }
6908
- return data || { success: true };
6909
- } catch (error) {
6910
- return { success: false, error: error instanceof Error ? error.message : "Network error" };
7081
+ } catch (_e) {
6911
7082
  }
6912
7083
  }
6913
- };
6914
- function createAIWorkflowClient(options = {}) {
6915
- return new AIWorkflowClient(options);
6916
- }
6917
- var aiWorkflow = createAIWorkflowClient({ baseUrl: "https://evoagentx-server" });
6918
-
6919
- // src/services/request/index.ts
6920
- import axios from "axios";
6921
- var Request = class {
6922
- constructor(config) {
6923
- this.abortControllers = /* @__PURE__ */ new Map();
6924
- this.instance = axios.create({
6925
- ...config,
6926
- validateStatus: (status) => {
6927
- return status >= 200 && status < 300;
7084
+ const workflowRequestWrapped = {
7085
+ get: ai.get.bind(ai),
7086
+ post: (config) => {
7087
+ const modifiedConfig = { ...config };
7088
+ if (opts?.projectId && modifiedConfig.url) {
7089
+ const workflowPattern = /^\/?(?:workflow\/)?([^\/]+)\/execute/;
7090
+ const match = modifiedConfig.url.match(workflowPattern);
7091
+ if (match) {
7092
+ const workflowId = match[1];
7093
+ modifiedConfig.url = `/workflow/${opts.projectId}/${workflowId}/execute`;
7094
+ }
6928
7095
  }
6929
- });
6930
- this.interceptors = config.interceptors;
6931
- this.instance.interceptors.request.use(
6932
- this.interceptors?.requestInterceptor,
6933
- this.interceptors?.requestInterceptorCatch
6934
- );
6935
- this.instance.interceptors.response.use(
6936
- this.interceptors?.responseInterceptor,
6937
- this.interceptors?.responseInterceptorCatch
6938
- );
6939
- this.instance.interceptors.request.use(
6940
- (config2) => {
6941
- return config2;
6942
- },
6943
- (err) => {
6944
- return Promise.reject(err);
7096
+ return ai.post(modifiedConfig);
7097
+ },
7098
+ put: ai.put.bind(ai),
7099
+ delete: ai.delete.bind(ai),
7100
+ request: ai.request.bind(ai),
7101
+ cancelRequest: ai.cancelRequest?.bind(ai),
7102
+ cancelAllRequests: ai.cancelAllRequests?.bind(ai)
7103
+ };
7104
+ return {
7105
+ // expose projectId so consumers can read it from the client instance
7106
+ projectId: opts?.projectId ?? null,
7107
+ request: bizWrapped,
7108
+ aiRequest: ai,
7109
+ workflowRequest: workflowRequestWrapped,
7110
+ // artifact helpers using artifacts-client
7111
+ artifacts: createArtifactsClient(biz),
7112
+ me: async () => {
7113
+ try {
7114
+ const t = token ?? (opts?.auth?.getToken ? await opts.auth.getToken() : null) ?? getToken();
7115
+ if (!t) return null;
7116
+ return parseUserFromToken(t);
7117
+ } catch (_e2) {
7118
+ return null;
6945
7119
  }
6946
- );
6947
- this.instance.interceptors.response.use(
6948
- (res) => {
6949
- return res.data;
7120
+ },
7121
+ // auth helpers
7122
+ auth: {
7123
+ setToken: (t) => {
7124
+ token = t;
7125
+ applyToken(t);
6950
7126
  },
6951
- (err) => {
6952
- if (axios.isCancel(err)) {
6953
- return Promise.reject({
6954
- isCanceled: true,
6955
- message: "request canceled",
6956
- originalError: err
6957
- });
6958
- }
6959
- if (err.response?.data?.error) {
6960
- return Promise.reject(err.response.data.error);
7127
+ getToken: () => token,
7128
+ isAuthenticated: () => Boolean(token),
7129
+ // minimal login/logout stubs - consumers can override behavior
7130
+ login: (redirect) => {
7131
+ if (typeof window === "undefined") return;
7132
+ const loc = redirect || window.location.href;
7133
+ try {
7134
+ const root = env2.baseUrl;
7135
+ const authUrl = new URL("/auth", String(root));
7136
+ authUrl.searchParams.set("redirect_uri", String(loc));
7137
+ if (opts?.projectId) authUrl.searchParams.set("project_id", String(opts.projectId));
7138
+ window.location.href = authUrl.toString();
7139
+ } catch {
7140
+ const encoded = encodeURIComponent(String(loc));
7141
+ const pid = opts?.projectId ? `&project_id=${encodeURIComponent(String(opts.projectId))}` : "";
7142
+ const root = env2.baseUrl;
7143
+ window.location.href = `${root}/auth?redirect_uri=${encoded}${pid}`;
6961
7144
  }
6962
- return Promise.reject(err);
6963
- }
6964
- );
6965
- }
6966
- cancelRequest(url) {
6967
- this.abortControllers.forEach((controller, key) => {
6968
- if (key.includes(url)) {
6969
- controller.abort();
6970
- this.abortControllers.delete(key);
7145
+ },
7146
+ logout: () => {
7147
+ token = null;
7148
+ applyToken(null);
6971
7149
  }
6972
- });
7150
+ },
7151
+ sanitizeUrl: (o) => {
7152
+ if (typeof window === "undefined") return;
7153
+ removeSensitiveParamsFromUrl({
7154
+ clearAll: o?.clearAll,
7155
+ sensitiveParams: o?.sensitiveParams
7156
+ });
7157
+ }
7158
+ };
7159
+ }
7160
+
7161
+ // src/hooks/use-mobile.ts
7162
+ import * as React8 from "react";
7163
+ var MOBILE_BREAKPOINT = 768;
7164
+ function useIsMobile() {
7165
+ const [isMobile, setIsMobile] = React8.useState(void 0);
7166
+ React8.useEffect(() => {
7167
+ const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
7168
+ const onChange = () => {
7169
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
7170
+ };
7171
+ mql.addEventListener("change", onChange);
7172
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
7173
+ return () => mql.removeEventListener("change", onChange);
7174
+ }, []);
7175
+ return !!isMobile;
7176
+ }
7177
+
7178
+ // src/hooks/use-debounce.ts
7179
+ import { useState as useState10, useEffect as useEffect9 } from "react";
7180
+ function useDebounce(value, delay) {
7181
+ const [debouncedValue, setDebouncedValue] = useState10(value);
7182
+ useEffect9(() => {
7183
+ const handler = setTimeout(() => {
7184
+ setDebouncedValue(value);
7185
+ }, delay);
7186
+ return () => {
7187
+ clearTimeout(handler);
7188
+ };
7189
+ }, [value, delay]);
7190
+ return debouncedValue;
7191
+ }
7192
+
7193
+ // src/utils/unified-error-handler/simple.ts
7194
+ var SimpleErrorHandler = class {
7195
+ constructor() {
7196
+ this.initialized = false;
6973
7197
  }
6974
- cancelAllRequests() {
6975
- this.abortControllers.forEach((controller) => {
6976
- controller.abort();
7198
+ // 使用明确赋值断言,因为在 init() 方法中会初始化
7199
+ /**
7200
+ * 初始化错误处理器
7201
+ */
7202
+ init() {
7203
+ if (this.initialized) return;
7204
+ this.sendMessage = createSimpleSendFunction({
7205
+ addTimestamp: false,
7206
+ // 简化版自己处理时间戳
7207
+ enableDebugLog: false
6977
7208
  });
6978
- this.abortControllers.clear();
7209
+ this.setupErrorListeners();
7210
+ this.setupCompatibility();
7211
+ this.initialized = true;
6979
7212
  }
6980
- request(config) {
6981
- const controller = new AbortController();
6982
- const url = config.url || "";
6983
- const method = config.method || "GET";
6984
- const key = `${method}:${url}`;
6985
- this.abortControllers.set(key, controller);
6986
- config.signal = controller.signal;
6987
- return new Promise((resolve, reject) => {
6988
- if (config.interceptors?.requestInterceptor) {
6989
- config = config.interceptors.requestInterceptor(config);
6990
- }
6991
- this.instance.request(config).then((res) => {
6992
- this.abortControllers.delete(key);
6993
- if (config.interceptors?.responseInterceptor) {
6994
- res = config.interceptors.responseInterceptor(res);
6995
- }
6996
- resolve(res);
6997
- }).catch((err) => {
6998
- this.abortControllers.delete(key);
6999
- reject(err);
7213
+ /**
7214
+ * 设置错误监听器
7215
+ */
7216
+ setupErrorListeners() {
7217
+ window.addEventListener("error", (event) => {
7218
+ this.sendError(event.error || new Error(event.message), {
7219
+ filename: event.filename,
7220
+ lineno: event.lineno,
7221
+ colno: event.colno,
7222
+ type: "runtime"
7000
7223
  });
7001
7224
  });
7225
+ window.addEventListener("unhandledrejection", (event) => {
7226
+ const error = event.reason instanceof Error ? event.reason : new Error(String(event.reason));
7227
+ this.sendError(error, { type: "promise" });
7228
+ });
7002
7229
  }
7003
- get(config) {
7004
- return this.request({ ...config, method: "GET" });
7005
- }
7006
- post(config) {
7007
- return this.request({ ...config, method: "POST" });
7008
- }
7009
- delete(config) {
7010
- return this.request({ ...config, method: "DELETE" });
7230
+ /**
7231
+ * 设置兼容性函数
7232
+ */
7233
+ setupCompatibility() {
7234
+ window.__SEND_ERROR_TO_PARENT__ = (error, details) => {
7235
+ const errorObj = error instanceof Error ? error : new Error(String(error));
7236
+ this.sendError(errorObj, details);
7237
+ };
7011
7238
  }
7012
- put(config) {
7013
- return this.request({ ...config, method: "PUT" });
7239
+ /**
7240
+ * 发送错误到父窗口
7241
+ */
7242
+ sendError(error, details = {}) {
7243
+ const payload = {
7244
+ message: error.message,
7245
+ stack: error.stack,
7246
+ filename: details.filename || details.file,
7247
+ lineno: details.lineno || details.line,
7248
+ colno: details.colno || details.column,
7249
+ timestamp: Date.now(),
7250
+ type: details.type || "unknown",
7251
+ severity: "medium",
7252
+ // 简化版使用默认严重性级别
7253
+ details
7254
+ };
7255
+ try {
7256
+ this.sendMessage({
7257
+ type: "ERROR_EVENT",
7258
+ payload,
7259
+ timestamp: Date.now()
7260
+ });
7261
+ } catch (e) {
7262
+ const originalConsole = window.__originalConsole;
7263
+ if (originalConsole?.error) {
7264
+ originalConsole.error("[\u7B80\u5316\u9519\u8BEF\u5904\u7406] \u53D1\u9001\u5931\u8D25:", e);
7265
+ }
7266
+ }
7014
7267
  }
7015
- patch(config) {
7016
- return this.request({ ...config, method: "PATCH" });
7268
+ /**
7269
+ * 手动捕获错误
7270
+ */
7271
+ captureError(error, details) {
7272
+ this.sendError(error, details);
7017
7273
  }
7018
7274
  };
7019
- var request_default = Request;
7020
7275
 
7021
- // src/services/ai-workflow-axios.ts
7022
- function createAIWorkflowClientAxios(options = {}) {
7023
- const basePath = options.basePath ?? "/api";
7024
- const baseUrl = (options.baseUrl || "https://evoagentx-server.fly.dev").replace(/\/+$/, "");
7025
- const baseAPI = `${baseUrl}${basePath.startsWith("/") ? "" : "/"}${basePath}`.replace(/\/+$/, "");
7026
- const client = options.requestInstance || new request_default({
7027
- baseURL: baseAPI,
7028
- timeout: options.timeout ?? 6e4,
7029
- interceptors: {
7030
- requestInterceptor: (config) => {
7031
- config.headers = config.headers || {};
7032
- if (options.apiKey && !config.headers["Authorization"]) {
7033
- config.headers["Authorization"] = `Bearer ${options.apiKey}`;
7034
- }
7035
- if (options.headers) {
7036
- config.headers = { ...config.headers || {}, ...options.headers };
7037
- }
7038
- return config;
7039
- },
7040
- requestInterceptorCatch: (err) => Promise.reject(err),
7041
- responseInterceptor: (res) => res,
7042
- responseInterceptorCatch: (err) => Promise.reject(err)
7043
- }
7044
- });
7045
- return {
7046
- async executeWorkflow(workflowId, inputs, opts) {
7047
- const url = `${baseUrl}/workflow/${workflowId}/execute`;
7048
- const data = await client.post({ url, data: { inputs, options: opts } });
7049
- return data;
7050
- }
7051
- };
7052
- }
7276
+ // src/index.ts
7277
+ init_config();
7053
7278
 
7054
- // src/services/artifact-types.ts
7055
- function canAccessArtifact(a, ctx = {}) {
7056
- if (!a) return false;
7057
- if (a.visibility === "public") return true;
7058
- if (a.visibility === "project") {
7059
- if (ctx.projectId && a.projectId && ctx.projectId === a.projectId) return true;
7060
- if (ctx.tokenScopes && ctx.tokenScopes.includes("project:read")) return true;
7061
- return false;
7062
- }
7063
- if (a.visibility === "private") {
7064
- if (ctx.userId && a.ownerId && ctx.userId === a.ownerId) return true;
7065
- if (ctx.tokenScopes && (ctx.tokenScopes.includes("artifact:read:all") || ctx.tokenScopes.includes("admin"))) return true;
7066
- return false;
7279
+ // src/utils/iframe-navigation.ts
7280
+ function getNavState() {
7281
+ if (typeof window === "undefined") {
7282
+ return {
7283
+ navigationHistory: [],
7284
+ currentHistoryIndex: -1,
7285
+ initialized: false
7286
+ };
7067
7287
  }
7068
- if (a.visibility === "shared") {
7069
- if (ctx.userId && a.sharedWith && a.sharedWith.includes(ctx.userId)) return true;
7070
- if (ctx.tokenScopes && (ctx.tokenScopes.includes("artifact:read:all") || ctx.tokenScopes.includes("admin"))) return true;
7071
- return false;
7288
+ if (!window.customNavigationState) {
7289
+ window.customNavigationState = {
7290
+ navigationHistory: [],
7291
+ currentHistoryIndex: -1,
7292
+ initialized: false
7293
+ };
7072
7294
  }
7073
- return false;
7295
+ return window.customNavigationState;
7074
7296
  }
7075
-
7076
- // src/services/artifacts-client.ts
7077
- function createArtifactsClient(req) {
7078
- return {
7079
- async create(input) {
7080
- return await req.post({ url: "/artifacts", data: input });
7081
- },
7082
- async list(query) {
7083
- return await req.get({ url: "/artifacts", params: query });
7084
- },
7085
- async get(id) {
7086
- return await req.get({ url: `/artifacts/${encodeURIComponent(id)}` });
7087
- },
7088
- async setVisibility(id, visibility) {
7089
- await req.patch({ url: `/artifacts/${encodeURIComponent(id)}/visibility`, data: { visibility } });
7090
- },
7091
- async delete(id) {
7092
- await req.delete({ url: `/artifacts/${encodeURIComponent(id)}` });
7093
- },
7094
- // convenience local check (server is authoritative)
7095
- canAccessLocal(a, ctx) {
7096
- if (!a) return false;
7097
- if (a.visibility === "public") return true;
7098
- if (a.visibility === "project") return Boolean(ctx.projectId && a.projectId && ctx.projectId === a.projectId);
7099
- if (a.visibility === "private") return Boolean(ctx.userId && a.ownerId && ctx.userId === a.ownerId);
7100
- if (a.visibility === "shared") return Boolean(ctx.userId && a.sharedWith && a.sharedWith.includes(ctx.userId));
7101
- return false;
7102
- }
7103
- };
7297
+ function getElementSelectorState() {
7298
+ if (typeof window === "undefined") {
7299
+ return { active: false, callback: null };
7300
+ }
7301
+ if (!window.elementSelectorState) {
7302
+ window.elementSelectorState = {
7303
+ active: false,
7304
+ callback: null
7305
+ };
7306
+ }
7307
+ return window.elementSelectorState;
7104
7308
  }
7105
-
7106
- // src/services/index.ts
7107
- init_auth();
7108
- init_config();
7109
- init_config();
7110
- init_auth();
7111
-
7112
- // src/utils/urlSanitizer.ts
7113
- var DEFAULT_SENSITIVE = ["token", "access_token", "auth", "auth_token"];
7114
- function removeSensitiveParamsFromUrl(opts) {
7115
- if (typeof window === "undefined") return;
7116
- try {
7117
- const { clearAll, sensitiveParams, includeHash = true, onChanged } = opts || {};
7118
- const sens = (sensitiveParams && sensitiveParams.length > 0 ? sensitiveParams : DEFAULT_SENSITIVE).map((s) => s.toLowerCase());
7119
- const before = window.location.href;
7120
- const url = new URL(before);
7121
- if (clearAll) {
7122
- url.search = "";
7123
- } else if (url.search) {
7124
- let changed = false;
7125
- for (const [k] of url.searchParams) {
7126
- if (sens.includes(k.toLowerCase())) {
7127
- url.searchParams.delete(k);
7128
- changed = true;
7129
- }
7130
- }
7131
- if (changed) {
7132
- const qs = url.searchParams.toString();
7133
- url.search = qs ? `?${qs}` : "";
7134
- }
7309
+ function sendNavigationState(targetWindow, targetOrigin) {
7310
+ const navState = getNavState();
7311
+ const canGoBack = navState.currentHistoryIndex > 0;
7312
+ const canGoForward = navState.currentHistoryIndex < navState.navigationHistory.length - 1;
7313
+ const state = {
7314
+ type: "NAVIGATION_STATE",
7315
+ payload: {
7316
+ canGoBack,
7317
+ canGoForward,
7318
+ historyLength: navState.navigationHistory.length,
7319
+ currentIndex: navState.currentHistoryIndex,
7320
+ maxIndex: navState.navigationHistory.length - 1
7135
7321
  }
7136
- if (includeHash && url.hash) {
7137
- const raw = url.hash.slice(1);
7138
- if (raw.includes("=")) {
7139
- const hp = new URLSearchParams(raw);
7140
- let changed = false;
7141
- for (const [k] of hp) {
7142
- if (clearAll || sens.includes(k.toLowerCase())) {
7143
- hp.delete(k);
7144
- changed = true;
7145
- }
7146
- }
7147
- if (changed) {
7148
- const hs = hp.toString();
7149
- url.hash = hs ? `#${hs}` : "";
7150
- }
7151
- } else {
7152
- if (!clearAll && sens.some((p) => raw.toLowerCase().startsWith(p))) {
7153
- url.hash = "";
7154
- } else if (clearAll) {
7155
- url.hash = "";
7156
- }
7322
+ };
7323
+ if (targetWindow && targetOrigin) {
7324
+ try {
7325
+ targetWindow.postMessage(state, targetOrigin);
7326
+ } catch (e) {
7327
+ if (typeof console !== "undefined" && console.warn) {
7328
+ console.warn("Failed to send navigation state:", e.message);
7157
7329
  }
7158
7330
  }
7159
- const next = url.pathname + url.search + url.hash;
7160
- if (next !== window.location.pathname + window.location.search + window.location.hash) {
7161
- window.history.replaceState(window.history.state, document.title, next);
7162
- onChanged && onChanged(next);
7163
- }
7164
- } catch (e) {
7165
- console.warn("[howone][urlSanitizer] failed", e);
7166
7331
  }
7167
7332
  }
7168
-
7169
- // src/services/index.ts
7170
- function getGlobalAvailableToken() {
7171
- try {
7172
- return getToken() || null;
7173
- } catch {
7174
- return null;
7333
+ function addToNavigationHistory(url, title) {
7334
+ const navState = getNavState();
7335
+ if (navState.currentHistoryIndex < navState.navigationHistory.length - 1) {
7336
+ navState.navigationHistory = navState.navigationHistory.slice(
7337
+ 0,
7338
+ navState.currentHistoryIndex + 1
7339
+ );
7175
7340
  }
7176
- }
7177
- function wrapRequestWithProjectPrefix(biz, projectId) {
7178
- if (!projectId) return biz;
7179
- const prefix = `/entities/apps/${String(projectId)}`;
7180
- function shouldPrefix(url) {
7181
- if (!url) return false;
7182
- const u = String(url);
7183
- if (u.startsWith(prefix)) return false;
7184
- if (/^https?:\/\//.test(u) || u.startsWith("//")) return false;
7185
- if (u.startsWith("/data")) return true;
7186
- return false;
7341
+ const currentPage = navState.navigationHistory[navState.currentHistoryIndex];
7342
+ if (currentPage && currentPage.url === url) {
7343
+ return;
7187
7344
  }
7188
- const wrapped = {
7189
- instance: biz.instance,
7190
- request: (config) => {
7191
- try {
7192
- if (config && typeof config.url === "string" && shouldPrefix(config.url)) {
7193
- config = { ...config, url: `${prefix}${config.url}` };
7194
- }
7195
- } catch (_e) {
7196
- }
7197
- return biz.request(config);
7198
- },
7199
- get: (config) => wrapped.request({ ...config, method: "GET" }),
7200
- post: (config) => wrapped.request({ ...config, method: "POST" }),
7201
- put: (config) => wrapped.request({ ...config, method: "PUT" }),
7202
- patch: (config) => wrapped.request({ ...config, method: "PATCH" }),
7203
- delete: (config) => wrapped.request({ ...config, method: "DELETE" }),
7204
- cancelRequest: (url) => biz.cancelRequest(url),
7205
- cancelAllRequests: () => biz.cancelAllRequests()
7345
+ const pageInfo = {
7346
+ url,
7347
+ title: title || (typeof document !== "undefined" ? document.title : "") || url,
7348
+ timestamp: Date.now()
7206
7349
  };
7207
- return wrapped;
7208
- }
7209
- function createClient(opts) {
7210
- const envValue = opts.env || getGlobalEnvironment() || "prod";
7211
- const env2 = setEnvironment(envValue);
7212
- function makeRequestFromBase(base) {
7213
- return new request_default({
7214
- baseURL: base,
7215
- timeout: 6e4,
7216
- interceptors: {
7217
- requestInterceptor: (config) => {
7218
- config.headers = config.headers || {};
7219
- if (!config.headers["Authorization"]) {
7220
- const availableToken = getAvailableToken();
7221
- if (availableToken) {
7222
- config.headers["Authorization"] = `Bearer ${availableToken}`;
7223
- }
7224
- }
7225
- return config;
7226
- },
7227
- requestInterceptorCatch: (err) => Promise.reject(err),
7228
- responseInterceptor: (res) => {
7229
- const data = res.data;
7230
- if (data && data.status && data.status === 4003) {
7231
- showLimitUpgradeToast(
7232
- "Your credits are exhausted. Please upgrade your plan to continue generating projects.",
7233
- () => window.open(`${getEnvs().AUTH_ROOT_VALUE}/price`, "_blank")
7234
- );
7235
- return res;
7236
- }
7237
- return res;
7238
- },
7239
- responseInterceptorCatch: (err) => Promise.reject(err)
7240
- }
7241
- });
7350
+ navState.navigationHistory.push(pageInfo);
7351
+ navState.currentHistoryIndex = navState.navigationHistory.length - 1;
7352
+ if (typeof window !== "undefined" && window.parent && window.parent !== window) {
7353
+ sendNavigationState(window.parent, "*");
7242
7354
  }
7243
- const biz = makeRequestFromBase(env2.baseUrl);
7244
- const ai = makeRequestFromBase(env2.aiBaseUrl);
7245
- const bizWrapped = wrapRequestWithProjectPrefix(biz, opts?.projectId);
7246
- let token = null;
7247
- function getAvailableToken() {
7248
- return token || getGlobalAvailableToken();
7355
+ }
7356
+ function customGoBack() {
7357
+ const navState = getNavState();
7358
+ if (navState.currentHistoryIndex > 0) {
7359
+ navState.currentHistoryIndex--;
7360
+ if (typeof window !== "undefined" && window.parent && window.parent !== window) {
7361
+ sendNavigationState(window.parent, "*");
7362
+ }
7363
+ return true;
7249
7364
  }
7250
- try {
7251
- if (opts?.projectId) {
7252
- setDefaultProjectId(String(opts.projectId));
7365
+ return false;
7366
+ }
7367
+ function customGoForward() {
7368
+ const navState = getNavState();
7369
+ if (navState.currentHistoryIndex < navState.navigationHistory.length - 1) {
7370
+ navState.currentHistoryIndex++;
7371
+ if (typeof window !== "undefined" && window.parent && window.parent !== window) {
7372
+ sendNavigationState(window.parent, "*");
7253
7373
  }
7254
- } catch {
7374
+ return true;
7255
7375
  }
7256
- function applyToken(t) {
7376
+ return false;
7377
+ }
7378
+ function triggerElementSelection() {
7379
+ if (typeof window === "undefined") return;
7380
+ const event = new CustomEvent("howone:start-element-selection");
7381
+ window.dispatchEvent(event);
7382
+ getElementSelectorState().active = true;
7383
+ }
7384
+ function cancelElementSelection() {
7385
+ if (typeof window === "undefined") return;
7386
+ const event = new CustomEvent("howone:cancel-element-selection");
7387
+ window.dispatchEvent(event);
7388
+ getElementSelectorState().active = false;
7389
+ }
7390
+ function handlePageChange() {
7391
+ if (typeof window === "undefined") return;
7392
+ const currentUrl = window.location.href;
7393
+ const currentTitle = document.title;
7394
+ addToNavigationHistory(currentUrl, currentTitle);
7395
+ }
7396
+ function initIframeNavigation() {
7397
+ if (typeof window === "undefined") return;
7398
+ const navState = getNavState();
7399
+ window.addEventListener("keydown", function(e) {
7400
+ if (e.key === "Escape" && getElementSelectorState().active) {
7401
+ cancelElementSelection();
7402
+ }
7403
+ });
7404
+ window.addEventListener("message", (event) => {
7257
7405
  try {
7258
- try {
7259
- if (biz && biz.instance) {
7260
- if (t) biz.instance.defaults.headers.common["Authorization"] = `Bearer ${t}`;
7261
- else delete biz.instance.defaults.headers.common["Authorization"];
7262
- }
7263
- if (ai && ai.instance) {
7264
- if (t) ai.instance.defaults.headers.common["Authorization"] = `Bearer ${t}`;
7265
- else delete ai.instance.defaults.headers.common["Authorization"];
7266
- }
7267
- } catch (_e) {
7406
+ const { type, payload } = event.data;
7407
+ switch (type) {
7408
+ case "NAVIGATE_BACK":
7409
+ case "GO_BACK":
7410
+ customGoBack();
7411
+ break;
7412
+ case "NAVIGATE_FORWARD":
7413
+ case "GO_FORWARD":
7414
+ customGoForward();
7415
+ break;
7416
+ case "REQUEST_NAVIGATION_STATE":
7417
+ case "CHECK_NAVIGATION_STATE":
7418
+ sendNavigationState(event.source, event.origin);
7419
+ break;
7420
+ case "START_ELEMENT_SELECTION":
7421
+ triggerElementSelection();
7422
+ break;
7423
+ case "ELEMENT_SELECTED":
7424
+ if (event.source && event.source !== window) {
7425
+ window.parent.postMessage(
7426
+ {
7427
+ type: "ELEMENT_SELECTED",
7428
+ payload
7429
+ },
7430
+ "*"
7431
+ );
7432
+ }
7433
+ break;
7434
+ case "CANCEL_ELEMENT_SELECTION":
7435
+ cancelElementSelection();
7436
+ break;
7437
+ }
7438
+ } catch (e) {
7439
+ }
7440
+ });
7441
+ window.addEventListener("popstate", () => {
7442
+ setTimeout(() => {
7443
+ if (window.parent && window.parent !== window) {
7444
+ sendNavigationState(window.parent, "*");
7445
+ }
7446
+ }, 50);
7447
+ });
7448
+ window.addEventListener("hashchange", () => {
7449
+ handlePageChange();
7450
+ });
7451
+ window.addEventListener("load", () => {
7452
+ if (!navState.initialized) {
7453
+ addToNavigationHistory(window.location.href, document.title);
7454
+ navState.initialized = true;
7455
+ }
7456
+ setTimeout(() => {
7457
+ if (window.parent && window.parent !== window) {
7458
+ sendNavigationState(window.parent, "*");
7459
+ }
7460
+ }, 500);
7461
+ });
7462
+ if (document.readyState === "loading") {
7463
+ document.addEventListener("DOMContentLoaded", () => {
7464
+ if (!navState.initialized) {
7465
+ addToNavigationHistory(window.location.href, document.title);
7466
+ navState.initialized = true;
7268
7467
  }
7269
- } catch (_e) {
7270
- }
7468
+ });
7469
+ } else if (!navState.initialized) {
7470
+ addToNavigationHistory(window.location.href, document.title);
7471
+ navState.initialized = true;
7271
7472
  }
7272
- const workflowRequestWrapped = {
7273
- get: ai.get.bind(ai),
7274
- post: (config) => {
7275
- const modifiedConfig = { ...config };
7276
- if (opts?.projectId && modifiedConfig.url) {
7277
- const workflowPattern = /^\/?(?:workflow\/)?([^\/]+)\/execute/;
7278
- const match = modifiedConfig.url.match(workflowPattern);
7279
- if (match) {
7280
- const workflowId = match[1];
7281
- modifiedConfig.url = `/workflow/${opts.projectId}/${workflowId}/execute`;
7282
- }
7283
- }
7284
- return ai.post(modifiedConfig);
7285
- },
7286
- put: ai.put.bind(ai),
7287
- delete: ai.delete.bind(ai),
7288
- request: ai.request.bind(ai),
7289
- cancelRequest: ai.cancelRequest?.bind(ai),
7290
- cancelAllRequests: ai.cancelAllRequests?.bind(ai)
7473
+ window.iframeElementSelector = {
7474
+ startSelection: function() {
7475
+ triggerElementSelection();
7476
+ }
7291
7477
  };
7292
- return {
7293
- // expose projectId so consumers can read it from the client instance
7294
- projectId: opts?.projectId ?? null,
7295
- request: bizWrapped,
7296
- aiRequest: ai,
7297
- workflowRequest: workflowRequestWrapped,
7298
- // artifact helpers using artifacts-client
7299
- artifacts: createArtifactsClient(biz),
7300
- me: async () => {
7301
- try {
7302
- const t = token ?? (opts?.auth?.getToken ? await opts.auth.getToken() : null) ?? getToken();
7303
- if (!t) return null;
7304
- return parseUserFromToken(t);
7305
- } catch (_e2) {
7306
- return null;
7307
- }
7478
+ window.iframeNavigation = {
7479
+ addPage: function(url, title) {
7480
+ addToNavigationHistory(
7481
+ url || window.location.href,
7482
+ title || document.title
7483
+ );
7308
7484
  },
7309
- // auth helpers
7310
- auth: {
7311
- setToken: (t) => {
7312
- token = t;
7313
- applyToken(t);
7314
- },
7315
- getToken: () => token,
7316
- isAuthenticated: () => Boolean(token),
7317
- // minimal login/logout stubs - consumers can override behavior
7318
- login: (redirect) => {
7319
- if (typeof window === "undefined") return;
7320
- const loc = redirect || window.location.href;
7321
- try {
7322
- const root = env2.baseUrl;
7323
- const authUrl = new URL("/auth", String(root));
7324
- authUrl.searchParams.set("redirect_uri", String(loc));
7325
- if (opts?.projectId) authUrl.searchParams.set("project_id", String(opts.projectId));
7326
- window.location.href = authUrl.toString();
7327
- } catch {
7328
- const encoded = encodeURIComponent(String(loc));
7329
- const pid = opts?.projectId ? `&project_id=${encodeURIComponent(String(opts.projectId))}` : "";
7330
- const root = env2.baseUrl;
7331
- window.location.href = `${root}/auth?redirect_uri=${encoded}${pid}`;
7332
- }
7333
- },
7334
- logout: () => {
7335
- token = null;
7336
- applyToken(null);
7337
- }
7485
+ getState: function() {
7486
+ return {
7487
+ canGoBack: navState.currentHistoryIndex > 0,
7488
+ canGoForward: navState.currentHistoryIndex < navState.navigationHistory.length - 1,
7489
+ historyLength: navState.navigationHistory.length,
7490
+ currentIndex: navState.currentHistoryIndex,
7491
+ currentPage: navState.navigationHistory[navState.currentHistoryIndex]
7492
+ };
7338
7493
  },
7339
- sanitizeUrl: (o) => {
7340
- if (typeof window === "undefined") return;
7341
- removeSensitiveParamsFromUrl({
7342
- clearAll: o?.clearAll,
7343
- sensitiveParams: o?.sensitiveParams
7344
- });
7494
+ updateState: function() {
7495
+ if (window.parent && window.parent !== window) {
7496
+ sendNavigationState(window.parent, "*");
7497
+ }
7345
7498
  }
7346
7499
  };
7347
7500
  }
7348
-
7349
- // src/hooks/use-mobile.ts
7350
- import * as React8 from "react";
7351
- var MOBILE_BREAKPOINT = 768;
7352
- function useIsMobile() {
7353
- const [isMobile, setIsMobile] = React8.useState(void 0);
7354
- React8.useEffect(() => {
7355
- const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
7356
- const onChange = () => {
7357
- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
7358
- };
7359
- mql.addEventListener("change", onChange);
7360
- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
7361
- return () => mql.removeEventListener("change", onChange);
7362
- }, []);
7363
- return !!isMobile;
7364
- }
7365
-
7366
- // src/hooks/use-debounce.ts
7367
- import { useState as useState10, useEffect as useEffect9 } from "react";
7368
- function useDebounce(value, delay) {
7369
- const [debouncedValue, setDebouncedValue] = useState10(value);
7370
- useEffect9(() => {
7371
- const handler = setTimeout(() => {
7372
- setDebouncedValue(value);
7373
- }, delay);
7374
- return () => {
7375
- clearTimeout(handler);
7376
- };
7377
- }, [value, delay]);
7378
- return debouncedValue;
7379
- }
7380
-
7381
- // src/utils/unified-error-handler/simple.ts
7382
- var SimpleErrorHandler = class {
7383
- constructor() {
7384
- this.initialized = false;
7385
- }
7386
- // 使用明确赋值断言,因为在 init() 方法中会初始化
7501
+ var iframeNavigation = {
7387
7502
  /**
7388
- * 初始化错误处理器
7503
+ * Initialize the navigation system
7389
7504
  */
7390
- init() {
7391
- if (this.initialized) return;
7392
- this.sendMessage = createSimpleSendFunction({
7393
- addTimestamp: false,
7394
- // 简化版自己处理时间戳
7395
- enableDebugLog: false
7396
- });
7397
- this.setupErrorListeners();
7398
- this.setupCompatibility();
7399
- this.initialized = true;
7400
- console.log("[\u7B80\u5316\u9519\u8BEF\u5904\u7406] \u521D\u59CB\u5316\u5B8C\u6210");
7401
- }
7505
+ init: initIframeNavigation,
7402
7506
  /**
7403
- * 设置错误监听器
7507
+ * Add a page to navigation history
7404
7508
  */
7405
- setupErrorListeners() {
7406
- window.addEventListener("error", (event) => {
7407
- this.sendError(event.error || new Error(event.message), {
7408
- filename: event.filename,
7409
- lineno: event.lineno,
7410
- colno: event.colno,
7411
- type: "runtime"
7412
- });
7413
- });
7414
- window.addEventListener("unhandledrejection", (event) => {
7415
- const error = event.reason instanceof Error ? event.reason : new Error(String(event.reason));
7416
- this.sendError(error, { type: "promise" });
7417
- });
7418
- }
7509
+ addPage: (url, title) => {
7510
+ if (typeof window === "undefined") return;
7511
+ addToNavigationHistory(
7512
+ url || window.location.href,
7513
+ title || (typeof document !== "undefined" ? document.title : "")
7514
+ );
7515
+ },
7419
7516
  /**
7420
- * 设置兼容性函数
7517
+ * Get current navigation state
7421
7518
  */
7422
- setupCompatibility() {
7423
- window.__SEND_ERROR_TO_PARENT__ = (error, details) => {
7424
- const errorObj = error instanceof Error ? error : new Error(String(error));
7425
- this.sendError(errorObj, details);
7519
+ getState: () => {
7520
+ const navState = getNavState();
7521
+ return {
7522
+ canGoBack: navState.currentHistoryIndex > 0,
7523
+ canGoForward: navState.currentHistoryIndex < navState.navigationHistory.length - 1,
7524
+ historyLength: navState.navigationHistory.length,
7525
+ currentIndex: navState.currentHistoryIndex,
7526
+ currentPage: navState.navigationHistory[navState.currentHistoryIndex]
7426
7527
  };
7427
- }
7528
+ },
7428
7529
  /**
7429
- * 发送错误到父窗口
7530
+ * Update navigation state (send to parent)
7430
7531
  */
7431
- sendError(error, details = {}) {
7432
- const payload = {
7433
- message: error.message,
7434
- stack: error.stack,
7435
- filename: details.filename || details.file,
7436
- lineno: details.lineno || details.line,
7437
- colno: details.colno || details.column,
7438
- timestamp: Date.now(),
7439
- type: details.type || "unknown",
7440
- severity: "medium",
7441
- // 简化版使用默认严重性级别
7442
- details
7443
- };
7444
- try {
7445
- this.sendMessage({
7446
- type: "ERROR_EVENT",
7447
- payload,
7448
- timestamp: Date.now()
7449
- });
7450
- } catch (e) {
7451
- const originalConsole = window.__originalConsole;
7452
- if (originalConsole?.error) {
7453
- originalConsole.error("[\u7B80\u5316\u9519\u8BEF\u5904\u7406] \u53D1\u9001\u5931\u8D25:", e);
7454
- }
7532
+ updateState: () => {
7533
+ if (typeof window !== "undefined" && window.parent && window.parent !== window) {
7534
+ sendNavigationState(window.parent, "*");
7455
7535
  }
7456
- }
7536
+ },
7457
7537
  /**
7458
- * 手动捕获错误
7538
+ * Go back in history
7459
7539
  */
7460
- captureError(error, details) {
7461
- this.sendError(error, details);
7462
- }
7540
+ goBack: customGoBack,
7541
+ /**
7542
+ * Go forward in history
7543
+ */
7544
+ goForward: customGoForward
7545
+ };
7546
+ var elementSelector = {
7547
+ /**
7548
+ * Start element selection mode
7549
+ */
7550
+ startSelection: triggerElementSelection,
7551
+ /**
7552
+ * Cancel element selection mode
7553
+ */
7554
+ cancel: cancelElementSelection,
7555
+ /**
7556
+ * Check if selector is active
7557
+ */
7558
+ isActive: () => getElementSelectorState().active
7463
7559
  };
7464
-
7465
- // src/index.ts
7466
- init_config();
7467
7560
  export {
7468
7561
  AUTH_TOKEN_KEY,
7469
7562
  ClayxButton,