| 35 | } |
| 36 | |
| 37 | function wrapWith401Retry(client: HyperframesCloudClient): HyperframesCloudClient { |
| 38 | return new Proxy(client, { |
| 39 | get(target, prop, receiver) { |
| 40 | const value = Reflect.get(target, prop, receiver); |
| 41 | if (typeof value !== "function") return value; |
| 42 | // Bind so internal `this`-references in the generated client |
| 43 | // resolve back to the original instance, not the Proxy. |
| 44 | const original = value.bind(target) as (...args: unknown[]) => Promise<unknown>; |
| 45 | // Only wrap the public endpoint methods (return Promises). Don't |
| 46 | // gate on method name — the generated client has stable shape, |
| 47 | // and a future endpoint would otherwise be missed. |
| 48 | // fallow-ignore-next-line complexity |
| 49 | return async (...args: unknown[]): Promise<unknown> => { |
| 50 | try { |
| 51 | return await original(...args); |
| 52 | } catch (err) { |
| 53 | if (err instanceof HyperframesApiError && err.status === 401) { |
| 54 | // Best-effort refresh; if it fails, surface the original |
| 55 | // 401 not the refresh error. |
| 56 | try { |
| 57 | await forceRefreshCredentials(); |
| 58 | } catch { |
| 59 | throw err; |
| 60 | } |
| 61 | return await original(...args); |
| 62 | } |
| 63 | throw err; |
| 64 | } |
| 65 | }; |
| 66 | }, |
| 67 | }); |
| 68 | } |