rewardsBridge.ts 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { rewardsContextSchema, type RewardsContext } from "./rewardsEmbedded.js";
  2. /** 此函数经 preload 序列化到网页主世界,不能引用模块外的运行时变量。 */
  3. export function installRewardsPageBridge() {
  4. // 持久分区可能遗留上次账号;在业务脚本运行前清除,等待本次 App 注入完成。
  5. const storage = (globalThis as unknown as { localStorage: { removeItem: (key: string) => void } })
  6. .localStorage;
  7. for (const key of ["oauth:zai:access_token", "oauth:bigmodel:access_token", "zcodejwttoken"])
  8. storage.removeItem(key);
  9. const window = (
  10. globalThis as unknown as {
  11. window: { addEventListener: (event: string, callback: (event: Event) => void) => void };
  12. }
  13. ).window;
  14. let current: RewardsContext | null = null;
  15. const listeners = {
  16. theme: new Set<(value: unknown) => void>(),
  17. locale: new Set<(value: unknown) => void>(),
  18. auth: new Set<(value: unknown) => void>(),
  19. };
  20. window.addEventListener("zcode-rewards-context", (event) => {
  21. const next = (event as CustomEvent).detail;
  22. if (
  23. !next ||
  24. !["zai-light", "zai-dark"].includes(next.theme) ||
  25. !["zh-CN", "en-US"].includes(next.locale) ||
  26. !next.auth ||
  27. !["ready", "anonymous"].includes(next.auth.status) ||
  28. ![null, "zai", "bigmodel"].includes(next.auth.provider) ||
  29. !Number.isSafeInteger(next.auth.revision) ||
  30. next.auth.revision < 0
  31. )
  32. return;
  33. const previous = current;
  34. current = next;
  35. for (const key of ["theme", "locale", "auth"] as const) {
  36. if (JSON.stringify(previous?.[key]) !== JSON.stringify(next[key])) {
  37. for (const callback of listeners[key]) callback(next[key]);
  38. }
  39. }
  40. });
  41. Object.defineProperty(window, "zcodeBridge", {
  42. configurable: false,
  43. writable: false,
  44. value: {
  45. // 对象方法不引入 esbuild keepNames 辅助闭包;序列化到主世界后可独立执行。
  46. getTheme() {
  47. return current?.theme ?? null;
  48. },
  49. getLang() {
  50. return current?.locale ?? null;
  51. },
  52. getAuthState() {
  53. return current?.auth ?? null;
  54. },
  55. onThemeChange(callback: (value: unknown) => void) {
  56. listeners.theme.add(callback);
  57. return () => listeners.theme.delete(callback);
  58. },
  59. onLangChange(callback: (value: unknown) => void) {
  60. listeners.locale.add(callback);
  61. return () => listeners.locale.delete(callback);
  62. },
  63. onAuthChange(callback: (value: unknown) => void) {
  64. listeners.auth.add(callback);
  65. return () => listeners.auth.delete(callback);
  66. },
  67. },
  68. });
  69. }
  70. export function createRewardsInjectionScript(
  71. context: RewardsContext,
  72. credentials: { oauth?: string | null; jwt?: string | null },
  73. expectedUrl?: string,
  74. ): string {
  75. const snapshot = rewardsContextSchema.parse(context);
  76. const values =
  77. snapshot.auth.status === "ready"
  78. ? {
  79. [`oauth:${snapshot.auth.provider}:access_token`]: credentials.oauth?.trim() || null,
  80. zcodejwttoken: credentials.jwt?.trim() || null,
  81. }
  82. : {};
  83. return `(() => {
  84. ${expectedUrl ? `if (window.location.href !== ${JSON.stringify(expectedUrl)}) return;` : ""}
  85. for (const key of ["oauth:zai:access_token", "oauth:bigmodel:access_token", "zcodejwttoken"]) localStorage.removeItem(key);
  86. for (const [key, value] of Object.entries(${JSON.stringify(values)})) if (value) localStorage.setItem(key, value);
  87. window.dispatchEvent(new CustomEvent("zcode-rewards-context", { detail: ${JSON.stringify(snapshot)} }));
  88. })()`;
  89. }