All files session-coordination.ts

51.78% Statements 29/56
48.14% Branches 13/27
52.94% Functions 9/17
52.72% Lines 29/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 1331x                                       5x                                                           3x 3x                       5x                 5x 5x 5x         5x 2x 2x     2x 2x 1x 1x             5x     3x 3x           2x 2x 1x   1x   1x                 1x 1x 1x 1x         5x 5x        
const localQueues = new Map<string, Promise<void>>();
 
export interface BrowserSessionRelay<T> {
  readonly available: boolean;
  publish(message: T): void;
  waitFor(
    predicate: (message: T) => boolean,
    timeoutMs?: number,
  ): Promise<T | null>;
  close(): void;
}
 
export class SessionCoordinationUnavailableError extends Error {
  constructor() {
    super("当前浏览器无法安全协调多个页面的会话刷新,请重新登录。");
    this.name = "SessionCoordinationUnavailableError";
  }
}
 
function isTestBrowser(): boolean {
  return typeof navigator !== "undefined"
    && navigator.userAgent.toLowerCase().includes("jsdom");
}
 
async function withLocalQueue<T>(
  name: string,
  operation: () => Promise<T>,
): Promise<T> {
  const previous = localQueues.get(name) ?? Promise.resolve();
  let release!: () => void;
  const current = new Promise<void>((resolve) => {
    release = resolve;
  });
  const queued = previous.then(() => current);
  localQueues.set(name, queued);
  await previous;
  try {
    return await operation();
  } finally {
    release();
    if (localQueues.get(name) === queued) {
      localQueues.delete(name);
    }
  }
}
 
export function withBrowserSessionLock<T>(
  name: string,
  operation: () => Promise<T>,
): Promise<T> {
  Eif (typeof navigator !== "undefined" && navigator.locks) {
    return navigator.locks.request(name, { mode: "exclusive" }, operation);
  }
  if (typeof window !== "undefined" && !isTestBrowser()) {
    return Promise.reject(new SessionCoordinationUnavailableError());
  }
  return withLocalQueue(name, operation);
}
 
export function createBrowserSessionRelay<T>(
  name: string,
  onMessage?: (message: T) => void,
): BrowserSessionRelay<T> {
  Iif (isTestBrowser() || typeof BroadcastChannel === "undefined") {
    return {
      available: false,
      publish: () => undefined,
      waitFor: () => Promise.resolve(null),
      close: () => undefined,
    };
  }
 
  const channel = new BroadcastChannel(name);
  const recent: T[] = [];
  const waiters = new Set<{
    predicate: (message: T) => boolean;
    resolve: (message: T) => void;
  }>();
 
  channel.addEventListener("message", (event: MessageEvent<T>) => {
    recent.push(event.data);
    Iif (recent.length > 4) {
      recent.shift();
    }
    onMessage?.(event.data);
    for (const waiter of [...waiters]) {
      Eif (!waiter.predicate(event.data)) {
        continue;
      }
      waiters.delete(waiter);
      waiter.resolve(event.data);
    }
  });
 
  return {
    available: true,
    publish(message) {
      try {
        channel.postMessage(message);
      } catch {
        // Cross-tab propagation must never invalidate an already verified local rotation.
      }
    },
    waitFor(predicate, timeoutMs = 500) {
      const cached = recent.findLast(predicate);
      if (cached) {
        return Promise.resolve(cached);
      }
      return new Promise<T | null>((resolve) => {
        let timeout: ReturnType<typeof setTimeout> | undefined;
        const waiter = {
          predicate,
          resolve: (message: T) => {
            if (timeout !== undefined) {
              clearTimeout(timeout);
            }
            resolve(message);
          },
        };
        waiters.add(waiter);
        timeout = setTimeout(() => {
          waiters.delete(waiter);
          resolve(null);
        }, timeoutMs);
      });
    },
    close() {
      waiters.clear();
      channel.close();
    },
  };
}