@huaqiu/dsh-auth 0.6.22 → 0.6.24

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/lib/client.js CHANGED
@@ -36,8 +36,8 @@ window.__ModuleLoader__.load({
36
36
  }
37
37
  //#endregion
38
38
  //#region src/client/transport.ts
39
- /** Accept only an absolute http(s) origin; anything else → null. */
40
- function normalizeOrigin(value) {
39
+ /** Accept only an absolute http(s) URL; anything else → null. A path is kept. */
40
+ function normalizeHttpUrl(value) {
41
41
  if (typeof value !== "string") return null;
42
42
  const trimmed = value.trim().replace(/\/+$/, "");
43
43
  if (!trimmed) return null;
@@ -83,19 +83,22 @@ window.__ModuleLoader__.load({
83
83
  if (!res.ok) return {
84
84
  hostMode: false,
85
85
  subscriptionOrigin: null,
86
- subscriptionApiBaseUrl: null
86
+ subscriptionApiBaseUrl: null,
87
+ profileUrl: null
87
88
  };
88
89
  const body = await res.json();
89
90
  return {
90
91
  hostMode: body.hostMode === true,
91
- subscriptionOrigin: normalizeOrigin(body.subscriptionOrigin),
92
- subscriptionApiBaseUrl: normalizeOrigin(body.subscriptionApiBaseUrl)
92
+ subscriptionOrigin: normalizeHttpUrl(body.subscriptionOrigin),
93
+ subscriptionApiBaseUrl: normalizeHttpUrl(body.subscriptionApiBaseUrl),
94
+ profileUrl: normalizeHttpUrl(body.profileUrl)
93
95
  };
94
96
  } catch {
95
97
  return {
96
98
  hostMode: false,
97
99
  subscriptionOrigin: null,
98
- subscriptionApiBaseUrl: null
100
+ subscriptionApiBaseUrl: null,
101
+ profileUrl: null
99
102
  };
100
103
  }
101
104
  },
@@ -148,7 +151,11 @@ window.__ModuleLoader__.load({
148
151
  }
149
152
  };
150
153
  }
151
- /**「Go to profile」destination: the eda.cn account page. */
154
+ /** Standalone-DSH fallback for the「Go to profile」destination. Under HQ Edge the full URL is
155
+ * resolved ONCE from `HQ_AI_ENV` (PROD: `https://www.eda.cn/account/profile`,
156
+ * TEST: `http://www.fdatasheets.com/account`) and arrives via the node half's
157
+ * `/config` route; this constant is used only when nothing supplies one.
158
+ */
152
159
  const PROFILE_URL = "https://www.eda.cn/account/profile";
153
160
  const SUBSCRIPTION_PATH = "/subscription";
154
161
  const SUBSCRIPTION_PREFERRED_SIZE = {
@@ -238,15 +245,16 @@ window.__ModuleLoader__.load({
238
245
  * in the query, mirroring `hq-eda-ai`'s `UserMenu`
239
246
  * (`/account/profile?token=…&phone=…`).
240
247
  *
241
- * The token is always attached: eda.cn consumes it to establish the session
242
- * and strips it from the address bar / history itself, so there is nothing to
243
- * leak beyond the target site. `encodeURIComponent` is required (not cosmetic):
244
- * tokens are base64-ish and may contain `+`, `/` or `=`, and a raw `+` in a
245
- * query string decodes to a space, which would corrupt the credential.
248
+ * `profileUrl` comes from the node half (HQ Edge → `HQ_AI_ENV`); omitted in
249
+ * standalone DSH, which keeps the {@link PROFILE_URL} PROD fallback. The
250
+ * injected value is a FULL URL (path included), because PROD and TEST do not
251
+ * share it (`/account/profile` vs `/account`); any existing query string on it
252
+ * is preserved and `token`/`phone` are appended.
246
253
  */
247
254
  function buildProfileUrl(options) {
248
255
  const phone = options.phone === void 0 || options.phone === null ? "" : String(options.phone);
249
- return `${PROFILE_URL}?token=${encodeURIComponent(options.token)}&phone=${encodeURIComponent(phone)}`;
256
+ const base = options.profileUrl?.length ? options.profileUrl : PROFILE_URL;
257
+ return `${base}${base.includes("?") ? "&" : "?"}token=${encodeURIComponent(options.token)}&phone=${encodeURIComponent(phone)}`;
250
258
  }
251
259
  /**
252
260
  * Contract version of the auth.eda.cn embed, shared with the web app
@@ -631,6 +639,9 @@ window.__ModuleLoader__.load({
631
639
  "subscription.ai": "AI 用量",
632
640
  "subscription.aiUsagePercent": "{percent}%",
633
641
  "subscription.aiUsageUnknown": "暂无数据",
642
+ "turnError.aiQuotaCta": "升级获取更多 AI 额度",
643
+ "turnError.aiQuotaSignIn": "登录后升级",
644
+ "turnError.aiQuotaOpenFailed": "无法打开订阅页面,请稍后重试。",
634
645
  "card.title": "华秋 EDA AI(eda.cn)登录",
635
646
  "card.desc": "工具「{tool}」需要登录华秋 EDA AI 账号才能继续。请在下方的登录框完成登录(或点击左侧「华秋EDA AI登录」按钮);登录完成后,回复助手「已登录,请重试」,助手会自动重新调用该工具。",
636
647
  "card.loggedIn": "✓ 已登录{nickname} —— 现在可以回复助手「已登录,请重试」,助手会重新调用工具。",
@@ -669,6 +680,9 @@ window.__ModuleLoader__.load({
669
680
  "subscription.ai": "AI usage",
670
681
  "subscription.aiUsagePercent": "{percent}%",
671
682
  "subscription.aiUsageUnknown": "No data",
683
+ "turnError.aiQuotaCta": "Upgrade for more AI tokens",
684
+ "turnError.aiQuotaSignIn": "Sign in to upgrade",
685
+ "turnError.aiQuotaOpenFailed": "Could not open the subscription page. Please try again later.",
672
686
  "card.title": "Huaqiu EDA AI (eda.cn) login",
673
687
  "card.desc": "Tool \"{tool}\" needs a Huaqiu EDA AI account. Complete the login below (or use the Huaqiu EDA AI button in the sidebar), then reply \"I have logged in, please retry\" so the assistant can retry the tool.",
674
688
  "card.loggedIn": "✓ Logged in{nickname} — reply \"I have logged in, please retry\" and the assistant will retry the tool.",
@@ -1053,6 +1067,12 @@ window.__ModuleLoader__.load({
1053
1067
  let hostSession = null;
1054
1068
  let hostSessionLoaded = false;
1055
1069
  /**
1070
+ * Why the last host-session resolution failed, if it did. Transport errors
1071
+ * must NOT masquerade as a healthy `signed-out`: the dialog opener surfaces
1072
+ * them as a rejection so callers can show retry copy instead of "sign in".
1073
+ */
1074
+ let hostResolveError;
1075
+ /**
1056
1076
  * Subscription origin resolved by HQ Edge from `HQ_AI_ENV` and served on the
1057
1077
  * node `/config` route. Null in standalone → lib's PROD fallback.
1058
1078
  */
@@ -1062,6 +1082,11 @@ window.__ModuleLoader__.load({
1062
1082
  * when no environment is configured → GEN/ERC quota calls are skipped.
1063
1083
  */
1064
1084
  let subscriptionApiBaseUrl = null;
1085
+ /**
1086
+ *「Go to profile」URL resolved by HQ Edge from `HQ_AI_ENV`. Null in
1087
+ * standalone → lib.ts keeps its PROD fallback.
1088
+ */
1089
+ let profileUrl = null;
1065
1090
  const emit = (info) => {
1066
1091
  for (const listener of listeners) listener(info);
1067
1092
  };
@@ -1092,6 +1117,7 @@ window.__ModuleLoader__.load({
1092
1117
  */
1093
1118
  const resolveHost = async () => {
1094
1119
  hostSessionLoaded = true;
1120
+ hostResolveError = void 0;
1095
1121
  if (!hostMode) {
1096
1122
  hostSession = null;
1097
1123
  return;
@@ -1099,8 +1125,9 @@ window.__ModuleLoader__.load({
1099
1125
  try {
1100
1126
  const session = await transport.fetchSession();
1101
1127
  hostSession = session.authenticated ? normalizeHostUserPayload(session.user) : null;
1102
- } catch {
1128
+ } catch (error) {
1103
1129
  hostSession = null;
1130
+ hostResolveError = error;
1104
1131
  }
1105
1132
  };
1106
1133
  const auth = {
@@ -1157,6 +1184,7 @@ window.__ModuleLoader__.load({
1157
1184
  ...subscriptionApiBaseUrl ? { baseUrl: subscriptionApiBaseUrl } : {}
1158
1185
  });
1159
1186
  },
1187
+ getProfileUrl: () => profileUrl,
1160
1188
  getAiTokenUsage: async () => {
1161
1189
  if (hostMode && !hostSessionLoaded) await resolveHost();
1162
1190
  if (!await auth.getAccessToken()) return null;
@@ -1165,13 +1193,16 @@ window.__ModuleLoader__.load({
1165
1193
  openSubscriptionDialog: async () => {
1166
1194
  if (hostMode && !hostSessionLoaded) await resolveHost();
1167
1195
  const token = await auth.getAccessToken();
1168
- if (!token) return;
1196
+ if (!token) {
1197
+ if (hostMode && hostResolveError !== void 0) throw hostResolveError;
1198
+ return { status: "signed-out" };
1199
+ }
1169
1200
  const url = buildSubscriptionUrl({
1170
1201
  token,
1171
1202
  ...subscriptionOrigin ? { origin: subscriptionOrigin } : {}
1172
1203
  });
1173
1204
  if (hostMode) {
1174
- if (!deps.openHostDialog) return;
1205
+ if (!deps.openHostDialog) return { status: "host-unavailable" };
1175
1206
  await deps.openHostDialog(url, {
1176
1207
  title: "Huaqiu EDA subscription",
1177
1208
  size: {
@@ -1180,10 +1211,11 @@ window.__ModuleLoader__.load({
1180
1211
  },
1181
1212
  key: "hq-subscription-dialog"
1182
1213
  });
1183
- return;
1214
+ return { status: "opened" };
1184
1215
  }
1185
- if (isSubscriptionDialogOpen()) return;
1216
+ if (isSubscriptionDialogOpen()) return { status: "already-open" };
1186
1217
  openSubscriptionDialog(url, { size: SUBSCRIPTION_PREFERRED_SIZE });
1218
+ return { status: "opened" };
1187
1219
  },
1188
1220
  onAuthStateChanged: (listener) => {
1189
1221
  listeners.add(listener);
@@ -1237,10 +1269,12 @@ window.__ModuleLoader__.load({
1237
1269
  mode = runtime.hostMode;
1238
1270
  subscriptionOrigin = runtime.subscriptionOrigin;
1239
1271
  subscriptionApiBaseUrl = runtime.subscriptionApiBaseUrl;
1272
+ profileUrl = runtime.profileUrl;
1240
1273
  } catch {
1241
1274
  mode = false;
1242
1275
  subscriptionOrigin = null;
1243
1276
  subscriptionApiBaseUrl = null;
1277
+ profileUrl = null;
1244
1278
  }
1245
1279
  hostMode = mode;
1246
1280
  hostSessionLoaded = false;
@@ -1278,6 +1312,7 @@ window.__ModuleLoader__.load({
1278
1312
  hostSessionLoaded = false;
1279
1313
  subscriptionOrigin = null;
1280
1314
  subscriptionApiBaseUrl = null;
1315
+ profileUrl = null;
1281
1316
  }
1282
1317
  };
1283
1318
  }
@@ -2174,7 +2209,11 @@ window.__ModuleLoader__.load({
2174
2209
  phone: i.phone
2175
2210
  } : null).catch(() => null);
2176
2211
  if (!info?.token) return;
2177
- window.open(buildProfileUrl(info), "_blank", "noopener,noreferrer");
2212
+ const profileUrl = auth.getProfileUrl();
2213
+ window.open(buildProfileUrl({
2214
+ ...info,
2215
+ ...profileUrl ? { profileUrl } : {}
2216
+ }), "_blank", "noopener,noreferrer");
2178
2217
  })();
2179
2218
  };
2180
2219
  const label = authenticated ? displayName ?? t("sidebar.account") : t("sidebar.login");
@@ -2343,6 +2382,152 @@ window.__ModuleLoader__.load({
2343
2382
  });
2344
2383
  });
2345
2384
  //#endregion
2385
+ //#region src/client/ui/turn-error-cta.tsx
2386
+ /**
2387
+ * `conversation.chat.turn-error.action` entry: a subscription button inside
2388
+ * the Chat terminal-failure card.
2389
+ *
2390
+ * The huaqiu gateway reports an exhausted token balance as a provider error
2391
+ * whose own payload code is `insufficient_user_quota`. The harness keeps that
2392
+ * code on the durable failure as `providerErrorCode` and attributes the
2393
+ * failure to the routed `provider`; this entry gates on those structured
2394
+ * fields only, so a wording change or an unrelated error simply renders no
2395
+ * button. Clicking it opens the subscription dialog owned by this package's
2396
+ * auth client (`openSubscriptionDialog`), which is the same path the sidebar
2397
+ * upgrade entry uses.
2398
+ *
2399
+ * Fallbacks stay inside the card: no host dialog service → the existing
2400
+ * "host provides no dialog service" copy; transport failure → retry copy; no
2401
+ * credential → the auth client's login surface. The entry never throws, so a
2402
+ * missing or older slot harness degrades to the shipped card.
2403
+ */
2404
+ /** Gateway provider whose balance signature this entry understands. */
2405
+ const QUOTA_PROVIDER = "huaqiu";
2406
+ /** The gateway's own code for a token balance that can be topped up. */
2407
+ const HUAQIU_QUOTA_SIGNATURE = "insufficient_user_quota";
2408
+ /**
2409
+ * Whether a durable failure is the huaqiu gateway's exhausted token balance.
2410
+ *
2411
+ * Two structured shapes qualify:
2412
+ * - the adapter extracted the gateway's own `insufficient_user_quota` code, or
2413
+ * - the routed provider is huaqiu and the harness classified the failure as
2414
+ * `QUOTA` (covers classifier fixes that stop carrying the payload code).
2415
+ *
2416
+ * Never gate on `message`: unrelated failures can quote provider text, and a
2417
+ * payload/wording change must degrade to "no button", not to a false positive.
2418
+ * @param node - durable turn-error node, possibly absent at runtime boundaries.
2419
+ * @returns true only for the huaqiu token-quota signature.
2420
+ */
2421
+ function isHuaqiuQuotaFailure(node) {
2422
+ if (node === null || node === void 0) return false;
2423
+ if (node.code !== "PI_AI_ERROR" && node.code !== "QUOTA") return false;
2424
+ if (node.providerErrorCode === HUAQIU_QUOTA_SIGNATURE) return true;
2425
+ return node.provider === QUOTA_PROVIDER && node.code === "QUOTA";
2426
+ }
2427
+ const ctaStyle = {
2428
+ display: "block",
2429
+ width: "fit-content",
2430
+ marginTop: 4,
2431
+ padding: "1px 10px",
2432
+ border: "1px solid var(--dsw-alias-brand-primary, #e62e2d)",
2433
+ borderRadius: 999,
2434
+ background: "transparent",
2435
+ color: "var(--dsw-alias-brand-primary, #e62e2d)",
2436
+ font: "inherit",
2437
+ fontSize: 13,
2438
+ lineHeight: "20px",
2439
+ cursor: "pointer"
2440
+ };
2441
+ const noticeStyle = {
2442
+ display: "block",
2443
+ marginTop: 2,
2444
+ color: "var(--dsw-alias-state-error-primary, #d4380d)",
2445
+ fontSize: 12,
2446
+ lineHeight: "18px"
2447
+ };
2448
+ const stopStyle = {
2449
+ borderRadius: 999,
2450
+ opacity: .6,
2451
+ cursor: "default"
2452
+ };
2453
+ /** Turn-error recovery affordance for the huaqiu token quota. */
2454
+ const HuaqiuTurnErrorSubscribeAction = (0, react.memo)(function HuaqiuTurnErrorSubscribeAction({ node }) {
2455
+ const auth = getAuth();
2456
+ const authState = (0, react.useSyncExternalStore)(subscribeAuth, getAuthState, getAuthState);
2457
+ const locale = useLocale();
2458
+ const dark = useIsDark();
2459
+ const t = useT();
2460
+ const [busy, setBusy] = (0, react.useState)(false);
2461
+ const [hovered, setHovered] = (0, react.useState)(false);
2462
+ const [notice, setNotice] = (0, react.useState)(null);
2463
+ const nodeKey = node.message;
2464
+ const visibleNotice = notice !== null && notice.key === nodeKey ? notice.text : null;
2465
+ const open = (0, react.useCallback)(() => {
2466
+ if (busy) return;
2467
+ const fail = () => {
2468
+ setNotice({
2469
+ key: nodeKey,
2470
+ text: t("turnError.aiQuotaOpenFailed")
2471
+ });
2472
+ };
2473
+ if (!auth) {
2474
+ fail();
2475
+ return;
2476
+ }
2477
+ const requestLogin = () => {
2478
+ try {
2479
+ auth.login({
2480
+ lang: locale,
2481
+ theme: dark ? "dark" : "light"
2482
+ }).catch(fail);
2483
+ } catch {
2484
+ fail();
2485
+ }
2486
+ };
2487
+ if (!authState.authenticated) {
2488
+ requestLogin();
2489
+ return;
2490
+ }
2491
+ setNotice(null);
2492
+ setBusy(true);
2493
+ auth.openSubscriptionDialog().then((outcome) => {
2494
+ if (outcome.status === "host-unavailable") setNotice({
2495
+ key: nodeKey,
2496
+ text: t("subscription.hostUnavailable")
2497
+ });
2498
+ else if (outcome.status === "signed-out") requestLogin();
2499
+ }).catch(fail).finally(() => setBusy(false));
2500
+ }, [
2501
+ auth,
2502
+ authState.authenticated,
2503
+ busy,
2504
+ dark,
2505
+ locale,
2506
+ nodeKey,
2507
+ t
2508
+ ]);
2509
+ if (!isHuaqiuQuotaFailure(node)) return null;
2510
+ const label = busy ? t("subscription.subscribing") : authState.authenticated ? t("turnError.aiQuotaCta") : t("turnError.aiQuotaSignIn");
2511
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2512
+ type: "button",
2513
+ style: {
2514
+ ...ctaStyle,
2515
+ ...hovered && !busy ? { background: "var(--dsw-alias-interactive-bg-hover, rgba(230, 46, 45, 0.08))" } : {},
2516
+ ...busy ? stopStyle : {}
2517
+ },
2518
+ disabled: busy,
2519
+ "aria-busy": busy,
2520
+ onClick: open,
2521
+ onMouseEnter: () => setHovered(true),
2522
+ onMouseLeave: () => setHovered(false),
2523
+ children: label
2524
+ }), visibleNotice === null ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2525
+ style: noticeStyle,
2526
+ "aria-live": "polite",
2527
+ children: visibleNotice
2528
+ })] });
2529
+ });
2530
+ //#endregion
2346
2531
  //#region src/client/index.tsx
2347
2532
  /**
2348
2533
  * `@huaqiu/dsh-auth` — browser half (the Phase 0A POC).
@@ -2400,7 +2585,7 @@ window.__ModuleLoader__.load({
2400
2585
  documentLike: document,
2401
2586
  openHostDialog: async (url, options) => {
2402
2587
  const hqEdge = ctx.get?.("hqEdge");
2403
- if (!hqEdge || typeof hqEdge.openUrl !== "function") return;
2588
+ if (!hqEdge || typeof hqEdge.openUrl !== "function") throw new Error("hqEdge.openUrl is unavailable");
2404
2589
  await hqEdge.openUrl(url, {
2405
2590
  ...options.title ? { title: options.title } : {},
2406
2591
  ...options.size ? { size: options.size } : {},
@@ -2470,6 +2655,10 @@ window.__ModuleLoader__.load({
2470
2655
  name: "sidebar.footer.action",
2471
2656
  id: "huaqiu-auth"
2472
2657
  }, HuaqiuAuthSidebarAction)));
2658
+ disposers.push(slots.inject("conversation.chat.turn-error.action", () => slots.register({
2659
+ name: "conversation.chat.turn-error.action",
2660
+ id: "huaqiu-turn-error-cta"
2661
+ }, HuaqiuTurnErrorSubscribeAction)));
2473
2662
  }
2474
2663
  });
2475
2664
  return () => {