···11+import { AsyncLocalStorage } from 'node:async_hooks';
22+33+type BunServer = ReturnType<typeof Bun.serve>;
44+55+const serverStorage = new AsyncLocalStorage<BunServer>();
66+77+/**
88+ * runs a callback with the server available via AsyncLocalStorage.
99+ * @param server bun server instance
1010+ * @param fn callback to run
1111+ * @returns result of the callback
1212+ */
1313+export const runWithServer = <T>(server: BunServer, fn: () => T): T => {
1414+ return serverStorage.run(server, fn);
1515+};
1616+1717+/**
1818+ * retrieves the bun server from the current async context.
1919+ * @returns the bun server instance
2020+ * @throws if called outside of a request context
2121+ */
2222+export const getServer = (): BunServer => {
2323+ const server = serverStorage.getStore();
2424+ if (server === undefined) {
2525+ throw new Error('server not available in current context');
2626+ }
2727+ return server;
2828+};