@lunora/studio 1.0.0-alpha.350 → 1.0.0-alpha.351
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.
- package/dist/index.d.mts +4 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.mjs +1 -1
- package/dist/mount.mjs +1 -1
- package/dist/packem_chunks/AdvisorHealthPanel.mjs +1 -1
- package/dist/packem_chunks/ApiTab.mjs +1 -1
- package/dist/packem_chunks/AuditPanel.mjs +1 -1
- package/dist/packem_chunks/ExportImportPanel.mjs +8 -8
- package/dist/packem_chunks/FileBrowser.mjs +1 -1
- package/dist/packem_chunks/FunctionRunner.mjs +1 -1
- package/dist/packem_chunks/FunctionStatsPanel.mjs +1 -1
- package/dist/packem_chunks/HealthPanel.mjs +1 -1
- package/dist/packem_chunks/InsightsPanel.mjs +1 -1
- package/dist/packem_chunks/LogsPanel.mjs +1 -1
- package/dist/packem_chunks/MailPanel.mjs +1 -1
- package/dist/packem_chunks/MetricsPanel.mjs +1 -1
- package/dist/packem_chunks/NotificationsPanel.mjs +1 -1
- package/dist/packem_chunks/PitrPanel.mjs +1 -1
- package/dist/packem_chunks/SchemaViewer.mjs +1 -1
- package/dist/packem_chunks/SecurityAdvisorPanel.mjs +1 -1
- package/dist/packem_chunks/SettingsPanel.mjs +1 -1
- package/dist/packem_chunks/SqlEditorPanel.mjs +1 -1
- package/dist/packem_chunks/TableEditor.mjs +1 -1
- package/dist/packem_chunks/agents-panel.mjs +1 -1
- package/dist/packem_chunks/ai-usage-panel.mjs +1 -1
- package/dist/packem_chunks/auth-audit-panel.mjs +1 -1
- package/dist/packem_chunks/containers-panel.mjs +1 -1
- package/dist/packem_chunks/dashboards-panel.mjs +1 -1
- package/dist/packem_chunks/evals-panel.mjs +1 -1
- package/dist/packem_chunks/fanout-panel.mjs +1 -1
- package/dist/packem_chunks/flags-panel.mjs +1 -1
- package/dist/packem_chunks/issues-panel.mjs +1 -1
- package/dist/packem_chunks/kv-browser.mjs +1 -1
- package/dist/packem_chunks/migrations-route.mjs +1 -1
- package/dist/packem_chunks/payments-panel.mjs +1 -1
- package/dist/packem_chunks/permissions-panel.mjs +1 -1
- package/dist/packem_chunks/queues-panel.mjs +1 -1
- package/dist/packem_chunks/reactors-panel.mjs +1 -1
- package/dist/packem_chunks/rls-panel.mjs +1 -1
- package/dist/packem_chunks/storage-rules-panel.mjs +1 -1
- package/dist/packem_chunks/subscriptions-panel.mjs +1 -1
- package/dist/packem_chunks/traces-panel.mjs +1 -1
- package/dist/packem_chunks/workflows-panel.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-B8yyk5BX.mjs → ADMIN_FUNCTIONS-4aGsMs95.mjs} +1 -1
- package/dist/packem_shared/{ApiDocsPanel-B_RaW7Br.mjs → ApiDocsPanel-E4Vr-8zW.mjs} +1 -1
- package/dist/packem_shared/{DataBrowser-Cc1qZX-4.mjs → DataBrowser-C5HbI4TH.mjs} +1 -1
- package/dist/packem_shared/{GlobalDataBrowser-Hq6gTlkb.mjs → GlobalDataBrowser-D0H2yJSl.mjs} +1 -1
- package/dist/packem_shared/{HomePanel-DeyYLVxc.mjs → HomePanel-CcYkDlR-.mjs} +1 -1
- package/dist/packem_shared/{MigrationsPanel-CMZYYcQ5.mjs → MigrationsPanel-YyCO_T-3.mjs} +1 -1
- package/dist/packem_shared/{Studio-BhTqTeGb.mjs → Studio-4vJzwwNa.mjs} +1 -1
- package/dist/packem_shared/{StudioApp-B1d0beD4.mjs → StudioApp-px2FMPDS.mjs} +1 -1
- package/dist/packem_shared/{home-panel-0XMGe1hP.mjs → home-panel-DPiMVQZ2.mjs} +1 -1
- package/dist/packem_shared/{studio-CA3ZKwVK.mjs → studio-DIUgH7k0.mjs} +1 -1
- package/dist/packem_shared/{table-list-sidebar-nA7g7uSk.mjs → table-list-sidebar-CCRB_iYz.mjs} +1 -1
- package/dist/packem_shared/{use-sql-assistant-DXnqbBs-.mjs → use-sql-assistant-BMVlguKF.mjs} +1 -1
- package/dist/standalone/{chunk-WQGT24W6.js → chunk-22O2JDWR.js} +1 -1
- package/dist/standalone/{chunk-RXVXXRYD.js → chunk-2DV455PX.js} +1 -1
- package/dist/standalone/{chunk-B7MHW3A5.js → chunk-2EMNPL3B.js} +1 -1
- package/dist/standalone/{chunk-LOV52GLG.js → chunk-35BGGOWV.js} +1 -1
- package/dist/standalone/{chunk-BTRYFPZH.js → chunk-3MQ477EE.js} +1 -1
- package/dist/standalone/{chunk-XWEDIIIT.js → chunk-453GHHZ4.js} +1 -1
- package/dist/standalone/{chunk-QAQVT4FS.js → chunk-4CITH2NU.js} +1 -1
- package/dist/standalone/{chunk-E32FS6PE.js → chunk-4EDOPHLM.js} +1 -1
- package/dist/standalone/{chunk-EDGOSJXL.js → chunk-4QRVJDM4.js} +1 -1
- package/dist/standalone/{chunk-B3AXFXAD.js → chunk-4UWYDYM5.js} +1 -1
- package/dist/standalone/{chunk-SXD6JQXF.js → chunk-57ZNR6IA.js} +1 -1
- package/dist/standalone/{chunk-R3KLR5EP.js → chunk-6DYXTEU7.js} +1 -1
- package/dist/standalone/chunk-6GPEHYCG.js +1 -0
- package/dist/standalone/{chunk-E3VSRIQU.js → chunk-6GRI2HXU.js} +1 -1
- package/dist/standalone/{chunk-7F3S5OQT.js → chunk-6QBK3Z7A.js} +1 -1
- package/dist/standalone/{chunk-4ZEL6BYL.js → chunk-6UTZXEW3.js} +1 -1
- package/dist/standalone/{chunk-CGZVMM3P.js → chunk-7EAHHRJR.js} +1 -1
- package/dist/standalone/{chunk-HOPAJ5F6.js → chunk-ACNWZIAH.js} +1 -1
- package/dist/standalone/{chunk-5J32EGHF.js → chunk-ANACHJRU.js} +1 -1
- package/dist/standalone/chunk-BAGJYLSU.js +8 -0
- package/dist/standalone/{chunk-HLAAOW33.js → chunk-BCOOULSO.js} +1 -1
- package/dist/standalone/{chunk-ZMQ6PKLN.js → chunk-BKH2NALB.js} +1 -1
- package/dist/standalone/{chunk-ZBFWT34B.js → chunk-BTOOJXUL.js} +1 -1
- package/dist/standalone/{chunk-2EL4EMYZ.js → chunk-C6FNBKCO.js} +1 -1
- package/dist/standalone/{chunk-OECMBE6Q.js → chunk-DSTNWB4N.js} +1 -1
- package/dist/standalone/{chunk-WIET27J3.js → chunk-DTW4E5AB.js} +1 -1
- package/dist/standalone/{chunk-VB6YJKPA.js → chunk-FNWRS4VQ.js} +1 -1
- package/dist/standalone/{chunk-UTX6IBA3.js → chunk-FST24UXA.js} +1 -1
- package/dist/standalone/{chunk-ZTOXQK4V.js → chunk-FXGYX2V6.js} +1 -1
- package/dist/standalone/{chunk-MFNO5BFR.js → chunk-HWTX54JM.js} +1 -1
- package/dist/standalone/{chunk-26OKWFLO.js → chunk-HZCLLEWP.js} +1 -1
- package/dist/standalone/{chunk-7AZYREIY.js → chunk-IRCUXARN.js} +1 -1
- package/dist/standalone/{chunk-W7Z35E2E.js → chunk-IVQKQBKK.js} +1 -1
- package/dist/standalone/{chunk-W2XSKODB.js → chunk-K7FZTYAY.js} +1 -1
- package/dist/standalone/{chunk-5NZWQEEJ.js → chunk-KNX3KB7E.js} +1 -1
- package/dist/standalone/{chunk-MMJTKSHL.js → chunk-LYHEBMM6.js} +1 -1
- package/dist/standalone/{chunk-BVKQA5OL.js → chunk-M2RIGPGL.js} +1 -1
- package/dist/standalone/{chunk-EOR73TZZ.js → chunk-MKVZXGJQ.js} +1 -1
- package/dist/standalone/chunk-OIDFWEJX.js +21 -0
- package/dist/standalone/{chunk-CLINNLLE.js → chunk-OJG65AG4.js} +1 -1
- package/dist/standalone/{chunk-XMEVNOCA.js → chunk-Q4N3TJPV.js} +1 -1
- package/dist/standalone/{chunk-NVHHB5EV.js → chunk-QEVFVWGC.js} +1 -1
- package/dist/standalone/{chunk-JAHK7RRJ.js → chunk-RHOQJNDW.js} +1 -1
- package/dist/standalone/{chunk-7MN724WR.js → chunk-RQDSPVVH.js} +1 -1
- package/dist/standalone/{chunk-P5GAJKDW.js → chunk-S5S2YICJ.js} +1 -1
- package/dist/standalone/{chunk-ZZAJHNZ6.js → chunk-S6JFSLBK.js} +1 -1
- package/dist/standalone/{chunk-GMW2DYFU.js → chunk-SDTHCM5H.js} +1 -1
- package/dist/standalone/{chunk-JG2C7SS2.js → chunk-SM2IQWCJ.js} +1 -1
- package/dist/standalone/{chunk-GPOSJNMV.js → chunk-T2QAOXUO.js} +1 -1
- package/dist/standalone/{chunk-2WNL74MI.js → chunk-T4VAXHRL.js} +1 -1
- package/dist/standalone/{chunk-FPIUVV7Q.js → chunk-TBDJVYCB.js} +1 -1
- package/dist/standalone/{chunk-HFYFYNSX.js → chunk-TTD7BKB6.js} +1 -1
- package/dist/standalone/{chunk-KFNDET5D.js → chunk-UCK6ITED.js} +1 -1
- package/dist/standalone/{chunk-UZIBQZ2F.js → chunk-UKKZJRJT.js} +1 -1
- package/dist/standalone/{chunk-F5LTDUMB.js → chunk-V74BXQXC.js} +1 -1
- package/dist/standalone/{chunk-2ZO7XY3Z.js → chunk-VHMA6YPT.js} +1 -1
- package/dist/standalone/{chunk-SOO2HXV6.js → chunk-W4X4J7BU.js} +1 -1
- package/dist/standalone/{chunk-S7XAAH7U.js → chunk-W6ZKEW5M.js} +1 -1
- package/dist/standalone/{chunk-D7JK65OK.js → chunk-WIYDA4XT.js} +1 -1
- package/dist/standalone/{chunk-2X6O33OX.js → chunk-X7GSROPX.js} +1 -1
- package/dist/standalone/{chunk-O3FDK56W.js → chunk-Y7SN6CTX.js} +1 -1
- package/dist/standalone/{chunk-JGMQQ3S7.js → chunk-YRQHFMEY.js} +1 -1
- package/dist/standalone/{chunk-YJ2WHOGO.js → chunk-ZKPRORLI.js} +1 -1
- package/dist/standalone/{chunk-TWMS2TMF.js → chunk-ZLSNET6H.js} +1 -1
- package/dist/standalone/{chunk-CIVMATZK.js → chunk-ZM4K2ETZ.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +5 -5
- package/dist/standalone/chunk-BHOLL76W.js +0 -8
- package/dist/standalone/chunk-GQYA5W5T.js +0 -1
- package/dist/standalone/chunk-U76DVXTR.js +0 -21
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import{a as n,d as U,e as re,f as Es,g as St}from"./chunk-OXFKZ4BM.js";var Te={BAD_REQUEST:{status:400,title:"Bad request"},UNAUTHORIZED:{status:401,title:"Unauthorized"},FORBIDDEN:{status:403,title:"Forbidden"},NOT_FOUND:{status:404,title:"Not found"},DELIVERY_FENCED:{status:409,title:"Delivery authorization changed"},DELIVERY_RECEIPT_FENCED:{status:409,title:"Committed receipt authorization changed"},CONFLICT:{status:409,title:"Conflict"},NOT_UNIQUE:{status:400,title:"Query matched more than one document"},VALIDATION_ERROR:{status:400,title:"Validation failed"},TOO_MANY_REQUESTS:{status:429,title:"Too many requests"},UNPROCESSABLE:{status:422,title:"Unprocessable"},NOT_IMPLEMENTED:{status:501,title:"Not implemented"},FUNCTION_NOT_FOUND:{status:404,title:"Function not found"},METHOD_NOT_ALLOWED:{status:405,title:"Method not allowed"},PAYLOAD_TOO_LARGE:{status:413,title:"Payload too large"},INTERNAL:{internal:!0,status:500,title:"Internal error"},INTERNAL_SERVER_ERROR:{internal:!0,status:500,title:"Internal error"},RPC_FAILED:{internal:!0,status:500,title:"Internal error"},COUNT_RLS_UNSUPPORTED:{status:422,title:"count() is unsupported under an RLS policy"},MASK_UNSUPPORTED:{status:422,title:"Aggregation over a masked column is unsupported"},RELATION_PREDICATE_UNSUPPORTED:{status:422,title:"Relation predicate is unsupported in a write policy"},RLS_REQUIRED:{status:403,title:"RLS policy required"},RUN_DEPTH_EXCEEDED:{internal:!0,status:500,title:"Run depth exceeded"},RUN_KIND_FORBIDDEN:{status:500,title:"Function kind may not be composed from a query"},TRANSACTION_LIMIT_EXCEEDED:{status:413,title:"Transaction limit exceeded"},MIGRATION_NOT_FOUND:{status:404,title:"Data migration not found"},MIGRATION_DRIFT:{status:409,title:"Migration drift"},UNKNOWN_TABLE:{status:404,title:"Unknown table"},GLOBAL_TABLE_NOT_EDITABLE:{status:400,title:"Global table is not editable"},SHARD_ERROR:{status:503,title:"Shard error"},SHARD_UNAVAILABLE:{status:503,title:"Shard unavailable"},SHARD_TIMEOUT:{status:504,title:"Shard timeout"},SHARD_HTTP_ERROR:{status:502,title:"Shard HTTP error"},SHARD_DRY_RUN_UNSUPPORTED:{status:501,title:"Shard cannot dry-run an import"},SUBSCRIPTION_PERSIST_FAILED:{status:500,title:"Subscription persist failed"},TOO_MANY_SUBSCRIPTIONS:{status:429,title:"Too many subscriptions"},LIVE_CONTROL_SUPERSEDED:{status:409,title:"A later live control call already applied"},OFFLINE_IDENTITY_CHANGED:{status:409,title:"Offline identity changed"},OFFLINE_NOT_QUEUED:{status:503,title:"Offline, write not queued"},IDENTITY_MISMATCH:{status:409,title:"Session changed since the write was queued"},CODEGEN_DIAGNOSTIC:{status:500,title:"Codegen diagnostic"},JURISDICTION_MOVE:{status:422,title:"Unacknowledged jurisdiction move"},INDEX_FIELD_NESTED_PATH:{status:500,title:"Index field is a nested path"},SCHEMA_SNAPSHOT_PARSE:{status:500,title:"Schema snapshot parse error"},ENV_INVALID:{internal:!0,status:500,title:"Invalid environment"},X402_FACILITATOR_ERROR:{internal:!0,status:502,title:"Payment facilitator error"},AUTH_HEADERS_MISSING:{internal:!0,status:500,title:"Auth headers missing"},PRIVACY_COVERAGE:{status:500,title:"Privacy coverage check failed"},PRIVACY_REQUEST_OPEN:{status:409,title:"A privacy request is already open"},PRIVACY_SESSION_NOT_FRESH:{status:403,title:"Recent sign-in required"},EMAIL_DOMAIN_BLOCKED:{status:400,title:"Email domain not allowed"},EMAIL_UNDELIVERABLE:{status:400,title:"Email domain cannot receive mail"},ANALYTICS_SQL_QUERY_ERROR:{status:502,title:"Analytics SQL query error"},BROWSER_RUN_ERROR:{status:502,title:"Browser Run API error"},BROWSER_TOO_MANY_REDIRECTS:{status:502,title:"Too many redirects"},R2_SQL_ERROR:{status:502,title:"R2 SQL API error"},WORKFLOWS_REST_ERROR:{status:502,title:"Cloudflare Workflows REST API error"},CONFIG_INVALID:{internal:!0,status:500,title:"Payment configuration invalid"},CURRENCY_MISMATCH:{status:400,title:"Currency mismatch"},PROVIDER_ERROR:{status:502,title:"Payment provider error"},WEBHOOK_EVENT_ID_MISSING:{status:400,title:"Webhook event id missing"},WEBHOOK_SIGNATURE_INVALID:{status:400,title:"Webhook signature invalid"},WEBHOOK_TIMESTAMP_INVALID:{status:400,title:"Webhook timestamp outside tolerance"},ADMIN_FORBIDDEN:{status:403,title:"Admin access forbidden"},ADMIN_TOKEN_NOT_CONFIGURED:{status:400,title:"Admin token not configured"},AUTH_MIGRATOR_UNSUPPORTED:{status:500,title:"Auth migrator cannot drive the configured database"},AUTH_NOT_CONFIGURED:{status:400,title:"Auth admin not configured"},AUTH_OP_NOT_SUPPORTED:{status:400,title:"Auth admin operation not supported"},AUTH_CIMD_FETCH_NOT_PUBLIC:{status:500,title:"CIMD transport needs the global_fetch_strictly_public flag"},AUTH_MCP_RESOURCE_AMBIGUOUS:{status:500,title:"MCP resource cannot be told apart from the provider's other resources"},AUTH_MCP_RESOURCE_INVALID:{status:500,title:"MCP resource missing or not an absolute URL"},MCP_STEP_UP_MISCONFIGURED:{status:500,title:"MCP step-up misconfigured"},BACKUP_NOT_CONFIGURED:{status:500,title:"Scheduled backup not configured"},BACKUP_RETENTION_NOT_CONFIGURED:{status:400,title:"Backup retention window not configured"},BACKUP_TOO_LARGE:{status:507,title:"Backup too large to assemble in a Worker"},CRON_JOBS_NOT_CONFIGURED:{status:400,title:"Cron jobs not configured"},CRON_JOB_NOT_FOUND:{status:404,title:"Cron job not found"},EXPORT_SHARD_FAILED:{status:502,title:"Export failed on one or more shards"},EXPORT_TAP_NOT_CONFIGURED:{status:400,title:"Export tap not configured"},FUNCTIONS_NOT_CONFIGURED:{status:400,title:"Functions registry not configured"},GLOBALS_NOT_CONFIGURED:{status:400,title:"Global-table introspector not configured"},ID_COLLISION:{status:409,title:"Document id already belongs to another table"},KV_NOT_CONFIGURED:{status:400,title:"KV introspector not configured"},MIGRATION_ID_REQUIRED:{status:400,title:"Migration id required"},PITR_UNAVAILABLE:{status:409,title:"Point-in-time recovery unavailable"},SCHEDULER_NOT_CONFIGURED:{status:400,title:"Scheduler not configured"},STORAGE_CHECKSUM_MISMATCH:{status:400,title:"Storage checksum mismatch"},STORAGE_DELETE_NOT_CONFIGURED:{status:400,title:"Storage delete not configured"},STORAGE_DOWNLOAD_NOT_CONFIGURED:{status:400,title:"Storage download not configured"},STORAGE_NOT_CONFIGURED:{status:400,title:"Storage not configured"},STORAGE_OBJECT_NOT_FOUND:{status:404,title:"Storage object not found"},STORAGE_UPLOAD_NOT_CONFIGURED:{status:400,title:"Storage upload not configured"},STORAGE_URL_NOT_CONFIGURED:{status:400,title:"Storage signed URL not configured"},AI_UNKNOWN_IMAGE_MODEL:{status:400,title:"Unknown image model"},RAG_DIMENSION_MISMATCH:{status:409,title:"Embedding dimension mismatch"},VECTORS_NOT_CONFIGURED:{status:400,title:"Vector index introspector not configured"},VECTOR_QUERY_UNSUPPORTED:{status:400,title:"Vector index querying not enabled"},WORKFLOWS_NOT_CONFIGURED:{status:501,title:"Workflows not configured"},AUTH_AUDIT_NOT_CONFIGURED:{status:400,title:"Auth audit reader not configured"},AUTH_AUDIT_READ_FAILED:{internal:!0,status:500,title:"Auth audit read failed"},AUTH_MOVE_NOT_CONFIGURED:{status:400,title:"Auth jurisdiction move not configured"},AUTH_MOVE_TARGET_NOT_EMPTY:{status:409,title:"Pinned auth object is not empty"},AUTH_MOVE_CONFLICT:{status:409,title:"Auth copy conflict"},AUTH_MOVE_SOURCE_CHANGED:{status:409,title:"Un-pinned auth object changed since the copy"},AUTH_MOVE_SOURCE_PURGED:{status:409,title:"Un-pinned auth object already purged"},AUTH_MOVE_INCOMPLETE:{status:409,title:"Auth copy not finished"},AUTH_MOVE_FAILED:{status:500,title:"Auth jurisdiction move failed"},CRON_EXPR_INVALID:{status:500,title:"Invalid cron expression"},CRON_EXPR_NOT_STATIC:{status:500,title:"Cron expression is not statically analyzable"},CRON_JOB_FAILED:{internal:!0,status:500,title:"Cron job failed"},CRON_NAME_NOT_STATIC:{status:500,title:"Cron job name is not statically analyzable"},CRON_NON_STATIC_FN:{status:500,title:"Cron function reference is not statically analyzable"},CRON_NON_STATIC_VALUE:{status:500,title:"Cron value is not statically analyzable"},CRON_SCHEDULE_INVALID:{status:500,title:"Invalid cron schedule"},CRON_SCHEDULE_NOT_STATIC:{status:500,title:"Cron schedule is not statically analyzable"},DUPLICATE_CRON_NAME:{status:500,title:"Duplicate cron job name"},DUPLICATE_AGENT_CLASS:{status:500,title:"Duplicate agent generated class name"},DUPLICATE_AGENT_NAME:{status:500,title:"Duplicate agent name"},DUPLICATE_MIGRATION_ID:{status:500,title:"Duplicate migration id"},DUPLICATE_QUEUE_BINDING:{status:500,title:"Duplicate queue binding"},DUPLICATE_QUEUE_NAME:{status:500,title:"Duplicate queue name"},DUPLICATE_ROOM_NAME:{status:500,title:"Duplicate room name"},ROOM_NAME_NOT_LITERAL:{status:500,title:"Room name is not a string literal"},DUPLICATE_SOCKET_PATH:{status:500,title:"Duplicate socket route path"},SOCKET_AUTH_NOT_LITERAL:{status:500,title:"Socket route auth is not a literal boolean"},SOCKET_PATH_INVALID:{status:500,title:"Socket route path is not a plain URL path"},SOCKET_PATH_NOT_LITERAL:{status:500,title:"Socket route path is not a string literal"},LIVE_STREAM_DUPLICATE:{status:500,title:"Duplicate live stream id or export name"},LIVE_STREAM_NOT_EXPORTED:{status:500,title:"Live stream is not a named export"},LIVE_STREAM_NOT_LITERAL:{status:500,title:"Live stream declaration is not a literal"},LIVE_TOPIC_INVALID:{status:500,title:"Live topic name or key field is not allowed"},DUPLICATE_WORKFLOW_CLASS:{status:500,title:"Duplicate workflow generated class name"},WORKFLOW_EVENT_DUPLICATE:{status:500,title:"Duplicate workflow event type"},WORKFLOW_EVENT_NOT_LITERAL:{status:500,title:"Workflow event type is not a string literal"},MIGRATION_ID_NOT_STATIC:{status:500,title:"Migration id is not statically analyzable"},NAMESPACE_COLLISION:{status:500,title:"Function namespace collision"},BAD_ROW:{status:400,title:"Malformed import row"},BAD_SUBSCRIPTION_ARGS:{status:400,title:"Invalid subscription arguments"},BATCH_LIMIT_EXCEEDED:{status:400,title:"Batch limit exceeded"},CASCADE_LIMIT:{status:400,title:"Cascade limit exceeded"},CROSS_SHARD_RANK_UNSUPPORTED:{status:400,title:"Cross-shard rank() is unsupported"},DISPATCH_UNAUTHENTICATED:{status:403,title:"Dispatch caller not authenticated"},DISPATCH_IN_PROGRESS:{status:409,title:"Dispatch already in progress"},FORBIDDEN_FANOUT:{status:403,title:"Fan-out forbidden"},GLOBAL_SEARCH_SCORES_UNSUPPORTED:{status:400,title:"collectWithScores() is unsupported on a global table"},FORBIDDEN_ORIGIN:{status:403,title:"Origin forbidden"},FORBIDDEN_SHARD:{status:403,title:"Shard access forbidden"},FORBIDDEN_TOPIC:{status:403,title:"Live topic publish forbidden"},GLOBAL_DRY_RUN_UNSUPPORTED:{status:400,title:"Global table dry run not supported"},GLOBAL_NOT_CONFIGURED:{status:400,title:"Global table import not configured"},INVALID_INPUT:{status:400,title:"Invalid input"},INVALID_SCHEDULE_ID:{status:400,title:"Invalid schedule id"},RATE_LIMITED:{status:429,title:"Rate limited"},REPLICA_NOT_READY:{status:421,title:"Replica not caught up"},REPLICA_READ_ONLY:{status:421,title:"Replica is read-only"},SEARCH_INDEX_BUILDING:{status:503,title:"Search index is still building"},SERVICE_UNAVAILABLE:{status:503,title:"Service unavailable"},SHAPE_MEMORY_TABLE:{status:400,title:"Shape over a memory table is unsupported"},SHAPE_CROSS_SHARD_JOIN:{status:400,title:"Shape cross-shard join is unsupported"},SHAPE_RELATION_PREDICATE:{status:400,title:"Shape filtered by a relation is unsupported"},UNAUTHENTICATED:{status:401,title:"Unauthenticated"},WIRE_DECODE_FAILED:{status:502,title:"Could not decode a server frame"},WIRE_ENCODE_FAILED:{status:500,title:"Could not encode a return value"},UNKNOWN_COLUMN:{status:404,title:"Unknown column"},CDC_LOG_TRIMMED:{status:409,title:"CDC log trimmed"},CDC_TIMELINE_FORKED:{status:409,title:"CDC timeline forked"},CDC_PAYLOAD_COMPACTED:{status:409,title:"CDC payloads compacted"},EXPIRED:{status:404,title:"Session expired"},LIVE_CONNECTION_LIMIT:{status:503,title:"Live connection limit reached"},LIVE_CONNECTION_NOT_FOUND:{status:404,title:"Live connection not found"},LIVE_STREAMS_UNSUPPORTED:{status:501,title:"Live streams are not served by this worker"},NESTED_TRANSACTION:{internal:!0,status:500,title:"Nested transaction"},OUT_OF_ORDER:{status:409,title:"Out-of-order mutation"},SHAPE_GLOBAL_TOO_LARGE:{status:413,title:"Global shape too large"},SHAPE_NOT_FOUND:{status:404,title:"Shape not found"},SHAPE_REQUIRES_CDC:{status:409,title:"Shape requires change-data-capture"},SQL_UNAVAILABLE:{internal:!0,status:500,title:"SQL storage unavailable"},STREAM_ID_IN_USE:{status:409,title:"Stream id already in use"},STREAM_IDLE:{status:504,title:"Stream went idle"},STREAM_INTERRUPTED:{status:503,title:"Durable stream interrupted"},STREAM_TOO_LONG:{status:507,title:"Durable stream exceeded its chunk ceiling"},SUBSCRIPTION_RESULT_TOO_LARGE:{status:413,title:"Subscription result too large"},TOKEN_EXPIRED:{status:401,title:"Authentication token expired"},TOO_MANY_LIVE_TOPICS:{status:429,title:"Too many live topics"},TOO_MANY_STREAMS:{status:429,title:"Too many streams"},TOO_MANY_WHISPER_TOPICS:{status:429,title:"Too many whisper topics"},UNKNOWN_ADMIN_OP:{status:404,title:"Unknown admin operation"},SOCKET_TAG_BUDGET_EXCEEDED:{status:400,title:"Socket tag budget exceeded"},RELAY_CANNOT_SEED:{status:500,title:"Relay cannot seed"},RELAY_MISCONFIGURED:{status:500,title:"Relay misconfigured"},RELAY_SEED_FAILED:{status:502,title:"Relay seed failed"},RELAY_SHAPE_UNROUTABLE:{status:500,title:"Relay shape unroutable"},MISCONFIGURED:{internal:!0,status:500,title:"Worker misconfigured"},LUNORA_RUNTIME_UNAVAILABLE:{status:500,title:"Lunora runtime unavailable"},INTERNAL_ERROR:{internal:!0,status:500,title:"Internal error"},BROWSER_TIMEOUT:{status:504,title:"Browser operation timed out"},CLIENT_CLOSED:{status:400,title:"Client is closed"},HTTP_STREAM_BAD_CHUNK:{status:502,title:"Malformed HTTP stream chunk"},HTTP_STREAM_CALLBACK:{status:500,title:"HTTP stream callback threw"},HTTP_STREAM_INTERRUPTED:{status:502,title:"HTTP stream interrupted"},HTTP_STREAM_MISSING_PARAM:{status:400,title:"HTTP stream missing path parameter"},HTTP_STREAM_NO_BODY:{status:502,title:"HTTP stream response has no body"},HTTP_STREAM_STATUS:{status:502,title:"HTTP stream request failed"},HTTP_STREAM_TRANSPORT:{status:502,title:"HTTP stream transport error"},STREAM_BACKPRESSURE:{status:429,title:"Stream backpressure"},STREAM_DISCONNECTED:{status:503,title:"Stream disconnected"},STREAM_QUEUE_OVERFLOW:{status:429,title:"Stream queue overflow"},UNKNOWN_MUTATION_FN:{status:404,title:"Unknown mutation function"},LOCAL_DEPENDENCY_MISSING:{status:500,title:"Required local tool not found"}},wt=n(t=>Object.hasOwn(Te,t)?Te[t]:void 0,"s");var Cs=Symbol.for("@lunora/errors/LunoraError"),g=class t extends Error{static{n(this,"s")}static[Symbol.hasInstance](e){return this!==t?Function.prototype[Symbol.hasInstance].call(this,e):typeof e=="object"&&e!==null&&e[Cs]===!0}type="VisulimaError";hint;title;loc;code;status;docsUrl;data;why;constructor(e,s,r={}){let i=wt(e);super(s??e,r.cause===void 0?void 0:{cause:r.cause}),this.name=r.name??"LunoraError",this.hint=r.hint,this.title=r.title??i?.title,this.loc=r.location,this.code=e,this.status=r.status??i?.status??500,this.docsUrl=r.docsUrl,this.data=r.data,this.why=r.why,Object.defineProperty(this,Cs,{value:!0}),r.internal!==void 0&&Object.defineProperty(this,"internal",{value:r.internal}),r.headers!==void 0&&Object.defineProperty(this,"headers",{value:r.headers})}};var oe="https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-5xx-errors/",he="https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/",gn=/string or blob too big/iu,bn=["Another write changed this row while your mutation was running (optimistic concurrency conflict).","","Re-read the row and retry the mutation with the fresh value. Lunora serializes a DO's mutations, so a persistent conflict usually means the handler conflicts **with itself** (e.g. a trigger or cascade touching the same row) \u2014 split that work rather than adding a retry loop."];var Is=[{body:["A single row exceeded the storage engine's per-row ceiling \u2014 2 MB on a Durable Object's SQLite, and 2,000,000 bytes on D1.","","The limit is on the STORED bytes, which are UTF-8: a document of multi-byte text (CJK, emoji) costs up to 3x its character count. `v.bytes()` and `v.bigint()` columns cost more again on a shard-local table, where the row stores both a SQL-comparable projection and the original.","","Keep the large payload out of the row and store a reference to it:","","```ts","const key = `uploads/${crypto.randomUUID()}`;","await ctx.storage.uploads.put(key, bytes);",'await ctx.db.insert("documents", { storageKey: key, title });',"```","","R2 has no practical object-size ceiling, and the row stays small enough to read, index, and replicate."].join(`
|
|
2
|
+
`),header:"Row too large for the storage engine",id:"lunora-row-too-big",test:n(t=>gn.test(t),"test")},{body:["Lunora codegen couldn't find a schema to generate from.","","Create `lunora/schema.ts` exporting a `defineSchema(...)` call:","","```ts",'import { defineSchema, defineTable, v } from "@lunora/server";',"","export default defineSchema({"," messages: defineTable({ body: v.string() }),","});","```","","Or run `lunora init` to scaffold Lunora (a sample `lunora/schema.ts` included) into your app."].join(`
|
|
3
|
+
`),header:"No Lunora schema found",id:"lunora-schema-missing",test:n(t=>t.includes("defineSchema() not found")||t.includes("schema.ts not found at"),"test")},{body:["`defineSchema(...)` must be called with an **inline object literal** mapping table names to `defineTable(...)`:","","```ts","export default defineSchema({"," todos: defineTable({ title: v.string(), done: v.boolean() }),","});","```","","Codegen reads the schema statically, so it can't follow a variable or a spread \u2014 pass the object literal directly."].join(`
|
|
4
|
+
`),header:"`defineSchema()` needs an inline object literal",id:"lunora-schema-not-object-literal",test:n(t=>t.includes("defineSchema() expects an object literal"),"test")},{body:["This table name collides with a built-in `ctx.db` member, so the generated client can't expose it.","","Rename the table to anything that isn't a `ctx.db` member (the error names the one it hit) \u2014 e.g. `userAccounts` instead of `insert`, or `pageViews` instead of `count`."].join(`
|
|
5
|
+
`),header:"Table name is reserved",id:"lunora-table-reserved",test:n(t=>t.includes("is reserved")&&t.includes("ctx.db"),"test")},{body:["Two tables resolve to the same name \u2014 usually a base table and a schema **extension** both defining it.","","Rename one of them, or drop the duplicate from the extension. Each table name must be unique across `defineSchema(...)` and every `.extend(...)`."].join(`
|
|
6
|
+
`),header:"Duplicate table name",id:"lunora-table-duplicate",test:n(t=>t.includes("already exists")&&t.includes(".extend("),"test")},{body:['`.jurisdiction(...)` accepts only a **string literal** of `"eu"`, `"us"`, or `"fedramp"`:',"","```ts",'defineSchema({ /* \u2026 */ }).jurisdiction("eu");',"```"].join(`
|
|
7
|
+
`),header:"Invalid `.jurisdiction(...)` value",id:"lunora-jurisdiction",test:n(t=>t.includes("unknown jurisdiction")||t.includes("jurisdiction")&&t.includes('"eu", "us", or "fedramp"'),"test")},{body:["The `unique` flag on an index must be a **literal** `true` or `false`, not a computed value \u2014 codegen needs to read it statically:","","```ts",'defineTable({ email: v.string() }).index("by_email", ["email"], { unique: true });',"```"].join(`
|
|
8
|
+
`),header:"`unique` must be a literal",id:"lunora-unique-literal",test:n(t=>t.includes("must be a literal")&&t.includes("unique"),"test")},{body:["A declared container/workflow class isn't re-exported by your worker entry, so `wrangler deploy` would reject it.","","Add the generated re-export shown in the error to your worker entry (e.g. `src/index.ts`):","","```ts",'export * from "./lunora/_generated/containers";',"```"].join(`
|
|
9
|
+
`),header:"Binding not exported by your worker entry",id:"lunora-worker-entry-export-gap",test:n(t=>t.includes("not exported by your worker entry"),"test")},{body:["A row with the same value already exists in a `unique` index.","","- If you meant to upsert, use `ctx.db.<table>().upsert(...)` (or `.patch(...)` an existing row) instead of `.insert(...)`.",`- Otherwise pick a value that isn't already taken, and consider surfacing a friendly "already exists" message to the user.`].join(`
|
|
10
|
+
`),header:"Unique constraint violation",id:"lunora-runtime-unique",test:n(t=>t.includes("unique constraint violation on"),"test")},{body:bn.join(`
|
|
11
|
+
`),header:"Optimistic concurrency conflict",id:"lunora-runtime-occ",test:n(t=>t.includes("optimistic concurrency conflict"),"test")}],Tt=[{causes:"the origin returned an empty, unknown, or malformed response Cloudflare couldn't interpret (often an origin crash or an oversized response header)",code:"520",docsUrl:oe,family:"5xx",fix:"check your origin's logs for a crash, ensure it returns a valid HTTP response, and keep response headers under the size limit",summary:"Cloudflare got an unknown/empty response from your origin web server.",title:"Web server returns an unknown error"},{causes:"the origin refused the connection \u2014 the web server is down, or a firewall is blocking Cloudflare's IP ranges",code:"521",docsUrl:oe,family:"5xx",fix:"confirm the origin process is running and allowlist Cloudflare's published IP ranges in your firewall/security groups",summary:"Cloudflare could not connect to your origin because it refused the connection.",title:"Web server is down"},{causes:"Cloudflare could not establish a TCP connection to the origin in time \u2014 the origin is overloaded, a firewall is dropping packets, or the origin IP is wrong",code:"522",docsUrl:oe,family:"5xx",fix:"verify the origin is reachable and not overloaded, and that the DNS record points at the correct origin IP",summary:"The connection to your origin timed out before it was established.",title:"Connection timed out"},{causes:"Cloudflare cannot route to the origin at all \u2014 a bad DNS record, an origin IP that changed, or invalid routing",code:"523",docsUrl:oe,family:"5xx",fix:"verify the DNS A/AAAA record points at a reachable origin IP and that no upstream network is blocking Cloudflare",summary:"Cloudflare could not reach your origin server.",title:"Origin is unreachable"},{causes:"Cloudflare made a TCP connection but the origin did not return an HTTP response within 100 seconds \u2014 a slow handler or long-running request",code:"524",docsUrl:oe,family:"5xx",fix:"speed up the slow origin handler, or move long work off the request path into a background job (a Durable Object, Queue, or Workflow)",summary:"Cloudflare connected to your origin but it did not respond in time.",title:"A timeout occurred"},{causes:"the TLS handshake between Cloudflare and the origin failed \u2014 a missing/invalid origin certificate, or a cipher/SNI mismatch under Full (Strict) SSL",code:"525",docsUrl:oe,family:"5xx",fix:"install a valid certificate on the origin and align your Cloudflare SSL/TLS mode with the origin's certificate setup",summary:"The SSL handshake with your origin failed.",title:"SSL handshake failed"},{causes:"Cloudflare could not validate the origin's certificate under Full (Strict) SSL \u2014 it is expired, self-signed, or issued for the wrong hostname",code:"526",docsUrl:oe,family:"5xx",fix:"install a valid, publicly-trusted certificate on the origin (or use a Cloudflare Origin CA cert), matching the request hostname",summary:"Cloudflare could not validate your origin's SSL certificate.",title:"Invalid SSL certificate"},{causes:"a DNS record points at a Cloudflare IP or another prohibited address instead of your real origin",code:"1000",docsUrl:he,family:"1xxx",fix:"point the DNS record at your real origin IP, not a Cloudflare-owned or loopback address",summary:"DNS points to a prohibited IP.",title:"DNS points to prohibited IP"},{causes:"Cloudflare could not resolve the requested hostname \u2014 a Worker fetched an unresolvable host, or a DNS record is misconfigured",code:"1001",docsUrl:he,family:"1xxx",fix:"check the hostname you're requesting and the DNS records for the zone resolve to a valid origin",summary:"Cloudflare could not resolve the origin DNS.",title:"DNS resolution error"},{causes:"a Worker or DNS record targets a restricted IP (for example a Cloudflare-owned or loopback address)",code:"1002",docsUrl:he,family:"1xxx",fix:"change the Worker fetch target or DNS record to a valid, non-restricted origin address",summary:"DNS points to a prohibited IP (Worker/restricted).",title:"DNS points to a prohibited IP"},{causes:"the visitor's IP was blocked by an IP Access Rule, WAF rule, or security configuration on the zone",code:"1006",docsUrl:he,family:"1xxx",fix:"review the zone's Firewall/WAF and IP Access Rules to see why the address was banned, and adjust if it was blocked in error",summary:"Access denied: the visitor's IP has been banned.",title:"Access denied: your IP has been banned"},{causes:"your Worker threw an unhandled JavaScript exception during the request",code:"1101",docsUrl:he,family:"1xxx",fix:"reproduce with `wrangler tail` (or the Workers Logs / Studio Logs panel) to get the stack trace, then handle the throwing code path",summary:"A Worker threw a JavaScript exception.",title:"Worker threw a JavaScript exception"},{causes:"the Worker used more CPU time than a single invocation is allowed \u2014 usually a hot loop or heavy synchronous work",code:"1102",docsUrl:he,family:"1xxx",fix:"reduce per-request CPU (optimize hot loops, avoid heavy synchronous work) or offload the heavy work to a Durable Object, Queue, or Workflow",summary:"A Worker exceeded its CPU-time resource limit.",title:"Worker exceeded resource limits"}],Et=n(t=>t!==void 0&&t>="0"&&t<="9","s"),vn=n((t,e)=>{for(let s=t.indexOf(e);s!==-1;s=t.indexOf(e,s+e.length))if(!Et(t[s-1])&&!Et(t[s+e.length]))return!0;return!1},"g"),Sn=n((t,e)=>{for(let s of[`error ${e}`,`error: ${e}`])for(let r=t.indexOf(s);r!==-1;r=t.indexOf(s,r+s.length))if(!Et(t[r+s.length]))return!0;return!1},"b"),wn=/error|cloudflare/iu,Os=n(t=>({body:[t.summary,"",`**Likely cause:** ${t.causes}.`,"",`**Fix:** ${t.fix}.`,"",`See [Cloudflare's ${t.family} error docs](${t.docsUrl}).`].join(`
|
|
12
|
+
`),header:`Cloudflare Error ${t.code}: ${t.title}`,id:`cloudflare-error-${t.code}`}),"h"),Rs=n(t=>{if(!wn.test(t))return;let e=t.toLowerCase(),s=e.includes("error"),r=e.includes("cloudflare");if(s){for(let i of Tt)if(Sn(e,i.code))return Os(i)}if(r){for(let i of Tt)if(vn(e,i.code))return Os(i)}},"y"),Tn=n(t=>(typeof t=="string"?t:t.join(`
|
|
13
|
+
`)).split(`
|
|
14
|
+
`).filter(e=>!e.startsWith("```")).join(`
|
|
15
|
+
`).replaceAll(/\*\*(.+?)\*\*/gu,"$1").replaceAll(/`([^`]+)`/gu,"$1"),"T"),ks=n(t=>{for(let e of Is)if(e.test(t))return{body:e.body,header:e.header,id:e.id}},"d"),En=n(t=>ks(t)??Rs(t),"x");var Ct="A mutation sent with `onlineOnly: true` found its connection down or reconnecting (the shard had connected before), or, on a shard that has never connected, its request failed on the wire. It was refused instead of queued. Nothing was persisted or replayed; issue the call again once the connection is back. See [keeping a write off the queue](/docs/concepts/offline-first#keeping-a-write-off-the-queue).",Ot=["The `fetch` implementation resolved with a response that exposes neither a `body` stream nor a `text()` read \u2014 a broken `fetch` substitute, not a runtime limitation.","A response with no `body` stream that can still be read as text (React Native's `whatwg-fetch` polyfill) is buffered through `text()` instead and never raises this code. Check the `fetch` override passed to the client or the `httpStream` call."];var Cn=/["\\\u0000-\u001F\uD800-\uDFFF]/,As=n(t=>Cn.test(t)?JSON.stringify(t):`"${t}"`,"c"),On=n(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"b"),In=n((t,e)=>{let s=Object.getPrototypeOf(t);if(s!==null&&s!==Object.prototype){let c=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${c} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,i=Object.keys(r).sort(),a="{",o=!0;for(let c of i){let u=r[c];u!==void 0&&(o?o=!1:a+=",",a+=As(c),a+=":",a+=e(u))}return`${a}}`},"u"),Ee=n(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="function"||typeof t=="symbol")throw new TypeError(`stableStringify: cannot use a ${typeof t} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported`);if(typeof t=="number"){let e=On(t);if(e!==void 0)return e}return typeof t=="string"?As(t):t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${Array.from({length:t.length},(e,s)=>Ee(t[s])).join(",")}]`:In(t,Ee)},"y");var Ke=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"e");var qe=n(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"f"),Rn=n(t=>{let e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)s[r]=e.codePointAt(r)??0;return s},"E"),_="$lunora.wire$",Be=64,We=1024,kn="__proto__",An=/^-?\d+$/,_s={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Ls={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},It=n((t,e,s)=>{e===kn?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"y");var _n=n(t=>{let e=t.toString();if(e.length>We)throw new RangeError(`wire-codec: over-long bigint (max ${String(We)} digits)`);return[_,"bigint",e]},"j"),Ln=n(t=>Number.isNaN(t)?[_,"nan"]:t===1/0?[_,"inf"]:t===-1/0?[_,"-inf"]:t,"R"),Pn=n((t,e)=>{let s=e(Object.fromEntries(Object.keys(t).map(a=>[a,t[a]]))),r=t,i=[_,"error",String(r.name),String(r.message),s];return t.cause!==void 0&&i.push(e(t.cause)),i},"S"),Nn=n(t=>{let e=t.constructor.name,s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return e==="Uint8Array"?[_,"bytes",qe(s)]:[_,"bytes",qe(s),e]},"U"),Dn=n((t,e)=>t instanceof Date?[_,"date",e(t.getTime())]:t instanceof Error?Pn(t,e):t instanceof URL?[_,"url",t.href]:t instanceof Map?[_,"map",[...t.entries()].map(([s,r])=>[e(s),e(r)])]:t instanceof Set?[_,"set",[...t].map(s=>e(s))]:t instanceof ArrayBuffer?[_,"bytes",qe(new Uint8Array(t)),"ArrayBuffer"]:ArrayBuffer.isView(t)?Nn(t):void 0,"I"),Mn=n((t,e)=>{let s=t.map(r=>e(r));return s.length>0&&s[0]===_?[_,"arr",s]:s},"N"),Fn=n((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&It(s,r,e(i))}return s},"B"),j=n((t,e=0)=>{if(e>Be)throw new RangeError(`wire-codec: value nesting exceeds the ${String(Be)}-level limit`);if(t===void 0)return[_,"undefined"];if(t===null)return t;if(typeof t=="bigint")return _n(t);if(typeof t=="number")return Ln(t);if(typeof t!="object")return t;let s=n(i=>j(i,e+1),"t"),r=Dn(t,s);if(r!==void 0)return r;if(Array.isArray(t))return Mn(t,s);if(!Ke(t)){let i=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${i} over the Lunora wire \u2014 only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}return Fn(t,s)},"m"),Un=n(t=>{let e=t[2];if(typeof e!="string"||e.length>We||!An.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(We)} digits)`);return BigInt(e)},"_"),xn=n((t,e)=>{let s=e(t[2]);if(typeof s!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(s)},"P"),Hn=n((t,e)=>{let s=t[2];return new Map(s.map(r=>{if(!Array.isArray(r)||r.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[e(r[0]),e(r[1])]}))},"$"),Qn=n(t=>{let e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(e)},"D"),jn=n((t,e)=>{let s=t[2],r=t[3];if(typeof s!="string"||typeof r!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let i=(Object.hasOwn(Ls,s)?Ls[s]:void 0)??Error,a=new i(r);a.name!==s&&Object.defineProperty(a,"name",{configurable:!0,value:s,writable:!0});let o=e(t[4]);if(o===null||typeof o!="object"||Array.isArray(o))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let[c,u]of Object.entries(o))It(a,c,u);return t.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:e(t[5]),writable:!0}),a},"k"),Kn=n(t=>{let e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let s=Rn(e);if(qe(s)!==e)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let r=t[3]??"Uint8Array";if(r==="ArrayBuffer")return s.buffer.byteLength===s.byteLength?s.buffer:new Uint8Array(s).buffer;let i=Object.hasOwn(_s,r)?_s[r]:void 0;return i?new i(new Uint8Array(s).buffer):s},"C"),qn=n((t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(s=>e(s));case"bigint":return Un(t);case"bytes":return Kn(t);case"date":return xn(t,e);case"error":return jn(t,e);case"inf":return 1/0;case"map":return Hn(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return Qn(t);default:return t.map(s=>e(s))}},"L"),Bn=n((t,e)=>{let s={};for(let r of Object.keys(t))It(s,r,e(t[r]));return s},"M"),C=n((t,e=0)=>{if(e>Be)throw new RangeError(`wire-codec: value nesting exceeds the ${String(Be)}-level limit`);if(t===null||typeof t!="object")return t;let s=n(r=>C(r,e+1),"t");if(Array.isArray(t)){let r=t;return r[0]===_?qn(r,s):r.map(i=>s(i))}return Bn(t,s)},"A"),Wn=n(t=>{try{let e=C(JSON.parse(t));return Ke(e)?e:void 0}catch{return}},"G");var K=n(t=>Ee(j(t)),"a");var le=U(re(),1),Ps=U(St(),1);var Ce=le.createContext(void 0),Oe=n(t=>{let e=le.useContext(Ce);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),Rt=n(({client:t,children:e})=>(le.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Ps.jsx)(Ce.Provider,{value:t,children:e})),"QueryClientProvider");var Q=class{static{n(this,"Subscribable")}constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var Gn=class extends Q{static{n(this,"FocusManager")}#e;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=n(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},pe=new Gn;var $n={setTimeout:n((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:n(t=>clearTimeout(t),"clearTimeout"),setInterval:n((t,e)=>setInterval(t,e),"setInterval"),clearInterval:n(t=>clearInterval(t),"clearInterval")},Vn=class{static{n(this,"TimeoutManager")}#e=$n;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},G=new Vn;function Ns(t){setTimeout(t,0)}n(Ns,"systemSetTimeoutZero");var At=typeof window>"u"||"Deno"in globalThis;function O(){}n(O,"noop");function Fs(t,e){return typeof t=="function"?t(e):t}n(Fs,"functionalUpdate");function Ie(t){return typeof t=="number"&&t>=0&&t!==1/0}n(Ie,"isValidTimeout");function Ge(t,e){return Math.max(t+(e||0)-Date.now(),0)}n(Ge,"timeUntilStale");function q(t,e){return typeof t=="function"?t(e):t}n(q,"resolveStaleTime");function D(t,e){return typeof t=="function"?t(e):t}n(D,"resolveQueryBoolean");function $e(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==Re(o,e.options))return!1}else if(!ie(e.queryKey,o))return!1}if(s!=="all"){let u=e.isActive();if(s==="active"&&!u||s==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||a&&!a(e))}n($e,"matchQuery");function Ve(t,e){let{exact:s,status:r,predicate:i,mutationKey:a}=t;if(a){if(!e.options.mutationKey)return!1;if(s){if($(e.options.mutationKey)!==$(a))return!1}else if(!ie(e.options.mutationKey,a))return!1}return!(r&&e.state.status!==r||i&&!i(e))}n(Ve,"matchMutation");function Re(t,e){return(e?.queryKeyHashFn||$)(t)}n(Re,"hashQueryKeyByOptions");function $(t){return JSON.stringify(t,(e,s)=>kt(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}n($,"hashKey");function ie(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){for(let r=0;r<e.length;r++)if(!ie(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!ie(t[r],e[r]))return!1;return!0}return!1}n(ie,"partialMatchKey");var zn=Object.prototype.hasOwnProperty;function _t(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=Ds(t)&&Ds(e);if(!r&&!(kt(t)&&kt(e)))return e;let a=(r?t:Object.keys(t)).length,o=r?e:Object.keys(e),c=o.length,u=r?new Array(c):{},h=0;for(let d=0;d<c;d++){let l=r?d:o[d],p=t[l],f=e[l];if(p===f){u[l]=p,(r?d<a:zn.call(t,l))&&h++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){u[l]=f;continue}let y=_t(p,f,s+1);u[l]=y,y===p&&h++}return a===c&&h===a?t:u}n(_t,"replaceEqualDeep");function fe(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let s in t)if(t[s]!==e[s])return!1;return!0}n(fe,"shallowEqualObjects");function Ds(t){return Array.isArray(t)&&t.length===Object.keys(t).length}n(Ds,"isPlainArray");function kt(t){if(!Ms(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!Ms(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}n(kt,"isPlainObject");function Ms(t){return Object.prototype.toString.call(t)==="[object Object]"}n(Ms,"hasObjectPrototype");function Us(t){return new Promise(e=>{G.setTimeout(e,t)})}n(Us,"sleep");function ke(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?_t(t,e):e}n(ke,"replaceData");function Jn(t){return t}n(Jn,"keepPreviousData");function xs(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}n(xs,"addToEnd");function Hs(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}n(Hs,"addToStart");var me=Symbol();function ze(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===me?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}n(ze,"ensureQueryFn");function ye(t,e){return typeof t=="function"?t(...e):!!t}n(ye,"shouldThrowError");function Qs(t,e,s){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:n(()=>(i??=e(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i),"get")}),t}n(Qs,"addConsumeAwareSignal");var V=(()=>{let t=n(()=>At,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function Ae(){let t,e,s=new Promise((i,a)=>{t=i,e=a});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return n(r,"finalize"),s.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},s.reject=i=>{r({status:"rejected",reason:i}),e(i)},s}n(Ae,"pendingThenable");var js=Ns;function Yn(){let t=[],e=0,s=n(c=>{c()},"notifyFn"),r=n(c=>{c()},"batchNotifyFn"),i=js,a=n(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),o=n(()=>{let c=t;t=[],c.length&&i(()=>{r(()=>{c.forEach(u=>{s(u)})})})},"flush");return{batch:n(c=>{let u;e++;try{u=c()}finally{e--,e||o()}return u},"batch"),batchCalls:n(c=>(...u)=>{a(()=>{c(...u)})},"batchCalls"),schedule:a,setNotifyFunction:n(c=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:n(c=>{r=c},"setBatchNotifyFunction"),setScheduler:n(c=>{i=c},"setScheduler")}}n(Yn,"createNotifyManager");var T=Yn();var Xn=class extends Q{static{n(this,"OnlineManager")}#e=!0;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=n(()=>t(!0),"onlineListener"),s=n(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(s=>{s(t)}))}isOnline(){return this.#e}},ge=new Xn;function Zn(t){return Math.min(1e3*2**t,3e4)}n(Zn,"defaultRetryDelay");function Lt(t){return(t??"online")==="online"?ge.isOnline():!0}n(Lt,"canFetch");var Je=class extends Error{static{n(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Ye(t){let e=!1,s=0,r,i=Ae(),a=n(()=>i.status!=="pending","isResolved"),o=n(m=>{if(!a()){let v=new Je(m);p(v),t.onCancel?.(v)}},"cancel"),c=n(()=>{e=!0},"cancelRetry"),u=n(()=>{e=!1},"continueRetry"),h=n(()=>pe.isFocused()&&(t.networkMode==="always"||ge.isOnline())&&t.canRun(),"canContinue"),d=n(()=>Lt(t.networkMode)&&t.canRun(),"canStart"),l=n(m=>{a()||(r?.(),i.resolve(m))},"resolve"),p=n(m=>{a()||(r?.(),i.reject(m))},"reject"),f=n(()=>new Promise(m=>{r=n(v=>{(a()||h())&&m(v)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,a()||t.onContinue?.()}),"pause"),y=n(()=>{if(a())return;let m,v=s===0?t.initialPromise:void 0;try{m=v??t.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(l).catch(S=>{if(a())return;let E=t.retry??(V.isServer()?0:3),I=t.retryDelay??Zn,w=typeof I=="function"?I(s,S):I,R=E===!0||typeof E=="number"&&s<E||typeof E=="function"&&E(s,S);if(e||!R){p(S);return}s++,t.onFail?.(s,S),Us(w).then(()=>h()?void 0:f()).then(()=>{e?p(S):y()})})},"run");return{promise:i,status:n(()=>i.status,"status"),cancel:o,continue:n(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:d,start:n(()=>(d()?y():f().then(y),i),"start")}}n(Ye,"createRetryer");var Xe=class{static{n(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ie(this.gcTime)&&(this.#e=G.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(V.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(G.clearTimeout(this.#e),this.#e=void 0)}};function qs(t){return{onFetch:n((e,s)=>{let r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,a=e.state.data?.pages||[],o=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,h=n(async()=>{let d=!1,l=n(y=>{Qs(y,()=>e.signal,()=>d=!0)},"addSignalProperty"),p=ze(e.options,e.fetchOptions),f=n(async(y,m,v)=>{if(d)return Promise.reject(e.signal.reason);if(m==null&&y.pages.length)return Promise.resolve(y);let E=n(()=>{let se={client:e.client,queryKey:e.queryKey,pageParam:m,direction:v?"backward":"forward",meta:e.options.meta};return l(se),se},"createQueryFnContext")(),I=await p(E),{maxPages:w}=e.options,R=v?Hs:xs;return{pages:R(y.pages,I,w),pageParams:R(y.pageParams,m,w)}},"fetchPage");if(i&&a.length){let y=i==="backward",m=y?ea:Ks,v={pages:a,pageParams:o},S=m(r,v);c=await f(v,S,y)}else{let y=t??a.length;do{let m=u===0?o[0]??r.initialPageParam:Ks(r,c);if(u>0&&m==null)break;c=await f(c,m),u++}while(u<y)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(h,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s):e.fetchFn=h},"onFetch")}}n(qs,"infiniteQueryBehavior");function Ks(t,{pages:e,pageParams:s}){let r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,s[r],s):void 0}n(Ks,"getNextPageParam");function ea(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}n(ea,"getPreviousPageParam");var Gs=class extends Xe{static{n(this,"Query")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t){super(),this.#a=!1,this.#o=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#n=t.client,this.#r=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=Ws(this.options),this.state=t.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#i?.promise}setOptions(t){if(this.options={...this.#o,...t},t?._type&&(this.#e=t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Ws(this.options);e.data!==void 0&&(this.setState(Bs(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=ke(this.state.data,t,this.options);return this.#c({data:s,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),s}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(O).catch(O):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>D(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===me||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>q(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Ge(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#i&&(this.#a||this.#d()?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#d(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#c({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(h=>h.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=n(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:n(()=>(this.#a=!0,s.signal),"get")})},"addSignalProperty"),i=n(()=>{let u=ze(this.options,e),d=n(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,d,this):u(d)},"fetchFn"),o=n(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(u),u},"createFetchContext")();(this.#e==="infinite"?qs(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#c({type:"fetch",meta:o.fetchOptions?.meta}),this.#i=Ye({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:n(u=>{u instanceof Je&&u.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},"onCancel"),onFail:n((u,h)=>{this.#c({type:"failed",failureCount:u,error:h})},"onFail"),onPause:n(()=>{this.#c({type:"pause"})},"onPause"),onContinue:n(()=>{this.#c({type:"continue"})},"onContinue"),retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:n(()=>!0,"canRun")});try{let u=await this.#i.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#r.config.onSuccess?.(u,this),this.#r.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Je){if(u.silent)return this.#i.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#c({type:"error",error:u}),this.#r.config.onError?.(u,this),this.#r.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=n(s=>{switch(t.type){case"failed":return{...s,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...Pt(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...Bs(t.data,t.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=t.manual?r:void 0,r;case"error":let i=t.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...t.state}}},"reducer");this.state=e(this.state),T.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:t})})}};function Pt(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Lt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}n(Pt,"fetchState");function Bs(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}n(Bs,"successState");function Ws(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,s=e!==void 0,r=s?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}n(Ws,"getDefaultState");var Dt=class extends Q{static{n(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=Ae(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#d;#c;#f;#h;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),$s(this.#t,this.options)?this.#p():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Nt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Nt(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#w(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof D(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#T(),this.#t.setOptions(this.options),e._defaulted&&!fe(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&Vs(this.#t,s,this.options,e)&&this.#p(),this.updateResult(),r&&(this.#t!==s||D(this.options.enabled,this.#t)!==D(e.enabled,this.#t)||q(this.options.staleTime,this.#t)!==q(e.staleTime,this.#t))&&this.#y();let i=this.#g();r&&(this.#t!==s||D(this.options.enabled,this.#t)!==D(e.enabled,this.#t)||i!==this.#u)&&this.#b(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return sa(this,s)&&(this.#r=s,this.#i=this.options,this.#n=this.#t.state),s}getCurrentResult(){return this.#r}trackResult(t,e){return new Proxy(t,{get:n((s,r)=>(this.trackProp(r),e?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r)),"get")})}trackProp(t){this.#m.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let e=this.#e.defaultQueryOptions(t),s=this.#e.getQueryCache().build(this.#e,e);return s.fetch().then(()=>this.createResult(s,e))}fetch(t){return this.#p({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#p(t){this.#T();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(O)),e}#y(){this.#S();let t=q(this.options.staleTime,this.#t);if(V.isServer()||this.#r.isStale||!Ie(t))return;let s=Ge(this.#r.dataUpdatedAt,t)+1;this.#h=G.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#g(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(t){this.#w(),this.#u=t,!(V.isServer()||D(this.options.enabled,this.#t)===!1||!Ie(this.#u)||this.#u===0)&&(this.#l=G.setInterval(()=>{(this.options.refetchIntervalInBackground||pe.isFocused())&&this.#p()},this.#u))}#v(){this.#y(),this.#b(this.#g())}#S(){this.#h!==void 0&&(G.clearTimeout(this.#h),this.#h=void 0)}#w(){this.#l!==void 0&&(G.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let s=this.#t,r=this.options,i=this.#r,a=this.#n,o=this.#i,u=t!==s?t.state:this.#s,{state:h}=t,d={...h},l=!1,p;if(e._optimisticResults){let A=this.hasListeners(),k=!A&&$s(t,e),Y=A&&Vs(t,s,e,r);(k||Y)&&(d={...d,...Pt(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:f,errorUpdatedAt:y,status:m}=d;p=d.data;let v=!1;if(e.placeholderData!==void 0&&p===void 0&&m==="pending"){let A;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(A=i.data,v=!0):A=typeof e.placeholderData=="function"?e.placeholderData(this.#f?.state.data,this.#f):e.placeholderData,A!==void 0&&(m="success",p=ke(i?.data,A,e),l=!0)}if(e.select&&p!==void 0&&!v)if(i&&p===a?.data&&e.select===this.#d)p=this.#c;else try{this.#d=e.select,p=e.select(p),p=ke(i?.data,p,e),this.#c=p,this.#a=null}catch(A){this.#a=A}this.#a&&(f=this.#a,p=this.#c,y=Date.now(),m="error");let S=d.fetchStatus==="fetching",E=m==="pending",I=m==="error",w=E&&S,R=p!==void 0,N={status:m,fetchStatus:d.fetchStatus,isPending:E,isSuccess:m==="success",isError:I,isInitialLoading:w,isLoading:w,data:p,dataUpdatedAt:d.dataUpdatedAt,error:f,errorUpdatedAt:y,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:S,isRefetching:S&&!E,isLoadingError:I&&!R,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:I&&R,isStale:Mt(t,e),refetch:this.refetch,promise:this.#o,isEnabled:D(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=N.data!==void 0,k=N.status==="error"&&!A,Y=n(je=>{k?je.reject(N.error):A&&je.resolve(N.data)},"finalizeThenableIfPossible"),Ts=n(()=>{let je=this.#o=N.promise=Ae();Y(je)},"recreateThenable"),Qe=this.#o;switch(Qe.status){case"pending":t.queryHash===s.queryHash&&Y(Qe);break;case"fulfilled":(k||N.data!==Qe.value)&&Ts();break;case"rejected":(!k||N.error!==Qe.reason)&&Ts();break}}return N}updateResult(){let t=this.#r,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#f=this.#t),fe(e,t))return;this.#r=e;let s=n(()=>{if(!t)return!0;let{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;let a=new Set(i??this.#m);return this.options.throwOnError&&a.add("error"),Object.keys(this.#r).some(o=>{let c=o;return this.#r[c]!==t[c]&&a.has(c)})},"shouldNotifyListeners");this.#E({listeners:s()})}#T(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#s=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#E(t){T.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function ta(t,e){return D(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&D(e.retryOnMount,t)===!1)}n(ta,"shouldLoadOnMount");function $s(t,e){return ta(t,e)||t.state.data!==void 0&&Nt(t,e,e.refetchOnMount)}n($s,"shouldFetchOnMount");function Nt(t,e,s){if(D(e.enabled,t)!==!1&&q(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&Mt(t,e)}return!1}n(Nt,"shouldFetchOn");function Vs(t,e,s,r){return(t!==e||D(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&Mt(t,s)}n(Vs,"shouldFetchOptionally");function Mt(t,e){return D(e.enabled,t)!==!1&&t.isStaleByTime(q(e.staleTime,t))}n(Mt,"isStale");function sa(t,e){return!fe(t.getCurrentResult(),e)}n(sa,"shouldAssignObserverCurrentProperties");var zs=class extends Xe{static{n(this,"Mutation")}#e;#t;#s;#r;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#s=t.mutationCache,this.#t=[],this.state=t.state||Ft(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(t){let e=n(()=>{this.#n({type:"continue"})},"onContinue"),s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=Ye({fn:n(()=>this.options.mutationFn?this.options.mutationFn(t,s):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:n((a,o)=>{this.#n({type:"failed",failureCount:a,error:o})},"onFail"),onPause:n(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:n(()=>this.#s.canRun(this),"canRun")});let r=this.state.status==="pending",i=!this.#r.canStart();try{if(r)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(t,this,s);let o=await this.options.onMutate?.(t,s);o!==this.state.context&&this.#n({type:"pending",context:o,variables:t,isPaused:i})}let a=await this.#r.start();return await this.#s.config.onSuccess?.(a,t,this.state.context,this,s),await this.options.onSuccess?.(a,t,this.state.context,s),await this.#s.config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,t,this.state.context,s),this.#n({type:"success",data:a}),a}catch(a){try{await this.#s.config.onError?.(a,t,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,t,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,t,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#n({type:"error",error:a}),a}finally{this.#s.runNext(this)}}#n(t){let e=n(s=>{switch(t.type){case"failed":return{...s,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...s,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:t.error,failureCount:s.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),T.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(t)}),this.#s.notify({mutation:this,type:"updated",action:t})})}};function Ft(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}n(Ft,"getDefaultState");var Js=class extends Q{static{n(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(t,e,s){let r=new zs({client:t,mutationCache:this,mutationId:++this.#s,options:t.defaultMutationOptions(e),state:s});return this.add(r),r}add(t){this.#e.add(t);let e=Ze(t);if(typeof e=="string"){let s=this.#t.get(e);s?s.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Ze(t);if(typeof e=="string"){let s=this.#t.get(e);if(s)if(s.length>1){let r=s.indexOf(t);r!==-1&&s.splice(r,1)}else s[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Ze(t);if(typeof e=="string"){let r=this.#t.get(e)?.find(i=>i.state.status==="pending");return!r||r===t}else return!0}runNext(t){let e=Ze(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){T.batch(()=>{this.#e.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(t){let e={exact:!0,...t};return this.getAll().find(s=>Ve(e,s))}findAll(t={}){return this.getAll().filter(e=>Ve(t,e))}notify(t){T.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return T.batch(()=>Promise.all(t.map(e=>e.continue().catch(O))))}};function Ze(t){return t.options.scope?.id}n(Ze,"scopeFor");var Ut=class extends Q{static{n(this,"MutationObserver")}#e;#t=void 0;#s;#r;constructor(t,e){super(),this.#e=t,this.setOptions(e),this.bindMethods(),this.#n()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let e=this.options;this.options=this.#e.defaultMutationOptions(t),fe(this.options,e)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),e?.mutationKey&&this.options.mutationKey&&$(e.mutationKey)!==$(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(t){this.#n(),this.#i(t)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#n(),this.#i()}mutate(t,e){return this.#r=e,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(t)}#n(){let t=this.#s?.state??Ft();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#i(t){T.batch(()=>{if(this.#r&&this.hasListeners()){let e=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#r.onSuccess?.(t.data,e,s,r)}catch(i){Promise.reject(i)}try{this.#r.onSettled?.(t.data,null,e,s,r)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{this.#r.onError?.(t.error,e,s,r)}catch(i){Promise.reject(i)}try{this.#r.onSettled?.(void 0,t.error,e,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(e=>{e(this.#t)})})}};var Ys=class extends Q{static{n(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,s){let r=e.queryKey,i=e.queryHash??Re(r,e),a=this.get(i);return a||(a=new Gs({client:t,queryKey:r,queryHash:i,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(r)}),this.add(a)),a}add(t){this.#e.has(t.queryHash)||(this.#e.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let e=this.#e.get(t.queryHash);e&&(t.destroy(),e===t&&this.#e.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){T.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#e.get(t)}getAll(){return[...this.#e.values()]}find(t){let e={exact:!0,...t};return this.getAll().find(s=>$e(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>$e(t,s)):e}notify(t){T.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){T.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){T.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var xt=class{static{n(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new Ys,this.#t=t.mutationCache||new Js,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=pe.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=ge.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),s=this.#e.build(this,e),r=s.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&s.isStaleByTime(q(e.staleTime,s))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:s})=>{let r=s.data;return[e,r]})}setQueryData(t,e,s){let r=this.defaultQueryOptions({queryKey:t}),a=this.#e.get(r.queryHash)?.state.data,o=Fs(e,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(t,e,s){return T.batch(()=>this.#e.findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,s)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;T.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){let s=this.#e;return T.batch(()=>(s.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let s={revert:!0,...e},r=T.batch(()=>this.#e.findAll(t).map(i=>i.cancel(s)));return Promise.all(r).then(O).catch(O)}invalidateQueries(t,e={}){return T.batch(()=>(this.#e.findAll(t).forEach(s=>{s.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let s={...e,cancelRefetch:e.cancelRefetch??!0},r=T.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,s);return s.throwOnError||(a=a.catch(O)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(O)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let s=this.#e.build(this,e);return s.isStaleByTime(q(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(O).catch(O)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(O).catch(O)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return ge.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(t){this.#s=t}setQueryDefaults(t,e){this.#r.set($(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{ie(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set($(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{ie(t,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#s.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Re(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===me&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#s.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var ne=U(re(),1);var _e=U(re(),1),ra=U(St(),1);function ia(){let t=!1;return{clearReset:n(()=>{t=!1},"clearReset"),reset:n(()=>{t=!0},"reset"),isReset:n(()=>t,"isReset")}}n(ia,"createValue");var na=_e.createContext(ia()),Xs=n(()=>_e.useContext(na),"useQueryErrorResetBoundary");var Zs=U(re(),1);var er=n((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?ye(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),tr=n(t=>{Zs.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),sr=n(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||ye(s,[t.error,r])),"getHasError");var et=U(re(),1);var rr=et.createContext(!1),ir=n(()=>et.useContext(rr),"useIsRestoring"),Rh=rr.Provider;var nr=n(t=>{if(t.suspense){let s=n(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),ar=n((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),or=n((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),Ht=n((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function cr(t,e,s){let r=ir(),i=Xs(),a=Oe(s),o=a.defaultQueryOptions(t);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=a.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":u?"optimistic":void 0,nr(o),er(o,i,c),tr(i);let h=!a.getQueryCache().get(o.queryHash),[d]=ne.useState(()=>new e(a,o)),l=d.getOptimisticResult(o),p=!r&&u;if(ne.useSyncExternalStore(ne.useCallback(f=>{let y=p?d.subscribe(T.batchCalls(f)):O;return d.updateResult(),y},[d,p]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),ne.useEffect(()=>{d.setOptions(o)},[o,d]),or(o,l))throw Ht(o,d,i);if(sr({result:l,errorResetBoundary:i,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw l.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!V.isServer()&&ar(l,r)&&(h?Ht(o,d,i):c?.promise)?.catch(O).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?l:d.trackResult(l)}n(cr,"useBaseQuery");function aa(t,e){return cr(t,Dt,e)}n(aa,"useQuery");var X=U(re(),1);function oa(t,e){let s=Oe(e),[r]=X.useState(()=>new Ut(s,t));X.useEffect(()=>{r.setOptions(t)},[r,t]);let i=X.useSyncExternalStore(X.useCallback(o=>r.subscribe(T.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=X.useCallback((o,c)=>{r.mutate(o,c).catch(O)},[r]);if(i.error&&ye(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}n(oa,"useMutation");var Z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Qt=n(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let a=t[s]<<16|t[s+1]<<8|t[s+2];e+=Z.charAt(a>>18&63)+Z.charAt(a>>12&63)+Z.charAt(a>>6&63)+Z.charAt(a&63)}let i=t.length-s;if(i===1){let a=t[s]<<16;e+=Z.charAt(a>>18&63)+Z.charAt(a>>12&63)}else if(i===2){let a=t[s]<<16|t[s+1]<<8;e+=Z.charAt(a>>18&63)+Z.charAt(a>>12&63)+Z.charAt(a>>6&63)}return e},"A");var ca=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),ua="_id",jt="_creationTime",Kt="page",ur="pageDelta",da=n(t=>{if(Array.isArray(t))return t;if(ca(t)&&Array.isArray(t[Kt]))return t[Kt]},"y"),ha=n(t=>{let e;for(let s of t){let r=s[jt];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"g"),la=n((t,e)=>{let s=e[jt];if(typeof s!="number")return t.length;let r=ha(t);for(let[i,a]of t.entries()){let o=a[jt];if(typeof o=="number"&&(r?o<s:o>s))return i}return t.length},"A"),pa=n(t=>{if(typeof t!="object"||t===null)return;let e=t[ua];return typeof e=="string"?e:void 0},"b"),fa=n(t=>{if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},"D"),ma=n((t,e)=>{let{key:s,op:r,row:i}=e,a=[],o=-1;for(let c of t){let u=pa(c);if(u===void 0)return;if(u===s){if(r==="delete")continue;o===-1&&(o=a.length)}a.push(c)}if(r==="delete")return a;if(i!==void 0)return o===-1?a.splice(la(a,i),0,i):a[o]=i,a},"x"),ya=n((t,e)=>{let s=da(t);if(s===void 0)return;let r=ma(s,e);return r===void 0||Array.isArray(t)?r:{...t,[Kt]:r}},"E"),qt=Symbol("lunora.unmergeableDelta"),dr=n((t,e)=>{if("data"in t&&t.data!==void 0)return C(t.data);let s=C(t.delta);return fa(s)?e===void 0?s:ya(e,s)??qt:s},"m");var hr=n(()=>{let t=null;return{get:n(()=>t,"get"),set:n(e=>{t=e},"set")}},"r");var cl=new Set(Object.keys(Te)),x=class extends g{static{n(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var tt=n(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),Bt=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),Le=n(t=>Bt.has(t?.code??""),"u");var Pe=n(t=>typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="string")?{hint:t}:{},"n");var Wt=n(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let s=Date.parse(t);if(Number.isNaN(s))return;let r=s-Date.now();return r>0?r:void 0},"v"),ga=n((t,e)=>{let s=Wt(e);if(!(s===void 0||tt(t)!==void 0))return t.data===void 0?{retryAfterMs:s}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:s}:void 0},"p"),be=n(t=>{let e=t?.error;if(typeof e!="object"||e===null||Array.isArray(e))return;let{why:s,...r}=e;return typeof s=="string"?{...r,why:s}:r},"y"),Gt=n(()=>new x("LunoraClient: batch slot carried no error envelope"),"E"),lr=n((t,e)=>{let s=t.error,r=typeof s?.code=="string"?s.code:void 0,i=typeof s?.message=="string"?s.message:void 0;return{code:r,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"c"),pr=n(t=>{let{code:e,messageText:s}=lr(t,"stream error"),r=t.error,i=r?.why,a=e===void 0?new Error(s):new g(e,s,Pe(r?.hint));return typeof i=="string"&&(a.why=i),a},"D"),$t=n(t=>{let{code:e,messageText:s}=lr(t,"subscription error"),r=t.error,i=typeof r?.why=="string"?{why:r.why}:{};return{message:s,...e===void 0?{}:{code:e},...Pe(r?.hint),...i}},"O"),ba=Symbol.for("lunora.serverVerdict"),Ne=n(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,e[ba]=!0,t.data!==void 0)try{e.data=C(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),typeof t.why=="string"&&(e.why=t.why),e},"d"),va=n(t=>Object.freeze(Object.fromEntries([...t].filter(([e])=>e!=="set-cookie"))),"b"),H=n((t,e)=>Object.defineProperty(t,"headers",{value:va(e)}),"w"),Vt=n((t,e)=>{let s=Ne(t),r=ga(s,e.get("retry-after"));return r!==void 0&&(s.data=r),H(s,e)},"j"),zt=n(t=>{let e=be(t);return e===void 0?Gt():Ne(e)},"M"),fr=new WeakSet,st=n(t=>{let e=new g("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) \u2014 ${t instanceof Error?t.message:String(t)}`,{cause:t});return fr.add(e),e},"N"),De=n(t=>t instanceof Error&&fr.has(t),"T");var rt=class{static{n(this,"u")}values=new Map;subscribers=new Map;get(e){return this.values.has(e.key)?this.values.get(e.key):e.defaultValue}set(e,s){if(s===void 0){this.reset(e);return}this.values.set(e.key,s),this.notify(e.key,s)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,s){let r=this.subscribers.get(e.key);return r||(r=new Set,this.subscribers.set(e.key,r)),r.add(s),()=>{r.delete(s),r.size===0&&this.subscribers.delete(e.key)}}notify(e,s){let r=this.subscribers.get(e);if(r)for(let i of r)try{i(s)}catch{}}};var it=n(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),Jt=n(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),B=n((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"$"),L=n((t,e)=>{let s=new URLSearchParams;for(let[i,a]of Object.entries(e))a!==void 0&&a!==""&&s.set(i,String(a));let r=s.toString();return r===""?t:`${t}?${r}`},"d"),Sa="http://same-origin.invalid",Me=n(t=>new URL(t,Sa),"p"),wa=/^[a-z][a-z\d+.-]*:/iu,Yt=n((t,e)=>{if(wa.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var mr=0,Ta="lunora-bridge",Ea=1e3,Ca=3e3,nt=class{static{n(this,"l")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;pendingData=new Map;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(mr+=1,this.tabId=`tab_${String(mr)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??Ea,this.leaderTimeout=e.leaderTimeout??Ca,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onLeaderClaimAnswered=e.onLeaderClaimAnswered,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??Ta),this.bc.addEventListener("message",s=>{this.handleMessage(s.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(e,s,r,i,a){this.leader&&(this.pendingData.size===0&&queueMicrotask(()=>{this.flushPendingData()}),this.pendingData.set(e,{type:"subscription-data",tabId:this.tabId,key:e,data:s,...r===void 0?{}:{cursor:r},...i===void 0?{}:{epoch:i},...a===void 0?{}:{identity:a}}))}broadcastSubscriptionError(e,s,r){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:s,...r===void 0?{}:{identity:r}})}broadcastSubscriptionSettled(e,s,r,i,a,o){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...s===void 0?{}:{cursor:s},...r===void 0?{}:{epoch:r},...i===void 0?{}:{lastMutationId:i},...a===void 0?{}:{clientId:a},...o===void 0?{}:{identity:o}})}broadcastConnectionStatus(e,s){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...s===void 0?{}:{identity:s}})}broadcast(e){this.flushPendingData(),this.bc?.postMessage(e)}flushPendingData(){if(this.pendingData.size===0)return;let e=[...this.pendingData.values()];if(this.pendingData.clear(),!!this.leader)for(let s of e)this.bc?.postMessage(s)}handleMessage(e){switch(e.type){case"claim-leadership":{this.handleClaimLeadership(e);break}case"connection-status":{if(this.leader||e.tabId===this.tabId)break;this.onConnectionStatus?.(e.status,e.identity);break}case"heartbeat":{this.handleHeartbeat(e);break}case"subscription-data":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionData?.(e.key,e.data,e.cursor,e.epoch,e.identity);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error,e.identity);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.knownLeader===e.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(e){if(e.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&e.tabId<this.tabId&&(this.knownLeader=e.tabId,this.lastHeartbeat=e.ts)}}handleHeartbeat(e){if(e.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(e);return}this.lastHeartbeat=e.ts,this.knownLeader=e.tabId}}resolveLeaderVsLeaderTieBreak(e){e.tabId<this.tabId?(this.leader=!1,this.knownLeader=e.tabId,this.lastHeartbeat=e.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!(!this.running||this.leader)){if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}};var Fe=n((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,a=0;return{next(){let o=Math.min(r,s*2**a);if(a+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){a=0}}},"s");var Oa=1024,at=n(t=>{let e=t.maxBuffer??Oa,s=[],r=[],i=!1,a,o=!1,c=n(()=>{let d=r.shift();if(!d)return!1;if(a)return d.reject(a),!0;if(s.length>0){let l=s.shift();return d.resolve({done:!1,value:l}),!0}return i?(d.resolve({done:!0,value:void 0}),!0):(r.unshift(d),!1)},"u"),u={complete(){if(!(i||a))for(i=!0;c(););},fail(d){if(!(i||a)){for(a=d,s.length=0;c(););t.onFail?.()}},push(d){if(!(i||a||o)){if(s.length>=e){u.fail(new g("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}s.push(d),c()}}},h=n(()=>{if(!o){o=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:h,[Symbol.asyncIterator](){return{next(){if(a)return Promise.reject(a);if(s.length>0){let d=s.shift();return Promise.resolve({done:!1,value:d})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((d,l)=>{r.push({reject:l,resolve:d})})},return(){return h(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var ve=n(t=>t.reason??Object.assign(new Error("The operation was aborted"),{name:"AbortError"}),"c"),ce=n(async(t,e,s,r=()=>new x(`LunoraClient: request timed out after ${t.toString()}ms`))=>{if(e?.aborted)throw ve(e);let i=new AbortController,a=[],o=new Promise((u,h)=>{if(t>0){let d=setTimeout(()=>{h(r()),i.abort()},t);a.push(()=>{clearTimeout(d)})}if(e){let d=n(()=>{i.abort(),h(ve(e))},"a");e.addEventListener("abort",d,{once:!0}),a.push(()=>{e.removeEventListener("abort",d)})}}),c=s(i.signal);c.catch(()=>{});try{return await Promise.race([c,o])}finally{for(let u of a)u()}},"m"),Xt=n(async(t,e)=>{if(e===void 0)return t;if(e.aborted)throw t.catch(()=>{}),ve(e);let s=n(()=>{},"o"),r=new Promise((i,a)=>{s=n(()=>{a(ve(e))},"o"),e.addEventListener("abort",s,{once:!0})});t.catch(()=>{});try{return await Promise.race([t,r])}finally{e.removeEventListener("abort",s)}},"E"),yr=n(async(t,e)=>!Number.isFinite(e)||e<=0?t.read():ce(e,void 0,async()=>t.read(),()=>new g("STREAM_IDLE",`stream received nothing for ${e.toString()}ms`)),"y");var ot=/^ /u,Ia=/^\d+$/u,Ra=2147483647,ka=10,Aa=1e3,gr=n(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"O"),_a=n(t=>{let e="",s,r,i=[];for(let a of t.split(`
|
|
16
|
+
`))if(a.startsWith("event:"))e=a.slice(6).replace(ot,"");else if(a.startsWith("data:"))i.push(a.slice(5).replace(ot,""));else if(a.startsWith("id:")){let o=a.slice(3).replace(ot,"");o.includes("\0")||(s=o)}else if(a.startsWith("retry:")){let o=a.slice(6).replace(ot,"");Ia.test(o)&&Number.isSafeInteger(Number(o))&&(r=Math.min(Number(o),Ra))}return{data:i.join(`
|
|
17
|
+
`),event:e,id:s,retry:r}},"U"),La=n((t,e,s)=>{let r=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),h=r[u];if(h===void 0)throw new g("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(gr(h))}).join("/"),a=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&a.set(c,gr(u));let o=a.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"Y"),Pa=n((t,e)=>{if(t.event==="complete")return e.complete(),!0;if(t.event==="error"){let s={};try{s=JSON.parse(t.data)}catch{}let r=typeof s.message=="string"?s.message:"stream error",i=typeof s.code=="string"?s.code:"HTTP_STREAM_ERROR",a=new g(i,r,Pe(s.hint));return typeof s.why=="string"&&(a.why=s.why),e.fail(a),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(C(JSON.parse(t.data)))}catch{return e.fail(new g("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"J"),vr=n((t,e)=>{let s="",r=!1,i=n(o=>{let c=r?`\r${o}`:o;r=c.endsWith("\r"),r&&(c=c.slice(0,-1)),s+=c.replaceAll(`\r
|
|
18
|
+
`,`
|
|
19
|
+
`)},"s"),a=n(()=>{let o=s.indexOf(`
|
|
20
|
+
|
|
21
|
+
`);if(o===-1)return"empty";let c=_a(s.slice(0,o));return s=s.slice(o+2),e.onFrame?.(),c.id!==void 0&&e.onId?.(c.id),c.retry!==void 0&&e.onRetry?.(c.retry),Pa(c,t)?"terminal":"dispatched"},"r");return{append:i,drain:n(()=>{for(;;){let o=a();if(o==="empty")return!1;if(o==="terminal")return!0}},"drain"),next:a}},"P"),Na=n(async(t,e,s,r,i=0)=>{let a=t.getReader(),o=new TextDecoder,c=vr(e,s),u=n(()=>a.cancel().then(()=>{},()=>{}),"a");try{for(;;){let{done:h,value:d}=await yr(a,i);if(h)break;if(c.append(o.decode(d,{stream:!0})),c.drain())return await u(),!0}return c.append(o.decode()),c.drain()}catch(h){throw r.abort(),u().catch(()=>{}),h}},"q"),Sr=n(async(t,e)=>{e.aborted||await new Promise(s=>{let r,i=n(()=>{clearTimeout(r),s()},"s");r=setTimeout(()=>{e.removeEventListener("abort",i),s()},t),e.addEventListener("abort",i,{once:!0})})},"N"),Da=n(async(t,e,s,r)=>{let i=vr(e,s);try{i.append(await t.text())}catch(a){throw r.abort(),a}for(;;){if(r.signal.aborted)return!1;let a=i.next();if(a==="empty")return!1;if(a==="terminal")return!0;await Sr(0,r.signal)}},"K"),Ma=n((t,e)=>{if(typeof t!="object"||t===null)return;let{code:s,error:r,why:i}=t;if(!(typeof s!="string"||typeof r!="string"))return new g("HTTP_STREAM_STATUS",`httpStream: request failed (status ${e.toString()}, ${s}): ${r}`,{status:e,why:typeof i=="string"?i:void 0})},"X"),Fa=n(async(t,e)=>{let s,r=new Promise(a=>{s=setTimeout(()=>{a(void 0)},Aa)}),i=t.json().catch(a=>{if(e.aborted)throw a});try{return await Promise.race([i,r])}finally{clearTimeout(s),await t.body?.cancel().catch(()=>{})}},"G"),Ua=n((t,e)=>{let s=Object.entries(t??{}).filter(([r])=>e===void 0||r.toLowerCase()!=="last-event-id");return{accept:"text/event-stream",...Object.fromEntries(s),...e===void 0?{}:{"last-event-id":e}}},"z"),br=n(t=>t instanceof Error&&"code"in t?t:new g("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"M"),wr=n((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new g("INTERNAL","httpStream: no `fetch` implementation available");let i=La(t,e??{},s.baseUrl??""),a=new AbortController,o;s.signal&&(s.signal.aborted?a.abort():(o=n(()=>{a.abort()},"i"),s.signal.addEventListener("abort",o,{once:!0})));let c=n(()=>{o&&s.signal?.removeEventListener("abort",o)},"c"),{handle:u,iterable:h}=at({maxBuffer:s.maxBuffer,onCancel:n(()=>{a.abort()},"onCancel"),onFail:n(()=>{a.abort()},"onFail")}),d=s.reconnect??!1,l=Fe(),{lastEventId:p}=s,f,y=0,m=n(()=>{l.reset(),y=0},"x"),v={},S=n(w=>{try{w()}catch(R){throw v.value={error:R},R}},"R"),E={onFrame:m,onId:n(w=>{S(()=>s.onEventId?.(w)),p=w},"onId"),onRetry:n(w=>{S(()=>s.onRetry?.(w)),f=w},"onRetry")},I=n(async()=>{let w=Ua(s.headers,p),R=new g("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"),se=n(k=>{if(a.signal.aborted){u.complete();return}return{completed:k,error:R}},"_"),N=new AbortController,A=n(()=>{N.abort()},"A");a.signal.addEventListener("abort",A,{once:!0});try{let k=await r(i,{headers:w,method:t.method,signal:N.signal});if(!k.ok){let Y=await Fa(k,a.signal);u.fail(Ma(Y,k.status)??new g("HTTP_STREAM_STATUS",`httpStream: request failed (status ${k.status.toString()})`,{status:k.status}));return}if(!k.body){if(typeof k.text!="function"){u.fail(new g("HTTP_STREAM_NO_BODY","httpStream: response exposes neither a body stream nor a text() read",{hint:Ot}));return}return se(await Da(k,u,E,N))}return se(await Na(k.body,u,E,N,s.idleTimeoutMs))}catch(k){if(a.signal.aborted){u.complete();return}if(v.value){let{error:Y}=v.value;u.fail(Y instanceof Error?Y:new g("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:br(k)}}finally{a.signal.removeEventListener("abort",A)}},"H");return(async()=>{try{for(;;){if(a.signal.aborted){u.complete();return}let w=await I();if(!w)return;if(w.completed||!d||y>=ka){w.completed||u.fail(w.error);return}y+=1,await Sr(f??l.next(),a.signal)}}finally{c()}})().catch(w=>{if(a.signal.aborted){u.complete();return}u.fail(br(w))}),h},"ne");var P=class t{static{n(this,"y")}static key(e,s,r){return`${e}::${K(s)}::${r??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let s=t.keyOf(e);this.byKey.get(s)===e&&this.byKey.delete(s),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}},z=n((t,e)=>{t.ack=e},"s"),ct=n(t=>{t.ack==="inflight"&&z(t,"idle")},"b");function ut(t){if(t!==void 0)return e=>{t(e)}}n(ut,"o");var ee=n((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Zt=0,Tr=n(()=>Zt,"h"),xa=n((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),Er=n((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),ae=n((t,e)=>{Er(t,xa(e,t.optimisticLayers))},"y"),es=n((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),Er(t,s);let a=n(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),o=n(()=>{ae(t,t.serverBase)},"s");return{confirm:n(c=>{if(c===void 0){a();return}r.commitCursor=c,Zt+=1,r.acknowledgedAt=Zt,t.serverCursor!==void 0&&t.serverCursor>=c&&a()&&o()},"confirm"),rollback:n(()=>{i||(i=!0,a(),o())},"rollback")}},"g"),dt=n((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let s=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(r=>r.commitCursor===void 0||r.commitCursor>e),t.optimisticLayers.length!==s},"k"),Cr=n((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),ue=n(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),Or=n((t,e)=>{let s=[],r=[],i=n((a,o)=>t.get(P.key(a,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:n(a=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===a.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:n((a,o)=>i(a.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:n((a,o,c)=>{let u=i(a.__lunoraRef,o??{});if(!u)return;let h=es(u,()=>c);h&&(s.push(h.confirm),r.push(h.rollback))},"setQuery")}}},"_");var Ir=0,Ha=n(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Ir+=1;let t=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${Ir.toString(36)}_${t}`},"d"),ts=n((t,e)=>t!==void 0&&e!==t,"l"),lt=Ha,Se=n((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"h"),ht=class{static{n(this,"p")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;onReplayingChange;version;items=[];replayingIds=new Set;appending=new Map;unsettled=new Map;unpersisted=new Set;constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.onReplayingChange=s.onReplayingChange,this.version=s.version}get size(){return this.items.length}get replaying(){return this.replayingIds.size}enqueue(e){let s=e;s.id??=lt();let r=this.items.length;for(;s.issueSeq!==void 0&&r>0&&(this.items[r-1]?.issueSeq??-1)>s.issueSeq;)r-=1;this.items.splice(r,0,s),this.unsettled.set(s.id,s),this.persist(this.recordOf(s,s.id)),this.evictOverflow(),this.notifySize()}discard(e){this.unsettled.delete(e),this.unpersisted.delete(e),this.replayingIds.delete(e)&&this.onReplayingChange?.();let{persistence:s}=this;s&&(this.appending.get(e)??Promise.resolve()).then(async()=>s.remove(e)).catch(r=>{Se(this.onPersistenceError,"remove",r,e)})}flushUnpersisted(){for(let e of this.unpersisted){let s=this.unsettled.get(e);s&&!this.appending.has(e)&&this.persist(this.recordOf(s,e))}}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw Se(this.onPersistenceError,"load",o),o}let s=[],r=new Set(this.items.map(o=>o.id));for(let o of e)if(!r.has(o.id)){if(ts(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{Se(this.onPersistenceError,"remove",c,o.id)});continue}r.add(o.id),s.push({args:o.args,baselineSeq:o.baselineSeq,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject:n(()=>{},"reject"),resolve:n(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),a=new Set;for(let o of s)i.has(o)&&a.add(o.shardKey);return[...a]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;!this.persistence||i===void 0||this.rewriteStamp(i,this.recordOf(r,i)).catch(a=>{Se(this.onPersistenceError,"replace",a,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.markReplaying(i),this.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.markReplaying(s),this.notifySize(),s}requeue(e){if(e.length!==0){for(let s of e)s.id!==void 0&&this.replayingIds.delete(s.id);this.items.unshift(...e),this.notifySize()}}drainConflict(){let e=[],s=[];for(let r of this.items){let i=!0,a;if(r.precondition!==void 0)try{i=r.precondition()}catch(o){i=!1,a=o}if(i)s.push(r);else{let o=new Error("offline mutation skipped: precondition failed before replay",a===void 0?void 0:{cause:a});o.code="OFFLINE_PRECONDITION_FAILED",r.reject(o),e.push(r)}}return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of new Set([...this.items,...this.unsettled.values()])){let s=new Error("CLIENT_CLOSED"),r=e.id??"",i=n(o=>{s.code="CLIENT_CLOSED",s.persisted=o,e.reject(s)},"n"),a=this.appending.get(r);this.replayingIds.has(r)?i(!1):a===void 0?i(this.persistence!==void 0&&!this.unpersisted.has(r)):a.catch(()=>!1).then(i).catch(()=>{})}this.items.length=0,this.replayingIds.clear(),this.unsettled.clear(),this.unpersisted.clear(),this.notifySize()}recordOf(e,s){return{args:e.args,...e.baselineSeq===void 0?{}:{baselineSeq:e.baselineSeq},clientId:e.clientId,functionPath:e.functionPath,id:s,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}}persist(e){let{persistence:s}=this;if(!s)return;let r=(async()=>{try{return await s.append(e),this.unpersisted.delete(e.id),!0}catch(i){return this.unsettled.has(e.id)&&this.unpersisted.add(e.id),Se(this.onPersistenceError,"append",i,e.id),!1}})();this.appending.set(e.id,r),r.finally(()=>{this.appending.get(e.id)===r&&this.appending.delete(e.id)}).catch(()=>{})}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await this.appending.get(e),await r.replace(s)}catch(i){Se(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.discard(e.id);let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}markReplaying(e){for(let s of e)s.id!==void 0&&this.replayingIds.add(s.id)}notifySize(){this.onSizeChange?.(this.items.length)}};var M=n(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),pt=n((t,e,s,r)=>{let i;return()=>{if(i)return i;let a=new Promise((o,c)=>{let u=t.open(e,s);u.addEventListener("upgradeneeded",()=>{r(u.result)}),u.addEventListener("success",()=>{o(u.result)}),u.addEventListener("error",()=>{c(u.error??new Error("IndexedDB open failed"))})});return i=a,a.catch(()=>{i===a&&(i=void 0)}),a}},"E"),ft=n((t,e)=>async(s,r)=>{let i=(await t()).transaction(e,s),a=await r(i.objectStore(e));return await new Promise((o,c)=>{i.addEventListener("complete",()=>{o()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),a},"u");var Qa="lunora-outbox",ja="offline-mutations",ss="by_id",Ka=n((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new g("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??Qa,r=t.storeName??ja,i=pt(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(ss,"id",{unique:!0})}),a=ft(i,r);return{append:n(async o=>{await a("readwrite",c=>M(c.add(o)))},"append"),clear:n(async()=>{await a("readwrite",o=>M(o.clear()))},"clear"),load:n(async()=>a("readonly",o=>M(o.getAll())),"load"),remove:n(async o=>{await a("readwrite",async c=>{let u=await M(c.index(ss).getKey(o));u!==void 0&&await M(c.delete(u))})},"remove"),replace:n(async o=>{await a("readwrite",async c=>{let u=await M(c.index(ss).getKey(o.id));u!==void 0&&await M(c.put(o,u))})},"replace")}},"w"),Rr=n((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Ka()}},"b");var de=n((t,e,s)=>`${t}::${e}::${s??""}`,"T"),qa=500,Ba=n((t,e)=>{if(!Number.isInteger(t)||t<1)throw new g("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var Wa="lunora-query-cache",Ga="query-cache",kr="by_ts",$a=1,Va=n((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new g("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let s=t.databaseName??Wa,r=t.storeName??Ga,i=Ba(t.maxEntries??qa,"createIndexedDbQueryCache"),a=pt(e,s,$a,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(kr,"ts",{unique:!1})}),o=ft(a,r),c=n(async u=>{let h=await M(u.count())-i;h<=0||await new Promise((d,l)=>{let p=u.index(kr).openCursor();p.addEventListener("success",()=>{let f=p.result;if(!f||h<=0){d();return}f.delete(),h-=1,f.continue()}),p.addEventListener("error",()=>{l(p.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:n(async()=>{await o("readwrite",u=>M(u.clear()))},"clear"),load:n(async()=>o("readonly",u=>M(u.getAll())),"load"),put:n(async(u,h)=>{await o("readwrite",async d=>{await M(d.put({...h,key:u})),await c(d)})},"put"),remove:n(async u=>{await o("readwrite",h=>M(h.delete(u)))},"remove")}},"N"),Ar=n(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return Va()}},"L");var _r=new WeakMap,rs=n((t,e)=>{_r.set(t,e)},"i"),is=n(t=>t===void 0?void 0:_r.get(t),"d"),Lr=n((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),a=i.present&&i.answered?K(i.value):void 0,o=n(()=>{let c=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!i.answered||!c.present||!c.answered?!0:K(c.value)===a},"c");return a!==void 0&&rs(o,{args:s,functionPath:e.__lunoraRef,shardKey:r}),o},"h");var Ya="/_lunora/rpc",ns="/_lunora/rpc-batch",as="/_lunora/ws",Qr="/_lunora/admin/shard-traffic",Xa="/_lunora/admin/scheduled",Za="/_lunora/admin/scheduled/status",eo="/_lunora/admin/scheduled/ws",to="/_lunora/admin/scheduled/cancel",Pr="/_lunora/admin/scheduled/dead",so="/_lunora/admin/scheduled/dead/retry",ro="/_lunora/admin/scheduled/dead/cancel",io="/_lunora/admin/workflows/instances",no="/_lunora/admin/workflows/instance",ao="/_lunora/admin/workflows/status",yt="/_lunora/admin/storage",jr="/_lunora/admin/storage/url",Kr="/_lunora/admin/storage/buckets",qr="/_lunora/admin/functions",Br="/_lunora/admin/cron-jobs",Wr="/_lunora/admin/cron-jobs/run",Gr="/_lunora/admin/architecture",$r="/_lunora/admin/openapi",Vr="/_lunora/admin/openrpc",zr="/_lunora/admin/global/tables",Jr="/_lunora/admin/global/table",Yr="/_lunora/admin/global/facet",Xr="/_lunora/admin/vector/indexes",Zr="/_lunora/admin/vector/query",ei="/_lunora/admin/logs/archive",ti="/_lunora/admin/kv/namespaces",si="/_lunora/admin/kv/keys",gt="/_lunora/admin/kv/value",ri="/_lunora/admin/auth/users",ii="/_lunora/admin/auth/sessions",ni="/_lunora/admin/auth/users/create",ai="/_lunora/admin/auth/users/role",oi="/_lunora/admin/auth/users/ban",ci="/_lunora/admin/auth/users/unban",ui="/_lunora/admin/auth/users/password",di="/_lunora/admin/auth/users/remove",hi="/_lunora/admin/auth/users/impersonate",li="/_lunora/admin/auth/sessions/revoke",pi="/_lunora/admin/auth/sessions/revoke-all",fi="/_lunora/admin/auth/capabilities",mi="/_lunora/admin/auth/users/update",yi="/_lunora/admin/auth/accounts",gi="/_lunora/admin/auth/accounts/unlink",bi="/_lunora/admin/auth/passkeys",vi="/_lunora/admin/auth/passkeys/delete",Si="/_lunora/admin/auth/two-factor/disable",wi="/_lunora/admin/auth/organizations",Ti="/_lunora/admin/auth/organizations/members",Ei="/_lunora/admin/auth/organizations/invitations",Ci="/_lunora/admin/auth/organizations/members/remove",Oi="/_lunora/admin/auth/organizations/invitations/cancel",Ii="/_lunora/admin/auth/config",Ri="/_lunora/admin/auth/sign-up-invitations",ki="/_lunora/admin/auth/sign-up-invitations/create",Ai="/_lunora/admin/auth/sign-up-invitations/revoke",_i="/_lunora/admin/auth/organizations/create",Li="/_lunora/admin/auth/organizations/update",Pi="/_lunora/admin/auth/organizations/remove",Ni="/_lunora/admin/auth/organizations/members/add",Di="/_lunora/admin/auth/organizations/members/invite",Mi="/_lunora/admin/auth/organizations/members/role",Fi="/_lunora/admin/auth/organizations/teams",Ui="/_lunora/admin/auth/organizations/teams/create",xi="/_lunora/admin/auth/organizations/teams/update",Hi="/_lunora/admin/auth/organizations/teams/remove",Qi="/_lunora/admin/auth/organizations/teams/members",ji="/_lunora/admin/auth/organizations/teams/members/add",Ki="/_lunora/admin/auth/organizations/teams/members/remove",qi="/_lunora/admin/auth/organizations/roles",Bi="/_lunora/admin/auth/organizations/roles/create",Wi="/_lunora/admin/auth/organizations/roles/update",Gi="/_lunora/admin/auth/organizations/roles/remove",oo="/api/auth",co="/get-session",uo="lunora-ping",os=500,$i=n((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Re");new TextDecoder;var ho=new TextEncoder,lo=n(t=>Qt(ho.encode(t)),"Ht"),po=n(t=>lo(JSON.stringify(t)),"Nt"),fo="x-lunora-expect-subject",mo=n(t=>po({subject:t}),"Dt"),Nr=Symbol.for("lunora:session-change"),yo="lunora:session-change",go="better-auth.message",bo="signout",Vi=n(()=>{let t=globalThis,e=t[Nr];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[Nr]=e),e},"Oe"),vo=n(()=>"document"in globalThis,"qt"),So=n(async()=>{let t=[];for(let e of Vi().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"Kt"),wo=n((t,e)=>{if(t!==go||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===bo}catch{return!1}},"jt"),To=n(t=>{let e=[],s=n(()=>{So().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(yo):void 0}catch{r=void 0}if(r!==void 0){let a=r;a.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{a.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let a=n(o=>{wo(o.key,o.newValue)&&s()},"r");i.addEventListener("storage",a),e.push(()=>{i.removeEventListener?.("storage",a)})}return()=>{for(let a of e)a()}},"Gt"),Eo=n(t=>{let e=Vi();return e.listeners.add(t),e.detach===void 0&&vo()&&(e.detach=To(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"$t"),Co="lunora",Oo="lunora.bearer.",Io=n(t=>`${Oo}${Qt(new TextEncoder().encode(t))}`,"Jt"),Ro=n(async t=>{let e=[],s;for(;;){let r=await t(s);if(e.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return e;if(r.cursor===s)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");s=r.cursor}},"Yt"),ms=n(t=>"args"in t?{...t,args:C(t.args)}:t,"oe"),zi=n(async t=>(t.assertOpen(),((await t.adminFetch(Xa,"GET")).records??[]).map(e=>ms(e))),"pr"),Ji=n(async t=>{t.assertOpen();let e=await t.adminFetch(Za,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"mr"),Yi=n(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(to,"POST",{id:e})).cancelled===!0}),"yr"),Xi=n(async t=>(t.assertOpen(),(await Ro(async e=>await t.adminFetch(e===void 0?Pr:`${Pr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>ms(e))),"Sr"),Zi=n(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(so,"POST",{id:e})).retried===!0}),"vr"),en=n(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(ro,"POST",{id:e})).removed===!0}),"br"),tn=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({name:e.name});e.status!==void 0&&s.set("status",e.status),e.page!==void 0&&s.set("page",String(e.page)),e.perPage!==void 0&&s.set("perPage",String(e.perPage));let r=await t.adminFetch(`${io}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"gr"),sn=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${no}?${s.toString()}`,"GET");return{createdOn:r.createdOn,endedOn:r.endedOn,error:r.error,id:r.id??e.id,output:r.output,params:r.params,startedOn:r.startedOn,status:r.status??"unknown",steps:r.steps??[]}},"wr"),rn=n(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(ao,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"Tr"),J=n((t,e)=>{try{return j(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"E"),ds=n(t=>{try{return j(t),!0}catch{return!1}},"ee"),nn=n(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Le"),ko=n((t,e,s)=>{let r=Array.from({length:e}),i=n(a=>({error:H(zt(a),s),ok:!1}),"i");for(let a of t){if(typeof a.id!="number"||a.id<0||a.id>=e)continue;if(!nn(a.body)){r[a.id]=i({});continue}let o=a.body;if("error"in o){r[a.id]=i(o);continue}try{r[a.id]={ok:!0,value:C(o.result)}}catch(c){r[a.id]={error:H(st(c),s),ok:!1}}}return r.map(a=>a??{error:H(new Error("batch call returned no result"),s),ok:!1})},"Xt"),cs=n((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"Y"),Ue=n(t=>t==="connected"||t==="polling","W"),b=n(t=>t??"","f"),W=n((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"T"),Ao=n(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)W(t,s)},"Zt"),_o=new TextDecoder,Lo=n(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return _o.decode(t)},"ts"),te=class{static{n(this,"O")}listeners=new Set;get size(){return this.listeners.size}add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},we=n(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"U"),Po=n((t,e,s)=>{we(t),!(e<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;let{socket:r}=t;if(Date.now()-t.lastFrameAt>e*2.5){try{r.close()}catch{}s();return}try{r.send(uo)}catch{}},e))},"ss"),Dr=n((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:a,heartbeatIntervalMs:o}=s;if(i===void 0)throw new g("INTERNAL","no WebSocket implementation available");let c=r.protocols===void 0?new i(e):new i(e,r.protocols);t.socket=c;let u=n(()=>{we(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),h=n(d=>{u(),r.onClose(d)},"d");a>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}h()}},a)),c.addEventListener("open",()=>{if(t.socket===c){t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now();try{r.onOpen?.()}catch(d){console.error("[lunora] connection open handler threw",d)}t.socket===c&&Po(t,o,h)}}),c.addEventListener("message",d=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(d)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",d=>{t.socket===c&&h(d)}),c.addEventListener("error",()=>{t.socket===c&&h()})},"we"),No=n(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:a}=t,o=s>0&&e>0,c=0,u,h=!1,d=!1,l=n(()=>{u!==void 0&&(clearInterval(u),u=void 0,h=!1,i())},"h"),p=n(y=>{if(u!==void 0){if(!y){l();return}h||(h=!0,i()),r()}},"l"),f=n(()=>{d||(d=!0,a().then(p).finally(()=>{d=!1}).catch(()=>{}))},"p");return{hasFailedOpen:n(()=>c>0,"hasFailedOpen"),isPolling:n(()=>u!==void 0&&h,"isPolling"),noteFailedOpen:n(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(f,s),i(),f())},"noteFailedOpen"),noteOpen:n(()=>{c=0,l()},"noteOpen"),stop:l}},"is"),Do=1e4,Mr=n(async t=>ce(Do,void 0,t,()=>new TypeError("LunoraClient: poll timed out")),"Te"),an=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Fr=n(t=>{if(t instanceof x)return!0;let e=t?.code;return e===void 0||an.has(e)||Bt.has(e)},"Ce"),Mo=1e3,on=6e4,Fo={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},xe=n((t,e,s)=>{let r=Wt(s.get("retry-after")),i=r===void 0?void 0:{retryAfterMs:r},a=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`,o=t<400||t>=500||t===408?new x(a,i):new g(Fo[t]??"BAD_REQUEST",a,{data:i});return H(o,s)},"D"),hs=n((t,e=Math.random)=>{let s=Math.min(Mo*2**Math.max(t-1,0),on);return Math.round(s*(.5+e()*.5))},"te"),Uo=n(t=>{let e=t?.code;return t instanceof x||e===void 0||an.has(e)},"as"),xo=n((t,e,s)=>{let r=tt(t);return r!==void 0&&r>0?Math.min(r,on):Uo(t)?hs(e,s):void 0},"cs"),Ho=983040,Qo=n(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"us"),jo=n(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&nn(s.body)&&e.set(s.id,s.body);return e},"hs"),Ko=n((t,e)=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:H(zt(t),e),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:C(t.result)}}catch(s){return{commitCursor:t.commitCursor,error:H(st(s),e),kind:"undecodable"}}},"ls"),us=n((t,e)=>`${b(t)}\0${e}`,"X"),qo=n((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"fs"),ls=class{static{n(this,"ps")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){$i(this.buffers,this.maxBuffers),this.buffers.set(us(e,s.pokeId),{baseCheckpoint:s.baseCheckpoint,bases:new Map,epoch:s.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,s){let r=this.buffers.get(us(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:C(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let a=r.parts.get(s.shapeId)??[];for(let c of i)a.push(c);r.parts.set(s.shapeId,a),s.lastMutationId!==void 0&&r.lastMutationId.set(s.shapeId,s.lastMutationId);let o=s.baseCheckpoint??r.baseCheckpoint;o!==void 0&&r.bases.set(s.shapeId,o),s.reset===!0&&r.resets.add(s.shapeId)}end(e,s){let r=us(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},Bo=n((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),a=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=a!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==a;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,t.answered=!1,"reseed";i&&t.rows.clear(),qo(t.rows,r),t.answered=!0,s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let u=e.lastMutationId.get(t.id);return u!==void 0&&(t.lastMutationId=u),"applied"},"ms"),Ur=n(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"ke"),Wo=n((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&ee(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"ys"),ps=n((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"se"),fs=n((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"ie"),cn=n((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Fe"),Go=n((t,e)=>e.cursor!==void 0&&t.serverCursor!==void 0&&t.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===t.serverEpoch&&e.cursor<t.serverCursor,"Ss"),$o=n(t=>t.type==="delta"&&t.more===!0,"vs"),bt=n((t,e)=>t!==void 0&&t!==e,"j"),Vo=n((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","bs"),zo=n(t=>{for(let e of t.activeSubscriptions())e.valueReceived=!1,t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.activeShapes())e.answered=!1,t.ensureSocket(e.shardKey);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint()),t.emitConnectionStatus()},"gs"),Jo=n(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1;for(let s of t.activeSubscriptions())z(s,"idle"),s.valueReceived=!1;for(let s of t.activeShapes())s.answered=!1;t.emitConnectionStatus()},"ws"),Yo=n((t,e,s)=>{if(bt(s,t.identityFingerprint()))return;let r=t.leader,i=Vo(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&(t.awaitLeaderAnswers(),t.flushOfflineQueues())},"Ts"),Xo=n(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Cs"),Zo=n((t,e,s,r,i,a)=>{if(bt(a,t.identityFingerprint()))return;let o=t.subscription(e);if(!o)return;t.dropCacheSeed(e);let c=!o.valueReceived;o.valueReceived=!0,cn(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&dt(o,r),ae(o,s),c&&t.emitConnectionStatus(),t.settleAwaitedAnswer(o,!0)},"ks"),ec=n((t,e,s,r)=>{if(bt(r,t.identityFingerprint()))return;let i=t.subscription(e);if(i){let a=!i.valueReceived;i.valueReceived=!0,ee(i.errorCallbacks,s),a&&t.emitConnectionStatus(),t.settleAwaitedAnswer(i,!1)}},"As"),tc=n((t,e,s,r,i,a,o)=>{if(bt(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&a===t.clientIdentifier()&&ps(c,i),fs(c))},"Es"),sc=n((t,e,s)=>t!==null||e&&s===null,"_s"),rc=n(t=>t.sensitive===!0,"Is"),ic=n((t,e)=>{if(!rc(t))return e;if(e.onlineOnly===!1)throw new g("BAD_REQUEST",`'${t.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},"Rs"),nc=[ur],ac=100,un=1e4,oc=1e4,cc=n((t,e)=>{let s,r=new Promise((a,o)=>{s=setTimeout(()=>{o(new Error("ws ticket mint timed out"))},e)}),i=(async()=>t())();return Promise.race([i,r]).finally(()=>{clearTimeout(s)})},"Ms"),xr=n(async t=>typeof t=="function"?await t():t,"Ae"),uc=n(async(t,e,s,r)=>{let i=new AbortController,a=setTimeout(()=>{i.abort()},un);try{let o=await t(e,{body:s,credentials:"include",headers:r,method:"POST",signal:i.signal});return await o.text(),o.status}finally{clearTimeout(a)}},"Fs"),Hr=n((t,e)=>new g("OFFLINE_NOT_QUEUED",`'${t}' is online-only and the connection is not live, so it was not queued`,{cause:e,hint:Ct}),"Ee"),dc=n((t,e)=>t instanceof TypeError&&ds(e),"Us"),hc=n((t,e,s,r)=>e||t===!0&&s&&!r,"Hs"),lc=Promise.resolve(),mt=class t{static{n(this,"He")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:n((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:n(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;authTokenOnUpgrade;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new P;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;tokenFingerprint;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new te;statusListeners=new te;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new te;identityChangeListeners=new te;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new te;pendingChangeListeners=new te;syncStatusListeners=new te;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;awaitingAnswer=new WeakSet;answeredUnreadable=new WeakSet;answerHeldShards=new Set;leaderAnswerTimers=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new ls(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??B(Jt(e.url),as),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;let s=e.authBasePath??oo;this.authBasePath=s.endsWith("/")?s.slice(0,-1):s,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??hr(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??3e4,this.connectTimeoutMs=e.connectTimeoutMs??1e4,this.rpcTimeoutMs=e.rpcTimeoutMs??3e4,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??5e3,this.authTokenOnUpgrade=e.authTokenOnUpgrade??!1,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??3,this.defaultConnectionContext=e.connectionContext,this.persistence=Rr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ar(e.queryCache),this.clientQueryStore=new rt,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=lc),this.offlineQueue=new ht(e.offlineQueue,{onEvict:n((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onReplayingChange:n(()=>{this.emitSyncStatus()},"onReplayingChange"),onSizeChange:n(r=>{this.pendingChangeListeners.emit(r),this.emitSyncStatus()},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${lt()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=Eo(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),a=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,r&&(this.tokenFingerprint=void 0),this.applySubject(e,s);let h=this.identityFingerprint(),d=!r&&e!==null&&a,l=!r&&e===null&&i===null&&a&&!c,p=h!==i,f=!1;p&&(d?(this.restampQueuedIdentity(i,h),this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):l?(this.restampWatermarks(i,h),this.restampConnectionIdentity(i,h),this.reseedFromHydratedCache()):f=this.retirePreviousIdentity(i,c,u,e)),f||this.applyUpgradeBearer(this.reconcileUpgradeBearer(u,e,p)),p&&this.restartTabCoordinatorForIdentity(),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(h!==i||r||o)&&this.offlineQueue.size>0&&Ue(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){let s=this.identityVerdict(e);if(s!=="match")return{verdict:s};let r=Object.freeze({});return this.replayCredentials.set(r,{authToken:this.authToken,stamp:e}),{credential:r,verdict:s}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new g("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let a=r?.shardKey??"",o=this.identityFingerprint(),c,u,h;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:n(d=>{c=d},"onMutationAck")})}catch(d){if(!De(d))throw d;h=d}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(a)??0)){let d=this.clientWatermarks.get(o??"");d===void 0&&($i(this.clientWatermarks,8),d=new Map,this.clientWatermarks.set(o??"",d)),d.set(a,c)}if(h!==void 0)throw h;return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(B(this.url,`${this.authBasePath}${co}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let a=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,a,r),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=b(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r),e===void 0&&this.releaseIdleShard(s.shardKey)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=b(s.shardKey),i={context:e},a=this.connectionContextHolders.get(r);a?a.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let o=!1;return()=>{if(o)return;o=!0;let c=this.connectionContextHolders.get(r);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=b(r.shardKey),a=this.whisperHandlers.get(i);a||(a=new Map,this.whisperHandlers.set(i,a));let o=a.get(e),c=o===void 0;if(o||(o=new Set,a.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&this.sendWhisperJoin(u,i,e)}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(s)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(r.shardKey);d&&W(d,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(r.shardKey)}}subscribeLiveTopic(e){let{onError:s,onEvent:r,shardKey:i,stream:a,topic:o}=e;if(o.length===0)throw new g("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;let c=`ws-live-${String(this.nextLiveSocketId)}`,u=b(i),h=`/live/${a}/control`,d=this.whisperSubscribe(o,()=>{},{shardKey:i}),l=n(()=>{let m=d;d=void 0,m?.()},"l"),p=this.liveSocketGrants.get(u);p===void 0&&(p=new Map,this.liveSocketGrants.set(u,p)),p.set(c,{onError:s,onEvent:r,release:l,stream:a,topic:o});let f=this.getConnection(i)?.connectionId;f!==void 0&&this.grantWhenJoined(i,c,f);let y=!1;return()=>{if(y)return;y=!0;let m=this.liveSocketGrants.get(u),v=m?.delete(c)===!0;m?.size===0&&this.liveSocketGrants.delete(u);let S=this.getConnection(i)?.connectionId;v&&S!==void 0&&this.postLiveControl(h,i,{action:"unsubscribe",connectionId:S,stream:a,subscriptionId:c,topic:o}),l()}}whisper(e,s,r={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,J(s??null,`whisper data for topic '${e}'`),r)}connectRoom(e,s,r={}){let i=`room:${e.name}`,a=this.whisperSubscribe(i,p=>{s.onMessage(p)},r),o=!1,c=[],u=n(()=>{c.length=0},"c"),h=n(()=>{for(;c.length>0&&this.roomSendsAdmitted(r.shardKey);){if(!this.sendEncodedWhisper(i,c[0],r))return;c.shift()}},"d"),d=b(r.shardKey),l=this.roomFlushes.get(d)??new Set;return l.add(h),this.roomFlushes.set(d,l),this.roomIdentityResets.add(u),{close:n(()=>{o=!0,c.length=0,l.delete(h),l.size===0&&this.roomFlushes.delete(d),this.roomIdentityResets.delete(u),a()},"close"),send:n(p=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;let f=J(p,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(f):JSON.parse(JSON.stringify(f));return h(),c.length===0&&this.roomSendsAdmitted(r.shardKey)&&this.sendEncodedWhisper(i,y,r)?!0:c.length>=ac?!1:(c.push(y),!0)},"send")}}connectWebSocket(e,s,r={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),send:n(()=>{},"send")};let i=n(c=>{try{c?.()}catch(u){console.error("[lunora] socket route handler threw",u)}},"i"),a,o=this.openSupplementarySocket(this.supplementaryUrl(e),{offerBearer:!0,onClose:n(()=>{clearTimeout(a),i(s.onClose)},"onClose"),onMessage:n(c=>{let u;try{u=JSON.parse(typeof c.data=="string"?c.data:"")}catch{return}u.type==="message"&&(o.resetBackoff(),i(()=>{s.onMessage(C(u.data))}))},"onMessage"),onOpen:n(()=>{clearTimeout(a);let c=o.socket();a=setTimeout(()=>{o.socket()===c&&o.resetBackoff()},5e3),i(s.onOpen)},"onOpen"),shardKey:r.shardKey});return{close:n(()=>{clearTimeout(a),o.close()},"close"),send:n(c=>{let u=JSON.stringify(J(c,`socket message for '${e}'`)),h=o.socket();if(h!==void 0)try{h.send(u)}catch{}},"send")}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}syncStatus(){let e=this.computeStatus(),s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader(),r=0;for(let a of this.subscriptions.all())(s||this.connectionGateState(a.shardKey).polling?a.valueReceived:a.ack==="acked")||(r+=1);for(let a of this.shapeSubscriptions.values())a.answered||(r+=1);let i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:r,pendingWrites:i,synced:Ue(e)&&r===0&&i===0}}onSyncStatus(e){let s=this.syncStatusListeners.add(e),r=this.syncStatus();return this.lastSyncStatus=r,e(r),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let a of r){let o=this.connections.get(a);e.push({confirmedMutationWatermark:s?.get(a)??0,hasSocket:o?.socket!==void 0,shardKey:a===""?void 0:a,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(a=>({acked:a.ack==="acked",functionPath:a.fn.__lunoraRef,id:a.id,kind:"query",lastMutationId:a.lastMutationId,pendingOptimisticLayers:a.optimisticLayers.length,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size}));for(let a of this.shapeSubscriptions.values())i.push({acked:a.answered,functionPath:`shape:${a.name}`,id:a.id,kind:"shape",lastMutationId:a.lastMutationId,pendingOptimisticLayers:0,rowCount:a.rows.size,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((a,o)=>(a.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((a,o)=>a.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){let s=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),s}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){let{WebSocketImpl:e}=this;if(e===void 0)return;let s=n(o=>o.protocol==="wss:"||o.protocol==="https:","t"),r=Me(this.wsUrl),i=n(o=>{let c=Me(String(o));return c.host===r.host&&s(c)===s(r)},"i"),a=e;return new Proxy(e,{construct:n((o,[c,u,...h])=>new a(c,u??(i(c)?this.upgradeProtocols():void 0),...h),"construct")})}isCrossTabFollower(){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()}expectsPush(e={}){let s=this.getConnection(e.shardKey);return s===void 0||s.wsState==="open"?!0:s.polling.isPolling()||!s.polling.hasFailedOpen()}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,s){this.clientQueryStore.set(e,s)}subscribeClientQuery(e,s){return this.clientQueryStore.subscribe(e,s)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,s,r){return Lr(this,e,s,r)}whenReady(e={}){return e.signal===void 0?this.readyPromise:Xt(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,K(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=de(e,s,r),a=this.hydratedQueryCache.get(i);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=P.key(e,s,r),a=this.subscriptions.get(i);return{answered:a!==void 0&&(a.lastValue!==void 0||a.ack==="acked"||a.valueReceived),present:a!==void 0,value:a?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,signal:r.signal})}async batch(e){return ce(this.rpcTimeoutMs,void 0,async s=>this.sendBatch(e,s))}async mutation(e,s,r={}){if(r.signal?.aborted)throw ve(r.signal);let{value:i}=await Xt(this.runMutation(e,s,r),r.signal);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0,signal:r.signal,unbounded:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),a=r.toArgs??(d=>({rows:d})),o=s.length,c=0,u=0,h=0;for(let d=0;d<o;d+=i){let l=s.slice(d,d+i),p=h,{committed:f}=await this.runMutation(e,a(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(p)}`},shardKey:r.shardKey});h+=1,c+=l.length,f&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:h,imported:u,queued:c-u}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=this.openSupplementarySocket(B(Jt(this.url),eo),{onMessage:n(r=>{let i;try{i=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(s.resetBackoff(),e(i.records.map(a=>ms(a))))},"onMessage")});return s.close}subscribe(e,s,r,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};let a=s??{},o=P.key(e.__lunoraRef,a,i.shardKey),c=this.subscriptions.get(o),u=ut(r),h=ut(i.onError),d=ut(i.onCheckpoint);if(!c){this.nextSubId+=1;let y=`sub_${this.nextSubId.toString()}`,m=K(a),v=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);c={ack:"idle",args:a,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:v?.value,optimisticLayers:[],serverBase:v?.value,serverCursor:v?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:J(a,`args for '${e.__lunoraRef}'`),...v?.serverEpoch===void 0?{}:{serverEpoch:v.serverEpoch}},this.subscriptions.add(c),this.emitSyncStatus(),this.isCrossTabFollower()&&Ue(this.computeStatus())&&this.awaitLeaderAnswer(c),v!==void 0&&this.cacheSeededQueries.set(o,v)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c,p=!1,f=n(()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",f),l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0)){this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(P.keyOf(l)),this.subscriptions.remove(l);let y=this.getConnection(l.shardKey);y&&this.settleSubscribeWatchdog(y,l.id),this.releaseIdleShard(l.shardKey),this.emitSyncStatus(),this.settleAwaitedAnswer(l,!0)}},"p");return i.signal?.addEventListener("abort",f,{once:!0}),i.signal?.aborted&&f(),f}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:o}=r;return o!==void 0&&queueMicrotask(()=>{o({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,a={answered:!1,args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:J(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,a),this.emitSyncStatus(),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(a),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(a.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(a.shardKey),this.emitSyncStatus()}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new g("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:a}=r,o=s??{},{handle:c,iterable:u}=at({maxBuffer:r.maxBuffer,onCancel:n(()=>{this.cancelStream(i,a)},"onCancel")});this.ensureSocket(a);let h=this.getConnection(a),d={id:i,query:{args:J(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:a},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:a};this.streams.set(i,l);let p=h?.wsState==="open"&&W(h,d);if(!p&&h===void 0)return this.forgetStream(i),c.fail(new g("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!p){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=64;){let f=h.pendingStreams.shift()?.id,y=f?this.streams.get(f):void 0;y&&(y.handle.fail(new g("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}h.pendingStreams.push(d)}return u}httpStream(e,s,r={}){if(this.closed)throw new g("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new g("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return wr(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0;for(let e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new g("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.supplementaryBounces.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear();for(let e of this.leaderAnswerTimers.values())clearTimeout(e);this.leaderAnswerTimers.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}retirePreviousIdentity(e,s,r,i){return this.rejectQueuedForIdentityChange(e),this.warnRefreshWithoutSubject(r,i),sc(e,s,i)?(this.evictPreviousIdentitySession(),!0):!1}reconcileUpgradeBearer(e,s,r){return!this.authTokenOnUpgrade||s===null||e===s?"none":r?e===null?"cold":"none":e===null?"none":"warm"}upgradeProtocols(){return this.authTokenOnUpgrade&&this.authToken?[Co,Io(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets()}assertOpen(){if(this.closed)throw new g("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new g("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){let s=n(r=>b(r)===e,"t");return this.subscriptions.all().some(r=>s(r.shardKey))||[...this.shapeSubscriptions.values()].some(r=>s(r.shardKey))||[...this.streams.values()].some(r=>s(r.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(r=>s(r.shardKey))}releaseIdleShard(e){let s=b(e),r=this.connections.get(s);this.closed||s===""||r===void 0||(clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.idleTimer=void 0,!(this.closed||this.connections.get(s)!==r||this.shardInUse(s))&&(r.wasEverConnected&&this.idleClosedShards.add(s),this.teardownConnection(r),this.connections.delete(s),this.emitConnectionStatus())},5e3))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=b(e.shardKey);for(let[i,a]of this.streams)b(a.shardKey)===s&&(a.handle.fail(new g("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,we(e);let{socket:r}=e;if(r){e.socket=void 0;try{r.close()}catch{}}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,s={activeShapes:n(()=>[...this.shapeSubscriptions.values()],"activeShapes"),activeSubscriptions:n(()=>this.subscriptions.all(),"activeSubscriptions"),awaitLeaderAnswers:n(()=>{this.awaitLeaderAnswers()},"awaitLeaderAnswers"),broadcastStatus:n((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:n(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:n(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:n(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:n(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:n(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:n(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:n(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:n(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:n(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:n(()=>this.clientId,"clientIdentifier"),dropCacheSeed:n(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:n((r,i,a)=>{this.ackAndAdvanceCursor(r,i,a)},"ackAndAdvanceCursor"),settleAwaitedAnswer:n((r,i)=>{this.settleAwaitedAnswer(r,i)},"settleAwaitedAnswer"),subscription:n(r=>this.subscriptions.get(r),"subscription")};return new nt({channelName:e,onBecomeLeader:n(()=>{zo(s)},"onBecomeLeader"),onStopBeingLeader:n(()=>{Jo(s)},"onStopBeingLeader"),onConnectionStatus:n((r,i)=>{Yo(s,r,i)},"onConnectionStatus"),onSubscriptionData:n((r,i,a,o,c)=>{Zo(s,r,i,a,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:n(()=>{Xo(s)},"onLeaderClaimAnswered"),onSubscriptionError:n((r,i,a)=>{ec(s,r,i,a)},"onSubscriptionError"),onSubscriptionSettled:n((r,i,a,o,c,u)=>{tc(s,r,i,a,o,c,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new g("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(B(this.url,ns),{body:JSON.stringify({calls:e.map((c,u)=>({args:J(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let a;try{a=await r.json()}catch{throw H(new g("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`),r.headers)}let o=be(a);if(!r.ok||o!==void 0&&!a.results)throw o!==void 0?H(Ne(o),r.headers):H(new g("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`),r.headers);for(let c of a.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return ko(a.results??[],e.length,r.headers)}async runMutation(e,s,r){this.assertOpen();let i=ic(e,r),a=s,o=i.mutationId??lt();this.mutationIssueCounter+=1;let c=this.mutationIssueCounter,u=this.takeReplayCredential(i.replayCredential),h=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);let{confirms:d,rollbacks:l}=this.applyOptimisticUpdates(e.__lunoraRef,a,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,s,i.shardKey,l,d);let p=i.onlineOnly?void 0:this.offlineFlushes.get(b(i.shardKey));p!==void 0&&await p;let{httpFirst:f,midReconnect:y,shouldQueueOffline:m,socketDown:v}=this.writeQueueGate(i.shardKey),S=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),E=n(async(w=!1)=>this.enqueueOfflineMutation(e,a,i.shardKey,h,o,l,d,w?void 0:i.precondition,i.mutationId,u?.stamp,w,c),"b");if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,l),v||y||S)return E();let I;try{let w=await this.rpc(e.__lunoraRef,a,i.shardKey,{baselineSeq:h,captureBookmark:!0,...u?.flags,mutationId:o,onCommitCursor:n(R=>{I=R},"onCommitCursor")});for(let R of d)R(I);return{committed:!0,value:w}}catch(w){let R=dc(w,a),se=f&&m&&R,N=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(w instanceof TypeError||w instanceof x)&&ds(a)){let A=E(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),A}throw this.settleFailedDirectWrite(w,I,d,l,u?.flags.authToken),hc(i.onlineOnly,se,R,N)?Hr(e.__lunoraRef,w):w}}refuseOnlineOnlyWhenDown(e,s,r=[]){if(!s.onlineOnly)return;let i=this.writeQueueGate(s.shardKey);if(i.socketDown||i.midReconnect)throw ue(r),Hr(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){let{hasSocket:s,idleClosed:r,polling:i,wasEverConnected:a,wsState:o}=this.connectionGateState(e),{queueBeforeFirstConnect:c}=this.offlineQueue,u=a||c,h=this.WebSocketImpl!==void 0&&u,d=i||r;return{httpFirst:d,midReconnect:o==="connecting"&&u&&!d,shouldQueueOffline:h,socketDown:o!=="open"&&!s&&h&&!d,socketOpen:o==="open"}}settleFailedDirectWrite(e,s,r,i,a){if(this.noteIdentityMismatch(e),a!==void 0&&this.noteReplayAuthRefusal(e,a),De(e)){for(let o of r)o(s);return}ue(i)}async enqueueOfflineMutation(e,s,r,i,a,o,c,u,h,d,l,p){let f=d===void 0?this.identityFingerprint():d;if(this.outbox){this.outboxMutationCounter+=1;let y=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:h??`${this.clientId}:${String(y)}`,identity:f,mutationId:y,...o.length>0&&{onRejected:n(()=>{ue(o)},"onRejected")},shardKey:r})}catch(m){throw ue(o),m instanceof Error?m:new Error(String(m))}for(let m of c)m(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((y,m)=>{let v={ambiguousSend:l,args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:a,issueSeq:p,clientId:this.clientId,identity:f,precondition:this.holdWhileUnanswered(u),onCommit:n(S=>{for(let E of c)E(S)},"onCommit"),reject:n(S=>{this.queuedIdentities.delete(a),De(S)||ue(o),m(S instanceof Error?S:new Error(String(S))),this.releaseIdleShard(r)},"reject"),resolve:y,shardKey:r};this.offlineQueue.enqueue(v),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),v.id!==void 0&&this.queuedIdentities.set(v.id,f)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=b(e);return this.offlineQueue.hasPending(r=>b(r.shardKey)===s)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let s of e)this.queuedOfflineShardKeys.add(s),this.ensureSocket(s)}catch{}}hydrateAsOutboxLeader(){let e=n(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),s=globalThis.navigator?.locks;if(!s){e();return}s.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(r=>{if(this.closed){r();return}this.outboxLeaderRelease=r}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),s=new Map;for(let r of this.subscriptions.all())s.set(de(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(ts(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let a=s.get(r);if(a&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(a,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(de(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),ae(e,s.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let s=this.cacheSeededQueries.get(e);s!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,s))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,s]of this.cacheSeededQueries){let r=this.subscriptions.get(e);r!==void 0&&(r.serverBase=void 0,r.serverCursor=void 0,r.serverEpoch=void 0,ae(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=de(e,s,r),a=this.hydratedQueryCache.get(i);if(!(a===void 0||!this.cachedQueryMatchesIdentity(a)))return this.hydratedQueryCache.delete(i),a}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=de(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.hydratedQueryCache.get(s);r!==void 0&&this.cachedQueryMatchesIdentity(r)&&(this.hydratedQueryCache.delete(s),this.seedSubscriptionFromCache(e,r))}}persistQueryValue(e){let s=e.serverBase;if(!this.queryCache||s===void 0)return;let r=de(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,a=i===void 0?this.identityFingerprint():i;a===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:a,serverCursor:e.serverCursor,ts:Date.now(),value:s,...a===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},250))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}installPageHideFlush(){let e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;let s=n(()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},"t"),r=n(()=>{e.document?.visibilityState==="hidden"&&s()},"s");e.addEventListener("pagehide",s),e.document?.addEventListener("visibilitychange",r),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",s),e.document?.removeEventListener("visibilitychange",r)}}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=b(e),r;for(let i of this.subscriptions.all())b(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}composedBaselineFor(e,s){return e===void 0?this.baselineCursorFor(s):e??void 0}async pollSubscriptions(e){let s=b(e),r=[];for(let c of this.subscriptions.all())b(c.shardKey)===s&&(ds(c.args)?r.push(c):(this.markQueryRejected(c,!0),ee(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(r.length===0)return this.probeOrigin();let i=Tr(),a=this.identityFingerprint(),o;try{o=await Mr(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==a)return!0;for(let[c,u]of r.entries()){let h=o[c];if(h!==void 0){if(!h.ok){this.markQueryRejected(u,!0),ee(u.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:j(h.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await Mr(async s=>e(B(this.url,ns),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;let e=this.syncStatus(),s=this.lastSyncStatus;s?.connection===e.connection&&s.pendingSubscriptions===e.pendingSubscriptions&&s.pendingWrites===e.pendingWrites&&s.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){let e=this.computeStatus();this.emitSyncStatus(),e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let a=[],o=[];if(!i)return{confirms:a,rollbacks:o};let c=P.key(e,s,r),u=this.subscriptions.get(c);if(u){let h=es(u,i);h&&(a.push(h.confirm),o.push(h.rollback))}return{confirms:a,rollbacks:o}}applyOptionalOptimisticUpdate(e,s,r,i,a){e&&this.applyOptimisticUpdate(e,s,r,i,a)}applyOptimisticUpdate(e,s,r,i,a){let{confirms:o,rollbacks:c,store:u}=Or(this.subscriptions,r);try{e(u,s)}catch{ue(c);return}i.push(...c),a.push(...o)}getConnection(e){return this.connections.get(b(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!W(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}let s=this.getConnection(e),r=s===void 0&&this.idleClosedShards.has(b(e));return{hasSocket:s?.socket!==void 0,idleClosed:r,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??r,wsState:s?.wsState??"idle"}}getOrCreateConnection(e){let s=b(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:No({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:n(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:n(()=>{this.emitConnectionStatus()},"onStateChange"),poll:n(async()=>this.pollSubscriptions(e),"poll")}),reconnect:Fe(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}openSupplementarySocket(e,s){if(this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),resetBackoff:n(()=>{},"resetBackoff"),socket:n(()=>{},"socket")};let r=Fe(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},a,o=!1,c=n(()=>{o||this.closed||(a=setTimeout(p,r.next()))},"o"),u=n(m=>{o||this.WebSocketImpl===void 0||Dr(i,this.wsUrlFor(s.shardKey,m,e),this.managedSocketOptions,{onClose:n(()=>{c(),s.onClose?.()},"onClose"),onMessage:s.onMessage,...s.onOpen===void 0?{}:{onOpen:s.onOpen},...s.offerBearer===!0?{protocols:this.upgradeProtocols()}:{}})},"c"),h=0,d,l=n(async m=>{let v=this.wsCredentialGeneration;h+=1;let S=h,E;d=v;try{E=await cc(m,oc)}catch{S===h&&(d=void 0,c());return}if(S===h){if(d=void 0,v!==this.wsCredentialGeneration){p();return}u(E)}},"h"),p=n(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsTicket:m}=this;if(typeof m=="function"){l(m).catch(()=>{});return}u(m)},"l");p();let f=n(()=>{o=!0,a!==void 0&&(clearTimeout(a),a=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),we(i);let{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}},"p");this.adminSocketTeardowns.add(f);let y=n(()=>{let{socket:m}=i;if(m===void 0){d!==void 0&&d!==this.wsCredentialGeneration&&(h+=1,d=void 0,p());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),we(i);try{m.close()}catch{}s.onClose?.(),c()},"y");return this.supplementaryBounces.add(y),{close:n(()=>{f(),this.adminSocketTeardowns.delete(f),this.supplementaryBounces.delete(y)},"close"),resetBackoff:n(()=>{r.reset()},"resetBackoff"),socket:n(()=>i.socket,"socket")}}supplementaryUrl(e){let s=Me(this.wsUrl),r=s.pathname.endsWith(as)?s.pathname.slice(0,-as.length):s.pathname;return s.pathname=B(r,e),Yt(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){let i=Me(r);if(e===void 0&&s===void 0&&!i.searchParams.has("token"))return r;let a=new Set([...e===void 0?[]:["shard"],"token"]),o=[...i.searchParams].filter(([c])=>!a.has(c)).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);return e!==void 0&&o.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&o.push(`token=${encodeURIComponent(s)}`),i.search=o.join("&"),Yt(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[fo]=mo(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let a=e.authToken===void 0?this.authToken:e.authToken;if(a&&(r.authorization=`Bearer ${a}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let o=this.bookmark.get();o&&(r["x-d1-bookmark"]=o)}return r}async rpc(e,s,r,i={}){let{fetchImpl:a}=this;if(!a)throw new x("LunoraClient: no `fetch` implementation available");let o=this.rpcRequestHeaders(i,r),c=i.authToken===void 0?this.authToken:i.authToken,u=JSON.stringify({args:J(s,`args for '${e}'`),functionPath:e,shardKey:r}),{body:h,response:d}=await ce(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{let y=await a(B(this.url,Ya),{body:u,headers:o,method:"POST",signal:f});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){let f=d.headers.get("x-d1-bookmark");f&&this.bookmark.set(f)}if(h===void 0)throw xe(d.status,d.statusText,d.headers);let l=h;if(typeof l!="object"||l===null||Array.isArray(l))throw xe(d.status,d.statusText,d.headers);let p=be(h);if(p!==void 0)throw Vt(p,d.headers);if(!d.ok)throw xe(d.status,d.statusText,d.headers);i.onMutationAck?.(h.lastMutationId),i.onCommitCursor?.(h.commitCursor),this.noteCredentialAccepted(c),this.learnDefaultShardKey(d,r),this.recordShardCursor(r,h.commitCursor);try{return C(h.result)}catch(f){throw H(st(f),d.headers)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new g("INTERNAL","LunoraClient: no `fetch` implementation available");let a={};this.authToken&&(a.authorization=`Bearer ${this.authToken}`);let o=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:o?(c=r,i!==void 0&&(a["content-type"]=i)):(c=JSON.stringify(r),a["content-type"]="application/json");let u=await this.fetchImpl(B(this.url,e),{body:c,headers:a,method:s}),h;try{h=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new g("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let d=be(h);if(d!==void 0)throw Ne({...d,message:d.message??"admin request failed"});if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new g("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return h}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(b(e.shardKey));W(e,{caps:nc,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())b(s.shardKey)===b(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);s.wsState==="open"||s.wsState==="connecting"||(s.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(s,e).catch(()=>{this.handleDisconnect(s)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,s){let{wsToken:r,wsTicket:i}=this;if(typeof r=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,s);return}this.openSocket(e,s,{session:r,ticket:i})}async openSocketWithProvidedCredentials(e,s){let r=this.wsCredentialGeneration,i=Symbol("ws-token-attempt"),a;e.providerAttempt=i;try{a=await ce(this.connectTimeoutMs,void 0,async()=>({session:await xr(this.wsToken),ticket:await xr(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(r!==this.wsCredentialGeneration){await this.startShardSocket(e,s);return}this.openSocket(e,s,a)}}openSocket(e,s,r){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),r.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=r.session,e.retired=!1;let i=this.wsCredentialGeneration;Dr(e,this.wsUrlFor(s,r.ticket),this.managedSocketOptions,{onClose:n(a=>{a?.code===4003&&e.polling.noteFailedOpen(),a?.code===4001?this.notifyTokenExpired():a?.code===4003&&a.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,this.notifyTokenExpired()),this.handleDisconnect(e)},"onClose"),onMessage:n(a=>{e.retired!==!0&&this.handleServerMessage(a.data,s)},"onMessage"),onOpen:n(()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},5e3),this.sendConnectEnvelope(e),this.markShardPendingAck(s,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(let c of this.subscriptions.all())b(c.shardKey)===b(s)&&this.queueResubscribe(c);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let c=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:u,type:h}of c)W(e,{id:u,type:h});this.releaseIdleShard(s)}Ao(e);let a=b(s),o=this.whisperHandlers.get(a);if(this.dropWhisperJoinWaiters(a),this.whisperJoins.set(a,new Map),o)for(let c of o.keys())this.sendWhisperJoin(e,a,c);e.roomsRejoined=!0,this.releaseRoomSends(s),this.flushOfflineQueue(s).catch(()=>{})},"onOpen"),protocols:this.upgradeProtocols()})}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),W(r,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),we(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(b(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,a]of this.streams)if(!(b(a.shardKey)!==b(e.shardKey)||s.has(i))){if(a.durable){let o={...a.message,...a.generation===void 0?{}:{generation:a.generation},sinceChunk:a.lastSeq};a.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}a.handle.fail(new g("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}markShardPendingAck(e,s=!1){let r=b(e);for(let i of this.subscriptions.all())b(i.shardKey)===r&&(z(i,"idle"),i.pendingDeltaRun=void 0,s&&(i.valueReceived=!1,this.awaitingAnswer.add(i),this.answeredUnreadable.delete(i)));for(let i of this.shapeSubscriptions.values())b(i.shardKey)===r&&(i.answered=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<3;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribeSlots.add(s.id)}}settleSubscribeWatchdog(e,s){clearTimeout(e.unackedWatchdogs.get(s)),e.unackedWatchdogs.delete(s),e.resubscribeSlots.delete(s)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(let s of e.unackedWatchdogs.values())clearTimeout(s);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,s=!1){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.ack==="acked"||!s&&e.ack==="inflight")return!1;let i=e.serverCursor!==void 0&&e.serverBase!==void 0,a=W(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return a&&z(e,"inflight"),a&&!s&&this.armUnackedWatchdog(r,e),a}armUnackedWatchdog(e,s,r=!1){clearTimeout(e.unackedWatchdogs.get(s.id)),e.unackedWatchdogs.set(s.id,setTimeout(()=>{if(r){e.unackedWatchdogs.delete(s.id),ct(s),this.settleAwaitedAnswer(s,!1);return}let i=s.ack!=="acked"&&this.subscriptions.getById(s.id)===s&&this.sendSubscribeIfOpen(s,!0);this.settleSubscribeWatchdog(e,s.id),i?this.armUnackedWatchdog(e,s,!0):ct(s)},1e4))}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&W(s,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,s){let r=Lo(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let a=this.getConnection(s);if(a){let{id:o}=i;this.settleSubscribeWatchdog(a,o)}}switch(i.type){case"ack":{let a=this.subscriptions.getById(i.id);a&&this.ackAndAdvanceCursor(a,void 0,void 0);return}case"chunk":{let{data:a,generation:o,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof o=="number"&&(h.generation=o),h.durable=!0),h?.handle.push(C(a));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s),this.adoptSocketConnectionId(i,s),this.confirmShardIdentity(s);break}case"live":{this.dispatchLive(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.pokeAssembler.part(s,i);break}case"pokeStart":{this.pokeAssembler.start(s,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(b(s),i.topic);break}}}handleErrorMessage(e){let s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;let{id:r}=e,i=r===void 0?void 0:this.streams.get(r);if(i&&r!==void 0){i.handle.fail(pr(e)),this.forgetStream(r);return}let a=r===void 0?void 0:this.subscriptions.getById(r);if(a){ct(a);let c=$t(e),u=this.identityFingerprint(),h=P.keyOf(a);this.markQueryRejected(a),ee(a.errorCallbacks,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(h,c,u);return}let o=r===void 0?void 0:this.shapeSubscriptions.get(r);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),ee(o.errorCallbacks,$t(e)))}markQueryRejected(e,s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){this.settleAwaitedAnswer(e,!1),!(s?e.valueReceived:e.ack==="acked")&&(s?e.valueReceived=!0:z(e,"acked"),this.emitSyncStatus())}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){Wo(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let a=this.shapeSubscriptions.get(i);a&&!r.undecodable.has(i)&&this.applyPokePart(a,r,e)}}}applyPokePart(e,s,r){let i=e.answered,a=Bo(e,s,r);if(e.answered!==i&&this.emitSyncStatus(),Ur(e),a==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){z(e,"idle"),e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i||e.type==="data"&&Go(i,e))return;let a,o=i.pendingDeltaRun;try{a=dr(e,o===void 0?i.serverBase:o.payload)}catch(u){i.pendingDeltaRun=void 0,ee(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${u instanceof Error?u.message:String(u)}`}),this.settleAwaitedAnswer(i,!1);return}if(a===qt){this.resnapshotSubscription(i);return}if($o(e)){i.pendingDeltaRun={payload:a};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(P.keyOf(i));let c=s!==void 0&&!i.valueReceived;if(cn(i,a,{cursor:e.cursor,epoch:e.epoch}),c&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(ps(i,e.lastMutationId),fs(i,!0)),this.persistQueryValue(i),dt(i,i.serverCursor),s!==void 0&&Cr(i,s),ae(i,a),this.tabCoordinator?.isLeader()){let u=P.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(u,a,i.serverCursor,i.serverEpoch,this.identityFingerprint())}this.settleAwaitedAnswer(i,!0)}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&(s.pendingDeltaRun=void 0,this.ackAndAdvanceCursor(s,e.cursor,e.epoch),this.tabCoordinator?.isLeader()&&s.serverBase!==void 0&&this.tabCoordinator.broadcastSubscriptionData(P.keyOf(s),s.serverBase,s.serverCursor,s.serverEpoch,this.identityFingerprint()),this.settleAwaitedAnswer(s,!0))}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s&&(this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&ps(s,e.lastMutationId),fs(s),this.tabCoordinator?.isLeader())){let r=P.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){let i=e.ack!=="acked";z(e,"acked"),i&&this.emitSyncStatus(),(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),dt(e,e.serverCursor)&&ae(e,e.serverBase))}adoptSocketConnectionId(e,s){let r=this.getConnection(s);if(!(r===void 0||typeof e.connectionId!="string")){r.connectionId=e.connectionId,r.whisperAck=e.whisperAck===!0;for(let i of this.liveSocketGrants.get(b(s))?.keys()??[])this.grantWhenJoined(s,i,e.connectionId)}}grantWhenJoined(e,s,r){let i=b(e),a=this.liveSocketGrants.get(i)?.get(s);if(a===void 0)return;let{stream:o,topic:c}=a,u=n(()=>{this.liveSocketGrants.get(i)?.get(s)===void 0||this.getConnection(e)?.connectionId!==r||this.postLiveControl(`/live/${o}/control`,e,{action:"subscribe",connectionId:r,stream:o,subscriptionId:s,topic:c},h=>{this.refuseLiveGrant(e,s,h,r)})},"c");this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,c,u):u()}sendWhisperJoin(e,s,r){let i=this.whisperJoinState(s,r);i.pending+=1,i.joined=!1,W(e,{topic:r,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,s){let r=this.whisperJoins.get(e)?.get(s);if(r!==void 0&&(r.pending=Math.max(0,r.pending-1),!(r.pending>0))){r.joined=!0;for(let i of r.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,s)}}releaseWhisperJoin(e,s){if(this.whisperHandlers.get(e)?.has(s)===!0)return;let r=this.whisperJoins.get(e),i=r?.get(s);if(!(r===void 0||i===void 0||i.pending>0)){for(let a of i.waiters.splice(0))clearTimeout(a.timer);r.delete(s),r.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,s,r){let i=this.whisperJoinState(e,s);if(i.joined){r();return}let a={run:r,timer:void 0};a.timer=setTimeout(()=>{i.waiters=i.waiters.filter(o=>o!==a),r()},un),i.waiters.push(a)}dropWhisperJoinWaiters(e){for(let s of this.whisperJoins.get(e)?.values()??[])for(let r of s.waiters.splice(0))clearTimeout(r.timer)}whisperJoinState(e,s){let r=this.whisperJoins.get(e);r===void 0&&(r=new Map,this.whisperJoins.set(e,r));let i=r.get(s);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},r.set(s,i)),i}refuseLiveGrant(e,s,r,i){let a=b(e),o=this.liveSocketGrants.get(a),c=o?.get(s);o===void 0||c===void 0||this.getConnection(e)?.connectionId!==i||(o.delete(s),o.size===0&&this.liveSocketGrants.delete(a),c.release(),c.onError?.({status:r,topic:c.topic}))}postLiveControl(e,s,r,i){let{fetchImpl:a}=this;if(!a)return;let o=JSON.stringify(s===void 0?r:{...r,shardKey:s}),c=this.rpcRequestHeaders({},s);this.liveControlChain=this.liveControlChain.then(()=>uc(a,B(this.url,e),o,c)).then(u=>{u>=400&&u<500&&u!==404&&u!==401&&i?.(u)}).catch(()=>{})}dispatchLive(e,s){let r=this.liveSocketGrants.get(b(s));if(!r)return;let i=C(e.data);for(let a of r.values())if(!(a.stream!==e.stream||a.topic!==e.topic))try{a.onEvent(i)}catch{}}dispatchWhisper(e,s){let r=this.whisperHandlers.get(b(s))?.get(e.topic);if(!r)return;let i=C(e.data);for(let a of r)try{a(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.forgetStream(e);return}let r=this.subscriptions.getById(e);r&&(z(r,"idle"),this.emitSyncStatus(),ee(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:(this.tokenFingerprint?.token!==e&&(this.tokenFingerprint={hash:this.hashToken(e),token:e}),this.tokenFingerprint.hash)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let a=e.charCodeAt(i);s^=a,s=Math.imul(s,16777619),r=Math.imul(r,33)+a}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&Ue(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,s,r){if(!(this.closed||this.authToken!==e||r!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(s?.id??null,r);return}s!==null&&this.setAuthToken(e,s.id)}}adoptCookieSubject(e,s){return this.closed||this.authToken!==null||s<this.identityAnsweredAt?!1:(this.identityAnsweredAt=s,this.identitySettled=!0,this.setAuthToken(null,e),!0)}sendEncodedWhisper(e,s,r){this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey),a=i!==void 0&&W(i,{data:s,topic:e,type:"whisper"});return this.releaseIdleShard(r.shardKey),a}roomSendsAdmitted(e){let s=this.getConnection(e);return s?.wsState==="open"&&s.retired!==!0&&s.identityConfirmed===!0&&s.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(let s of this.roomFlushes.get(b(e))??[])s()}confirmShardIdentity(e){let s=this.getConnection(e);s!==void 0&&(s.identityConfirmed=!0,s.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}warnRefreshWithoutSubject(e,s){e===null||s===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let a=new Error("offline mutation discarded: auth identity changed before replay");a.code="OFFLINE_IDENTITY_CHANGED",i.reject(a),this.emitItemSettled(i,"rejected",a)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let a=s??"",o=this.clientWatermarks.get(a);if(o===void 0)this.clientWatermarks.set(a,i);else for(let[c,u]of i)o.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.resetRoomSends(),this.revokeCacheSeededValues(),this.reconnectCold(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}resetRoomSends(){for(let e of this.roomIdentityResets)e()}reconnectCold(){for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.pendingDeltaRun=void 0,z(e,"idle"),e.valueReceived=!1,ae(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,Ur(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)});for(let e of this.supplementaryBounces)e()}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=b(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:a}=this;try{await this.drainOfflineQueue(e,a)}catch{}!this.closed&&this.authToken!==a&&this.offlineQueue.size>0&&Ue(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&(this.offlineFlushes.delete(s),this.releaseIdleShard(e))}snapshotAnswer(e){let s=is(e),r=s&&this.subscriptions.get(P.key(s.functionPath,s.args,s.shardKey));if(r!==void 0)return this.awaitingAnswer.has(r)?"awaiting":this.answeredUnreadable.has(r)?"unreadable":void 0}holdWhileUnanswered(e){let s=is(e);if(e===void 0||s===void 0)return e;let r=n(()=>this.snapshotAnswer(e)!==void 0||e(),"s");return rs(r,s),r}awaitLeaderAnswers(){for(let e of this.subscriptions.all())this.awaitLeaderAnswer(e)}awaitLeaderAnswer(e){this.awaitingAnswer.add(e),this.answeredUnreadable.delete(e),clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.set(e,setTimeout(()=>{this.leaderAnswerTimers.delete(e),this.isCrossTabFollower()&&this.settleAwaitedAnswer(e,!1)},2*1e4))}settleAwaitedAnswer(e,s){clearTimeout(this.leaderAnswerTimers.get(e)),this.leaderAnswerTimers.delete(e),s&&this.answeredUnreadable.delete(e),this.awaitingAnswer.delete(e)&&(s||this.answeredUnreadable.add(e),this.answerHeldShards.delete(b(e.shardKey))&&this.flushOfflineQueue(e.shardKey).catch(()=>{}))}holdUndecidedWrites(e,s){let r=s.findIndex(i=>this.snapshotAnswer(i.precondition)==="awaiting");return r===-1?s:(this.offlineQueue.requeue(s.slice(r)),this.answerHeldShards.add(e),s.slice(0,r))}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let d of r){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",l)}let i=b(e),a=this.holdUndecidedWrites(i,this.offlineQueue.drain(d=>b(d.shardKey)===i));if(a.length===0)return;let o=[],c=[];for(let d of a){let l=this.replayGateVerdict(d);l==="send"?o.push(d):l==="hold"&&c.push(d)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(o);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let h=[];for(let d=0;d<u.length;d+=os){let l=u.slice(d,d+os),p=await this.replayBatched(l,e,s);if(h.push(...p.requeue),p.stop||p.requeue.length>0){h.push(...u.slice(d+os));break}}h.length>0&&this.offlineQueue.requeue(h),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=b(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,hs(i))})}noteReplayRetryDelay(e,s,r){let i=b(e),a=this.replayRetryState.get(i),o=(a?.attempts??0)+1,c=xo(s,o)??(r===null&&Le(s)?hs(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?a?.delayMs:Math.max(a?.delayMs??0,c)})}scheduleRateLimitedRetry(e){let s=b(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let a=this.replayRetryTimers.get(s);a!==void 0&&clearTimeout(a),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{J(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let s=this.identityFingerprint();return s===null&&this.identityUnresolved()?"unknown":e===s||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":s===null?"unknown":"mismatch"}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.identityVerdict(s);if(r==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),r==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.resolve(s),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,s){let r=e.headers.get("x-lunora-shard-key");if(r===null||s!==void 0||this.defaultShardKey===r)return;this.defaultShardKey=r;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,s){if(typeof s!="number")return;let r=this.cursorKeyFor(e);this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,s))}shouldRequeueReplayFailure(e,s){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,s)||Fr(e)}noteReplayAuthRefusal(e,s){if(!Le(e))return!1;let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;let s=this.replayCredentials.get(e);if(s===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:s.authToken,...cs(s.stamp,s.authToken)},stamp:s.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}spendsLastReplayAttempt(e,s){if(e.id===void 0)return!1;let r=s?.code;if(e.ambiguousSend!==!0||Le(s)||r==="RATE_LIMITED"||r==="TOO_MANY_REQUESTS"||!Fr(s))return!1;let i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=5}keepUnexhaustedAmbiguousWrites(e,s){return e.filter(r=>r.ambiguousSend===!0&&this.spendsLastReplayAttempt(r,s)?(this.settleReplayTerminal(r,s),!1):!0)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let a=e[i];if(!a)continue;let o;try{let c=await this.rpc(a.functionPath,a.args,a.shardKey,{authToken:r,baselineSeq:a.baselineSeq,captureBookmark:!0,clientId:a.clientId??this.clientId,...cs(a.identity,r),mutationId:a.id,onCommitCursor:n(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(a,c,o)}catch(c){if(De(c)){this.settleReplayUndecodable(a,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)||this.spendsLastReplayAttempt(a,c)){this.settleReplayTerminal(a,c);continue}this.noteReplayRetryDelay(s,c,r),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,s,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let i=JSON.stringify({calls:e.map((h,d)=>({args:J(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Qo(i)>Ho)return await this.replayBatchedHalves(e,s,r);let{fetchImpl:a}=this,o,c;try{({payload:c,response:o}=await ce(this.rpcTimeoutMs,void 0,async h=>{let d=await a(B(this.url,ns),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...cs(e.find(l=>l.identity!==void 0)?.identity,r)}),method:"POST",signal:h});if(d.status===413&&e.length>1)return{payload:void 0,response:d};try{return{payload:await d.json(),response:d}}catch{return{payload:void 0,response:d}}}))}catch(h){return this.noteReplayRetryDelay(s,h,r),{requeue:this.keepUnexhaustedAmbiguousWrites(e,h),stop:!0}}let u=o.headers.get("x-d1-bookmark");if(u&&this.bookmark.set(u),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);if(!c)return this.settleWholeBatchError(e,xe(o.status,o.statusText,o.headers),s,r);if(!Array.isArray(c.results)){let h=be(c),d=h===void 0?xe(o.status,o.statusText,o.headers):Vt(h,o.headers);return this.settleWholeBatchError(e,d,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r,o.headers),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof x||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,s),stop:!0};for(let a of e)this.settleReplayTerminal(a,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),a=await this.replayBatched(e.slice(0,i),s,r);if(a.stop||a.requeue.length>0)return{requeue:[...a.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...a.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i,a){let o=jo(s),c=[],u=!1,h=!1;for(let[d,l]of e.entries()){let p=Ko(o.get(d),a);switch(p.kind){case"committed":{u=!0,this.settleReplaySuccess(l,p.value,p.commitCursor);break}case"errored":{h||=Le(p.error),this.shouldRequeueReplayFailure(p.error,i)&&!this.spendsLastReplayAttempt(l,p.error)?(this.noteReplayRetryDelay(r,p.error,i),c.push(l)):this.settleReplayTerminal(l,p.error);break}case"unanswered":{let f=H(Gt(),a);if(this.spendsLastReplayAttempt(l,f)){this.settleReplayTerminal(l,f);break}this.noteReplayRetryDelay(r,f,i),c.push(l);break}default:u=!0,this.settleReplayUndecodable(l,p.error,p.commitCursor)}}return u&&!h&&this.noteCredentialAccepted(i),c}};var pc=n(async t=>(t.assertOpen(),(await t.adminFetch(qr,"GET")).functions??[]),"Rt"),fc=n(async t=>(t.assertOpen(),(await t.adminFetch(Br,"GET")).jobs??[]),"gt"),mc=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Wr,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Gt"),yc=n(async t=>(t.assertOpen(),await t.adminFetch($r,"GET")),"Ct"),gc=n(async t=>(t.assertOpen(),await t.adminFetch(Gr,"GET")),"Nt"),bc=n(async t=>(t.assertOpen(),await t.adminFetch(Vr,"GET")),"Mt"),vc=n(async t=>(t.assertOpen(),await t.adminFetch(zr,"GET")),"kt"),Sc=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(j(e.filters))),C(await t.adminFetch(`${Jr}?${s.toString()}`,"GET"))},"vt"),wc=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(j(e.filters))),C(await t.adminFetch(`${Yr}?${s.toString()}`,"GET"))},"Lt"),Tc=n(async t=>(t.assertOpen(),(await t.adminFetch(ti,"GET")).namespaces??[]),"Vt"),Ec=n(async(t,e)=>{t.assertOpen();let s=L(si,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"Kt"),Cc=n(async(t,e)=>{t.assertOpen();let s=L(gt,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Bt"),Oc=n(async(t,e)=>{t.assertOpen(),await t.adminFetch(gt,"PUT",e)},"Dt"),Ic=n(async(t,e)=>{t.assertOpen();let s=L(gt,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"Jt"),Rc=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Qr,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"xt"),kc=n(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(ei,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"$t"),Ac=n(async(t,e={})=>{t.assertOpen();let s=L(yt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await t.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}},"zt"),_c=n(async(t,e,s)=>{t.assertOpen();let r=`${yt}?key=${encodeURIComponent(e)}${it(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"jt"),Lc=n(async t=>(t.assertOpen(),(await t.adminFetch(Kr,"GET")).buckets??[]),"Wt"),Pc=n(async(t,e)=>{t.assertOpen();let s=`${yt}?key=${encodeURIComponent(e.key)}${it(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"qt"),Nc=n(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,a=`${jr}?key=${encodeURIComponent(e)}${i}${it(s?.bucket)}`,o=await t.adminFetch(a,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"Qt"),Dc=n(async t=>(t.assertOpen(),(await t.adminFetch(Xr,"GET")).indexes??[]),"Yt"),Mc=n(async(t,e)=>(t.assertOpen(),(await t.adminFetch(Zr,"POST",e)).matches??[]),"Xt"),ys=class extends mt{static{n(this,"sa")}async shardTraffic(e){return Rc(this.adminHost,e)}async listScheduledJobs(){return zi(this.adminHost)}async schedulerStatus(){return Ji(this.adminHost)}async cancelScheduledJob(e){return Yi(this.adminHost,e)}async listDeadJobs(){return Xi(this.adminHost)}async retryDeadJob(e){return Zi(this.adminHost,e)}async removeDeadJob(e){return en(this.adminHost,e)}async listWorkflowInstances(e){return tn(this.adminHost,e)}async getWorkflowInstance(e){return sn(this.adminHost,e)}async setWorkflowInstanceStatus(e){return rn(this.adminHost,e)}async listFunctions(){return pc(this.adminHost)}async getCronJobs(){return fc(this.adminHost)}async runCronJob(e){return mc(this.adminHost,e)}async fetchOpenApi(){return yc(this.adminHost)}async fetchArchitecture(){return gc(this.adminHost)}async fetchOpenRpc(){return bc(this.adminHost)}async listStorageObjects(e={}){return Ac(this.adminHost,e)}async deleteStorageObject(e,s){return _c(this.adminHost,e,s)}async listStorageBuckets(){return Lc(this.adminHost)}async uploadStorageObject(e){return Pc(this.adminHost,e)}async signedStorageUrl(e,s){return Nc(this.adminHost,e,s)}async listGlobalTables(){return vc(this.adminHost)}async readGlobalTablePage(e){return Sc(this.adminHost,e)}async facetGlobalColumn(e){return wc(this.adminHost,e)}async listVectorIndexes(){return Dc(this.adminHost)}async queryVectorIndex(e){return Mc(this.adminHost,e)}async queryLogArchive(e={}){return kc(this.adminHost,e)}async listKvNamespaces(){return Tc(this.adminHost)}async listKvKeys(e){return Ec(this.adminHost,e)}async getKvValue(e){return Cc(this.adminHost,e)}async putKvValue(e){return Oc(this.adminHost,e)}async deleteKvKey(e){return Ic(this.adminHost,e)}async listAuthUsers(e={}){this.adminHost.assertOpen();let s=L(ri,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminHost.adminFetch(s,"GET")}async createAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ni,"POST",e)}async setAuthUserRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ai,"POST",e)}async banAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(oi,"POST",e)}async unbanAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ci,"POST",e)}async setAuthUserPassword(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(ui,"POST",e)}async removeAuthUser(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(di,"POST",e)}async impersonateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(hi,"POST",e)}async revokeAuthSession(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(li,"POST",e)}async revokeAuthUserSessions(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(pi,"POST",e)}async getAuthCapabilities(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(fi,"GET")}async updateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(mi,"POST",e)}async listAuthAccounts(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(yi,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(gi,"POST",e)}async listAuthPasskeys(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(bi,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(vi,"POST",e)}async disableAuthTwoFactor(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Si,"POST",e)}async listAuthOrganizations(e={}){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(wi,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.adminHost.assertOpen();let s=L(Ti,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.adminHost.assertOpen();let s=L(Ei,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.adminHost.assertOpen();let s=L(Ri,{limit:e.limit,offset:e.offset});return await this.adminHost.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ki,"POST",e)}async revokeAuthSignUpInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ai,"POST",e)}async removeAuthOrgMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ci,"POST",e)}async cancelAuthOrgInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Oi,"POST",e)}async getAuthConfig(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ii,"GET")}async createAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(_i,"POST",e)}async updateAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Li,"POST",e)}async deleteAuthOrganization(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Pi,"POST",e)}async addAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ni,"POST",e)}async inviteAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Di,"POST",e)}async setAuthOrgMemberRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Mi,"POST",e)}async listAuthOrgTeams(e){this.adminHost.assertOpen();let s=L(Fi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ui,"POST",e)}async updateAuthOrgTeam(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(xi,"POST",e)}async removeAuthOrgTeam(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Hi,"POST",e)}async listAuthOrgTeamMembers(e){this.adminHost.assertOpen();let s=L(Qi,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminHost.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ji,"POST",e)}async removeAuthOrgTeamMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ki,"POST",e)}async listAuthOrgRoles(e){this.adminHost.assertOpen();let s=L(qi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminHost.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Bi,"POST",e)}async updateAuthOrgRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Wi,"POST",e)}async deleteAuthOrgRole(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Gi,"POST",e)}async listAuthSessions(e={}){this.adminHost.assertOpen();let s=L(ii,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminHost.adminFetch(s,"GET")}},gs=n(t=>"listAuthUsers"in t,"ea");var pn=U(Es(),1);var F=U(re(),1);var vt=U(St(),1);var bs=n(t=>K(t),"b");var dn=n(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"E"),vs={status:"idle"},hn=n((t,e)=>{for(let s of t.waiters)s(e);t.waiters.clear()},"F"),Fc=1e4,Uc=n(async(t,e,s)=>new Promise((r,i)=>{if(e.aborted){i(e.reason);return}let a,o,c=n(()=>{clearTimeout(a),o?.(),t.waiters.delete(h),e.removeEventListener("abort",u)},"l"),u=n(()=>{c(),i(e.reason)},"t"),h=n(d=>{c(),r(d)},"n");a=setTimeout(()=>{h(!1)},Fc),t.waiters.add(h),e.addEventListener("abort",u,{once:!0}),o=s(()=>{h(!1)}),t.waiters.has(h)||o()}),"U"),ws=class{static{n(this,"V")}constructor(e){this.client=e}client;entries=new Map;live=new Map;identityWatched=new Set;listening=!1;hasConsumers(e){return this.entries.has(bs(e))}async liveValue(e,s,r,i){let{fetch:a,shardKey:o,waitForPush:c=!0}=i;if(!("window"in globalThis)||this.client.getWebSocketImpl()===void 0)return a();let u=bs(s),h=this.liveFor(u),d=h.state.status==="pushed"?e.getQueryData(s)??h.state.value:void 0;if(d!==void 0)return d;if(c&&h.state.status!=="errored"&&!this.client.isCrossTabFollower()&&this.client.expectsPush({shardKey:o})){let f;try{f=await Uc(h,r,y=>this.client.onConnectionStatus(()=>{this.client.expectsPush({shardKey:o})||y()}))}finally{this.forgetIdleLive(u)}if(f)return this.liveValue(e,s,r,i)}let l=h.state,p;try{p=await a()}finally{this.forgetIdleLive(u)}if(h.state!==l&&h.state.status==="pushed"){let f=e.getQueryData(s);return f!==void 0?f:h.state.value}return p}clearOnIdentityChange(e){this.listenForIdentityChange(),this.identityWatched.add(e)}stopClearingOnIdentityChange(e){this.identityWatched.delete(e)}subscribeIdentityEpoch=n(e=>(this.listenForIdentityChange(),this.client.onIdentityChange(e)),"subscribeIdentityEpoch");listenForIdentityChange(){this.listening||(this.listening=!0,this.client.onIdentityChange(()=>{for(let e of this.identityWatched)this.clearQueries(e)}))}clearQueries(e){let s=e.getQueryCache();for(let r of s.findAll({queryKey:["lunora"]}))dn(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,a,o={}){let c=bs(s),u=this.entries.get(c);if(!u){u={clients:new Map([[e,0]]),errorCallbacks:new Set,unsubscribe:void 0},this.entries.set(c,u);let p=u;try{u.unsubscribe=this.client.subscribe(r,i,f=>{let y=this.liveFor(c);if(f===void 0){y.state=vs;for(let m of p.clients.keys())dn(m.getQueryCache().find({exact:!0,queryKey:s}));return}for(let m of p.clients.keys())m.setQueryData(s,f);y.state={status:"pushed",value:f},hn(y,!0)},{onError:n(f=>{let y=this.liveFor(c);y.state.status!=="pushed"&&(y.state={status:"errored"},hn(y,!1));for(let m of p.errorCallbacks)m(f)},"onError"),shardKey:a})}catch(f){throw this.entries.delete(c),this.dropLive(c),f}}u.clients.set(e,(u.clients.get(e)??0)+1);let h=this.live.get(c);h?.state.status==="pushed"&&e.setQueryData(s,h.state.value);let{onError:d}=o;d&&u.errorCallbacks.add(d);let l=!1;return()=>{if(l)return;l=!0;let p=this.entries.get(c);if(!p)return;let f=(p.clients.get(e)??1)-1;f>0?p.clients.set(e,f):p.clients.delete(e),d&&p.errorCallbacks.delete(d),p.clients.size===0&&(p.unsubscribe?.(),this.entries.delete(c),this.dropLive(c))}}liveFor(e){let s=this.live.get(e);return s||(s={state:vs,waiters:new Set},this.live.set(e,s)),s}forgetIdleLive(e){!this.entries.has(e)&&this.live.get(e)?.waiters.size===0&&this.live.delete(e)}dropLive(e){let s=this.live.get(e);s!==void 0&&(s.waiters.size===0?this.live.delete(e):s.state=vs)}},ln=new WeakMap,Ss=n(t=>{let e=ln.get(t);return e||(e=new ws(t),ln.set(t,e)),e},"L"),fn=(0,F.createContext)(null),xc=(0,F.createContext)(!1),Hc=n(()=>new xt({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"B"),Qc=n(t=>{let e=(0,pn.c)(20),{children:s,client:r,queryClient:i}=t,a=(0,F.use)(Ce),o;e[0]!==a||e[1]!==i?(o=n(()=>i??a??Hc(),"h"),e[0]=a,e[1]=i,e[2]=o):o=e[2];let[c]=(0,F.useState)(o),u=i??a??c,h,d;e[3]!==r||e[4]!==u?(h=n(()=>{Ss(r).clearOnIdentityChange(u)},"n"),d=[r,u],e[3]=r,e[4]=u,e[5]=h,e[6]=d):(h=e[5],d=e[6]),(0,F.useEffect)(h,d);let l=(0,F.useRef)(r),p,f;e[7]!==r||e[8]!==u?(p=n(()=>{l.current!==r&&(Ss(l.current).stopClearingOnIdentityChange(u),l.current=r,Ss(r).clearQueries(u),u.invalidateQueries({queryKey:["lunora"]}))},"a"),f=[r,u],e[7]=r,e[8]=u,e[9]=p,e[10]=f):(p=e[9],f=e[10]),(0,F.useEffect)(p,f);let[y]=(0,F.useState)(r),m=r!==y,v;e[11]!==s||e[12]!==m?(v=(0,vt.jsx)(xc,{value:m,children:s}),e[11]=s,e[12]=m,e[13]=v):v=e[13];let S;e[14]!==r||e[15]!==v?(S=(0,vt.jsx)(fn,{value:r,children:v}),e[14]=r,e[15]=v,e[16]=S):S=e[16];let E=S;if(a===u)return E;let I;return e[17]!==E||e[18]!==u?(I=(0,vt.jsx)(Rt,{client:u,children:E}),e[17]=E,e[18]=u,e[19]=I):I=e[19],I},"X");var He=n(()=>{let t=(0,F.use)(fn);if(!t)throw new g("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var mn=U(Es(),1),yn=U(re(),1);var jc=n(()=>{let t=(0,mn.c)(4),e=He(),s,r,i;return t[0]!==e?(s=n(a=>e.onConnectionStatus(()=>{a()}),"o"),r=n(()=>e.connectionStatus(),"e"),i=n(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=s,t[2]=r,t[3]=i):(s=t[1],r=t[2],i=t[3]),(0,yn.useSyncExternalStore)(s,r,i)},"S");var df=n(()=>{let t=He();if(!gs(t))throw new g("INTERNAL","The Studio needs a LunoraAdminClient (`@lunora/client/admin`), not a plain LunoraClient.");return t},"a");export{g as a,Tn as b,En as c,Ee as d,Ke as e,j as f,C as g,Wn as h,ys as i,Jn as j,Oe as k,aa as l,oa as m,Qc as n,jc as o,df as p};
|