rivetkit 2.0.40 → 2.0.41

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.
Files changed (97) hide show
  1. package/dist/schemas/actor-persist/v1.js +167 -0
  2. package/dist/schemas/actor-persist/v2.js +200 -0
  3. package/dist/schemas/actor-persist/v3.js +200 -0
  4. package/dist/schemas/client-protocol/v1.js +301 -0
  5. package/dist/schemas/client-protocol/v2.js +299 -0
  6. package/dist/schemas/file-system-driver/v1.js +76 -0
  7. package/dist/schemas/file-system-driver/v2.js +103 -0
  8. package/dist/schemas/file-system-driver/v3.js +122 -0
  9. package/dist/tsup/actor/errors.cjs.map +1 -1
  10. package/dist/tsup/{chunk-J2R742IE.js → chunk-4J5EFV3E.js} +5 -5
  11. package/dist/tsup/{chunk-B5BMSBR4.cjs → chunk-4UHJ3ADW.cjs} +105 -95
  12. package/dist/tsup/chunk-4UHJ3ADW.cjs.map +1 -0
  13. package/dist/tsup/{chunk-J6YRLC6K.js → chunk-7KIR3QLO.js} +18 -8
  14. package/dist/tsup/{chunk-J6YRLC6K.js.map → chunk-7KIR3QLO.js.map} +1 -1
  15. package/dist/tsup/{chunk-4KNL47JA.cjs → chunk-B5UXC4QV.cjs} +65 -61
  16. package/dist/tsup/chunk-B5UXC4QV.cjs.map +1 -0
  17. package/dist/tsup/{chunk-XCDGPOZT.cjs → chunk-DSNSFYDL.cjs} +3 -3
  18. package/dist/tsup/chunk-DSNSFYDL.cjs.map +1 -0
  19. package/dist/tsup/chunk-GBENOENJ.cjs.map +1 -1
  20. package/dist/tsup/{chunk-FB4TVPDQ.cjs → chunk-GTQKDCM4.cjs} +46 -46
  21. package/dist/tsup/chunk-GTQKDCM4.cjs.map +1 -0
  22. package/dist/tsup/chunk-KDFWJKMJ.cjs.map +1 -1
  23. package/dist/tsup/{chunk-ZUMPCWKF.js → chunk-LMG4QMDO.js} +2 -2
  24. package/dist/tsup/{chunk-ZUMPCWKF.js.map → chunk-LMG4QMDO.js.map} +1 -1
  25. package/dist/tsup/{chunk-4T4UWXHN.js → chunk-NRP2OHSW.js} +4 -4
  26. package/dist/tsup/{chunk-KVB2SG32.js → chunk-OXN6EZUB.js} +9 -5
  27. package/dist/tsup/chunk-OXN6EZUB.js.map +1 -0
  28. package/dist/tsup/{chunk-D2HB4PM5.cjs → chunk-QDVKDX7G.cjs} +9 -9
  29. package/dist/tsup/chunk-QDVKDX7G.cjs.map +1 -0
  30. package/dist/tsup/{chunk-HZOBB3KP.cjs → chunk-S6F7EKC7.cjs} +2 -2
  31. package/dist/tsup/chunk-S6F7EKC7.cjs.map +1 -0
  32. package/dist/tsup/chunk-SNAUKDDK.cjs.map +1 -1
  33. package/dist/tsup/{chunk-XCRJ245S.js → chunk-UGOCTUBG.js} +4 -4
  34. package/dist/tsup/chunk-UGOCTUBG.js.map +1 -0
  35. package/dist/tsup/{chunk-6NBNCWEC.cjs → chunk-WYZLRPQM.cjs} +248 -248
  36. package/dist/tsup/chunk-WYZLRPQM.cjs.map +1 -0
  37. package/dist/tsup/{chunk-7Q7R3QYT.js → chunk-Y7ZDTLD2.js} +2 -2
  38. package/dist/tsup/client/mod.cjs +5 -5
  39. package/dist/tsup/client/mod.cjs.map +1 -1
  40. package/dist/tsup/client/mod.d.cts +2 -2
  41. package/dist/tsup/client/mod.d.ts +2 -2
  42. package/dist/tsup/client/mod.js +4 -4
  43. package/dist/tsup/common/log.cjs +2 -2
  44. package/dist/tsup/common/log.cjs.map +1 -1
  45. package/dist/tsup/common/log.d.cts +2 -2
  46. package/dist/tsup/common/log.d.ts +2 -2
  47. package/dist/tsup/common/log.js +1 -1
  48. package/dist/tsup/common/websocket.cjs +3 -3
  49. package/dist/tsup/common/websocket.cjs.map +1 -1
  50. package/dist/tsup/common/websocket.js +2 -2
  51. package/dist/tsup/{config-cizn-tcF.d.cts → config-COyis_uH.d.cts} +19 -10
  52. package/dist/tsup/{config-OR5ZtHFa.d.ts → config-D43N-CFi.d.ts} +19 -10
  53. package/dist/tsup/{driver-Bg4evbcN.d.cts → driver-Bt7B-qMd.d.cts} +1 -1
  54. package/dist/tsup/{driver-BrAG8ioa.d.ts → driver-KyM2v645.d.ts} +1 -1
  55. package/dist/tsup/driver-helpers/mod.cjs +3 -3
  56. package/dist/tsup/driver-helpers/mod.cjs.map +1 -1
  57. package/dist/tsup/driver-helpers/mod.d.cts +2 -2
  58. package/dist/tsup/driver-helpers/mod.d.ts +2 -2
  59. package/dist/tsup/driver-helpers/mod.js +2 -2
  60. package/dist/tsup/driver-test-suite/mod.cjs +34 -34
  61. package/dist/tsup/driver-test-suite/mod.cjs.map +1 -1
  62. package/dist/tsup/driver-test-suite/mod.d.cts +2 -2
  63. package/dist/tsup/driver-test-suite/mod.d.ts +2 -2
  64. package/dist/tsup/driver-test-suite/mod.js +7 -7
  65. package/dist/tsup/inspector/mod.cjs.map +1 -1
  66. package/dist/tsup/mod.cjs +7 -7
  67. package/dist/tsup/mod.cjs.map +1 -1
  68. package/dist/tsup/mod.d.cts +4 -4
  69. package/dist/tsup/mod.d.ts +4 -4
  70. package/dist/tsup/mod.js +6 -6
  71. package/dist/tsup/test/mod.cjs +7 -7
  72. package/dist/tsup/test/mod.cjs.map +1 -1
  73. package/dist/tsup/test/mod.d.cts +1 -1
  74. package/dist/tsup/test/mod.d.ts +1 -1
  75. package/dist/tsup/test/mod.js +6 -6
  76. package/dist/tsup/utils.cjs +2 -2
  77. package/dist/tsup/utils.cjs.map +1 -1
  78. package/dist/tsup/utils.js +1 -1
  79. package/package.json +2 -2
  80. package/src/common/router.ts +2 -0
  81. package/src/engine-process/mod.ts +8 -1
  82. package/src/registry/config/index.ts +1 -0
  83. package/src/registry/config/serverless.ts +2 -0
  84. package/src/remote-manager-driver/api-endpoints.ts +2 -0
  85. package/src/serverless/configure.ts +3 -0
  86. package/dist/tsup/chunk-4KNL47JA.cjs.map +0 -1
  87. package/dist/tsup/chunk-6NBNCWEC.cjs.map +0 -1
  88. package/dist/tsup/chunk-B5BMSBR4.cjs.map +0 -1
  89. package/dist/tsup/chunk-D2HB4PM5.cjs.map +0 -1
  90. package/dist/tsup/chunk-FB4TVPDQ.cjs.map +0 -1
  91. package/dist/tsup/chunk-HZOBB3KP.cjs.map +0 -1
  92. package/dist/tsup/chunk-KVB2SG32.js.map +0 -1
  93. package/dist/tsup/chunk-XCDGPOZT.cjs.map +0 -1
  94. package/dist/tsup/chunk-XCRJ245S.js.map +0 -1
  95. /package/dist/tsup/{chunk-J2R742IE.js.map → chunk-4J5EFV3E.js.map} +0 -0
  96. /package/dist/tsup/{chunk-4T4UWXHN.js.map → chunk-NRP2OHSW.js.map} +0 -0
  97. /package/dist/tsup/{chunk-7Q7R3QYT.js.map → chunk-Y7ZDTLD2.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/rivet/rivet/rivetkit-typescript/packages/rivetkit/dist/tsup/chunk-FB4TVPDQ.cjs","../../src/actor/router.ts","../../src/common/inline-websocket-adapter.ts","../../src/utils/node.ts","../../src/drivers/file-system/actor.ts","../../src/drivers/file-system/global-state.ts","../../src/schemas/file-system-driver/versioned.ts","../schemas/file-system-driver/v1.ts","../schemas/file-system-driver/v2.ts","../schemas/file-system-driver/v3.ts","../../src/drivers/file-system/log.ts","../../src/drivers/file-system/utils.ts","../../src/drivers/file-system/manager.ts","../../src/drivers/file-system/mod.ts"],"names":["config"],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACrCA,4BAAqB;AAmDd,SAAS,iBAAA,CACfA,OAAAA,EACA,WAAA,EACA,mBAAA,EACA,MAAA,EACc;AACd,EAAA,MAAM,OAAA,EAAS,IAAI,eAAA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A;AACA;AACA","file":"/home/runner/work/rivet/rivet/rivetkit-typescript/packages/rivetkit/dist/tsup/chunk-FB4TVPDQ.cjs","sourcesContent":[null,"import { Hono } from \"hono\";\nimport {\n\ttype ActionOpts,\n\ttype ActionOutput,\n\ttype ConnsMessageOpts,\n\thandleAction,\n\thandleRawRequest,\n} from \"@/actor/router-endpoints\";\nimport {\n\tPATH_CONNECT,\n\tPATH_INSPECTOR_CONNECT,\n\tPATH_WEBSOCKET_PREFIX,\n} from \"@/common/actor-router-consts\";\nimport {\n\thandleRouteError,\n\thandleRouteNotFound,\n\tloggerMiddleware,\n} from \"@/common/router\";\nimport { noopNext } from \"@/common/utils\";\n\nimport type { RegistryConfig } from \"@/registry/config\";\nimport { type GetUpgradeWebSocket, VERSION } from \"@/utils\";\nimport { CONN_DRIVER_SYMBOL } from \"./conn/mod\";\nimport type { ActorDriver } from \"./driver\";\nimport { loggerWithoutContext } from \"./log\";\nimport {\n\tparseWebSocketProtocols,\n\trouteWebSocket,\n} from \"./router-websocket-endpoints\";\n\nexport type { ActionOpts, ActionOutput, ConnsMessageOpts };\n\ninterface ActorRouterBindings {\n\tactorId: string;\n}\n\nexport type ActorRouter = Hono<{ Bindings: ActorRouterBindings }>;\n\nexport interface MetadataResponse {\n\truntime: string;\n\tversion: string;\n}\n\n/**\n * Creates a router that runs on the partitioned instance.\n *\n * You only need to pass `getUpgradeWebSocket` if this router is exposed\n * directly publicly. Usually WebSockets are routed manually in the\n * ManagerDriver instead of via Hono. The only platform that uses this\n * currently is Cloudflare Workers.\n */\nexport function createActorRouter(\n\tconfig: RegistryConfig,\n\tactorDriver: ActorDriver,\n\tgetUpgradeWebSocket: GetUpgradeWebSocket | undefined,\n\tisTest: boolean,\n): ActorRouter {\n\tconst router = new Hono<{ Bindings: ActorRouterBindings }>({\n\t\tstrict: false,\n\t});\n\n\trouter.use(\"*\", loggerMiddleware(loggerWithoutContext()));\n\n\t// Track all HTTP requests to prevent actor from sleeping during active requests\n\trouter.use(\"*\", async (c, next) => {\n\t\tconst actor = await actorDriver.loadActor(c.env.actorId);\n\t\tactor.beginHonoHttpRequest();\n\t\ttry {\n\t\t\tawait next();\n\t\t} finally {\n\t\t\tactor.endHonoHttpRequest();\n\t\t}\n\t});\n\n\trouter.get(\"/\", (c) => {\n\t\treturn c.text(\n\t\t\t\"This is an RivetKit actor.\\n\\nLearn more at https://rivetkit.org\",\n\t\t);\n\t});\n\n\trouter.get(\"/health\", (c) => {\n\t\treturn c.text(\"ok\");\n\t});\n\n\trouter.get(\"/metadata\", async (c) => {\n\t\treturn c.json({\n\t\t\truntime: \"rivetkit\",\n\t\t\tversion: VERSION,\n\t\t} satisfies MetadataResponse);\n\t});\n\n\tif (isTest) {\n\t\t// Test endpoint to force disconnect a connection non-cleanly\n\t\trouter.post(\"/.test/force-disconnect\", async (c) => {\n\t\t\tconst connId = c.req.query(\"conn\");\n\n\t\t\tif (!connId) {\n\t\t\t\treturn c.text(\"Missing conn query parameter\", 400);\n\t\t\t}\n\n\t\t\tconst actor = await actorDriver.loadActor(c.env.actorId);\n\t\t\tconst conn = actor.connectionManager.getConnForId(connId);\n\n\t\t\tif (!conn) {\n\t\t\t\treturn c.text(`Connection not found: ${connId}`, 404);\n\t\t\t}\n\n\t\t\t// Force close the connection without clean shutdown\n\t\t\tif (conn[CONN_DRIVER_SYMBOL]?.terminate) {\n\t\t\t\tconn[CONN_DRIVER_SYMBOL].terminate(actor, conn);\n\t\t\t}\n\n\t\t\treturn c.json({ success: true });\n\t\t});\n\t}\n\n\t// Route all WebSocket paths using the same handler\n\t//\n\t// All WebSockets use a separate underlying router in routeWebSocket since\n\t// WebSockets also need to be routed from ManagerDriver.proxyWebSocket and\n\t// ManagerDriver.openWebSocket.\n\tif (getUpgradeWebSocket) {\n\t\trouter.on(\n\t\t\t\"GET\",\n\t\t\t[PATH_CONNECT, `${PATH_WEBSOCKET_PREFIX}*`, PATH_INSPECTOR_CONNECT],\n\t\t\tasync (c) => {\n\t\t\t\tconst upgradeWebSocket = getUpgradeWebSocket();\n\t\t\t\tif (upgradeWebSocket) {\n\t\t\t\t\treturn upgradeWebSocket(async (c) => {\n\t\t\t\t\t\tconst protocols = c.req.header(\n\t\t\t\t\t\t\t\"sec-websocket-protocol\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst { encoding, connParams } =\n\t\t\t\t\t\t\tparseWebSocketProtocols(protocols);\n\n\t\t\t\t\t\treturn await routeWebSocket(\n\t\t\t\t\t\t\tc.req.raw,\n\t\t\t\t\t\t\tc.req.path,\n\t\t\t\t\t\t\tc.req.header(),\n\t\t\t\t\t\t\tconfig,\n\t\t\t\t\t\t\tactorDriver,\n\t\t\t\t\t\t\tc.env.actorId,\n\t\t\t\t\t\t\tencoding,\n\t\t\t\t\t\t\tconnParams,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t);\n\t\t\t\t\t})(c, noopNext());\n\t\t\t\t} else {\n\t\t\t\t\treturn c.text(\n\t\t\t\t\t\t\"WebSockets are not enabled for this driver.\",\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t}\n\n\trouter.post(\"/action/:action\", async (c) => {\n\t\tconst actionName = c.req.param(\"action\");\n\n\t\treturn handleAction(c, config, actorDriver, actionName, c.env.actorId);\n\t});\n\n\trouter.all(\"/request/*\", async (c) => {\n\t\t// TODO: This is not a clean way of doing this since `/http/` might exist mid-path\n\t\t// Strip the /http prefix from the URL to get the original path\n\t\tconst url = new URL(c.req.url);\n\t\tconst originalPath = url.pathname.replace(/^\\/request/, \"\") || \"/\";\n\n\t\t// Create a new request with the corrected URL\n\t\tconst correctedUrl = new URL(originalPath + url.search, url.origin);\n\t\tconst correctedRequest = new Request(correctedUrl, {\n\t\t\tmethod: c.req.method,\n\t\t\theaders: c.req.raw.headers,\n\t\t\tbody: c.req.raw.body,\n\t\t\tduplex: \"half\",\n\t\t} as RequestInit);\n\n\t\tloggerWithoutContext().debug({\n\t\t\tmsg: \"rewriting http url\",\n\t\t\tfrom: c.req.url,\n\t\t\tto: correctedRequest.url,\n\t\t});\n\n\t\treturn await handleRawRequest(\n\t\t\tc,\n\t\t\tcorrectedRequest,\n\t\t\tactorDriver,\n\t\t\tc.env.actorId,\n\t\t);\n\t});\n\n\trouter.notFound(handleRouteNotFound);\n\trouter.onError(handleRouteError);\n\n\treturn router;\n}\n","import { WSContext } from \"hono/ws\";\nimport type { UpgradeWebSocketArgs } from \"@/actor/router-websocket-endpoints\";\nimport type { UniversalWebSocket } from \"@/common/websocket-interface\";\nimport { VirtualWebSocket } from \"@rivetkit/virtual-websocket\";\nimport { getLogger } from \"./log\";\n\nfunction logger() {\n\treturn getLogger(\"inline-websocket-adapter\");\n}\n\n/**\n * InlineWebSocketAdapter creates two linked WebSocket objects:\n * - clientWs: for the client/proxy side (returned from openWebSocket)\n * - actorWs: for the actor side (passed via wsContext.raw)\n *\n * Each side's send() triggers the OTHER side's message event.\n */\nexport class InlineWebSocketAdapter {\n\t#handler: UpgradeWebSocketArgs;\n\t#wsContext: WSContext;\n\t#readyState: 0 | 1 | 2 | 3 = 0;\n\n\t#clientWs: VirtualWebSocket;\n\t#actorWs: VirtualWebSocket;\n\n\tconstructor(handler: UpgradeWebSocketArgs) {\n\t\tthis.#handler = handler;\n\n\t\t// Create linked WebSocket pair\n\t\t// Client's send() -> handler.onMessage (for RPC) + Actor's message event (for raw WS)\n\t\t// Actor's send() -> Client's message event\n\t\tthis.#clientWs = new VirtualWebSocket({\n\t\t\tgetReadyState: () => this.#readyState,\n\t\t\tonSend: (data) => {\n\t\t\t\ttry {\n\t\t\t\t\t// Call handler.onMessage for protocol-based connections (RPC)\n\t\t\t\t\tthis.#handler.onMessage({ data }, this.#wsContext);\n\t\t\t\t\t// Also trigger message event on actor's websocket for raw websocket handlers\n\t\t\t\t\tthis.#actorWs.triggerMessage(data);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.#handleError(err);\n\t\t\t\t\tthis.#close(1011, \"Internal error processing message\");\n\t\t\t\t}\n\t\t\t},\n\t\t\tonClose: (code, reason) => this.#close(code, reason),\n\t\t});\n\n\t\tthis.#actorWs = new VirtualWebSocket({\n\t\t\tgetReadyState: () => this.#readyState,\n\t\t\tonSend: (data) => this.#clientWs.triggerMessage(data),\n\t\t\tonClose: (code, reason) => this.#close(code, reason),\n\t\t});\n\n\t\t// Create WSContext with actorWs as raw\n\t\tthis.#wsContext = new WSContext({\n\t\t\traw: this.#actorWs,\n\t\t\tsend: (data: string | ArrayBuffer | Uint8Array) => {\n\t\t\t\tlogger().debug({ msg: \"WSContext.send called\" });\n\t\t\t\tthis.#clientWs.triggerMessage(data);\n\t\t\t},\n\t\t\tclose: (code?: number, reason?: string) => {\n\t\t\t\tlogger().debug({ msg: \"WSContext.close called\", code, reason });\n\t\t\t\tthis.#close(code || 1000, reason || \"\");\n\t\t\t},\n\t\t\treadyState: 1,\n\t\t});\n\n\t\t// Defer initialization to allow event listeners to be attached first\n\t\tsetTimeout(() => {\n\t\t\tthis.#initialize();\n\t\t}, 0);\n\t}\n\n\t/** Get the client-side WebSocket (for proxy/client code) */\n\tget clientWebSocket(): UniversalWebSocket {\n\t\treturn this.#clientWs;\n\t}\n\n\t/** Get the actor-side WebSocket (passed to actor via wsContext.raw) */\n\tget actorWebSocket(): UniversalWebSocket {\n\t\treturn this.#actorWs;\n\t}\n\n\tasync #initialize(): Promise<void> {\n\t\ttry {\n\t\t\tlogger().debug({ msg: \"websocket initializing\" });\n\n\t\t\tthis.#readyState = 1; // OPEN\n\n\t\t\tlogger().debug({ msg: \"calling handler.onOpen with WSContext\" });\n\t\t\tthis.#handler.onOpen(undefined, this.#wsContext);\n\n\t\t\t// Fire open event to both sides\n\t\t\tthis.#clientWs.triggerOpen();\n\t\t\tthis.#actorWs.triggerOpen();\n\t\t} catch (err) {\n\t\t\tthis.#handleError(err);\n\t\t\tthis.#close(1011, \"Internal error during initialization\");\n\t\t}\n\t}\n\n\t#handleError(err: unknown): void {\n\t\tlogger().error({\n\t\t\tmsg: \"error in websocket\",\n\t\t\terror: err,\n\t\t\terrorMessage: err instanceof Error ? err.message : String(err),\n\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t});\n\n\t\t// Call handler.onError\n\t\ttry {\n\t\t\tthis.#handler.onError(err, this.#wsContext);\n\t\t} catch (handlerErr) {\n\t\t\tlogger().error({ msg: \"error in onError handler\", error: handlerErr });\n\t\t}\n\n\t\t// Fire error event to both sides\n\t\tthis.#clientWs.triggerError(err);\n\t\tthis.#actorWs.triggerError(err);\n\t}\n\n\t#close(code: number, reason: string): void {\n\t\tif (this.#readyState === 3 || this.#readyState === 2) {\n\t\t\treturn;\n\t\t}\n\n\t\tlogger().debug({ msg: \"closing websocket\", code, reason });\n\n\t\tthis.#readyState = 2; // CLOSING\n\n\t\ttry {\n\t\t\tthis.#handler.onClose({ code, reason, wasClean: true }, this.#wsContext);\n\t\t} catch (err) {\n\t\t\tlogger().error({ msg: \"error closing websocket\", error: err });\n\t\t} finally {\n\t\t\tthis.#readyState = 3; // CLOSED\n\n\t\t\t// Fire close event to both sides\n\t\t\tthis.#clientWs.triggerClose(code, reason);\n\t\t\tthis.#actorWs.triggerClose(code, reason);\n\t\t}\n\t}\n}\n\n/**\n * Creates an InlineWebSocketAdapter and returns the client-side WebSocket.\n * This is the main entry point for creating inline WebSocket connections.\n */\nexport function createInlineWebSocket(\n\thandler: UpgradeWebSocketArgs,\n): UniversalWebSocket {\n\tconst adapter = new InlineWebSocketAdapter(handler);\n\treturn adapter.clientWebSocket;\n}\n","import { createRequire } from \"node:module\";\n\n// Global variables for Node.js modules.\n//\n// We use synchronous require() instead of async import() for Node.js module loading because:\n// 1. These modules are only needed in Node.js environments (not browser/edge)\n// 2. registry.start() cannot be async and needs immediate access to Node modules\n// 3. The setup process must be synchronous to avoid breaking the API\n//\n// Biome only allows imports of node modules in this file in order to ensure\n// we're forcing the use of dynamic imports.\nlet nodeCrypto: typeof import(\"node:crypto\") | undefined;\nlet nodeFsSync: typeof import(\"node:fs\") | undefined;\nlet nodeFs: typeof import(\"node:fs/promises\") | undefined;\nlet nodePath: typeof import(\"node:path\") | undefined;\nlet nodeOs: typeof import(\"node:os\") | undefined;\nlet nodeChildProcess: typeof import(\"node:child_process\") | undefined;\nlet nodeStream: typeof import(\"node:stream/promises\") | undefined;\n\nlet hasImportedDependencies = false;\n\n// Helper to get a require function that works in both CommonJS and ESM.\n// We use require() instead of await import() because registry.start() cannot\n// be async and needs immediate access to Node.js modules during setup.\nfunction getRequireFn() {\n\t// TODO: This causes issues in tsup\n\t// CommonJS context - use global require\n\t// if (typeof require !== \"undefined\") {\n\t// \tconsole.log(\"existing require\");\n\t// \treturn require;\n\t// }\n\n\t// ESM context - use createRequire with import.meta.url\n\treturn createRequire(import.meta.url);\n}\n\n/**\n * Dynamically imports all required Node.js dependencies. We do this early in a\n * single function call in order to surface errors early.\n *\n * This function is idempotent and will only import once.\n *\n * @throws Error if Node.js modules are not available (e.g., in browser/edge environments)\n */\nexport function importNodeDependencies(): void {\n\t// Check if already loaded\n\tif (hasImportedDependencies) return;\n\n\ttry {\n\t\t// Get a require function that works in both CommonJS and ESM\n\t\tconst requireFn = getRequireFn();\n\n\t\t// Use requireFn with webpack ignore comment to prevent bundling\n\t\tnodeCrypto = requireFn(/* webpackIgnore: true */ \"node:crypto\");\n\t\tnodeFsSync = requireFn(/* webpackIgnore: true */ \"node:fs\");\n\t\tnodeFs = requireFn(/* webpackIgnore: true */ \"node:fs/promises\");\n\t\tnodePath = requireFn(/* webpackIgnore: true */ \"node:path\");\n\t\tnodeOs = requireFn(/* webpackIgnore: true */ \"node:os\");\n\t\tnodeChildProcess = requireFn(\n\t\t\t/* webpackIgnore: true */ \"node:child_process\",\n\t\t);\n\t\tnodeStream = requireFn(\n\t\t\t/* webpackIgnore: true */ \"node:stream/promises\",\n\t\t);\n\n\t\thasImportedDependencies = true;\n\t} catch (err) {\n\t\tconsole.warn(\n\t\t\t\"Node.js modules not available, file system driver will not work\",\n\t\t\terr,\n\t\t);\n\t\tthrow err;\n\t}\n}\n\n/**\n * Gets the Node.js crypto module.\n * @throws Error if crypto module is not loaded\n */\nexport function getNodeCrypto(): typeof import(\"node:crypto\") {\n\tif (!nodeCrypto) {\n\t\tthrow new Error(\n\t\t\t\"Node crypto module not loaded. Ensure importNodeDependencies() has been called.\",\n\t\t);\n\t}\n\treturn nodeCrypto;\n}\n\n/**\n * Gets the Node.js fs module.\n * @throws Error if fs module is not loaded\n */\nexport function getNodeFsSync(): typeof import(\"node:fs\") {\n\tif (!nodeFsSync) {\n\t\tthrow new Error(\n\t\t\t\"Node fs module not loaded. Ensure importNodeDependencies() has been called.\",\n\t\t);\n\t}\n\treturn nodeFsSync;\n}\n\n/**\n * Gets the Node.js fs/promises module.\n * @throws Error if fs/promises module is not loaded\n */\nexport function getNodeFs(): typeof import(\"node:fs/promises\") {\n\tif (!nodeFs) {\n\t\tthrow new Error(\n\t\t\t\"Node fs/promises module not loaded. Ensure importNodeDependencies() has been called.\",\n\t\t);\n\t}\n\treturn nodeFs;\n}\n\n/**\n * Gets the Node.js path module.\n * @throws Error if path module is not loaded\n */\nexport function getNodePath(): typeof import(\"node:path\") {\n\tif (!nodePath) {\n\t\tthrow new Error(\n\t\t\t\"Node path module not loaded. Ensure importNodeDependencies() has been called.\",\n\t\t);\n\t}\n\treturn nodePath;\n}\n\n/**\n * Gets the Node.js os module.\n * @throws Error if os module is not loaded\n */\nexport function getNodeOs(): typeof import(\"node:os\") {\n\tif (!nodeOs) {\n\t\tthrow new Error(\n\t\t\t\"Node os module not loaded. Ensure importNodeDependencies() has been called.\",\n\t\t);\n\t}\n\treturn nodeOs;\n}\n\n/**\n * Gets the Node.js child_process module.\n * @throws Error if child_process module is not loaded\n */\nexport function getNodeChildProcess(): typeof import(\"node:child_process\") {\n\tif (!nodeChildProcess) {\n\t\tthrow new Error(\n\t\t\t\"Node child_process module not loaded. Ensure importNodeDependencies() has been called.\",\n\t\t);\n\t}\n\treturn nodeChildProcess;\n}\n\n/**\n * Gets the Node.js stream/promises module.\n * @throws Error if stream/promises module is not loaded\n */\nexport function getNodeStream(): typeof import(\"node:stream/promises\") {\n\tif (!nodeStream) {\n\t\tthrow new Error(\n\t\t\t\"Node stream/promises module not loaded. Ensure importNodeDependencies() has been called.\",\n\t\t);\n\t}\n\treturn nodeStream;\n}\n","import type { AnyClient } from \"@/client/client\";\nimport type {\n\tActorDriver,\n\tAnyActorInstance,\n\tManagerDriver,\n} from \"@/driver-helpers/mod\";\nimport type { FileSystemGlobalState } from \"./global-state\";\nimport { RegistryConfig } from \"@/registry/config\";\n\nexport type ActorDriverContext = Record<never, never>;\n\n/**\n * File System implementation of the Actor Driver\n */\nexport class FileSystemActorDriver implements ActorDriver {\n\t#config: RegistryConfig;\n\t#managerDriver: ManagerDriver;\n\t#inlineClient: AnyClient;\n\t#state: FileSystemGlobalState;\n\n\tconstructor(\n\t\tconfig: RegistryConfig,\n\t\tmanagerDriver: ManagerDriver,\n\t\tinlineClient: AnyClient,\n\t\tstate: FileSystemGlobalState,\n\t) {\n\t\tthis.#config = config;\n\t\tthis.#managerDriver = managerDriver;\n\t\tthis.#inlineClient = inlineClient;\n\t\tthis.#state = state;\n\t}\n\n\tasync loadActor(actorId: string): Promise<AnyActorInstance> {\n\t\treturn this.#state.startActor(\n\t\t\tthis.#config,\n\t\t\tthis.#inlineClient,\n\t\t\tthis,\n\t\t\tactorId,\n\t\t);\n\t}\n\n\t/**\n\t * Get the current storage directory path\n\t */\n\tget storagePath(): string {\n\t\treturn this.#state.storagePath;\n\t}\n\n\tgetContext(_actorId: string): ActorDriverContext {\n\t\treturn {};\n\t}\n\n\tasync kvBatchPut(\n\t\tactorId: string,\n\t\tentries: [Uint8Array, Uint8Array][],\n\t): Promise<void> {\n\t\tawait this.#state.kvBatchPut(actorId, entries);\n\t}\n\n\tasync kvBatchGet(\n\t\tactorId: string,\n\t\tkeys: Uint8Array[],\n\t): Promise<(Uint8Array | null)[]> {\n\t\treturn await this.#state.kvBatchGet(actorId, keys);\n\t}\n\n\tasync kvBatchDelete(actorId: string, keys: Uint8Array[]): Promise<void> {\n\t\tawait this.#state.kvBatchDelete(actorId, keys);\n\t}\n\n\tasync kvListPrefix(\n\t\tactorId: string,\n\t\tprefix: Uint8Array,\n\t): Promise<[Uint8Array, Uint8Array][]> {\n\t\treturn await this.#state.kvListPrefix(actorId, prefix);\n\t}\n\n\tasync setAlarm(actor: AnyActorInstance, timestamp: number): Promise<void> {\n\t\tawait this.#state.setActorAlarm(actor.id, timestamp);\n\t}\n\n\tgetDatabase(actorId: string): Promise<unknown | undefined> {\n\t\treturn this.#state.createDatabase(actorId);\n\t}\n\n\tstartSleep(actorId: string): void {\n\t\t// Spawns the sleepActor promise\n\t\tthis.#state.sleepActor(actorId);\n\t}\n\n\tasync startDestroy(actorId: string): Promise<void> {\n\t\tawait this.#state.destroyActor(actorId);\n\t}\n}\n","import invariant from \"invariant\";\nimport { lookupInRegistry } from \"@/actor/definition\";\nimport { ActorDuplicateKey } from \"@/actor/errors\";\nimport type { AnyActorInstance } from \"@/actor/instance/mod\";\nimport type { ActorKey } from \"@/actor/mod\";\nimport type { AnyClient } from \"@/client/client\";\nimport { type ActorDriver, getInitialActorKvState } from \"@/driver-helpers/mod\";\nimport type * as schema from \"@/schemas/file-system-driver/mod\";\nimport {\n\tACTOR_ALARM_VERSIONED,\n\tACTOR_STATE_VERSIONED,\n\tCURRENT_VERSION as FILE_SYSTEM_DRIVER_CURRENT_VERSION,\n} from \"@/schemas/file-system-driver/versioned\";\nimport {\n\tarrayBuffersEqual,\n\tbufferToArrayBuffer,\n\ttype LongTimeoutHandle,\n\tpromiseWithResolvers,\n\tsetLongTimeout,\n\tstringifyError,\n} from \"@/utils\";\nimport {\n\tgetNodeCrypto,\n\tgetNodeFs,\n\tgetNodeFsSync,\n\tgetNodePath,\n} from \"@/utils/node\";\nimport { logger } from \"./log\";\nimport {\n\tensureDirectoryExists,\n\tensureDirectoryExistsSync,\n\tgetStoragePath,\n} from \"./utils\";\nimport { RegistryConfig } from \"@/registry/config\";\n\n// Actor handler to track running instances\n\nenum ActorLifecycleState {\n\tNONEXISTENT, // Entry exists but actor not yet created\n\tAWAKE, // Actor is running normally\n\tSTARTING_SLEEP, // Actor is being put to sleep\n\tSTARTING_DESTROY, // Actor is being destroyed\n\tDESTROYED, // Actor was destroyed, should not be recreated\n}\n\ninterface ActorEntry {\n\tid: string;\n\n\tstate?: schema.ActorState;\n\n\t/** Promise for loading the actor state. */\n\tloadPromise?: Promise<ActorEntry>;\n\n\tactor?: AnyActorInstance;\n\t/** Promise for starting the actor. */\n\tstartPromise?: ReturnType<typeof promiseWithResolvers<void>>;\n\n\talarmTimeout?: LongTimeoutHandle;\n\t/** The timestamp currently scheduled for this actor's alarm (ms since epoch). */\n\talarmTimestamp?: number;\n\n\t/** Resolver for pending write operations that need to be notified when any write completes */\n\tpendingWriteResolver?: PromiseWithResolvers<void>;\n\n\tlifecycleState: ActorLifecycleState;\n\n\t// TODO: This might make sense to move in to actorstate, but we have a\n\t// single reader/writer so it's not an issue\n\t/** Generation of this actor when creating/destroying. */\n\tgeneration: string;\n}\n\n/**\n * Global state for the file system driver\n */\nexport class FileSystemGlobalState {\n\t#storagePath: string;\n\t#stateDir: string;\n\t#dbsDir: string;\n\t#alarmsDir: string;\n\n\t#persist: boolean;\n\n\t// IMPORTANT: Never delete from this map. Doing so will result in race\n\t// conditions since the actor generation will cease to be tracked\n\t// correctly. Always increment generation if a new actor is created.\n\t#actors = new Map<string, ActorEntry>();\n\n\t#actorCountOnStartup: number = 0;\n\n\t#runnerParams?: {\n\t\tconfig: RegistryConfig;\n\t\tinlineClient: AnyClient;\n\t\tactorDriver: ActorDriver;\n\t};\n\n\tget persist(): boolean {\n\t\treturn this.#persist;\n\t}\n\n\tget storagePath() {\n\t\treturn this.#storagePath;\n\t}\n\n\tget actorCountOnStartup() {\n\t\treturn this.#actorCountOnStartup;\n\t}\n\n\tconstructor(persist: boolean = true, customPath?: string) {\n\t\tthis.#persist = persist;\n\t\tthis.#storagePath = persist ? (customPath ?? getStoragePath()) : \"/tmp\";\n\t\tconst path = getNodePath();\n\t\tthis.#stateDir = path.join(this.#storagePath, \"state\");\n\t\tthis.#dbsDir = path.join(this.#storagePath, \"databases\");\n\t\tthis.#alarmsDir = path.join(this.#storagePath, \"alarms\");\n\n\t\tif (this.#persist) {\n\t\t\t// Ensure storage directories exist synchronously during initialization\n\t\t\tensureDirectoryExistsSync(this.#stateDir);\n\t\t\tensureDirectoryExistsSync(this.#dbsDir);\n\t\t\tensureDirectoryExistsSync(this.#alarmsDir);\n\n\t\t\ttry {\n\t\t\t\tconst fsSync = getNodeFsSync();\n\t\t\t\tconst actorIds = fsSync.readdirSync(this.#stateDir);\n\t\t\t\tthis.#actorCountOnStartup = actorIds.length;\n\t\t\t} catch (error) {\n\t\t\t\tlogger().error({ msg: \"failed to count actors\", error });\n\t\t\t}\n\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"file system driver ready\",\n\t\t\t\tdir: this.#storagePath,\n\t\t\t\tactorCount: this.#actorCountOnStartup,\n\t\t\t});\n\n\t\t\t// Cleanup stale temp files on startup\n\t\t\ttry {\n\t\t\t\tthis.#cleanupTempFilesSync();\n\t\t\t} catch (err) {\n\t\t\t\tlogger().error({\n\t\t\t\t\tmsg: \"failed to cleanup temp files\",\n\t\t\t\t\terror: err,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tlogger().debug({ msg: \"memory driver ready\" });\n\t\t}\n\t}\n\n\tgetActorStatePath(actorId: string): string {\n\t\treturn getNodePath().join(this.#stateDir, actorId);\n\t}\n\n\tgetActorDbPath(actorId: string): string {\n\t\treturn getNodePath().join(this.#dbsDir, `${actorId}.db`);\n\t}\n\n\tgetActorAlarmPath(actorId: string): string {\n\t\treturn getNodePath().join(this.#alarmsDir, actorId);\n\t}\n\n\tasync *getActorsIterator(params: {\n\t\tcursor?: string;\n\t}): AsyncGenerator<schema.ActorState> {\n\t\tlet actorIds = Array.from(this.#actors.keys()).sort();\n\n\t\t// Check if state directory exists first\n\t\tconst fsSync = getNodeFsSync();\n\t\tif (fsSync.existsSync(this.#stateDir)) {\n\t\t\tactorIds = fsSync\n\t\t\t\t.readdirSync(this.#stateDir)\n\t\t\t\t.filter((id) => !id.includes(\".tmp\"))\n\t\t\t\t.sort();\n\t\t}\n\n\t\tconst startIndex = params.cursor\n\t\t\t? actorIds.indexOf(params.cursor) + 1\n\t\t\t: 0;\n\n\t\tfor (let i = startIndex; i < actorIds.length; i++) {\n\t\t\tconst actorId = actorIds[i];\n\t\t\tif (!actorId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst state = await this.loadActorStateOrError(actorId);\n\t\t\t\tyield state;\n\t\t\t} catch (error) {\n\t\t\t\tlogger().error({\n\t\t\t\t\tmsg: \"failed to load actor state\",\n\t\t\t\t\tactorId,\n\t\t\t\t\terror,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Ensures an entry exists for this actor.\n\t *\n\t * Used for #createActor and #loadActor.\n\t */\n\t#upsertEntry(actorId: string): ActorEntry {\n\t\tlet entry = this.#actors.get(actorId);\n\t\tif (entry) {\n\t\t\treturn entry;\n\t\t}\n\n\t\tentry = {\n\t\t\tid: actorId,\n\t\t\tlifecycleState: ActorLifecycleState.NONEXISTENT,\n\t\t\tgeneration: crypto.randomUUID(),\n\t\t};\n\t\tthis.#actors.set(actorId, entry);\n\t\treturn entry;\n\t}\n\n\t/**\n\t * Creates a new actor and writes to file system.\n\t */\n\tasync createActor(\n\t\tactorId: string,\n\t\tname: string,\n\t\tkey: ActorKey,\n\t\tinput: unknown | undefined,\n\t): Promise<ActorEntry> {\n\t\t// TODO: Does not check if actor already exists on fs\n\n\t\tconst entry = this.#upsertEntry(actorId);\n\n\t\t// Check if actor already exists (has state or is being stopped)\n\t\tif (entry.state) {\n\t\t\tthrow new ActorDuplicateKey(name, key);\n\t\t}\n\t\tif (this.isActorStopping(actorId)) {\n\t\t\tthrow new Error(`Actor ${actorId} is stopping`);\n\t\t}\n\n\t\t// If actor was destroyed, reset to NONEXISTENT and increment generation\n\t\tif (entry.lifecycleState === ActorLifecycleState.DESTROYED) {\n\t\t\tentry.lifecycleState = ActorLifecycleState.NONEXISTENT;\n\t\t\tentry.generation = crypto.randomUUID();\n\t\t}\n\n\t\t// Initialize storage\n\t\tconst kvStorage: schema.ActorKvEntry[] = [];\n\t\tconst initialKvState = getInitialActorKvState(input);\n\t\tfor (const [key, value] of initialKvState) {\n\t\t\tkvStorage.push({\n\t\t\t\tkey: bufferToArrayBuffer(key),\n\t\t\t\tvalue: bufferToArrayBuffer(value),\n\t\t\t});\n\t\t}\n\n\t\t// Initialize metadata\n\t\tentry.state = {\n\t\t\tactorId,\n\t\t\tname,\n\t\t\tkey,\n\t\t\tcreatedAt: BigInt(Date.now()),\n\t\t\tkvStorage,\n\t\t\tstartTs: null,\n\t\t\tconnectableTs: null,\n\t\t\tsleepTs: null,\n\t\t\tdestroyTs: null,\n\t\t};\n\t\tentry.lifecycleState = ActorLifecycleState.AWAKE;\n\n\t\tawait this.writeActor(actorId, entry.generation, entry.state);\n\n\t\treturn entry;\n\t}\n\n\t/**\n\t * Loads the actor from disk or returns the existing actor entry. This will return an entry even if the actor does not actually exist.\n\t */\n\tasync loadActor(actorId: string): Promise<ActorEntry> {\n\t\tconst entry = this.#upsertEntry(actorId);\n\n\t\t// Check if destroyed - don't load from disk\n\t\tif (entry.lifecycleState === ActorLifecycleState.DESTROYED) {\n\t\t\treturn entry;\n\t\t}\n\n\t\t// Check if already loaded\n\t\tif (entry.state) {\n\t\t\treturn entry;\n\t\t}\n\n\t\t// If not persisted, then don't load from FS\n\t\tif (!this.#persist) {\n\t\t\treturn entry;\n\t\t}\n\n\t\t// If state is currently being loaded, wait for it\n\t\tif (entry.loadPromise) {\n\t\t\tawait entry.loadPromise;\n\t\t\treturn entry;\n\t\t}\n\n\t\t// Start loading state\n\t\tentry.loadPromise = this.loadActorState(entry);\n\t\treturn entry.loadPromise;\n\t}\n\n\tprivate async loadActorState(entry: ActorEntry) {\n\t\tconst stateFilePath = this.getActorStatePath(entry.id);\n\n\t\t// Read & parse file\n\t\ttry {\n\t\t\tconst fs = getNodeFs();\n\t\t\tconst stateData = await fs.readFile(stateFilePath);\n\n\t\t\t// Cache the loaded state in handler\n\t\t\tentry.state = ACTOR_STATE_VERSIONED.deserializeWithEmbeddedVersion(\n\t\t\t\tnew Uint8Array(stateData),\n\t\t\t);\n\n\t\t\treturn entry;\n\t\t} catch (innerError: any) {\n\t\t\t// File does not exist, meaning the actor does not exist\n\t\t\tif (innerError.code === \"ENOENT\") {\n\t\t\t\tentry.loadPromise = undefined;\n\t\t\t\treturn entry;\n\t\t\t}\n\n\t\t\t// For other errors, throw\n\t\t\tconst error = new Error(\n\t\t\t\t`Failed to load actor state: ${innerError}`,\n\t\t\t);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync loadOrCreateActor(\n\t\tactorId: string,\n\t\tname: string,\n\t\tkey: ActorKey,\n\t\tinput: unknown | undefined,\n\t): Promise<ActorEntry> {\n\t\t// Attempt to load actor\n\t\tconst entry = await this.loadActor(actorId);\n\n\t\t// If no state for this actor, then create & write state\n\t\tif (!entry.state) {\n\t\t\tif (this.isActorStopping(actorId)) {\n\t\t\t\tthrow new Error(`Actor ${actorId} stopping`);\n\t\t\t}\n\n\t\t\t// If actor was destroyed, reset to NONEXISTENT and increment generation\n\t\t\tif (entry.lifecycleState === ActorLifecycleState.DESTROYED) {\n\t\t\t\tentry.lifecycleState = ActorLifecycleState.NONEXISTENT;\n\t\t\t\tentry.generation = crypto.randomUUID();\n\t\t\t}\n\n\t\t\t// Initialize kvStorage with the initial persist data\n\t\t\tconst kvStorage: schema.ActorKvEntry[] = [];\n\t\t\tconst initialKvState = getInitialActorKvState(input);\n\t\t\tfor (const [key, value] of initialKvState) {\n\t\t\t\tkvStorage.push({\n\t\t\t\t\tkey: bufferToArrayBuffer(key),\n\t\t\t\t\tvalue: bufferToArrayBuffer(value),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tentry.state = {\n\t\t\t\tactorId,\n\t\t\t\tname,\n\t\t\t\tkey: key as readonly string[],\n\t\t\t\tcreatedAt: BigInt(Date.now()),\n\t\t\t\tkvStorage,\n\t\t\t\tstartTs: null,\n\t\t\t\tconnectableTs: null,\n\t\t\t\tsleepTs: null,\n\t\t\t\tdestroyTs: null,\n\t\t\t};\n\t\t\tawait this.writeActor(actorId, entry.generation, entry.state);\n\t\t}\n\t\treturn entry;\n\t}\n\n\tasync sleepActor(actorId: string) {\n\t\tinvariant(\n\t\t\tthis.#persist,\n\t\t\t\"cannot sleep actor with memory driver, must use file system driver\",\n\t\t);\n\n\t\t// Get the actor. We upsert it even though we're about to destroy it so we have a lock on flagging `destroying` as true.\n\t\tconst actor = this.#upsertEntry(actorId);\n\t\tinvariant(actor, `tried to sleep ${actorId}, does not exist`);\n\n\t\t// Check if already destroying\n\t\tif (this.isActorStopping(actorId)) {\n\t\t\treturn;\n\t\t}\n\t\tactor.lifecycleState = ActorLifecycleState.STARTING_SLEEP;\n\n\t\t// Wait for actor to fully start before stopping it to avoid race conditions\n\t\tif (actor.loadPromise) await actor.loadPromise.catch();\n\t\tif (actor.startPromise?.promise)\n\t\t\tawait actor.startPromise.promise.catch();\n\n\t\t// Update state with sleep timestamp\n\t\tif (actor.state) {\n\t\t\tactor.state = {\n\t\t\t\t...actor.state,\n\t\t\t\tsleepTs: BigInt(Date.now()),\n\t\t\t};\n\t\t\tawait this.writeActor(actorId, actor.generation, actor.state);\n\t\t}\n\n\t\t// Stop actor\n\t\tinvariant(actor.actor, \"actor should be loaded\");\n\t\tawait actor.actor.onStop(\"sleep\");\n\n\t\t// Remove from map after stop is complete\n\t\tthis.#actors.delete(actorId);\n\t}\n\n\tasync destroyActor(actorId: string) {\n\t\t// Get the actor. We upsert it even though we're about to destroy it so we have a lock on flagging `destroying` as true.\n\t\tconst actor = this.#upsertEntry(actorId);\n\n\t\t// If actor is loaded, stop it first\n\t\t// Check if already destroying\n\t\tif (this.isActorStopping(actorId)) {\n\t\t\treturn;\n\t\t}\n\t\tactor.lifecycleState = ActorLifecycleState.STARTING_DESTROY;\n\n\t\t// Wait for actor to fully start before stopping it to avoid race conditions\n\t\tif (actor.loadPromise) await actor.loadPromise.catch();\n\t\tif (actor.startPromise?.promise)\n\t\t\tawait actor.startPromise.promise.catch();\n\n\t\t// Update state with destroy timestamp\n\t\tif (actor.state) {\n\t\t\tactor.state = {\n\t\t\t\t...actor.state,\n\t\t\t\tdestroyTs: BigInt(Date.now()),\n\t\t\t};\n\t\t\tawait this.writeActor(actorId, actor.generation, actor.state);\n\t\t}\n\n\t\t// Stop actor if it's running\n\t\tif (actor.actor) {\n\t\t\tawait actor.actor.onStop(\"destroy\");\n\t\t}\n\n\t\t// Clear alarm timeout if exists\n\t\tif (actor.alarmTimeout) {\n\t\t\tactor.alarmTimeout.abort();\n\t\t}\n\n\t\t// Delete persisted files if using file system driver\n\t\tif (this.#persist) {\n\t\t\tconst fs = getNodeFs();\n\n\t\t\t// Delete all actor files in parallel\n\t\t\tawait Promise.all([\n\t\t\t\t// Delete actor state file\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait fs.unlink(this.getActorStatePath(actorId));\n\t\t\t\t\t} catch (err: any) {\n\t\t\t\t\t\tif (err?.code !== \"ENOENT\") {\n\t\t\t\t\t\t\tlogger().error({\n\t\t\t\t\t\t\t\tmsg: \"failed to delete actor state file\",\n\t\t\t\t\t\t\t\tactorId,\n\t\t\t\t\t\t\t\terror: stringifyError(err),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})(),\n\t\t\t\t// Delete actor database file\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait fs.unlink(this.getActorDbPath(actorId));\n\t\t\t\t\t} catch (err: any) {\n\t\t\t\t\t\tif (err?.code !== \"ENOENT\") {\n\t\t\t\t\t\t\tlogger().error({\n\t\t\t\t\t\t\t\tmsg: \"failed to delete actor database file\",\n\t\t\t\t\t\t\t\tactorId,\n\t\t\t\t\t\t\t\terror: stringifyError(err),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})(),\n\t\t\t\t// Delete actor alarm file\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait fs.unlink(this.getActorAlarmPath(actorId));\n\t\t\t\t\t} catch (err: any) {\n\t\t\t\t\t\tif (err?.code !== \"ENOENT\") {\n\t\t\t\t\t\t\tlogger().error({\n\t\t\t\t\t\t\t\tmsg: \"failed to delete actor alarm file\",\n\t\t\t\t\t\t\t\tactorId,\n\t\t\t\t\t\t\t\terror: stringifyError(err),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})(),\n\t\t\t]);\n\t\t}\n\n\t\t// Reset the entry\n\t\t//\n\t\t// Do not remove entry in order to avoid race condition with\n\t\t// destroying. Next actor creation will increment the generation.\n\t\tactor.state = undefined;\n\t\tactor.loadPromise = undefined;\n\t\tactor.actor = undefined;\n\t\tactor.startPromise = undefined;\n\t\tactor.alarmTimeout = undefined;\n\t\tactor.alarmTimeout = undefined;\n\t\tactor.pendingWriteResolver = undefined;\n\t\tactor.lifecycleState = ActorLifecycleState.DESTROYED;\n\t}\n\n\t/**\n\t * Save actor state to disk.\n\t */\n\tasync writeActor(\n\t\tactorId: string,\n\t\tgeneration: string,\n\t\tstate: schema.ActorState,\n\t): Promise<void> {\n\t\tif (!this.#persist) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst entry = this.#actors.get(actorId);\n\t\tinvariant(entry, \"actor entry does not exist\");\n\n\t\tawait this.#performWrite(actorId, generation, state);\n\t}\n\n\tisGenerationCurrentAndNotDestroyed(\n\t\tactorId: string,\n\t\tgeneration: string,\n\t): boolean {\n\t\tconst entry = this.#upsertEntry(actorId);\n\t\tif (!entry) return false;\n\t\treturn (\n\t\t\tentry.generation === generation &&\n\t\t\tentry.lifecycleState !== ActorLifecycleState.STARTING_DESTROY\n\t\t);\n\t}\n\n\tisActorStopping(actorId: string) {\n\t\tconst entry = this.#upsertEntry(actorId);\n\t\tif (!entry) return false;\n\t\treturn (\n\t\t\tentry.lifecycleState === ActorLifecycleState.STARTING_SLEEP ||\n\t\t\tentry.lifecycleState === ActorLifecycleState.STARTING_DESTROY\n\t\t);\n\t}\n\n\tasync setActorAlarm(actorId: string, timestamp: number) {\n\t\tconst entry = this.#actors.get(actorId);\n\t\tinvariant(entry, \"actor entry does not exist\");\n\n\t\t// Track generation of the actor when the write started to detect\n\t\t// destroy/create race condition\n\t\tconst writeGeneration = entry.generation;\n\t\tif (this.isActorStopping(actorId)) {\n\t\t\tlogger().info(\"skipping set alarm since actor stopping\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Persist alarm to disk\n\t\tif (this.#persist) {\n\t\t\tconst alarmPath = this.getActorAlarmPath(actorId);\n\t\t\tconst crypto = getNodeCrypto();\n\t\t\tconst tempPath = `${alarmPath}.tmp.${crypto.randomUUID()}`;\n\t\t\ttry {\n\t\t\t\tconst path = getNodePath();\n\t\t\t\tawait ensureDirectoryExists(path.dirname(alarmPath));\n\t\t\t\tconst alarmData: schema.ActorAlarm = {\n\t\t\t\t\tactorId,\n\t\t\t\t\ttimestamp: BigInt(timestamp),\n\t\t\t\t};\n\t\t\t\tconst data = ACTOR_ALARM_VERSIONED.serializeWithEmbeddedVersion(\n\t\t\t\t\talarmData,\n\t\t\t\t\tFILE_SYSTEM_DRIVER_CURRENT_VERSION,\n\t\t\t\t);\n\t\t\t\tconst fs = getNodeFs();\n\t\t\t\tawait fs.writeFile(tempPath, data);\n\n\t\t\t\tif (\n\t\t\t\t\t!this.isGenerationCurrentAndNotDestroyed(\n\t\t\t\t\t\tactorId,\n\t\t\t\t\t\twriteGeneration,\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tlogger().debug(\n\t\t\t\t\t\t\"skipping writing alarm since actor destroying or new generation\",\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tawait fs.rename(tempPath, alarmPath);\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tconst fs = getNodeFs();\n\t\t\t\t\tawait fs.unlink(tempPath);\n\t\t\t\t} catch {}\n\t\t\t\tlogger().error({\n\t\t\t\t\tmsg: \"failed to write alarm\",\n\t\t\t\t\tactorId,\n\t\t\t\t\terror,\n\t\t\t\t});\n\t\t\t\tthrow new Error(`Failed to write alarm: ${error}`);\n\t\t\t}\n\t\t}\n\n\t\t// Schedule timeout\n\t\tthis.#scheduleAlarmTimeout(actorId, timestamp);\n\t}\n\n\t/**\n\t * Perform the actual write operation with atomic writes\n\t */\n\tasync #performWrite(\n\t\tactorId: string,\n\t\tgeneration: string,\n\t\tstate: schema.ActorState,\n\t): Promise<void> {\n\t\tconst dataPath = this.getActorStatePath(actorId);\n\t\t// Generate unique temp filename to prevent any race conditions\n\t\tconst crypto = getNodeCrypto();\n\t\tconst tempPath = `${dataPath}.tmp.${crypto.randomUUID()}`;\n\n\t\ttry {\n\t\t\t// Create directory if needed\n\t\t\tconst path = getNodePath();\n\t\t\tawait ensureDirectoryExists(path.dirname(dataPath));\n\n\t\t\t// Convert to BARE types for serialization\n\t\t\tconst bareState: schema.ActorState = {\n\t\t\t\tactorId: state.actorId,\n\t\t\t\tname: state.name,\n\t\t\t\tkey: state.key,\n\t\t\t\tcreatedAt: state.createdAt,\n\t\t\t\tkvStorage: state.kvStorage,\n\t\t\t\tstartTs: state.startTs,\n\t\t\t\tconnectableTs: state.connectableTs,\n\t\t\t\tsleepTs: state.sleepTs,\n\t\t\t\tdestroyTs: state.destroyTs,\n\t\t\t};\n\n\t\t\t// Perform atomic write\n\t\t\tconst serializedState =\n\t\t\t\tACTOR_STATE_VERSIONED.serializeWithEmbeddedVersion(\n\t\t\t\t\tbareState,\n\t\t\t\t\tFILE_SYSTEM_DRIVER_CURRENT_VERSION,\n\t\t\t\t);\n\t\t\tconst fs = getNodeFs();\n\t\t\tawait fs.writeFile(tempPath, serializedState);\n\n\t\t\tif (!this.isGenerationCurrentAndNotDestroyed(actorId, generation)) {\n\t\t\t\tlogger().debug(\n\t\t\t\t\t\"skipping writing alarm since actor destroying or new generation\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait fs.rename(tempPath, dataPath);\n\t\t} catch (error) {\n\t\t\t// Cleanup temp file on error\n\t\t\ttry {\n\t\t\t\tconst fs = getNodeFs();\n\t\t\t\tawait fs.unlink(tempPath);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\t\t\tlogger().error({\n\t\t\t\tmsg: \"failed to save actor state\",\n\t\t\t\tactorId,\n\t\t\t\terror,\n\t\t\t});\n\t\t\tthrow new Error(`Failed to save actor state: ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Call this method after the actor driver has been initiated.\n\t *\n\t * This will trigger all initial alarms from the file system.\n\t *\n\t * This needs to be sync since DriverConfig.actor is sync\n\t */\n\tonRunnerStart(\n\t\tconfig: RegistryConfig,\n\t\tinlineClient: AnyClient,\n\t\tactorDriver: ActorDriver,\n\t) {\n\t\tif (this.#runnerParams) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Save runner params for future use\n\t\tthis.#runnerParams = {\n\t\t\tconfig: config,\n\t\t\tinlineClient,\n\t\t\tactorDriver,\n\t\t};\n\n\t\t// Load alarms from disk and schedule timeouts\n\t\ttry {\n\t\t\tthis.#loadAlarmsSync();\n\t\t} catch (err) {\n\t\t\tlogger().error({\n\t\t\t\tmsg: \"failed to load alarms on startup\",\n\t\t\t\terror: err,\n\t\t\t});\n\t\t}\n\t}\n\n\tasync startActor(\n\t\tconfig: RegistryConfig,\n\t\tinlineClient: AnyClient,\n\t\tactorDriver: ActorDriver,\n\t\tactorId: string,\n\t): Promise<AnyActorInstance> {\n\t\t// Get the actor metadata\n\t\tconst entry = await this.loadActor(actorId);\n\t\tif (!entry.state) {\n\t\t\tthrow new Error(\n\t\t\t\t`Actor does not exist and cannot be started: \"${actorId}\"`,\n\t\t\t);\n\t\t}\n\n\t\t// Actor already starting\n\t\tif (entry.startPromise) {\n\t\t\tawait entry.startPromise.promise;\n\t\t\tinvariant(entry.actor, \"actor should have loaded\");\n\t\t\treturn entry.actor;\n\t\t}\n\n\t\t// Actor already loaded\n\t\tif (entry.actor) {\n\t\t\treturn entry.actor;\n\t\t}\n\n\t\t// Create start promise\n\t\tentry.startPromise = promiseWithResolvers();\n\n\t\ttry {\n\t\t\t// Create actor\n\t\t\tconst definition = lookupInRegistry(\n\t\t\t\tconfig,\n\t\t\t\tentry.state.name,\n\t\t\t);\n\t\t\tentry.actor = definition.instantiate();\n\n\t\t\t// Start actor\n\t\t\tawait entry.actor.start(\n\t\t\t\tactorDriver,\n\t\t\t\tinlineClient,\n\t\t\t\tactorId,\n\t\t\t\tentry.state.name,\n\t\t\t\tentry.state.key as string[],\n\t\t\t\t\"unknown\",\n\t\t\t);\n\n\t\t\t// Update state with start timestamp\n\t\t\t// NOTE: connectableTs is always in sync with startTs since actors become connectable immediately after starting\n\t\t\tconst now = BigInt(Date.now());\n\t\t\tentry.state = {\n\t\t\t\t...entry.state,\n\t\t\t\tstartTs: now,\n\t\t\t\tconnectableTs: now,\n\t\t\t\tsleepTs: null, // Clear sleep timestamp when actor wakes up\n\t\t\t};\n\t\t\tawait this.writeActor(actorId, entry.generation, entry.state);\n\n\t\t\t// Finish\n\t\t\tentry.startPromise.resolve();\n\t\t\tentry.startPromise = undefined;\n\n\t\t\treturn entry.actor;\n\t\t} catch (innerError) {\n\t\t\tconst error = new Error(\n\t\t\t\t`Failed to start actor ${actorId}: ${innerError}`,\n\t\t\t\t{ cause: innerError },\n\t\t\t);\n\t\t\tentry.startPromise?.reject(error);\n\t\t\tentry.startPromise = undefined;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync loadActorStateOrError(actorId: string): Promise<schema.ActorState> {\n\t\tconst state = (await this.loadActor(actorId)).state;\n\t\tif (!state) throw new Error(`Actor does not exist: ${actorId}`);\n\t\treturn state;\n\t}\n\n\tgetActorOrError(actorId: string): ActorEntry {\n\t\tconst entry = this.#actors.get(actorId);\n\t\tif (!entry) throw new Error(`No entry for actor: ${actorId}`);\n\t\treturn entry;\n\t}\n\n\tasync createDatabase(actorId: string): Promise<string | undefined> {\n\t\treturn this.getActorDbPath(actorId);\n\t}\n\n\t/**\n\t * Load all persisted alarms from disk and schedule their timers.\n\t */\n\t#loadAlarmsSync(): void {\n\t\ttry {\n\t\t\tconst fsSync = getNodeFsSync();\n\t\t\tconst files = fsSync.existsSync(this.#alarmsDir)\n\t\t\t\t? fsSync.readdirSync(this.#alarmsDir)\n\t\t\t\t: [];\n\t\t\tfor (const file of files) {\n\t\t\t\t// Skip temp files\n\t\t\t\tif (file.includes(\".tmp.\")) continue;\n\t\t\t\tconst path = getNodePath();\n\t\t\t\tconst fullPath = path.join(this.#alarmsDir, file);\n\t\t\t\ttry {\n\t\t\t\t\tconst buf = fsSync.readFileSync(fullPath);\n\t\t\t\t\tconst alarmData =\n\t\t\t\t\t\tACTOR_ALARM_VERSIONED.deserializeWithEmbeddedVersion(\n\t\t\t\t\t\t\tnew Uint8Array(buf),\n\t\t\t\t\t\t);\n\t\t\t\t\tconst timestamp = Number(alarmData.timestamp);\n\t\t\t\t\tif (Number.isFinite(timestamp)) {\n\t\t\t\t\t\tthis.#scheduleAlarmTimeout(\n\t\t\t\t\t\t\talarmData.actorId,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\t\tmsg: \"invalid alarm file contents\",\n\t\t\t\t\t\t\tfile,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlogger().error({\n\t\t\t\t\t\tmsg: \"failed to read alarm file\",\n\t\t\t\t\t\tfile,\n\t\t\t\t\t\terror: stringifyError(err),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger().error({\n\t\t\t\tmsg: \"failed to list alarms directory\",\n\t\t\t\terror: err,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Schedule an alarm timer for an actor without writing to disk.\n\t */\n\t#scheduleAlarmTimeout(actorId: string, timestamp: number) {\n\t\tconst entry = this.#upsertEntry(actorId);\n\n\t\t// If there's already an earlier alarm scheduled, do not override it.\n\t\tif (\n\t\t\tentry.alarmTimestamp !== undefined &&\n\t\t\ttimestamp >= entry.alarmTimestamp\n\t\t) {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"skipping alarm schedule (later than existing)\",\n\t\t\t\tactorId,\n\t\t\t\ttimestamp,\n\t\t\t\tcurrent: entry.alarmTimestamp,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tlogger().debug({ msg: \"scheduling alarm\", actorId, timestamp });\n\n\t\t// Cancel existing timeout and update the current scheduled timestamp\n\t\tentry.alarmTimeout?.abort();\n\t\tentry.alarmTimestamp = timestamp;\n\n\t\tconst delay = Math.max(0, timestamp - Date.now());\n\t\tentry.alarmTimeout = setLongTimeout(async () => {\n\t\t\t// Clear currently scheduled timestamp as this alarm is firing now\n\t\t\tentry.alarmTimestamp = undefined;\n\t\t\t// On trigger: remove persisted alarm file\n\t\t\tif (this.#persist) {\n\t\t\t\ttry {\n\t\t\t\t\tconst fs = getNodeFs();\n\t\t\t\t\tawait fs.unlink(this.getActorAlarmPath(actorId));\n\t\t\t\t} catch (err: any) {\n\t\t\t\t\tif (err?.code !== \"ENOENT\") {\n\t\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\t\tmsg: \"failed to remove alarm file\",\n\t\t\t\t\t\t\tactorId,\n\t\t\t\t\t\t\terror: stringifyError(err),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tlogger().debug({ msg: \"triggering alarm\", actorId, timestamp });\n\n\t\t\t\t// Ensure actor state exists and start actor if needed\n\t\t\t\tconst loaded = await this.loadActor(actorId);\n\t\t\t\tif (!loaded.state)\n\t\t\t\t\tthrow new Error(`Actor does not exist: ${actorId}`);\n\n\t\t\t\t// Start actor if not already running\n\t\t\t\tconst runnerParams = this.#runnerParams;\n\t\t\t\tinvariant(runnerParams, \"missing runner params\");\n\t\t\t\tif (!loaded.actor) {\n\t\t\t\t\tawait this.startActor(\n\t\t\t\t\t\trunnerParams.config,\n\t\t\t\t\t\trunnerParams.inlineClient,\n\t\t\t\t\t\trunnerParams.actorDriver,\n\t\t\t\t\t\tactorId,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tinvariant(loaded.actor, \"actor should be loaded after wake\");\n\t\t\t\tawait loaded.actor.onAlarm();\n\t\t\t} catch (err) {\n\t\t\t\tlogger().error({\n\t\t\t\t\tmsg: \"failed to handle alarm\",\n\t\t\t\t\tactorId,\n\t\t\t\t\terror: stringifyError(err),\n\t\t\t\t});\n\t\t\t}\n\t\t}, delay);\n\t}\n\n\t/**\n\t * Cleanup stale temp files on startup (synchronous)\n\t */\n\t#cleanupTempFilesSync(): void {\n\t\ttry {\n\t\t\tconst fsSync = getNodeFsSync();\n\t\t\tconst files = fsSync.readdirSync(this.#stateDir);\n\t\t\tconst tempFiles = files.filter((f) => f.includes(\".tmp.\"));\n\n\t\t\tconst oneHourAgo = Date.now() - 3600000; // 1 hour in ms\n\n\t\t\tfor (const tempFile of tempFiles) {\n\t\t\t\ttry {\n\t\t\t\t\tconst path = getNodePath();\n\t\t\t\t\tconst fullPath = path.join(this.#stateDir, tempFile);\n\t\t\t\t\tconst stat = fsSync.statSync(fullPath);\n\n\t\t\t\t\t// Remove if older than 1 hour\n\t\t\t\t\tif (stat.mtimeMs < oneHourAgo) {\n\t\t\t\t\t\tfsSync.unlinkSync(fullPath);\n\t\t\t\t\t\tlogger().info({\n\t\t\t\t\t\t\tmsg: \"cleaned up stale temp file\",\n\t\t\t\t\t\t\tfile: tempFile,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\tmsg: \"failed to cleanup temp file\",\n\t\t\t\t\t\tfile: tempFile,\n\t\t\t\t\t\terror: err,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger().error({\n\t\t\t\tmsg: \"failed to read actors directory for cleanup\",\n\t\t\t\terror: err,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Batch put KV entries for an actor.\n\t */\n\tasync kvBatchPut(\n\t\tactorId: string,\n\t\tentries: [Uint8Array, Uint8Array][],\n\t): Promise<void> {\n\t\tconst entry = await this.loadActor(actorId);\n\t\tif (!entry.state) {\n\t\t\tif (this.isActorStopping(actorId)) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Actor ${actorId} state not loaded`);\n\t\t\t}\n\t\t}\n\n\t\t// Create a mutable copy of kvStorage\n\t\tconst newKvStorage = [...entry.state.kvStorage];\n\n\t\t// Update kvStorage with new entries\n\t\tfor (const [key, value] of entries) {\n\t\t\t// Find existing entry with the same key\n\t\t\tconst existingIndex = newKvStorage.findIndex((e) =>\n\t\t\t\tarrayBuffersEqual(e.key, bufferToArrayBuffer(key)),\n\t\t\t);\n\n\t\t\tif (existingIndex >= 0) {\n\t\t\t\t// Replace existing entry with new one\n\t\t\t\tnewKvStorage[existingIndex] = {\n\t\t\t\t\tkey: bufferToArrayBuffer(key),\n\t\t\t\t\tvalue: bufferToArrayBuffer(value),\n\t\t\t\t};\n\t\t\t} else {\n\t\t\t\t// Add new entry\n\t\t\t\tnewKvStorage.push({\n\t\t\t\t\tkey: bufferToArrayBuffer(key),\n\t\t\t\t\tvalue: bufferToArrayBuffer(value),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Update state with new kvStorage\n\t\tentry.state = {\n\t\t\t...entry.state,\n\t\t\tkvStorage: newKvStorage,\n\t\t};\n\n\t\t// Save state to disk\n\t\tawait this.writeActor(actorId, entry.generation, entry.state);\n\t}\n\n\t/**\n\t * Batch get KV entries for an actor.\n\t */\n\tasync kvBatchGet(\n\t\tactorId: string,\n\t\tkeys: Uint8Array[],\n\t): Promise<(Uint8Array | null)[]> {\n\t\tconst entry = await this.loadActor(actorId);\n\t\tif (!entry.state) {\n\t\t\tif (this.isActorStopping(actorId)) {\n\t\t\t\tthrow new Error(`Actor ${actorId} is stopping`);\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Actor ${actorId} state not loaded`);\n\t\t\t}\n\t\t}\n\n\t\tconst results: (Uint8Array | null)[] = [];\n\t\tfor (const key of keys) {\n\t\t\t// Find entry with the same key\n\t\t\tconst foundEntry = entry.state.kvStorage.find((e) =>\n\t\t\t\tarrayBuffersEqual(e.key, bufferToArrayBuffer(key)),\n\t\t\t);\n\n\t\t\tif (foundEntry) {\n\t\t\t\tresults.push(new Uint8Array(foundEntry.value));\n\t\t\t} else {\n\t\t\t\tresults.push(null);\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\t/**\n\t * Batch delete KV entries for an actor.\n\t */\n\tasync kvBatchDelete(actorId: string, keys: Uint8Array[]): Promise<void> {\n\t\tconst entry = await this.loadActor(actorId);\n\t\tif (!entry.state) {\n\t\t\tif (this.isActorStopping(actorId)) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Actor ${actorId} state not loaded`);\n\t\t\t}\n\t\t}\n\n\t\t// Create a mutable copy of kvStorage\n\t\tconst newKvStorage = [...entry.state.kvStorage];\n\n\t\t// Delete entries from kvStorage\n\t\tfor (const key of keys) {\n\t\t\tconst indexToDelete = newKvStorage.findIndex((e) =>\n\t\t\t\tarrayBuffersEqual(e.key, bufferToArrayBuffer(key)),\n\t\t\t);\n\n\t\t\tif (indexToDelete >= 0) {\n\t\t\t\tnewKvStorage.splice(indexToDelete, 1);\n\t\t\t}\n\t\t}\n\n\t\t// Update state with new kvStorage\n\t\tentry.state = {\n\t\t\t...entry.state,\n\t\t\tkvStorage: newKvStorage,\n\t\t};\n\n\t\t// Save state to disk\n\t\tawait this.writeActor(actorId, entry.generation, entry.state);\n\t}\n\n\t/**\n\t * List KV entries with a given prefix for an actor.\n\t */\n\tasync kvListPrefix(\n\t\tactorId: string,\n\t\tprefix: Uint8Array,\n\t): Promise<[Uint8Array, Uint8Array][]> {\n\t\tconst entry = await this.loadActor(actorId);\n\t\tif (!entry.state) {\n\t\t\tif (this.isActorStopping(actorId)) {\n\t\t\t\tthrow new Error(`Actor ${actorId} is destroying`);\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Actor ${actorId} state not loaded`);\n\t\t\t}\n\t\t}\n\n\t\tconst results: [Uint8Array, Uint8Array][] = [];\n\t\tfor (const kvEntry of entry.state.kvStorage) {\n\t\t\tconst keyBytes = new Uint8Array(kvEntry.key);\n\t\t\t// Check if key starts with prefix\n\t\t\tif (keyBytes.length >= prefix.length) {\n\t\t\t\tlet hasPrefix = true;\n\t\t\t\tfor (let i = 0; i < prefix.length; i++) {\n\t\t\t\t\tif (keyBytes[i] !== prefix[i]) {\n\t\t\t\t\t\thasPrefix = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (hasPrefix) {\n\t\t\t\t\tresults.push([keyBytes, new Uint8Array(kvEntry.value)]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n}\n","import { createVersionedDataHandler } from \"vbare\";\nimport { bufferToArrayBuffer } from \"@/utils\";\nimport * as v1 from \"../../../dist/schemas/file-system-driver/v1\";\nimport * as v2 from \"../../../dist/schemas/file-system-driver/v2\";\nimport * as v3 from \"../../../dist/schemas/file-system-driver/v3\";\n\nexport const CURRENT_VERSION = 3;\n\n// Converter from v1 to v2\nconst v1ToV2 = (v1State: v1.ActorState): v2.ActorState => {\n\t// Create a new kvStorage list with the legacy persist data\n\tconst kvStorage: v2.ActorKvEntry[] = [];\n\n\t// Store the legacy persist data under key [1]\n\tif (v1State.persistedData) {\n\t\t// Key [1] as Uint8Array\n\t\tconst key = new Uint8Array([1]);\n\t\tkvStorage.push({\n\t\t\tkey: bufferToArrayBuffer(key),\n\t\t\tvalue: v1State.persistedData,\n\t\t});\n\t}\n\n\treturn {\n\t\tactorId: v1State.actorId,\n\t\tname: v1State.name,\n\t\tkey: v1State.key,\n\t\tkvStorage,\n\t\tcreatedAt: v1State.createdAt,\n\t};\n};\n\n// Converter from v2 to v3\nconst v2ToV3 = (v2State: v2.ActorState): v3.ActorState => {\n\t// Migrate from v2 to v3 by adding the new optional timestamp fields\n\treturn {\n\t\tactorId: v2State.actorId,\n\t\tname: v2State.name,\n\t\tkey: v2State.key,\n\t\tkvStorage: v2State.kvStorage,\n\t\tcreatedAt: v2State.createdAt,\n\t\tstartTs: null,\n\t\tconnectableTs: null,\n\t\tsleepTs: null,\n\t\tdestroyTs: null,\n\t};\n};\n\n// Converter from v3 to v2\nconst v3ToV2 = (v3State: v3.ActorState): v2.ActorState => {\n\t// Downgrade from v3 to v2 by removing the timestamp fields\n\treturn {\n\t\tactorId: v3State.actorId,\n\t\tname: v3State.name,\n\t\tkey: v3State.key,\n\t\tkvStorage: v3State.kvStorage,\n\t\tcreatedAt: v3State.createdAt,\n\t};\n};\n\n// Converter from v2 to v1\nconst v2ToV1 = (v2State: v2.ActorState): v1.ActorState => {\n\t// Downgrade from v2 to v1 by converting kvStorage back to persistedData\n\t// Find the persist data entry (key [1])\n\tconst persistDataEntry = v2State.kvStorage.find((entry) => {\n\t\tconst key = new Uint8Array(entry.key);\n\t\treturn key.length === 1 && key[0] === 1;\n\t});\n\n\treturn {\n\t\tactorId: v2State.actorId,\n\t\tname: v2State.name,\n\t\tkey: v2State.key,\n\t\tpersistedData: persistDataEntry?.value || new ArrayBuffer(0),\n\t\tcreatedAt: v2State.createdAt,\n\t};\n};\n\nexport const ACTOR_STATE_VERSIONED = createVersionedDataHandler<v3.ActorState>({\n\tdeserializeVersion: (bytes, version) => {\n\t\tswitch (version) {\n\t\t\tcase 1:\n\t\t\t\treturn v1.decodeActorState(bytes);\n\t\t\tcase 2:\n\t\t\t\treturn v2.decodeActorState(bytes);\n\t\t\tcase 3:\n\t\t\t\treturn v3.decodeActorState(bytes);\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unknown version ${version}`);\n\t\t}\n\t},\n\tserializeVersion: (data, version) => {\n\t\tswitch (version) {\n\t\t\tcase 1:\n\t\t\t\treturn v1.encodeActorState(data as v1.ActorState);\n\t\t\tcase 2:\n\t\t\t\treturn v2.encodeActorState(data as v2.ActorState);\n\t\t\tcase 3:\n\t\t\t\treturn v3.encodeActorState(data as v3.ActorState);\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unknown version ${version}`);\n\t\t}\n\t},\n\tdeserializeConverters: () => [v1ToV2, v2ToV3],\n\tserializeConverters: () => [v3ToV2, v2ToV1],\n});\n\nexport const ACTOR_ALARM_VERSIONED = createVersionedDataHandler<v3.ActorAlarm>({\n\tdeserializeVersion: (bytes, version) => {\n\t\tswitch (version) {\n\t\t\tcase 1:\n\t\t\t\treturn v1.decodeActorAlarm(bytes);\n\t\t\tcase 2:\n\t\t\t\treturn v2.decodeActorAlarm(bytes);\n\t\t\tcase 3:\n\t\t\t\treturn v3.decodeActorAlarm(bytes);\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unknown version ${version}`);\n\t\t}\n\t},\n\tserializeVersion: (data, version) => {\n\t\tswitch (version) {\n\t\t\tcase 1:\n\t\t\t\treturn v1.encodeActorAlarm(data as v1.ActorAlarm);\n\t\t\tcase 2:\n\t\t\t\treturn v2.encodeActorAlarm(data as v2.ActorAlarm);\n\t\t\tcase 3:\n\t\t\t\treturn v3.encodeActorAlarm(data as v3.ActorAlarm);\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unknown version ${version}`);\n\t\t}\n\t},\n\tdeserializeConverters: () => [],\n\tserializeConverters: () => [],\n});\n","// @generated - post-processed by compile-bare.ts\nimport * as bare from \"@rivetkit/bare-ts\"\n\nconst config = /* @__PURE__ */ bare.Config({})\n\nexport type u64 = bigint\nexport type uint = bigint\n\nfunction read0(bc: bare.ByteCursor): readonly string[] {\n const len = bare.readUintSafe(bc)\n if (len === 0) { return [] }\n const result = [bare.readString(bc)]\n for (let i = 1; i < len; i++) {\n result[i] = bare.readString(bc)\n }\n return result\n}\n\nfunction write0(bc: bare.ByteCursor, x: readonly string[]): void {\n bare.writeUintSafe(bc, x.length)\n for (let i = 0; i < x.length; i++) {\n bare.writeString(bc, x[i])\n }\n}\n\nexport type ActorState = {\n readonly actorId: string,\n readonly name: string,\n readonly key: readonly string[],\n readonly persistedData: ArrayBuffer,\n readonly createdAt: u64,\n}\n\nexport function readActorState(bc: bare.ByteCursor): ActorState {\n return {\n actorId: bare.readString(bc),\n name: bare.readString(bc),\n key: read0(bc),\n persistedData: bare.readData(bc),\n createdAt: bare.readU64(bc),\n }\n}\n\nexport function writeActorState(bc: bare.ByteCursor, x: ActorState): void {\n bare.writeString(bc, x.actorId)\n bare.writeString(bc, x.name)\n write0(bc, x.key)\n bare.writeData(bc, x.persistedData)\n bare.writeU64(bc, x.createdAt)\n}\n\nexport function encodeActorState(x: ActorState): Uint8Array {\n const bc = new bare.ByteCursor(\n new Uint8Array(config.initialBufferLength),\n config\n )\n writeActorState(bc, x)\n return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset)\n}\n\nexport function decodeActorState(bytes: Uint8Array): ActorState {\n const bc = new bare.ByteCursor(bytes, config)\n const result = readActorState(bc)\n if (bc.offset < bc.view.byteLength) {\n throw new bare.BareError(bc.offset, \"remaining bytes\")\n }\n return result\n}\n\nexport type ActorAlarm = {\n readonly actorId: string,\n readonly timestamp: uint,\n}\n\nexport function readActorAlarm(bc: bare.ByteCursor): ActorAlarm {\n return {\n actorId: bare.readString(bc),\n timestamp: bare.readUint(bc),\n }\n}\n\nexport function writeActorAlarm(bc: bare.ByteCursor, x: ActorAlarm): void {\n bare.writeString(bc, x.actorId)\n bare.writeUint(bc, x.timestamp)\n}\n\nexport function encodeActorAlarm(x: ActorAlarm): Uint8Array {\n const bc = new bare.ByteCursor(\n new Uint8Array(config.initialBufferLength),\n config\n )\n writeActorAlarm(bc, x)\n return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset)\n}\n\nexport function decodeActorAlarm(bytes: Uint8Array): ActorAlarm {\n const bc = new bare.ByteCursor(bytes, config)\n const result = readActorAlarm(bc)\n if (bc.offset < bc.view.byteLength) {\n throw new bare.BareError(bc.offset, \"remaining bytes\")\n }\n return result\n}\n\n\nfunction assert(condition: boolean, message?: string): asserts condition {\n if (!condition) throw new Error(message ?? \"Assertion failed\")\n}\n","// @generated - post-processed by compile-bare.ts\nimport * as bare from \"@rivetkit/bare-ts\"\n\nconst config = /* @__PURE__ */ bare.Config({})\n\nexport type u64 = bigint\nexport type uint = bigint\n\nexport type ActorKvEntry = {\n readonly key: ArrayBuffer,\n readonly value: ArrayBuffer,\n}\n\nexport function readActorKvEntry(bc: bare.ByteCursor): ActorKvEntry {\n return {\n key: bare.readData(bc),\n value: bare.readData(bc),\n }\n}\n\nexport function writeActorKvEntry(bc: bare.ByteCursor, x: ActorKvEntry): void {\n bare.writeData(bc, x.key)\n bare.writeData(bc, x.value)\n}\n\nfunction read0(bc: bare.ByteCursor): readonly string[] {\n const len = bare.readUintSafe(bc)\n if (len === 0) { return [] }\n const result = [bare.readString(bc)]\n for (let i = 1; i < len; i++) {\n result[i] = bare.readString(bc)\n }\n return result\n}\n\nfunction write0(bc: bare.ByteCursor, x: readonly string[]): void {\n bare.writeUintSafe(bc, x.length)\n for (let i = 0; i < x.length; i++) {\n bare.writeString(bc, x[i])\n }\n}\n\nfunction read1(bc: bare.ByteCursor): readonly ActorKvEntry[] {\n const len = bare.readUintSafe(bc)\n if (len === 0) { return [] }\n const result = [readActorKvEntry(bc)]\n for (let i = 1; i < len; i++) {\n result[i] = readActorKvEntry(bc)\n }\n return result\n}\n\nfunction write1(bc: bare.ByteCursor, x: readonly ActorKvEntry[]): void {\n bare.writeUintSafe(bc, x.length)\n for (let i = 0; i < x.length; i++) {\n writeActorKvEntry(bc, x[i])\n }\n}\n\nexport type ActorState = {\n readonly actorId: string,\n readonly name: string,\n readonly key: readonly string[],\n readonly kvStorage: readonly ActorKvEntry[],\n readonly createdAt: u64,\n}\n\nexport function readActorState(bc: bare.ByteCursor): ActorState {\n return {\n actorId: bare.readString(bc),\n name: bare.readString(bc),\n key: read0(bc),\n kvStorage: read1(bc),\n createdAt: bare.readU64(bc),\n }\n}\n\nexport function writeActorState(bc: bare.ByteCursor, x: ActorState): void {\n bare.writeString(bc, x.actorId)\n bare.writeString(bc, x.name)\n write0(bc, x.key)\n write1(bc, x.kvStorage)\n bare.writeU64(bc, x.createdAt)\n}\n\nexport function encodeActorState(x: ActorState): Uint8Array {\n const bc = new bare.ByteCursor(\n new Uint8Array(config.initialBufferLength),\n config\n )\n writeActorState(bc, x)\n return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset)\n}\n\nexport function decodeActorState(bytes: Uint8Array): ActorState {\n const bc = new bare.ByteCursor(bytes, config)\n const result = readActorState(bc)\n if (bc.offset < bc.view.byteLength) {\n throw new bare.BareError(bc.offset, \"remaining bytes\")\n }\n return result\n}\n\nexport type ActorAlarm = {\n readonly actorId: string,\n readonly timestamp: uint,\n}\n\nexport function readActorAlarm(bc: bare.ByteCursor): ActorAlarm {\n return {\n actorId: bare.readString(bc),\n timestamp: bare.readUint(bc),\n }\n}\n\nexport function writeActorAlarm(bc: bare.ByteCursor, x: ActorAlarm): void {\n bare.writeString(bc, x.actorId)\n bare.writeUint(bc, x.timestamp)\n}\n\nexport function encodeActorAlarm(x: ActorAlarm): Uint8Array {\n const bc = new bare.ByteCursor(\n new Uint8Array(config.initialBufferLength),\n config\n )\n writeActorAlarm(bc, x)\n return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset)\n}\n\nexport function decodeActorAlarm(bytes: Uint8Array): ActorAlarm {\n const bc = new bare.ByteCursor(bytes, config)\n const result = readActorAlarm(bc)\n if (bc.offset < bc.view.byteLength) {\n throw new bare.BareError(bc.offset, \"remaining bytes\")\n }\n return result\n}\n\n\nfunction assert(condition: boolean, message?: string): asserts condition {\n if (!condition) throw new Error(message ?? \"Assertion failed\")\n}\n","// @generated - post-processed by compile-bare.ts\nimport * as bare from \"@rivetkit/bare-ts\"\n\nconst config = /* @__PURE__ */ bare.Config({})\n\nexport type u64 = bigint\nexport type uint = bigint\n\nexport type ActorKvEntry = {\n readonly key: ArrayBuffer,\n readonly value: ArrayBuffer,\n}\n\nexport function readActorKvEntry(bc: bare.ByteCursor): ActorKvEntry {\n return {\n key: bare.readData(bc),\n value: bare.readData(bc),\n }\n}\n\nexport function writeActorKvEntry(bc: bare.ByteCursor, x: ActorKvEntry): void {\n bare.writeData(bc, x.key)\n bare.writeData(bc, x.value)\n}\n\nfunction read0(bc: bare.ByteCursor): readonly string[] {\n const len = bare.readUintSafe(bc)\n if (len === 0) { return [] }\n const result = [bare.readString(bc)]\n for (let i = 1; i < len; i++) {\n result[i] = bare.readString(bc)\n }\n return result\n}\n\nfunction write0(bc: bare.ByteCursor, x: readonly string[]): void {\n bare.writeUintSafe(bc, x.length)\n for (let i = 0; i < x.length; i++) {\n bare.writeString(bc, x[i])\n }\n}\n\nfunction read1(bc: bare.ByteCursor): readonly ActorKvEntry[] {\n const len = bare.readUintSafe(bc)\n if (len === 0) { return [] }\n const result = [readActorKvEntry(bc)]\n for (let i = 1; i < len; i++) {\n result[i] = readActorKvEntry(bc)\n }\n return result\n}\n\nfunction write1(bc: bare.ByteCursor, x: readonly ActorKvEntry[]): void {\n bare.writeUintSafe(bc, x.length)\n for (let i = 0; i < x.length; i++) {\n writeActorKvEntry(bc, x[i])\n }\n}\n\nfunction read2(bc: bare.ByteCursor): u64 | null {\n return bare.readBool(bc)\n ? bare.readU64(bc)\n : null\n}\n\nfunction write2(bc: bare.ByteCursor, x: u64 | null): void {\n bare.writeBool(bc, x !== null)\n if (x !== null) {\n bare.writeU64(bc, x)\n }\n}\n\nexport type ActorState = {\n readonly actorId: string,\n readonly name: string,\n readonly key: readonly string[],\n readonly kvStorage: readonly ActorKvEntry[],\n readonly createdAt: u64,\n readonly startTs: u64 | null,\n readonly connectableTs: u64 | null,\n readonly sleepTs: u64 | null,\n readonly destroyTs: u64 | null,\n}\n\nexport function readActorState(bc: bare.ByteCursor): ActorState {\n return {\n actorId: bare.readString(bc),\n name: bare.readString(bc),\n key: read0(bc),\n kvStorage: read1(bc),\n createdAt: bare.readU64(bc),\n startTs: read2(bc),\n connectableTs: read2(bc),\n sleepTs: read2(bc),\n destroyTs: read2(bc),\n }\n}\n\nexport function writeActorState(bc: bare.ByteCursor, x: ActorState): void {\n bare.writeString(bc, x.actorId)\n bare.writeString(bc, x.name)\n write0(bc, x.key)\n write1(bc, x.kvStorage)\n bare.writeU64(bc, x.createdAt)\n write2(bc, x.startTs)\n write2(bc, x.connectableTs)\n write2(bc, x.sleepTs)\n write2(bc, x.destroyTs)\n}\n\nexport function encodeActorState(x: ActorState): Uint8Array {\n const bc = new bare.ByteCursor(\n new Uint8Array(config.initialBufferLength),\n config\n )\n writeActorState(bc, x)\n return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset)\n}\n\nexport function decodeActorState(bytes: Uint8Array): ActorState {\n const bc = new bare.ByteCursor(bytes, config)\n const result = readActorState(bc)\n if (bc.offset < bc.view.byteLength) {\n throw new bare.BareError(bc.offset, \"remaining bytes\")\n }\n return result\n}\n\nexport type ActorAlarm = {\n readonly actorId: string,\n readonly timestamp: uint,\n}\n\nexport function readActorAlarm(bc: bare.ByteCursor): ActorAlarm {\n return {\n actorId: bare.readString(bc),\n timestamp: bare.readUint(bc),\n }\n}\n\nexport function writeActorAlarm(bc: bare.ByteCursor, x: ActorAlarm): void {\n bare.writeString(bc, x.actorId)\n bare.writeUint(bc, x.timestamp)\n}\n\nexport function encodeActorAlarm(x: ActorAlarm): Uint8Array {\n const bc = new bare.ByteCursor(\n new Uint8Array(config.initialBufferLength),\n config\n )\n writeActorAlarm(bc, x)\n return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset)\n}\n\nexport function decodeActorAlarm(bytes: Uint8Array): ActorAlarm {\n const bc = new bare.ByteCursor(bytes, config)\n const result = readActorAlarm(bc)\n if (bc.offset < bc.view.byteLength) {\n throw new bare.BareError(bc.offset, \"remaining bytes\")\n }\n return result\n}\n\n\nfunction assert(condition: boolean, message?: string): asserts condition {\n if (!condition) throw new Error(message ?? \"Assertion failed\")\n}\n","import { getLogger } from \"@/common/log\";\n\nexport function logger() {\n\treturn getLogger(\"driver-fs\");\n}\n","import type { ActorKey } from \"@/actor/mod\";\nimport {\n\tgetNodeCrypto,\n\tgetNodeFs,\n\tgetNodeFsSync,\n\tgetNodeOs,\n\tgetNodePath,\n} from \"@/utils/node\";\n\n/**\n * Generate a deterministic actor ID from name and key\n */\nexport function generateActorId(name: string, key: ActorKey): string {\n\t// Generate deterministic key string\n\tconst jsonString = JSON.stringify([name, key]);\n\n\t// Hash to ensure safe file system names\n\tconst crypto = getNodeCrypto();\n\tconst hash = crypto\n\t\t.createHash(\"sha256\")\n\t\t.update(jsonString)\n\t\t.digest(\"hex\")\n\t\t.substring(0, 16);\n\n\treturn hash;\n}\n\n/**\n * Create a hash for a path, normalizing it first\n */\nfunction createHashForPath(dirPath: string): string {\n\tconst path = getNodePath();\n\t// Normalize the path first\n\tconst normalizedPath = path.normalize(dirPath);\n\n\t// Extract the last path component for readability\n\tconst lastComponent = path.basename(normalizedPath);\n\n\t// Create SHA-256 hash\n\tconst crypto = getNodeCrypto();\n\tconst hash = crypto\n\t\t.createHash(\"sha256\")\n\t\t.update(normalizedPath)\n\t\t.digest(\"hex\")\n\t\t.substring(0, 8); // Take first 8 characters for brevity\n\n\treturn `${lastComponent}-${hash}`;\n}\n\n/**\n * Get the storage path for the current working directory or a specified path\n */\nexport function getStoragePath(): string {\n\tconst dataPath = getDataPath(\"rivetkit\");\n\tconst dirHash = createHashForPath(process.cwd());\n\tconst path = getNodePath();\n\treturn path.join(dataPath, dirHash);\n}\n\n/**\n * Check if a path exists\n */\nexport async function pathExists(path: string): Promise<boolean> {\n\ttry {\n\t\tconst fs = getNodeFs();\n\t\tawait fs.access(path);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Ensure a directory exists, creating it if necessary\n */\nexport async function ensureDirectoryExists(\n\tdirectoryPath: string,\n): Promise<void> {\n\tif (!(await pathExists(directoryPath))) {\n\t\tconst fs = getNodeFs();\n\t\tawait fs.mkdir(directoryPath, { recursive: true });\n\t}\n}\n\n/**\n * Ensure a directory exists synchronously - only used during initialization\n * All other operations use the async version\n */\nexport function ensureDirectoryExistsSync(directoryPath: string): void {\n\tconst fsSync = getNodeFsSync();\n\tif (!fsSync.existsSync(directoryPath)) {\n\t\tfsSync.mkdirSync(directoryPath, { recursive: true });\n\t}\n}\n\n/**\n * Returns platform-specific data directory\n */\nfunction getDataPath(appName: string): string {\n\tconst platform = process.platform;\n\tconst os = getNodeOs();\n\tconst homeDir = os.homedir();\n\tconst path = getNodePath();\n\n\tswitch (platform) {\n\t\tcase \"win32\":\n\t\t\treturn path.join(\n\t\t\t\tprocess.env.APPDATA || path.join(homeDir, \"AppData\", \"Roaming\"),\n\t\t\t\tappName,\n\t\t\t);\n\t\tcase \"darwin\":\n\t\t\treturn path.join(\n\t\t\t\thomeDir,\n\t\t\t\t\"Library\",\n\t\t\t\t\"Application Support\",\n\t\t\t\tappName,\n\t\t\t);\n\t\tdefault: // linux and others\n\t\t\treturn path.join(\n\t\t\t\tprocess.env.XDG_DATA_HOME ||\n\t\t\t\t\tpath.join(homeDir, \".local\", \"share\"),\n\t\t\t\tappName,\n\t\t\t);\n\t}\n}\n","import type { Context as HonoContext } from \"hono\";\nimport invariant from \"invariant\";\nimport { ActorStopping } from \"@/actor/errors\";\nimport { type ActorRouter, createActorRouter } from \"@/actor/router\";\nimport { routeWebSocket } from \"@/actor/router-websocket-endpoints\";\nimport { createClientWithDriver } from \"@/client/client\";\nimport { ClientConfigSchema } from \"@/client/config\";\nimport { createInlineWebSocket } from \"@/common/inline-websocket-adapter\";\nimport { noopNext } from \"@/common/utils\";\nimport type {\n\tActorDriver,\n\tActorOutput,\n\tCreateInput,\n\tGetForIdInput,\n\tGetOrCreateWithKeyInput,\n\tGetWithKeyInput,\n\tListActorsInput,\n\tManagerDriver,\n} from \"@/driver-helpers/mod\";\nimport type { ManagerDisplayInformation } from \"@/manager/driver\";\nimport type { Encoding, UniversalWebSocket } from \"@/mod\";\nimport type { DriverConfig, RegistryConfig } from \"@/registry/config\";\nimport type * as schema from \"@/schemas/file-system-driver/mod\";\nimport type { GetUpgradeWebSocket } from \"@/utils\";\nimport type { FileSystemGlobalState } from \"./global-state\";\nimport { logger } from \"./log\";\nimport { generateActorId } from \"./utils\";\n\nexport class FileSystemManagerDriver implements ManagerDriver {\n\t#config: RegistryConfig;\n\t#state: FileSystemGlobalState;\n\t#driverConfig: DriverConfig;\n\t#getUpgradeWebSocket: GetUpgradeWebSocket | undefined;\n\n\t#actorDriver: ActorDriver;\n\t#actorRouter: ActorRouter;\n\n\tconstructor(\n\t\tconfig: RegistryConfig,\n\t\tstate: FileSystemGlobalState,\n\t\tdriverConfig: DriverConfig,\n\t) {\n\t\tthis.#config = config;\n\t\tthis.#state = state;\n\t\tthis.#driverConfig = driverConfig;\n\n\t\t// Actors run on the same node as the manager, so we create a dummy actor router that we route requests to\n\t\tconst inlineClient = createClientWithDriver(this);\n\n\t\tthis.#actorDriver = this.#driverConfig.actor(\n\t\t\tconfig,\n\t\t\tthis,\n\t\t\tinlineClient,\n\t\t);\n\t\tthis.#actorRouter = createActorRouter(\n\t\t\tthis.#config,\n\t\t\tthis.#actorDriver,\n\t\t\tundefined,\n\t\t\tconfig.test.enabled,\n\t\t);\n\t}\n\n\tasync sendRequest(\n\t\tactorId: string,\n\t\tactorRequest: Request,\n\t): Promise<Response> {\n\t\treturn await this.#actorRouter.fetch(actorRequest, {\n\t\t\tactorId,\n\t\t});\n\t}\n\n\tasync openWebSocket(\n\t\tpath: string,\n\t\tactorId: string,\n\t\tencoding: Encoding,\n\t\tparams: unknown,\n\t): Promise<UniversalWebSocket> {\n\t\t// Normalize the path (add leading slash if needed) but preserve query params\n\t\tconst normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n\n\t\t// Create a fake request with the full URL including query parameters\n\t\tconst fakeUrl = `http://inline-actor${normalizedPath}`;\n\t\tconst fakeRequest = new Request(fakeUrl, {\n\t\t\tmethod: \"GET\",\n\t\t});\n\n\t\t// Extract just the pathname for routing (without query params)\n\t\tconst pathOnly = normalizedPath.split(\"?\")[0];\n\n\t\tconst wsHandler = await routeWebSocket(\n\t\t\tfakeRequest,\n\t\t\tpathOnly,\n\t\t\t{},\n\t\t\tthis.#config,\n\t\t\tthis.#actorDriver,\n\t\t\tactorId,\n\t\t\tencoding,\n\t\t\tparams,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t);\n\t\treturn createInlineWebSocket(wsHandler);\n\t}\n\n\tasync proxyRequest(\n\t\tc: HonoContext,\n\t\tactorRequest: Request,\n\t\tactorId: string,\n\t): Promise<Response> {\n\t\treturn await this.#actorRouter.fetch(actorRequest, {\n\t\t\tactorId,\n\t\t});\n\t}\n\n\tasync proxyWebSocket(\n\t\tc: HonoContext,\n\t\tpath: string,\n\t\tactorId: string,\n\t\tencoding: Encoding,\n\t\tparams: unknown,\n\t): Promise<Response> {\n\t\tconst upgradeWebSocket = this.#getUpgradeWebSocket?.();\n\t\tinvariant(upgradeWebSocket, \"missing getUpgradeWebSocket\");\n\n\t\t// Handle raw WebSocket paths\n\t\tconst pathOnly = path.split(\"?\")[0];\n\t\tconst normalizedPath = pathOnly.startsWith(\"/\")\n\t\t\t? pathOnly\n\t\t\t: `/${pathOnly}`;\n\t\tconst wsHandler = await routeWebSocket(\n\t\t\t// TODO: Create new request with new path\n\t\t\tc.req.raw,\n\t\t\tnormalizedPath,\n\t\t\tc.req.header(),\n\t\t\tthis.#config,\n\t\t\tthis.#actorDriver,\n\t\t\tactorId,\n\t\t\tencoding,\n\t\t\tparams,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t);\n\t\treturn upgradeWebSocket(() => wsHandler)(c, noopNext());\n\t}\n\n\tasync buildGatewayUrl(actorId: string): Promise<string> {\n\t\tconst port = this.#config.managerPort ?? 6420;\n\t\treturn `http://127.0.0.1:${port}/gateway/${encodeURIComponent(actorId)}`;\n\t}\n\n\tasync getForId({\n\t\tactorId,\n\t}: GetForIdInput): Promise<ActorOutput | undefined> {\n\t\t// Validate the actor exists\n\t\tconst actor = await this.#state.loadActor(actorId);\n\t\tif (!actor.state) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (this.#state.isActorStopping(actorId)) {\n\t\t\tthrow new ActorStopping(actorId);\n\t\t}\n\n\t\treturn actorStateToOutput(actor.state);\n\t}\n\n\tasync getWithKey({\n\t\tname,\n\t\tkey,\n\t}: GetWithKeyInput): Promise<ActorOutput | undefined> {\n\t\t// Generate the deterministic actor ID\n\t\tconst actorId = generateActorId(name, key);\n\n\t\t// Check if actor exists\n\t\tconst actor = await this.#state.loadActor(actorId);\n\t\tif (actor.state) {\n\t\t\treturn actorStateToOutput(actor.state);\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync getOrCreateWithKey(\n\t\tinput: GetOrCreateWithKeyInput,\n\t): Promise<ActorOutput> {\n\t\t// Generate the deterministic actor ID\n\t\tconst actorId = generateActorId(input.name, input.key);\n\n\t\t// Use the atomic getOrCreateActor method\n\t\tawait this.#state.loadOrCreateActor(\n\t\t\tactorId,\n\t\t\tinput.name,\n\t\t\tinput.key,\n\t\t\tinput.input,\n\t\t);\n\n\t\t// Start the actor immediately so timestamps are set\n\t\tawait this.#actorDriver.loadActor(actorId);\n\n\t\t// Reload state to get updated timestamps\n\t\tconst state = await this.#state.loadActorStateOrError(actorId);\n\t\treturn actorStateToOutput(state);\n\t}\n\n\tasync createActor({ name, key, input }: CreateInput): Promise<ActorOutput> {\n\t\t// Generate the deterministic actor ID\n\t\tconst actorId = generateActorId(name, key);\n\n\t\tawait this.#state.createActor(actorId, name, key, input);\n\n\t\t// Start the actor immediately so timestamps are set\n\t\tawait this.#actorDriver.loadActor(actorId);\n\n\t\t// Reload state to get updated timestamps\n\t\tconst state = await this.#state.loadActorStateOrError(actorId);\n\t\treturn actorStateToOutput(state);\n\t}\n\n\tasync listActors({ name }: ListActorsInput): Promise<ActorOutput[]> {\n\t\tconst actors: ActorOutput[] = [];\n\t\tconst itr = this.#state.getActorsIterator({});\n\n\t\tfor await (const actor of itr) {\n\t\t\tif (actor.name === name) {\n\t\t\t\tactors.push(actorStateToOutput(actor));\n\t\t\t}\n\t\t}\n\n\t\t// Sort by create ts desc (most recent first)\n\t\tactors.sort((a, b) => {\n\t\t\tconst aTs = a.createTs ?? 0;\n\t\t\tconst bTs = b.createTs ?? 0;\n\t\t\treturn bTs - aTs;\n\t\t});\n\n\t\treturn actors;\n\t}\n\n\tasync kvGet(actorId: string, key: Uint8Array): Promise<string | null> {\n\t\tconst response = await this.#state.kvBatchGet(actorId, [key]);\n\t\treturn response[0] !== null\n\t\t\t? new TextDecoder().decode(response[0])\n\t\t\t: null;\n\t}\n\n\tdisplayInformation(): ManagerDisplayInformation {\n\t\treturn {\n\t\t\tproperties: {\n\t\t\t\t...(this.#state.persist\n\t\t\t\t\t? { Data: this.#state.storagePath }\n\t\t\t\t\t: {}),\n\t\t\t\tInstances: this.#state.actorCountOnStartup.toString(),\n\t\t\t},\n\t\t};\n\t}\n\n\textraStartupLog() {\n\t\treturn {\n\t\t\tinstances: this.#state.actorCountOnStartup,\n\t\t\tdata: this.#state.storagePath,\n\t\t};\n\t}\n\n\tsetGetUpgradeWebSocket(getUpgradeWebSocket: GetUpgradeWebSocket): void {\n\t\tthis.#getUpgradeWebSocket = getUpgradeWebSocket;\n\t}\n}\n\nfunction actorStateToOutput(state: schema.ActorState): ActorOutput {\n\treturn {\n\t\tactorId: state.actorId,\n\t\tname: state.name,\n\t\tkey: state.key as string[],\n\t\tcreateTs: Number(state.createdAt),\n\t\tstartTs: state.startTs !== null ? Number(state.startTs) : null,\n\t\tconnectableTs:\n\t\t\tstate.connectableTs !== null ? Number(state.connectableTs) : null,\n\t\tsleepTs: state.sleepTs !== null ? Number(state.sleepTs) : null,\n\t\tdestroyTs: state.destroyTs !== null ? Number(state.destroyTs) : null,\n\t};\n}\n","import { importNodeDependencies } from \"@/utils/node\";\nimport { FileSystemActorDriver } from \"./actor\";\nimport { FileSystemGlobalState } from \"./global-state\";\nimport { FileSystemManagerDriver } from \"./manager\";\nimport { DriverConfig } from \"@/registry/config\";\n\nexport { FileSystemActorDriver } from \"./actor\";\nexport { FileSystemGlobalState } from \"./global-state\";\nexport { FileSystemManagerDriver } from \"./manager\";\nexport { getStoragePath } from \"./utils\";\n\nexport function createFileSystemOrMemoryDriver(\n\tpersist: boolean = true,\n\tcustomPath?: string,\n): DriverConfig {\n\timportNodeDependencies();\n\n\tconst state = new FileSystemGlobalState(persist, customPath);\n\tconst driverConfig: DriverConfig = {\n\t\tname: persist ? \"file-system\" : \"memory\",\n\t\tdisplayName: persist ? \"File System\" : \"Memory\",\n\t\tmanager: (config) =>\n\t\t\tnew FileSystemManagerDriver(\n\t\t\t\tconfig,\n\t\t\t\tstate,\n\t\t\t\tdriverConfig,\n\t\t\t),\n\t\tactor: (config, managerDriver, inlineClient) => {\n\t\t\tconst actorDriver = new FileSystemActorDriver(\n\t\t\t\tconfig,\n\t\t\t\tmanagerDriver,\n\t\t\t\tinlineClient,\n\t\t\t\tstate,\n\t\t\t);\n\n\t\t\tstate.onRunnerStart(\n\t\t\t\tconfig,\n\t\t\t\tinlineClient,\n\t\t\t\tactorDriver,\n\t\t\t);\n\n\t\t\treturn actorDriver;\n\t\t},\n\t\tautoStartActorDriver: true,\n\t};\n\treturn driverConfig;\n}\n\nexport function createFileSystemDriver(opts?: { path?: string }): DriverConfig {\n\treturn createFileSystemOrMemoryDriver(true, opts?.path);\n}\n\nexport function createMemoryDriver(): DriverConfig {\n\treturn createFileSystemOrMemoryDriver(false);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/rivet/rivet/rivetkit-typescript/packages/rivetkit/dist/tsup/chunk-HZOBB3KP.cjs","../../src/utils/env-vars.ts","../../src/common/utils.ts","../../package.json","../../src/common/log.ts","../../src/common/log-levels.ts","../../src/common/logfmt.ts","../../src/utils.ts"],"names":["logger","VERSION"],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACEO,IAAM,eAAA,EAAiB,CAAA,EAAA,GAC7B,eAAA,CAAgB,cAAc,CAAA;AACxB,IAAM,iBAAA,EAAmB,CAAA,EAAA,GAC/B,eAAA,CAAgB,gBAAgB,CAAA;AAC1B,IAAM,cAAA,EAAgB,CAAA,EAAA,GAC5B,eAAA,CAAgB,aAAa,CAAA;AACvB,IAAM,kBAAA,EAAoB,CAAA,EAAA,GAChC,eAAA,CAAgB,iBAAiB,CAAA;AAC3B,IAAM,eAAA,EAAiB,CAAA,EAAA,GAC7B,eAAA,CAAgB,cAAc,CAAA;AACxB,IAAM,mBAAA,EAAqB,CAAA,EAAA,GAA0B;AAC3D,EAAA,MAAM,MAAA,EAAQ,eAAA,CAAgB,mBAAmB,CAAA;AACjD,EAAA,OAAO,MAAA,IAAU,KAAA,EAAA,E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AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/rivet/rivet/rivetkit-typescript/packages/rivetkit/dist/tsup/chunk-HZOBB3KP.cjs","sourcesContent":[null,"// This file consolidates all environment variables that affect RivetKit's behavior.\n//\n// IMPORTANT: When adding or modifying environment variables here, also update the\n// documentation at: docs/general/registry-configuration.mdx\n\nimport { getEnvUniversal } from \"@/utils\";\n\n// Rivet configuration\nexport const getRivetEngine = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_ENGINE\");\nexport const getRivetEndpoint = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_ENDPOINT\");\nexport const getRivetToken = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_TOKEN\");\nexport const getRivetNamespace = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_NAMESPACE\");\nexport const getRivetRunner = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_RUNNER\");\nexport const getRivetTotalSlots = (): number | undefined => {\n\tconst value = getEnvUniversal(\"RIVET_TOTAL_SLOTS\");\n\treturn value !== undefined ? parseInt(value, 10) : undefined;\n};\nexport const getRivetRunnerKey = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_RUNNER_KEY\");\nexport const getRivetRunEngine = (): boolean =>\n\tgetEnvUniversal(\"RIVET_RUN_ENGINE\") === \"1\";\nexport const getRivetRunEngineVersion = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_RUN_ENGINE_VERSION\");\nexport const getRivetRunnerKind = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_RUNNER_KIND\");\nexport const getRivetRunnerVersion = (): number | undefined => {\n\tconst value = getEnvUniversal(\"RIVET_RUNNER_VERSION\");\n\treturn value !== undefined ? parseInt(value, 10) : undefined;\n};\nexport const getRivetPublicEndpoint = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_PUBLIC_ENDPOINT\");\nexport const getRivetPublicToken = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_PUBLIC_TOKEN\");\n// There is no RIVET_PUBLIC_NAMESPACE because the frontend and backend cannot\n// use different namespaces\n\n// RivetKit configuration\nexport const getRivetkitInspectorToken = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_INSPECTOR_TOKEN\");\nexport const getRivetkitInspectorDisable = (): boolean =>\n\tgetEnvUniversal(\"RIVET_INSPECTOR_DISABLE\") === \"1\";\n\n// Logging configuration\n// DEPRECATED: LOG_LEVEL will be removed in a future version\nexport const getLogLevel = (): string | undefined =>\n\tgetEnvUniversal(\"RIVET_LOG_LEVEL\") ?? getEnvUniversal(\"LOG_LEVEL\");\nexport const getLogTarget = (): boolean =>\n\tgetEnvUniversal(\"RIVET_LOG_TARGET\") === \"1\";\nexport const getLogTimestamp = (): boolean =>\n\tgetEnvUniversal(\"RIVET_LOG_TIMESTAMP\") === \"1\";\nexport const getLogMessage = (): boolean =>\n\tgetEnvUniversal(\"RIVET_LOG_MESSAGE\") === \"1\";\nexport const getLogErrorStack = (): boolean =>\n\tgetEnvUniversal(\"RIVET_LOG_ERROR_STACK\") === \"1\";\nexport const getLogHeaders = (): boolean =>\n\tgetEnvUniversal(\"RIVET_LOG_HEADERS\") === \"1\";\n\n// Environment configuration\nexport const getNodeEnv = (): string | undefined => getEnvUniversal(\"NODE_ENV\");\nexport const getNextPhase = (): string | undefined =>\n\tgetEnvUniversal(\"NEXT_PHASE\");\nexport const isDev = (): boolean => getNodeEnv() !== \"production\";\n","import type { Next } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\nimport * as errors from \"@/actor/errors\";\nimport { EXTRA_ERROR_LOG, VERSION } from \"@/utils\";\nimport { getLogErrorStack } from \"@/utils/env-vars\";\nimport type { Logger } from \"./log\";\n\nexport function assertUnreachable(x: never): never {\n\tthrow new Error(`Unreachable case: ${x}`);\n}\n\n/**\n * Safely stringifies an object, ensuring that the stringified object is under a certain size.\n * @param obj any object to stringify\n * @param maxSize maximum size of the stringified object in bytes\n * @returns stringified object\n */\nexport function safeStringify(obj: unknown, maxSize: number) {\n\tlet size = 0;\n\n\tfunction replacer(key: string, value: unknown) {\n\t\tif (value === null || value === undefined) return value;\n\t\tconst valueSize =\n\t\t\ttypeof value === \"string\"\n\t\t\t\t? value.length\n\t\t\t\t: JSON.stringify(value).length;\n\t\tsize += key.length + valueSize;\n\n\t\tif (size > maxSize) {\n\t\t\tthrow new Error(\n\t\t\t\t`JSON object exceeds size limit of ${maxSize} bytes.`,\n\t\t\t);\n\t\t}\n\n\t\treturn value;\n\t}\n\n\treturn JSON.stringify(obj, replacer);\n}\n\n// TODO: Instead of doing this, use a temp var for state and attempt to write\n// it. Roll back state if fails to serialize.\n\n/**\n * Check if a value is CBOR serializable.\n * Optionally pass an onInvalid callback to receive the path to invalid values.\n *\n * For a complete list of supported CBOR tags, see:\n * https://github.com/kriszyp/cbor-x/blob/cc1cf9df8ba72288c7842af1dd374d73e34cdbc1/README.md#list-of-supported-tags-for-decoding\n */\nexport function isCborSerializable(\n\tvalue: unknown,\n\tonInvalid?: (path: string) => void,\n\tcurrentPath = \"\",\n): boolean {\n\t// Handle primitive types directly\n\tif (value === null || value === undefined) {\n\t\treturn true;\n\t}\n\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tonInvalid?.(currentPath);\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tif (typeof value === \"boolean\" || typeof value === \"string\") {\n\t\treturn true;\n\t}\n\n\t// Handle BigInt (CBOR tags 2 and 3)\n\tif (typeof value === \"bigint\") {\n\t\treturn true;\n\t}\n\n\t// Handle Date objects (CBOR tags 0 and 1)\n\tif (value instanceof Date) {\n\t\treturn true;\n\t}\n\n\t// Handle typed arrays (CBOR tags 64-82)\n\tif (\n\t\tvalue instanceof Uint8Array ||\n\t\tvalue instanceof Uint8ClampedArray ||\n\t\tvalue instanceof Uint16Array ||\n\t\tvalue instanceof Uint32Array ||\n\t\tvalue instanceof BigUint64Array ||\n\t\tvalue instanceof Int8Array ||\n\t\tvalue instanceof Int16Array ||\n\t\tvalue instanceof Int32Array ||\n\t\tvalue instanceof BigInt64Array ||\n\t\tvalue instanceof Float32Array ||\n\t\tvalue instanceof Float64Array\n\t) {\n\t\treturn true;\n\t}\n\n\t// Handle Map (CBOR tag 259)\n\tif (value instanceof Map) {\n\t\tfor (const [key, val] of value.entries()) {\n\t\t\tconst keyPath = currentPath\n\t\t\t\t? `${currentPath}.key(${String(key)})`\n\t\t\t\t: `key(${String(key)})`;\n\t\t\tconst valPath = currentPath\n\t\t\t\t? `${currentPath}.value(${String(key)})`\n\t\t\t\t: `value(${String(key)})`;\n\t\t\tif (\n\t\t\t\t!isCborSerializable(key, onInvalid, keyPath) ||\n\t\t\t\t!isCborSerializable(val, onInvalid, valPath)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Handle Set (CBOR tag 258)\n\tif (value instanceof Set) {\n\t\tlet index = 0;\n\t\tfor (const item of value.values()) {\n\t\t\tconst itemPath = currentPath\n\t\t\t\t? `${currentPath}.set[${index}]`\n\t\t\t\t: `set[${index}]`;\n\t\t\tif (!isCborSerializable(item, onInvalid, itemPath)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Handle RegExp (CBOR tag 27)\n\tif (value instanceof RegExp) {\n\t\treturn true;\n\t}\n\n\t// Handle Error objects (CBOR tag 27)\n\tif (value instanceof Error) {\n\t\treturn true;\n\t}\n\n\t// Handle arrays\n\tif (Array.isArray(value)) {\n\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\tconst itemPath = currentPath ? `${currentPath}[${i}]` : `[${i}]`;\n\t\t\tif (!isCborSerializable(value[i], onInvalid, itemPath)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Handle plain objects and records (CBOR tags 105, 51, 57344-57599)\n\tif (typeof value === \"object\") {\n\t\t// Allow plain objects and objects with prototypes (for records and named objects)\n\t\tconst proto = Object.getPrototypeOf(value);\n\t\tif (proto !== null && proto !== Object.prototype) {\n\t\t\t// Check if it's a known serializable object type\n\t\t\tconst protoConstructor = value.constructor;\n\t\t\tif (protoConstructor && typeof protoConstructor.name === \"string\") {\n\t\t\t\t// Allow objects with named constructors (records, named objects)\n\t\t\t\t// This includes user-defined classes and built-in objects\n\t\t\t\t// that CBOR can serialize with tag 27 or record tags\n\t\t\t}\n\t\t}\n\n\t\t// Check all properties recursively\n\t\tfor (const key in value) {\n\t\t\tconst propPath = currentPath ? `${currentPath}.${key}` : key;\n\t\t\tif (\n\t\t\t\t!isCborSerializable(\n\t\t\t\t\tvalue[key as keyof typeof value],\n\t\t\t\t\tonInvalid,\n\t\t\t\t\tpropPath,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Not serializable\n\tonInvalid?.(currentPath);\n\treturn false;\n}\n\nexport interface DeconstructedError {\n\t__type: \"ActorError\";\n\tstatusCode: ContentfulStatusCode;\n\tpublic: boolean;\n\tgroup: string;\n\tcode: string;\n\tmessage: string;\n\tmetadata?: unknown;\n}\n\n/** Deconstructs error in to components that are used to build responses. */\nexport function deconstructError(\n\terror: unknown,\n\tlogger: Logger,\n\textraLog: Record<string, unknown>,\n\texposeInternalError = false,\n): DeconstructedError {\n\t// Build response error information. Only return errors if flagged as public in order to prevent leaking internal behavior.\n\t//\n\t// We log the error here instead of after generating the code & message because we need to log the original error, not the masked internal error.\n\tlet statusCode: ContentfulStatusCode;\n\tlet public_: boolean;\n\tlet group: string;\n\tlet code: string;\n\tlet message: string;\n\tlet metadata: unknown;\n\tif (errors.ActorError.isActorError(error) && error.public) {\n\t\t// Check if error has statusCode (could be ActorError instance or DeconstructedError)\n\t\tstatusCode = (\n\t\t\t\"statusCode\" in error && error.statusCode ? error.statusCode : 400\n\t\t) as ContentfulStatusCode;\n\t\tpublic_ = true;\n\t\tgroup = error.group;\n\t\tcode = error.code;\n\t\tmessage = getErrorMessage(error);\n\t\tmetadata = error.metadata;\n\n\t\tlogger.info({\n\t\t\tmsg: \"public error\",\n\t\t\tgroup,\n\t\t\tcode,\n\t\t\tmessage,\n\t\t\t...EXTRA_ERROR_LOG,\n\t\t\t...extraLog,\n\t\t});\n\t} else if (exposeInternalError) {\n\t\tif (errors.ActorError.isActorError(error)) {\n\t\t\tstatusCode = 500;\n\t\t\tpublic_ = false;\n\t\t\tgroup = error.group;\n\t\t\tcode = error.code;\n\t\t\tmessage = getErrorMessage(error);\n\t\t\tmetadata = error.metadata;\n\n\t\t\tlogger.info({\n\t\t\t\tmsg: \"internal error\",\n\t\t\t\tgroup,\n\t\t\t\tcode,\n\t\t\t\tmessage,\n\t\t\t\tstack: (error as Error)?.stack,\n\t\t\t\t...EXTRA_ERROR_LOG,\n\t\t\t\t...extraLog,\n\t\t\t});\n\t\t} else {\n\t\t\tstatusCode = 500;\n\t\t\tpublic_ = false;\n\t\t\tgroup = \"internal\";\n\t\t\tcode = errors.INTERNAL_ERROR_CODE;\n\t\t\tmessage = getErrorMessage(error);\n\n\t\t\tlogger.info({\n\t\t\t\tmsg: \"internal error\",\n\t\t\t\tgroup,\n\t\t\t\tcode,\n\t\t\t\tmessage,\n\t\t\t\tstack: (error as Error)?.stack,\n\t\t\t\t...EXTRA_ERROR_LOG,\n\t\t\t\t...extraLog,\n\t\t\t});\n\t\t}\n\t} else {\n\t\tstatusCode = 500;\n\t\tpublic_ = false;\n\t\tgroup = \"internal\";\n\t\tcode = errors.INTERNAL_ERROR_CODE;\n\t\tmessage = errors.INTERNAL_ERROR_DESCRIPTION;\n\t\tmetadata = {\n\t\t\t//url: `https://hub.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,\n\t\t} satisfies errors.InternalErrorMetadata;\n\n\t\tlogger.warn({\n\t\t\tmsg: \"internal error\",\n\t\t\terror: getErrorMessage(error),\n\t\t\tstack: (error as Error)?.stack,\n\t\t\t...EXTRA_ERROR_LOG,\n\t\t\t...extraLog,\n\t\t});\n\t}\n\n\treturn {\n\t\t__type: \"ActorError\",\n\t\tstatusCode,\n\t\tpublic: public_,\n\t\tgroup,\n\t\tcode,\n\t\tmessage,\n\t\tmetadata,\n\t};\n}\n\nexport function stringifyError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tif (\n\t\t\ttypeof process !== \"undefined\" &&\n\t\t\tgetLogErrorStack()\n\t\t) {\n\t\t\treturn `${error.name}: ${error.message}${error.stack ? `\\n${error.stack}` : \"\"}`;\n\t\t} else {\n\t\t\treturn `${error.name}: ${error.message}`;\n\t\t}\n\t} else if (typeof error === \"string\") {\n\t\treturn error;\n\t} else if (typeof error === \"object\" && error !== null) {\n\t\ttry {\n\t\t\treturn `${JSON.stringify(error)}`;\n\t\t} catch {\n\t\t\treturn \"[cannot stringify error]\";\n\t\t}\n\t} else {\n\t\treturn `Unknown error: ${getErrorMessage(error)}`;\n\t}\n}\n\nfunction getErrorMessage(err: unknown): string {\n\tif (\n\t\terr &&\n\t\ttypeof err === \"object\" &&\n\t\t\"message\" in err &&\n\t\ttypeof err.message === \"string\"\n\t) {\n\t\treturn err.message;\n\t} else {\n\t\treturn String(err);\n\t}\n}\n\n/** Generates a `Next` handler to pass to middleware in order to be able to call arbitrary middleware. */\nexport function noopNext(): Next {\n\treturn async () => {};\n}\n","{\n\t\"name\": \"rivetkit\",\n\t\"version\": \"2.0.40\",\n\t\"description\": \"Lightweight libraries for building stateful actors on edge platforms\",\n\t\"license\": \"Apache-2.0\",\n\t\"keywords\": [\n\t\t\"rivetkit\",\n\t\t\"stateful\",\n\t\t\"serverless\",\n\t\t\"actors\",\n\t\t\"agents\",\n\t\t\"realtime\",\n\t\t\"websocket\",\n\t\t\"actors\",\n\t\t\"framework\"\n\t],\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"src\",\n\t\t\"deno.json\",\n\t\t\"bun.json\",\n\t\t\"package.json\"\n\t],\n\t\"type\": \"module\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/mod.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/mod.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/mod.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/mod.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./client\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/client/mod.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/client/mod.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/client/mod.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/client/mod.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./log\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/common/log.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/common/log.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/common/log.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/common/log.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./errors\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/actor/errors.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/actor/errors.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/actor/errors.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/actor/errors.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./utils\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/utils.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/utils.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/utils.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/utils.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./driver-helpers\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/driver-helpers/mod.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/driver-helpers/mod.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/driver-helpers/mod.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/driver-helpers/mod.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./driver-helpers/websocket\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/common/websocket.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/common/websocket.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/common/websocket.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/common/websocket.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./driver-test-suite\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/driver-test-suite/mod.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/driver-test-suite/mod.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/driver-test-suite/mod.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/driver-test-suite/mod.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./topologies/coordinate\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/topologies/coordinate/mod.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/topologies/coordinate/mod.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/topologies/coordinate/mod.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/topologies/coordinate/mod.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./topologies/partition\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/topologies/partition/mod.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/topologies/partition/mod.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/topologies/partition/mod.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/topologies/partition/mod.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./test\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/test/mod.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/test/mod.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/test/mod.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/test/mod.cjs\"\n\t\t\t}\n\t\t},\n\t\t\"./inspector\": {\n\t\t\t\"import\": {\n\t\t\t\t\"types\": \"./dist/tsup/inspector/mod.d.ts\",\n\t\t\t\t\"default\": \"./dist/tsup/inspector/mod.js\"\n\t\t\t},\n\t\t\t\"require\": {\n\t\t\t\t\"types\": \"./dist/tsup/inspector/mod.d.cts\",\n\t\t\t\t\"default\": \"./dist/tsup/inspector/mod.cjs\"\n\t\t\t}\n\t\t}\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=22.0.0\"\n\t},\n\t\"sideEffects\": [\n\t\t\"./dist/tsup/chunk-*.js\",\n\t\t\"./dist/tsup/chunk-*.cjs\"\n\t],\n\t\"scripts\": {\n\t\t\"build\": \"tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/topologies/coordinate/mod.ts src/topologies/partition/mod.ts src/utils.ts src/driver-helpers/mod.ts src/driver-test-suite/mod.ts src/test/mod.ts src/inspector/mod.ts\",\n\t\t\"build:schema\": \"./scripts/compile-bare.ts compile schemas/client-protocol/v1.bare -o dist/schemas/client-protocol/v1.ts && ./scripts/compile-bare.ts compile schemas/client-protocol/v2.bare -o dist/schemas/client-protocol/v2.ts && ./scripts/compile-bare.ts compile schemas/file-system-driver/v1.bare -o dist/schemas/file-system-driver/v1.ts && ./scripts/compile-bare.ts compile schemas/file-system-driver/v2.bare -o dist/schemas/file-system-driver/v2.ts && ./scripts/compile-bare.ts compile schemas/file-system-driver/v3.bare -o dist/schemas/file-system-driver/v3.ts && ./scripts/compile-bare.ts compile schemas/actor-persist/v1.bare -o dist/schemas/actor-persist/v1.ts && ./scripts/compile-bare.ts compile schemas/actor-persist/v2.bare -o dist/schemas/actor-persist/v2.ts && ./scripts/compile-bare.ts compile schemas/actor-persist/v3.bare -o dist/schemas/actor-persist/v3.ts && ./scripts/compile-bare.ts compile schemas/actor-inspector/v1.bare -o dist/schemas/actor-inspector/v1.ts\",\n\t\t\"check-types\": \"tsc --noEmit\",\n\t\t\"lint\": \"biome check .\",\n\t\t\"lint:fix\": \"biome check --write .\",\n\t\t\"format\": \"biome format .\",\n\t\t\"format:write\": \"biome format --write .\",\n\t\t\"test\": \"vitest run\",\n\t\t\"test:watch\": \"vitest\",\n\t\t\"manager-openapi-gen\": \"tsx scripts/manager-openapi-gen.ts\",\n\t\t\"dump-asyncapi\": \"tsx scripts/dump-asyncapi.ts\",\n\t\t\"registry-config-schema-gen\": \"tsx scripts/registry-config-schema-gen.ts\",\n\t\t\"actor-config-schema-gen\": \"tsx scripts/actor-config-schema-gen.ts\"\n\t},\n\t\"dependencies\": {\n\t\t\"@hono/standard-validator\": \"^0.1.3\",\n\t\t\"@hono/zod-openapi\": \"^1.1.5\",\n\t\t\"@rivetkit/bare-ts\": \"^0.6.2\",\n\t\t\"@rivetkit/engine-runner\": \"workspace:*\",\n\t\t\"@rivetkit/fast-json-patch\": \"^3.1.2\",\n\t\t\"@rivetkit/on-change\": \"^6.0.2-rc.1\",\n\t\t\"@rivetkit/virtual-websocket\": \"workspace:*\",\n\t\t\"cbor-x\": \"^1.6.0\",\n\t\t\"get-port\": \"^7.1.0\",\n\t\t\"hono\": \"^4.7.0\",\n\t\t\"invariant\": \"^2.2.4\",\n\t\t\"nanoevents\": \"^9.1.0\",\n\t\t\"p-retry\": \"^6.2.1\",\n\t\t\"pino\": \"^9.5.0\",\n\t\t\"uuid\": \"^12.0.0\",\n\t\t\"vbare\": \"^0.0.4\",\n\t\t\"zod\": \"^4.1.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@bare-ts/tools\": \"^0.13.0\",\n\t\t\"@biomejs/biome\": \"^2.2.3\",\n\t\t\"@hono/node-server\": \"^1.18.2\",\n\t\t\"@hono/node-ws\": \"^1.1.1\",\n\t\t\"@types/invariant\": \"^2\",\n\t\t\"@types/node\": \"^22.13.1\",\n\t\t\"@types/ws\": \"^8\",\n\t\t\"@vitest/ui\": \"3.1.1\",\n\t\t\"commander\": \"^12.1.0\",\n\t\t\"eventsource\": \"^4.0.0\",\n\t\t\"local-pkg\": \"^0.5.1\",\n\t\t\"tsup\": \"^8.4.0\",\n\t\t\"tsx\": \"^4.19.4\",\n\t\t\"typescript\": \"^5.7.3\",\n\t\t\"vite-tsconfig-paths\": \"^5.1.4\",\n\t\t\"vitest\": \"^3.1.1\",\n\t\t\"ws\": \"^8.18.1\",\n\t\t\"zod-to-json-schema\": \"^3.25.0\"\n\t},\n\t\"peerDependencies\": {\n\t\t\"@hono/node-server\": \"^1.14.0\",\n\t\t\"@hono/node-ws\": \"^1.1.1\",\n\t\t\"eventsource\": \"^4.0.0\",\n\t\t\"ws\": \"^8.0.0\"\n\t},\n\t\"peerDependenciesMeta\": {\n\t\t\"@hono/node-server\": {\n\t\t\t\"optional\": true\n\t\t},\n\t\t\"@hono/node-ws\": {\n\t\t\t\"optional\": true\n\t\t},\n\t\t\"eventsource\": {\n\t\t\t\"optional\": true\n\t\t},\n\t\t\"ws\": {\n\t\t\t\"optional\": true\n\t\t}\n\t},\n\t\"stableVersion\": \"0.8.0\"\n}\n","import {\n\ttype LevelWithSilent,\n\ttype Logger,\n\tpino,\n\tstdTimeFunctions,\n} from \"pino\";\nimport { z } from \"zod\";\nimport { getLogLevel, getLogTarget, getLogTimestamp } from \"@/utils/env-vars\";\nimport {\n\tcastToLogValue,\n\tformatTimestamp,\n\tLOGGER_CONFIG,\n\tstringify,\n} from \"./logfmt\";\n\nexport type { Logger } from \"pino\";\n\nlet baseLogger: Logger | undefined;\nlet configuredLogLevel: LogLevel | undefined;\n\n/** Cache of child loggers by logger name. */\nconst loggerCache = new Map<string, Logger>();\n\nexport const LogLevelSchema = z.enum([\n\t\"trace\",\n\t\"debug\",\n\t\"info\",\n\t\"warn\",\n\t\"error\",\n\t\"fatal\",\n\t\"silent\",\n]);\n\nexport type LogLevel = z.infer<typeof LogLevelSchema>;\n\nexport function getPinoLevel(logLevel?: LogLevel): LevelWithSilent {\n\t// Priority: provided > configured > env > default\n\tif (logLevel) {\n\t\treturn logLevel;\n\t}\n\n\tif (configuredLogLevel) {\n\t\treturn configuredLogLevel;\n\t}\n\n\tconst raw = (getLogLevel() || \"warn\").toString().toLowerCase();\n\n\tconst parsed = LogLevelSchema.safeParse(raw);\n\tif (parsed.success) {\n\t\treturn parsed.data;\n\t}\n\n\t// Default to info if invalid\n\treturn \"info\";\n}\n\nexport function getIncludeTarget(): boolean {\n\treturn getLogTarget();\n}\n\n/**\n * Configure a custom base logger.\n */\nexport function configureBaseLogger(logger: Logger): void {\n\tbaseLogger = logger;\n\tloggerCache.clear();\n}\n\n// TODO: This can be simplified in logfmt.ts\nfunction customWrite(level: string, o: any) {\n\tconst entries: any = {};\n\n\t// Add timestamp if enabled\n\tif (getLogTimestamp() && o.time) {\n\t\tconst date = typeof o.time === \"number\" ? new Date(o.time) : new Date();\n\t\tentries.ts = formatTimestamp(date);\n\t}\n\n\t// Add level\n\tentries.level = level.toUpperCase();\n\n\t// Add target if present\n\tif (o.target) {\n\t\tentries.target = o.target;\n\t}\n\n\t// Add message\n\tif (o.msg) {\n\t\tentries.msg = o.msg;\n\t}\n\n\t// Add other properties\n\tfor (const [key, value] of Object.entries(o)) {\n\t\tif (\n\t\t\tkey !== \"time\" &&\n\t\t\tkey !== \"level\" &&\n\t\t\tkey !== \"target\" &&\n\t\t\tkey !== \"msg\" &&\n\t\t\tkey !== \"pid\" &&\n\t\t\tkey !== \"hostname\"\n\t\t) {\n\t\t\tentries[key] = castToLogValue(value);\n\t\t}\n\t}\n\n\tconst output = stringify(entries);\n\tconsole.log(output);\n}\n\n/**\n * Configure the default logger with optional log level.\n */\nexport function configureDefaultLogger(logLevel?: LogLevel) {\n\t// Store the configured log level\n\tif (logLevel) {\n\t\tconfiguredLogLevel = logLevel;\n\t}\n\n\tbaseLogger = pino({\n\t\tlevel: getPinoLevel(logLevel),\n\t\tmessageKey: \"msg\",\n\t\t// Do not include pid/hostname in output\n\t\tbase: {},\n\t\t// Keep a string level in the output\n\t\tformatters: {\n\t\t\tlevel(_label: string, number: number) {\n\t\t\t\treturn { level: number };\n\t\t\t},\n\t\t},\n\t\ttimestamp: getLogTimestamp() ? stdTimeFunctions.epochTime : false,\n\t\tbrowser: {\n\t\t\twrite: {\n\t\t\t\tfatal: customWrite.bind(null, \"fatal\"),\n\t\t\t\terror: customWrite.bind(null, \"error\"),\n\t\t\t\twarn: customWrite.bind(null, \"warn\"),\n\t\t\t\tinfo: customWrite.bind(null, \"info\"),\n\t\t\t\tdebug: customWrite.bind(null, \"debug\"),\n\t\t\t\ttrace: customWrite.bind(null, \"trace\"),\n\t\t\t},\n\t\t},\n\t\thooks: {\n\t\t\tlogMethod(inputArgs, method, level) {\n\t\t\t\t// TODO: This is a hack to not implement our own Pino transport target. We can get better perf if we have our own transport target.\n\n\t\t\t\tconst levelMap: Record<number, string> = {\n\t\t\t\t\t10: \"trace\",\n\t\t\t\t\t20: \"debug\",\n\t\t\t\t\t30: \"info\",\n\t\t\t\t\t40: \"warn\",\n\t\t\t\t\t50: \"error\",\n\t\t\t\t\t60: \"fatal\",\n\t\t\t\t};\n\t\t\t\tconst levelName = levelMap[level] || \"info\";\n\t\t\t\tconst time = getLogTimestamp() ? Date.now() : undefined;\n\n\t\t\t\t// Get bindings from the logger instance (child logger fields)\n\t\t\t\tconst bindings = (this as any).bindings?.() || {};\n\n\t\t\t\t// TODO: This can be simplified in logfmt.ts\n\t\t\t\tif (inputArgs.length >= 2) {\n\t\t\t\t\tconst [objOrMsg, msg] = inputArgs;\n\t\t\t\t\tif (typeof objOrMsg === \"object\" && objOrMsg !== null) {\n\t\t\t\t\t\tcustomWrite(levelName, {\n\t\t\t\t\t\t\t...bindings,\n\t\t\t\t\t\t\t...objOrMsg,\n\t\t\t\t\t\t\tmsg,\n\t\t\t\t\t\t\ttime,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcustomWrite(levelName, {\n\t\t\t\t\t\t\t...bindings,\n\t\t\t\t\t\t\tmsg: String(objOrMsg),\n\t\t\t\t\t\t\ttime,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (inputArgs.length === 1) {\n\t\t\t\t\tconst [objOrMsg] = inputArgs;\n\t\t\t\t\tif (typeof objOrMsg === \"object\" && objOrMsg !== null) {\n\t\t\t\t\t\tcustomWrite(levelName, {\n\t\t\t\t\t\t\t...bindings,\n\t\t\t\t\t\t\t...objOrMsg,\n\t\t\t\t\t\t\ttime,\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcustomWrite(levelName, {\n\t\t\t\t\t\t\t...bindings,\n\t\t\t\t\t\t\tmsg: String(objOrMsg),\n\t\t\t\t\t\t\ttime,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t});\n\n\tloggerCache.clear();\n}\n\n/**\n * Get or initialize the base logger.\n */\nexport function getBaseLogger(): Logger {\n\tif (!baseLogger) {\n\t\tconfigureDefaultLogger();\n\t}\n\treturn baseLogger!;\n}\n\n/**\n * Returns a child logger with `target` bound for the given name.\n */\nexport function getLogger(name = \"default\"): Logger {\n\t// Check cache first\n\tconst cached = loggerCache.get(name);\n\tif (cached) {\n\t\treturn cached;\n\t}\n\n\t// Create\n\tconst base = getBaseLogger();\n\n\t// Add target to log if enabled\n\tconst child = getIncludeTarget() ? base.child({ target: name }) : base;\n\n\t// Cache the logger\n\tloggerCache.set(name, child);\n\n\treturn child;\n}\n","export type LogLevel =\n\t| \"TRACE\"\n\t| \"DEBUG\"\n\t| \"INFO\"\n\t| \"WARN\"\n\t| \"ERROR\"\n\t| \"CRITICAL\";\n\nexport const LogLevels: Record<LogLevel, LevelIndex> = {\n\tTRACE: 0,\n\tDEBUG: 1,\n\tINFO: 2,\n\tWARN: 3,\n\tERROR: 4,\n\tCRITICAL: 5,\n} as const;\n\nexport const LevelNameMap: Record<number, LogLevel> = {\n\t0: \"TRACE\",\n\t1: \"DEBUG\",\n\t2: \"INFO\",\n\t3: \"WARN\",\n\t4: \"ERROR\",\n\t5: \"CRITICAL\",\n};\n\nexport type LevelIndex = number;\n","import { type LogLevel, LogLevels } from \"./log-levels\";\n\nconst LOG_LEVEL_COLORS: Record<number, string> = {\n\t[LogLevels.CRITICAL]: \"\\x1b[31m\", // Red\n\t[LogLevels.ERROR]: \"\\x1b[31m\", // Red\n\t[LogLevels.WARN]: \"\\x1b[33m\", // Yellow\n\t[LogLevels.INFO]: \"\\x1b[32m\", // Green\n\t[LogLevels.DEBUG]: \"\\x1b[36m\", // Cyan\n\t[LogLevels.TRACE]: \"\\x1b[36m\", // Cyan\n};\n\nconst RESET_COLOR = \"\\x1b[0m\";\n\n/**\n * Serializes logfmt line from an object.\n *\n * ## Styling Methodology\n *\n * The three things you need to know for every log line is the level, the\n * message, and who called it. These properties are highlighted in different colros\n * and sorted in th eorder that you usually read them.\n *\n * Once you've found a log line you care about, then you want to find the\n * property you need to see. The property names are bolded and the default color\n * while the rest of the data is dim. This lets you scan to find the property\n * name quickly then look closer to read the data associated with the\n * property.\n */\nexport function stringify(data: any) {\n\tlet line = \"\";\n\tconst entries = Object.entries(data);\n\n\tfor (let i = 0; i < entries.length; i++) {\n\t\tconst [key, valueRaw] = entries[i];\n\n\t\tlet isNull = false;\n\t\tlet valueString: string;\n\t\tif (valueRaw == null) {\n\t\t\tisNull = true;\n\t\t\tvalueString = \"\";\n\t\t} else {\n\t\t\tvalueString = valueRaw.toString();\n\t\t}\n\n\t\t// Clip value unless specifically the error message\n\t\tif (valueString.length > 512 && key !== \"msg\" && key !== \"error\")\n\t\t\tvalueString = `${valueString.slice(0, 512)}...`;\n\n\t\tconst needsQuoting =\n\t\t\tvalueString.indexOf(\" \") > -1 || valueString.indexOf(\"=\") > -1;\n\t\tconst needsEscaping =\n\t\t\tvalueString.indexOf('\"') > -1 || valueString.indexOf(\"\\\\\") > -1;\n\n\t\tvalueString = valueString.replace(/\\n/g, \"\\\\n\");\n\t\tif (needsEscaping) valueString = valueString.replace(/[\"\\\\]/g, \"\\\\$&\");\n\t\tif (needsQuoting || needsEscaping) valueString = `\"${valueString}\"`;\n\t\tif (valueString === \"\" && !isNull) valueString = '\"\"';\n\n\t\tif (LOGGER_CONFIG.enableColor) {\n\t\t\t// With color\n\n\t\t\t// Special message colors\n\t\t\tlet color = \"\\x1b[2m\";\n\t\t\tif (key === \"level\") {\n\t\t\t\tconst level = LogLevels[valueString as LogLevel];\n\t\t\t\tconst levelColor = LOG_LEVEL_COLORS[level];\n\t\t\t\tif (levelColor) {\n\t\t\t\t\tcolor = levelColor;\n\t\t\t\t}\n\t\t\t} else if (key === \"msg\") {\n\t\t\t\tcolor = \"\\x1b[32m\";\n\t\t\t} else if (key === \"trace\") {\n\t\t\t\tcolor = \"\\x1b[34m\";\n\t\t\t}\n\n\t\t\t// Format line\n\t\t\tline += `\\x1b[0m\\x1b[1m${key}\\x1b[0m\\x1b[2m=\\x1b[0m${color}${valueString}${RESET_COLOR}`;\n\t\t} else {\n\t\t\t// No color\n\t\t\tline += `${key}=${valueString}`;\n\t\t}\n\n\t\tif (i !== entries.length - 1) {\n\t\t\tline += \" \";\n\t\t}\n\t}\n\n\treturn line;\n}\n\nexport function formatTimestamp(date: Date): string {\n\tconst year = date.getUTCFullYear();\n\tconst month = String(date.getUTCMonth() + 1).padStart(2, \"0\");\n\tconst day = String(date.getUTCDate()).padStart(2, \"0\");\n\tconst hours = String(date.getUTCHours()).padStart(2, \"0\");\n\tconst minutes = String(date.getUTCMinutes()).padStart(2, \"0\");\n\tconst seconds = String(date.getUTCSeconds()).padStart(2, \"0\");\n\tconst milliseconds = String(date.getUTCMilliseconds()).padStart(3, \"0\");\n\n\treturn `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}Z`;\n}\n\nexport function castToLogValue(v: unknown): any {\n\tif (\n\t\ttypeof v === \"string\" ||\n\t\ttypeof v === \"number\" ||\n\t\ttypeof v === \"bigint\" ||\n\t\ttypeof v === \"boolean\" ||\n\t\tv === null ||\n\t\tv === undefined\n\t) {\n\t\treturn v;\n\t}\n\tif (v instanceof Error) {\n\t\t//args.push(...errorToLogEntries(k, v));\n\t\treturn String(v);\n\t}\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch {\n\t\treturn \"[cannot stringify]\";\n\t}\n}\n\n// MARK: Config\ninterface GlobalLoggerConfig {\n\tenableColor: boolean;\n\tenableSpreadObject: boolean;\n\tenableErrorStack: boolean;\n}\n\nexport const LOGGER_CONFIG: GlobalLoggerConfig = {\n\tenableColor: false,\n\tenableSpreadObject: false,\n\tenableErrorStack: false,\n};\n\n// MARK: Utils\n/**\n * Converts an object in to an easier to read KV of entries.\n */\nexport function spreadObjectToLogEntries(base: string, data: unknown): any {\n\tif (\n\t\tLOGGER_CONFIG.enableSpreadObject &&\n\t\ttypeof data === \"object\" &&\n\t\t!Array.isArray(data) &&\n\t\tdata !== null &&\n\t\tObject.keys(data).length !== 0 &&\n\t\tObject.keys(data).length < 16\n\t) {\n\t\tconst logData: any = {};\n\t\tfor (const key in data) {\n\t\t\tObject.assign(\n\t\t\t\tlogData,\n\t\t\t\tspreadObjectToLogEntries(\n\t\t\t\t\t`${base}.${key}`,\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: FIXME\n\t\t\t\t\t(data as any)[key],\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn logData;\n\t}\n\n\treturn { [base]: JSON.stringify(data) };\n}\n\nexport function errorToLogEntries(base: string, error: unknown): any {\n\tif (error instanceof Error) {\n\t\treturn {\n\t\t\t[`${base}.message`]: error.message,\n\t\t\t...(LOGGER_CONFIG.enableErrorStack && error.stack\n\t\t\t\t? { [`${base}.stack`]: formatStackTrace(error.stack) }\n\t\t\t\t: {}),\n\t\t\t...(error.cause\n\t\t\t\t? errorToLogEntries(`${base}.cause`, error.cause)\n\t\t\t\t: {}),\n\t\t};\n\t}\n\treturn { [base]: `${error}` };\n}\n\n// export function errorToLogEntries(base: string, error: unknown): LogEntry[] {\n// \tif (error instanceof RuntimeError) {\n// \t\treturn [\n// \t\t\t[`${base}.code`, error.code],\n// \t\t\t[`${base}.description`, error.errorConfig?.description],\n// \t\t\t[`${base}.module`, error.moduleName],\n// \t\t\t...(error.trace ? [[`${base}.trace`, stringifyTrace(error.trace)] as LogEntry] : []),\n// \t\t\t...(LOGGER_CONFIG.enableErrorStack && error.stack\n// \t\t\t\t? [[`${base}.stack`, formatStackTrace(error.stack)] as LogEntry]\n// \t\t\t\t: []),\n// \t\t\t...(error.meta ? [[`${base}.meta`, JSON.stringify(error.meta)] as LogEntry] : []),\n// \t\t\t...(error.cause ? errorToLogEntries(`${base}.cause`, error.cause) : []),\n// \t\t];\n// \t} else if (error instanceof Error) {\n// \t\treturn [\n// \t\t\t[`${base}.name`, error.name],\n// \t\t\t[`${base}.message`, error.message],\n// \t\t\t...(LOGGER_CONFIG.enableErrorStack && error.stack\n// \t\t\t\t? [[`${base}.stack`, formatStackTrace(error.stack)] as LogEntry]\n// \t\t\t\t: []),\n// \t\t\t...(error.cause ? errorToLogEntries(`${base}.cause`, error.cause) : []),\n// \t\t];\n// \t} else {\n// \t\treturn [\n// \t\t\t[base, `${error}`],\n// \t\t];\n// \t}\n// }\n\n/**\n * Formats a JS stack trace in to a legible one-liner.\n */\nfunction formatStackTrace(stackTrace: string): string {\n\tconst regex = /at (.+?)$/gm;\n\tconst matches = [...stackTrace.matchAll(regex)];\n\t// Reverse array since the stack goes from top level -> bottom level\n\tmatches.reverse();\n\treturn matches.map((match) => match[1].trim()).join(\" > \");\n}\n","export { stringifyError } from \"@/common/utils\";\nexport { assertUnreachable } from \"./common/utils\";\n\nimport type { Context as HonoContext, Handler as HonoHandler } from \"hono\";\nimport { stringify as uuidstringify } from \"uuid\";\nimport { stringifyError } from \"@/common/utils\";\nimport pkgJson from \"../package.json\" with { type: \"json\" };\nimport { getLogger } from \"./common/log\";\n\nexport const VERSION = pkgJson.version;\n\nlet _userAgent: string | undefined;\n\nfunction logger() {\n\treturn getLogger(\"utils\");\n}\n\nexport function httpUserAgent(): string {\n\t// Return cached value if already initialized\n\tif (_userAgent !== undefined) {\n\t\treturn _userAgent;\n\t}\n\n\t// Library\n\tlet userAgent = `RivetKit/${VERSION}`;\n\n\t// Navigator\n\tconst navigatorObj =\n\t\ttypeof navigator !== \"undefined\" ? navigator : undefined;\n\tif (navigatorObj?.userAgent) userAgent += ` ${navigatorObj.userAgent}`;\n\n\t_userAgent = userAgent;\n\n\treturn userAgent;\n}\n\nexport type UpgradeWebSocket = (\n\tcreateEvents: (c: HonoContext) => any,\n) => HonoHandler;\n\nexport type GetUpgradeWebSocket = () => UpgradeWebSocket;\n\nexport function getEnvUniversal(key: string): string | undefined {\n\tif (typeof Deno !== \"undefined\") {\n\t\treturn Deno.env.get(key);\n\t} else if (typeof process !== \"undefined\") {\n\t\t// Do this after Deno since `process` is sometimes polyfilled\n\t\treturn process.env[key];\n\t}\n}\n\nexport function dbg<T>(x: T): T {\n\tconsole.trace(`=== DEBUG ===\\n${x}`);\n\treturn x;\n}\n\n/**\n * Converts various ArrayBuffer-like types to Uint8Array.\n * Handles ArrayBuffer, ArrayBufferView (including typed arrays), and passes through existing Uint8Array.\n *\n * @param data - The ArrayBuffer or ArrayBufferView to convert\n * @returns A Uint8Array view of the data\n */\nexport function toUint8Array(data: ArrayBuffer | ArrayBufferView): Uint8Array {\n\tif (data instanceof Uint8Array) {\n\t\treturn data;\n\t} else if (data instanceof ArrayBuffer) {\n\t\treturn new Uint8Array(data);\n\t} else if (ArrayBuffer.isView(data)) {\n\t\t// Handle other ArrayBufferView types (Int8Array, Uint16Array, DataView, etc.)\n\t\treturn new Uint8Array(\n\t\t\tdata.buffer.slice(\n\t\t\t\tdata.byteOffset,\n\t\t\t\tdata.byteOffset + data.byteLength,\n\t\t\t),\n\t\t);\n\t} else {\n\t\tthrow new TypeError(\"Input must be ArrayBuffer or ArrayBufferView\");\n\t}\n}\n\n// Long timeouts\n//\n// JavaScript timers use a signed 32-bit integer for delays, so values above 2^31-1 (~24.8 days)\n// are not reliable and may fire immediately or overflow.\n//\n// https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#maximum_delay_value\nconst TIMEOUT_MAX = 2147483647; // 2^31-1\n\nexport type LongTimeoutHandle = { abort: () => void };\n\n/**\n * Polyfill for Promise.withResolvers().\n *\n * This is specifically for Cloudflare Workers. Their implementation of Promise.withResolvers does not work correctly.\n */\nexport function promiseWithResolvers<T>(): {\n\tpromise: Promise<T>;\n\tresolve: (value: T | PromiseLike<T>) => void;\n\treject: (reason?: any) => void;\n} {\n\tlet resolve!: (value: T | PromiseLike<T>) => void;\n\tlet reject!: (reason?: any) => void;\n\tconst promise = new Promise<T>((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\treturn { promise, resolve, reject };\n}\n\nexport function setLongTimeout(\n\tlistener: () => void,\n\tafter: number,\n): LongTimeoutHandle {\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\n\tfunction start(remaining: number) {\n\t\tif (remaining <= TIMEOUT_MAX) {\n\t\t\ttimeout = setTimeout(listener, remaining);\n\t\t} else {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tstart(remaining - TIMEOUT_MAX);\n\t\t\t}, TIMEOUT_MAX);\n\t\t}\n\t}\n\n\tstart(after);\n\n\treturn {\n\t\tabort: () => {\n\t\t\tif (timeout !== undefined) clearTimeout(timeout);\n\t\t},\n\t};\n}\n\n/**\n * A tiny utility that coalesces/enqueues async operations so only the latest\n * queued task runs per cycle, while callers receive a promise that resolves\n * when the task for the cycle they joined has completed.\n */\nexport class SinglePromiseQueue {\n\t/** Next operation to execute in the queue. If attempting to enqueue another op, it will override the existing op. */\n\t#queuedOp?: () => Promise<void>;\n\n\t/** The currently running promise of #drainLoop. Do not await this, instead await `pending` to await the current cycle. */\n\trunningDrainLoop?: Promise<void>;\n\n\t/** Pending resolver fro the currently queued entry. */\n\t#pending?: ReturnType<typeof promiseWithResolvers<void>>;\n\n\t/** Queue the next operation and return a promise that resolves when it flushes. */\n\tenqueue(op: () => Promise<void>): Promise<void> {\n\t\t// Replace any previously queued operation with the latest one\n\t\tthis.#queuedOp = op;\n\n\t\t// Ensure a shared resolver exists for all callers in this cycle\n\t\tif (!this.#pending) {\n\t\t\tthis.#pending = promiseWithResolvers<void>();\n\t\t}\n\n\t\tconst waitForThisCycle = this.#pending.promise;\n\n\t\t// Start runner if not already running\n\t\tif (!this.runningDrainLoop) {\n\t\t\tthis.runningDrainLoop = this.#drainLoop();\n\t\t}\n\n\t\treturn waitForThisCycle;\n\t}\n\n\t/** Drain queued operations sequentially until there is nothing left. */\n\tasync #drainLoop(): Promise<void> {\n\t\ttry {\n\t\t\twhile (this.#queuedOp) {\n\t\t\t\t// Capture current cycle resolver then reset for the next cycle\n\t\t\t\tconst resolver = this.#pending;\n\t\t\t\tthis.#pending = undefined;\n\n\t\t\t\t// Capture and clear the currently queued operation\n\t\t\t\tconst op = this.#queuedOp;\n\t\t\t\tthis.#queuedOp = undefined;\n\n\t\t\t\ttry {\n\t\t\t\t\tawait op();\n\t\t\t\t\t// Notify all waiters for this cycle\n\t\t\t\t\tresolver?.resolve();\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlogger().error({\n\t\t\t\t\t\tmsg: \"error in SinglePromiseQueue drain loop\",\n\t\t\t\t\t\terror: stringifyError(err),\n\t\t\t\t\t});\n\t\t\t\t\t// Reject all waiters for this cycle\n\t\t\t\t\tresolver?.reject(err);\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.runningDrainLoop = undefined;\n\t\t}\n\t}\n}\n\nexport function bufferToArrayBuffer(buf: Buffer | Uint8Array): ArrayBuffer {\n\treturn buf.buffer.slice(\n\t\tbuf.byteOffset,\n\t\tbuf.byteOffset + buf.byteLength,\n\t) as ArrayBuffer;\n}\n\n/**\n * Properly combines a base URL endpoint with a path, preserving any base path in the endpoint.\n *\n * @example\n * combineUrlPath(\"http://localhost:8787/rivet\", \"/actors/action\")\n * // Returns: \"http://localhost:8787/rivet/actors/action\"\n *\n * @example\n * combineUrlPath(\"http://localhost:8787/rivet\", \"/actors?type=foo\", { namespace: \"test\" })\n * // Returns: \"http://localhost:8787/rivet/actors?type=foo&namespace=test\"\n *\n * @param endpoint The base URL endpoint that may contain a path component\n * @param path The path to append to the endpoint (may include query parameters)\n * @param queryParams Optional additional query parameters to append\n * @returns The properly combined URL string\n */\nexport function combineUrlPath(\n\tendpoint: string,\n\tpath: string,\n\tqueryParams?: Record<string, string | undefined>,\n): string {\n\tconst baseUrl = new URL(endpoint);\n\n\t// Extract path and query from the provided path\n\tconst pathParts = path.split(\"?\");\n\tconst pathOnly = pathParts[0];\n\tconst existingQuery = pathParts[1] || \"\";\n\n\t// Remove trailing slash from base path and ensure path starts with /\n\tconst basePath = baseUrl.pathname.replace(/\\/$/, \"\");\n\tconst cleanPath = pathOnly.startsWith(\"/\") ? pathOnly : `/${pathOnly}`;\n\t// Combine paths and remove any double slashes\n\tconst fullPath = (basePath + cleanPath).replace(/\\/\\//g, \"/\");\n\n\t// Build query string\n\tconst queryParts: string[] = [];\n\tif (existingQuery) {\n\t\tqueryParts.push(existingQuery);\n\t}\n\tif (queryParams) {\n\t\tfor (const [key, value] of Object.entries(queryParams)) {\n\t\t\tif (value !== undefined) {\n\t\t\t\tqueryParts.push(\n\t\t\t\t\t`${encodeURIComponent(key)}=${encodeURIComponent(value)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst fullQuery = queryParts.length > 0 ? `?${queryParts.join(\"&\")}` : \"\";\n\treturn `${baseUrl.protocol}//${baseUrl.host}${fullPath}${fullQuery}`;\n}\n\nexport function arrayBuffersEqual(\n\tbuf1: ArrayBuffer,\n\tbuf2: ArrayBuffer,\n): boolean {\n\tif (buf1.byteLength !== buf2.byteLength) return false;\n\n\tconst view1 = new Uint8Array(buf1);\n\tconst view2 = new Uint8Array(buf2);\n\n\tfor (let i = 0; i < view1.length; i++) {\n\t\tif (view1[i] !== view2[i]) return false;\n\t}\n\treturn true;\n}\n\nexport const EXTRA_ERROR_LOG = {\n\tissues: \"https://github.com/rivet-dev/rivetkit/issues\",\n\tsupport: \"https://rivet.dev/discord\",\n\tversion: VERSION,\n};\n\nexport type Runtime = \"deno\" | \"bun\" | \"node\";\n\nexport function detectRuntime(): Runtime {\n\tconst userAgent =\n\t\ttypeof navigator !== \"undefined\" ? navigator.userAgent : \"\";\n\tif (userAgent.includes(\"Deno\")) {\n\t\treturn \"deno\";\n\t}\n\tif (userAgent.includes(\"Bun\")) {\n\t\treturn \"bun\";\n\t}\n\treturn \"node\";\n}\n\nexport type DeepReadonly<T> = {\n\treadonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];\n};\n\nexport type DeepMutable<T> = {\n\t-readonly [K in keyof T]: T[K] extends object ? DeepMutable<T[K]> : T[K];\n};\n"]}