@lunora/studio 1.0.0-alpha.354 → 1.0.0-alpha.355
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/standalone/{chunk-35BGGOWV.js → chunk-2CWGRQ5L.js} +1 -1
- package/dist/standalone/{chunk-FST24UXA.js → chunk-2PHY5V5E.js} +1 -1
- package/dist/standalone/{chunk-BKH2NALB.js → chunk-3QGR4DC7.js} +1 -1
- package/dist/standalone/{chunk-4EDOPHLM.js → chunk-4BNWYVLP.js} +1 -1
- package/dist/standalone/{chunk-ZKPRORLI.js → chunk-4SJDWMH3.js} +1 -1
- package/dist/standalone/{chunk-BTOOJXUL.js → chunk-5IIX2STA.js} +1 -1
- package/dist/standalone/{chunk-V74BXQXC.js → chunk-5KD75VXP.js} +1 -1
- package/dist/standalone/{chunk-LYHEBMM6.js → chunk-64S3IDR2.js} +1 -1
- package/dist/standalone/{chunk-6GPEHYCG.js → chunk-7DMOBHYC.js} +1 -1
- package/dist/standalone/{chunk-TTD7BKB6.js → chunk-7W6WESSS.js} +1 -1
- package/dist/standalone/{chunk-QEVFVWGC.js → chunk-AMLIZFTD.js} +1 -1
- package/dist/standalone/{chunk-BAGJYLSU.js → chunk-AQJXOPBW.js} +1 -1
- package/dist/standalone/{chunk-W6ZKEW5M.js → chunk-AZRUSOAH.js} +1 -1
- package/dist/standalone/{chunk-22O2JDWR.js → chunk-BCIFRJ3Q.js} +1 -1
- package/dist/standalone/{chunk-HWTX54JM.js → chunk-CDV6T5KM.js} +1 -1
- package/dist/standalone/{chunk-X7GSROPX.js → chunk-CHGMDVEQ.js} +1 -1
- package/dist/standalone/{chunk-ACNWZIAH.js → chunk-D5LY65EX.js} +1 -1
- package/dist/standalone/{chunk-TBDJVYCB.js → chunk-DN3HPAOA.js} +1 -1
- package/dist/standalone/{chunk-DTW4E5AB.js → chunk-DUQ7KXNS.js} +1 -1
- package/dist/standalone/{chunk-OJG65AG4.js → chunk-E423VRTC.js} +1 -1
- package/dist/standalone/{chunk-453GHHZ4.js → chunk-EEPCLLGE.js} +1 -1
- package/dist/standalone/{chunk-2DV455PX.js → chunk-ESUUPILO.js} +1 -1
- package/dist/standalone/{chunk-T4VAXHRL.js → chunk-F7GMBSJP.js} +1 -1
- package/dist/standalone/{chunk-ZM4K2ETZ.js → chunk-FIJVZCBO.js} +1 -1
- package/dist/standalone/chunk-FKM35PXF.js +21 -0
- package/dist/standalone/{chunk-4QRVJDM4.js → chunk-FXTT2XP3.js} +1 -1
- package/dist/standalone/{chunk-UKKZJRJT.js → chunk-GNVWTK4S.js} +1 -1
- package/dist/standalone/{chunk-T2QAOXUO.js → chunk-GZX5XABE.js} +1 -1
- package/dist/standalone/{chunk-6DYXTEU7.js → chunk-I2PP6Q6F.js} +1 -1
- package/dist/standalone/{chunk-W4X4J7BU.js → chunk-ILLDX6LU.js} +1 -1
- package/dist/standalone/{chunk-DSTNWB4N.js → chunk-IMF6DJKL.js} +1 -1
- package/dist/standalone/{chunk-UCK6ITED.js → chunk-M3KSCNKR.js} +1 -1
- package/dist/standalone/{chunk-MKVZXGJQ.js → chunk-MQ3FFFP4.js} +1 -1
- package/dist/standalone/{chunk-3MQ477EE.js → chunk-N5FOHLIG.js} +1 -1
- package/dist/standalone/{chunk-IRCUXARN.js → chunk-NQX6SAC6.js} +1 -1
- package/dist/standalone/{chunk-S5S2YICJ.js → chunk-NXNUGQHB.js} +1 -1
- package/dist/standalone/{chunk-C6FNBKCO.js → chunk-O6XMGPGY.js} +1 -1
- package/dist/standalone/{chunk-YRQHFMEY.js → chunk-OGKRWT6I.js} +1 -1
- package/dist/standalone/{chunk-57ZNR6IA.js → chunk-OKSZWLJX.js} +1 -1
- package/dist/standalone/{chunk-SDTHCM5H.js → chunk-OT4KZ6Y6.js} +1 -1
- package/dist/standalone/{chunk-BCOOULSO.js → chunk-Q5GY7D5H.js} +1 -1
- package/dist/standalone/{chunk-K7FZTYAY.js → chunk-QSNQXPIX.js} +1 -1
- package/dist/standalone/{chunk-FNWRS4VQ.js → chunk-R5ACA3OC.js} +1 -1
- package/dist/standalone/{chunk-ZLSNET6H.js → chunk-R66XCM3J.js} +1 -1
- package/dist/standalone/{chunk-IVQKQBKK.js → chunk-RNHTOEL7.js} +1 -1
- package/dist/standalone/{chunk-WIYDA4XT.js → chunk-S6OBDEAQ.js} +1 -1
- package/dist/standalone/{chunk-6QBK3Z7A.js → chunk-SL7LF2SO.js} +1 -1
- package/dist/standalone/{chunk-FXGYX2V6.js → chunk-SOVH524I.js} +1 -1
- package/dist/standalone/{chunk-4UWYDYM5.js → chunk-SPPJFTWE.js} +1 -1
- package/dist/standalone/{chunk-RQDSPVVH.js → chunk-SV34MAIK.js} +1 -1
- package/dist/standalone/{chunk-HZCLLEWP.js → chunk-TAGWTOFD.js} +1 -1
- package/dist/standalone/{chunk-VHMA6YPT.js → chunk-TIQ3NI77.js} +1 -1
- package/dist/standalone/{chunk-4CITH2NU.js → chunk-TNII7Q2L.js} +1 -1
- package/dist/standalone/{chunk-ANACHJRU.js → chunk-U2YFL6EA.js} +1 -1
- package/dist/standalone/{chunk-Q4N3TJPV.js → chunk-UHGLZ5RV.js} +1 -1
- package/dist/standalone/{chunk-7EAHHRJR.js → chunk-UWAVY3IF.js} +1 -1
- package/dist/standalone/{chunk-S6JFSLBK.js → chunk-VO6GV6F2.js} +1 -1
- package/dist/standalone/{chunk-2EMNPL3B.js → chunk-VPG46PCA.js} +1 -1
- package/dist/standalone/{chunk-6GRI2HXU.js → chunk-XFTWGZKD.js} +1 -1
- package/dist/standalone/{chunk-M2RIGPGL.js → chunk-YHK5UBXI.js} +1 -1
- package/dist/standalone/{chunk-RHOQJNDW.js → chunk-YJYXN3WQ.js} +1 -1
- package/dist/standalone/{chunk-Y7SN6CTX.js → chunk-Z3NZJ4C2.js} +1 -1
- package/dist/standalone/{chunk-SM2IQWCJ.js → chunk-ZXUEBA56.js} +1 -1
- package/dist/standalone/{chunk-KNX3KB7E.js → chunk-ZZ5564FZ.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +5 -5
- package/dist/standalone/chunk-OIDFWEJX.js +0 -21
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import{a as n,d as U,e as re,f as Os,g as Et}from"./chunk-OXFKZ4BM.js";var Ee={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"},STALE_CREDENTIAL:{status:409,title:"Stale credential"},IDENTITY_CHANGED:{status:409,title:"Socket identity changed"},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"}},Ct=n(t=>Object.hasOwn(Ee,t)?Ee[t]:void 0,"s");var Is=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[Is]===!0}type="VisulimaError";hint;title;loc;code;status;docsUrl;data;why;constructor(e,s,r={}){let i=Ct(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,Is,{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/",En=/string or blob too big/iu,Cn=["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 Rs=[{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=>En.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:Cn.join(`
|
|
11
|
+
`),header:"Optimistic concurrency conflict",id:"lunora-runtime-occ",test:n(t=>t.includes("optimistic concurrency conflict"),"test")}],Ot=[{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"}],It=n(t=>t!==void 0&&t>="0"&&t<="9","s"),On=n((t,e)=>{for(let s=t.indexOf(e);s!==-1;s=t.indexOf(e,s+e.length))if(!It(t[s-1])&&!It(t[s+e.length]))return!0;return!1},"g"),In=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(!It(t[r+s.length]))return!0;return!1},"b"),kn=/error|cloudflare/iu,ks=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"),As=n(t=>{if(!kn.test(t))return;let e=t.toLowerCase(),s=e.includes("error"),r=e.includes("cloudflare");if(s){for(let i of Ot)if(In(e,i.code))return ks(i)}if(r){for(let i of Ot)if(On(e,i.code))return ks(i)}},"y"),Rn=n(t=>(typeof t=="string"?t:t.join(`
|
|
13
|
+
`)).split(`
|
|
14
|
+
`).filter(e=>!e.startsWith("```")).join(`
|
|
15
|
+
`).replaceAll(/\*\*(.+?)\*\*/gu,"$1").replaceAll(/`([^`]+)`/gu,"$1"),"T"),_s=n(t=>{for(let e of Rs)if(e.test(t))return{body:e.body,header:e.header,id:e.id}},"d"),An=n(t=>_s(t)??As(t),"x");var kt="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).",Rt=["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 _n=/["\\\u0000-\u001F\uD800-\uDFFF]/,Ls=n(t=>_n.test(t)?JSON.stringify(t):`"${t}"`,"c"),Ln=n(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"b"),Nn=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+=Ls(c),a+=":",a+=e(u))}return`${a}}`},"u"),Ce=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=Ln(t);if(e!==void 0)return e}return typeof t=="string"?Ls(t):t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${Array.from({length:t.length},(e,s)=>Ce(t[s])).join(",")}]`:Nn(t,Ce)},"y");var qe=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"e");var Be=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"),Dn=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$",We=64,Ge=1024,Pn="__proto__",Mn=/^-?\d+$/,Ns={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Ds={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},At=n((t,e,s)=>{e===Pn?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"y");var Fn=n(t=>{let e=t.toString();if(e.length>Ge)throw new RangeError(`wire-codec: over-long bigint (max ${String(Ge)} digits)`);return[_,"bigint",e]},"j"),Un=n(t=>Number.isNaN(t)?[_,"nan"]:t===1/0?[_,"inf"]:t===-1/0?[_,"-inf"]:t,"R"),xn=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"),Hn=n(t=>{let e=t.constructor.name,s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return e==="Uint8Array"?[_,"bytes",Be(s)]:[_,"bytes",Be(s),e]},"U"),Qn=n((t,e)=>t instanceof Date?[_,"date",e(t.getTime())]:t instanceof Error?xn(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",Be(new Uint8Array(t)),"ArrayBuffer"]:ArrayBuffer.isView(t)?Hn(t):void 0,"I"),jn=n((t,e)=>{let s=t.map(r=>e(r));return s.length>0&&s[0]===_?[_,"arr",s]:s},"N"),Kn=n((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&At(s,r,e(i))}return s},"B"),K=n((t,e=0)=>{if(e>We)throw new RangeError(`wire-codec: value nesting exceeds the ${String(We)}-level limit`);if(t===void 0)return[_,"undefined"];if(t===null)return t;if(typeof t=="bigint")return Fn(t);if(typeof t=="number")return Un(t);if(typeof t!="object")return t;let s=n(i=>K(i,e+1),"t"),r=Qn(t,s);if(r!==void 0)return r;if(Array.isArray(t))return jn(t,s);if(!qe(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 Kn(t,s)},"m"),qn=n(t=>{let e=t[2];if(typeof e!="string"||e.length>Ge||!Mn.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(Ge)} digits)`);return BigInt(e)},"_"),Bn=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"),Wn=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])]}))},"$"),Gn=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"),$n=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(Ds,s)?Ds[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))At(a,c,u);return t.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:e(t[5]),writable:!0}),a},"k"),Vn=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=Dn(e);if(Be(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(Ns,r)?Ns[r]:void 0;return i?new i(new Uint8Array(s).buffer):s},"C"),zn=n((t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(s=>e(s));case"bigint":return qn(t);case"bytes":return Vn(t);case"date":return Bn(t,e);case"error":return $n(t,e);case"inf":return 1/0;case"map":return Wn(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return Gn(t);default:return t.map(s=>e(s))}},"L"),Jn=n((t,e)=>{let s={};for(let r of Object.keys(t))At(s,r,e(t[r]));return s},"M"),C=n((t,e=0)=>{if(e>We)throw new RangeError(`wire-codec: value nesting exceeds the ${String(We)}-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]===_?zn(r,s):r.map(i=>s(i))}return Jn(t,s)},"A"),Yn=n(t=>{try{let e=C(JSON.parse(t));return qe(e)?e:void 0}catch{return}},"G");var q=n(t=>Ce(K(t)),"a");var le=U(re(),1),Ps=U(Et(),1);var Oe=le.createContext(void 0),Ie=n(t=>{let e=le.useContext(Oe);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),_t=n(({client:t,children:e})=>(le.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Ps.jsx)(Oe.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 Xn=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 Xn;var Zn={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")},ea=class{static{n(this,"TimeoutManager")}#e=Zn;#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 ea;function Ms(t){setTimeout(t,0)}n(Ms,"systemSetTimeoutZero");var Nt=typeof window>"u"||"Deno"in globalThis;function O(){}n(O,"noop");function xs(t,e){return typeof t=="function"?t(e):t}n(xs,"functionalUpdate");function ke(t){return typeof t=="number"&&t>=0&&t!==1/0}n(ke,"isValidTimeout");function $e(t,e){return Math.max(t+(e||0)-Date.now(),0)}n($e,"timeUntilStale");function B(t,e){return typeof t=="function"?t(e):t}n(B,"resolveStaleTime");function P(t,e){return typeof t=="function"?t(e):t}n(P,"resolveQueryBoolean");function Ve(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(Ve,"matchQuery");function ze(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(ze,"matchMutation");function Re(t,e){return(e?.queryKeyHashFn||$)(t)}n(Re,"hashQueryKeyByOptions");function $(t){return JSON.stringify(t,(e,s)=>Lt(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 ta=Object.prototype.hasOwnProperty;function Dt(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=Fs(t)&&Fs(e);if(!r&&!(Lt(t)&&Lt(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:ta.call(t,l))&&h++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){u[l]=f;continue}let y=Dt(p,f,s+1);u[l]=y,y===p&&h++}return a===c&&h===a?t:u}n(Dt,"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 Fs(t){return Array.isArray(t)&&t.length===Object.keys(t).length}n(Fs,"isPlainArray");function Lt(t){if(!Us(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!Us(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}n(Lt,"isPlainObject");function Us(t){return Object.prototype.toString.call(t)==="[object Object]"}n(Us,"hasObjectPrototype");function Hs(t){return new Promise(e=>{G.setTimeout(e,t)})}n(Hs,"sleep");function Ae(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?Dt(t,e):e}n(Ae,"replaceData");function sa(t){return t}n(sa,"keepPreviousData");function Qs(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}n(Qs,"addToEnd");function js(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}n(js,"addToStart");var me=Symbol();function Je(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(Je,"ensureQueryFn");function ye(t,e){return typeof t=="function"?t(...e):!!t}n(ye,"shouldThrowError");function Ks(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(Ks,"addConsumeAwareSignal");var V=(()=>{let t=n(()=>Nt,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function _e(){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(_e,"pendingThenable");var qs=Ms;function ra(){let t=[],e=0,s=n(c=>{c()},"notifyFn"),r=n(c=>{c()},"batchNotifyFn"),i=qs,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(ra,"createNotifyManager");var T=ra();var ia=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 ia;function na(t){return Math.min(1e3*2**t,3e4)}n(na,"defaultRetryDelay");function Pt(t){return(t??"online")==="online"?ge.isOnline():!0}n(Pt,"canFetch");var Ye=class extends Error{static{n(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Xe(t){let e=!1,s=0,r,i=_e(),a=n(()=>i.status!=="pending","isResolved"),o=n(m=>{if(!a()){let v=new Ye(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(()=>Pt(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??na,w=typeof I=="function"?I(s,S):I,k=E===!0||typeof E=="number"&&s<E||typeof E=="function"&&E(s,S);if(e||!k){p(S);return}s++,t.onFail?.(s,S),Hs(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(Xe,"createRetryer");var Ze=class{static{n(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ke(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 Ws(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=>{Ks(y,()=>e.signal,()=>d=!0)},"addSignalProperty"),p=Je(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,k=v?js:Qs;return{pages:k(y.pages,I,w),pageParams:k(y.pageParams,m,w)}},"fetchPage");if(i&&a.length){let y=i==="backward",m=y?aa:Bs,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:Bs(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(Ws,"infiniteQueryBehavior");function Bs(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(Bs,"getNextPageParam");function aa(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}n(aa,"getPreviousPageParam");var Vs=class extends Ze{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=$s(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=$s(this.options);e.data!==void 0&&(this.setState(Gs(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=Ae(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=>P(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=>B(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:!$e(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=Je(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"?Ws(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=Xe({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:n(u=>{u instanceof Ye&&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 Ye){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,...Mt(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...Gs(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 Mt(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Pt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}n(Mt,"fetchState");function Gs(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}n(Gs,"successState");function $s(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($s,"getDefaultState");var Ut=class extends Q{static{n(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=_e(),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),zs(this.#t,this.options)?this.#p():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ft(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ft(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 P(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&&Js(this.#t,s,this.options,e)&&this.#p(),this.updateResult(),r&&(this.#t!==s||P(this.options.enabled,this.#t)!==P(e.enabled,this.#t)||B(this.options.staleTime,this.#t)!==B(e.staleTime,this.#t))&&this.#y();let i=this.#g();r&&(this.#t!==s||P(this.options.enabled,this.#t)!==P(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 ca(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=B(this.options.staleTime,this.#t);if(V.isServer()||this.#r.isStale||!ke(t))return;let s=$e(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()||P(this.options.enabled,this.#t)===!1||!ke(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(),R=!A&&zs(t,e),Y=A&&Js(t,s,e,r);(R||Y)&&(d={...d,...Mt(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=Ae(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=Ae(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,k=p!==void 0,D={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&&!k,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:I&&k,isStale:xt(t,e),refetch:this.refetch,promise:this.#o,isEnabled:P(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=D.data!==void 0,R=D.status==="error"&&!A,Y=n(Ke=>{R?Ke.reject(D.error):A&&Ke.resolve(D.data)},"finalizeThenableIfPossible"),Cs=n(()=>{let Ke=this.#o=D.promise=_e();Y(Ke)},"recreateThenable"),je=this.#o;switch(je.status){case"pending":t.queryHash===s.queryHash&&Y(je);break;case"fulfilled":(R||D.data!==je.value)&&Cs();break;case"rejected":(!R||D.error!==je.reason)&&Cs();break}}return D}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 oa(t,e){return P(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&P(e.retryOnMount,t)===!1)}n(oa,"shouldLoadOnMount");function zs(t,e){return oa(t,e)||t.state.data!==void 0&&Ft(t,e,e.refetchOnMount)}n(zs,"shouldFetchOnMount");function Ft(t,e,s){if(P(e.enabled,t)!==!1&&B(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&xt(t,e)}return!1}n(Ft,"shouldFetchOn");function Js(t,e,s,r){return(t!==e||P(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&xt(t,s)}n(Js,"shouldFetchOptionally");function xt(t,e){return P(e.enabled,t)!==!1&&t.isStaleByTime(B(e.staleTime,t))}n(xt,"isStale");function ca(t,e){return!fe(t.getCurrentResult(),e)}n(ca,"shouldAssignObserverCurrentProperties");var Ys=class extends Ze{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||Ht(),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=Xe({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 Ht(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}n(Ht,"getDefaultState");var Xs=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 Ys({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=et(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=et(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=et(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=et(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=>ze(e,s))}findAll(t={}){return this.getAll().filter(e=>ze(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 et(t){return t.options.scope?.id}n(et,"scopeFor");var Qt=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??Ht();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 Zs=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 Vs({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=>Ve(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>Ve(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 jt=class{static{n(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new Zs,this.#t=t.mutationCache||new Xs,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(B(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=xs(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(B(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 Le=U(re(),1),ua=U(Et(),1);function da(){let t=!1;return{clearReset:n(()=>{t=!1},"clearReset"),reset:n(()=>{t=!0},"reset"),isReset:n(()=>t,"isReset")}}n(da,"createValue");var ha=Le.createContext(da()),er=n(()=>Le.useContext(ha),"useQueryErrorResetBoundary");var tr=U(re(),1);var sr=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"),rr=n(t=>{tr.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),ir=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 tt=U(re(),1);var nr=tt.createContext(!1),ar=n(()=>tt.useContext(nr),"useIsRestoring"),Mh=nr.Provider;var or=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"),cr=n((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),ur=n((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),Kt=n((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function dr(t,e,s){let r=ar(),i=er(),a=Ie(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,or(o),sr(o,i,c),rr(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]),ur(o,l))throw Kt(o,d,i);if(ir({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()&&cr(l,r)&&(h?Kt(o,d,i):c?.promise)?.catch(O).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?l:d.trackResult(l)}n(dr,"useBaseQuery");function la(t,e){return dr(t,Ut,e)}n(la,"useQuery");var X=U(re(),1);function pa(t,e){let s=Ie(e),[r]=X.useState(()=>new Qt(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(pa,"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 fa=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),ma="_id",Bt="_creationTime",Wt="page",hr="pageDelta",ya=n(t=>{if(Array.isArray(t))return t;if(fa(t)&&Array.isArray(t[Wt]))return t[Wt]},"y"),ga=n(t=>{let e;for(let s of t){let r=s[Bt];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"g"),ba=n((t,e)=>{let s=e[Bt];if(typeof s!="number")return t.length;let r=ga(t);for(let[i,a]of t.entries()){let o=a[Bt];if(typeof o=="number"&&(r?o<s:o>s))return i}return t.length},"A"),va=n(t=>{if(typeof t!="object"||t===null)return;let e=t[ma];return typeof e=="string"?e:void 0},"b"),Sa=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"),wa=n((t,e)=>{let{key:s,op:r,row:i}=e,a=[],o=-1;for(let c of t){let u=va(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(ba(a,i),0,i):a[o]=i,a},"x"),Ta=n((t,e)=>{let s=ya(t);if(s===void 0)return;let r=wa(s,e);return r===void 0||Array.isArray(t)?r:{...t,[Wt]:r}},"E"),Gt=Symbol("lunora.unmergeableDelta"),lr=n((t,e)=>{if("data"in t&&t.data!==void 0)return C(t.data);let s=C(t.delta);return Sa(s)?e===void 0?s:Ta(e,s)??Gt:s},"m");var pr=n(()=>{let t=null;return{get:n(()=>t,"get"),set:n(e=>{t=e},"set")}},"r");var yl=new Set(Object.keys(Ee)),x=class extends g{static{n(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var st=n(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),$t=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),Ne=n(t=>$t.has(t?.code??""),"u");var De=n(t=>typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="string")?{hint:t}:{},"n");var Vt=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"),Ea=n((t,e)=>{let s=Vt(e);if(!(s===void 0||st(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"),zt=n(()=>new x("LunoraClient: batch slot carried no error envelope"),"E"),fr=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"),mr=n(t=>{let{code:e,messageText:s}=fr(t,"stream error"),r=t.error,i=r?.why,a=e===void 0?new Error(s):new g(e,s,De(r?.hint));return typeof i=="string"&&(a.why=i),a},"D"),Jt=n(t=>{let{code:e,messageText:s}=fr(t,"subscription error"),r=t.error,i=typeof r?.why=="string"?{why:r.why}:{};return{message:s,...e===void 0?{}:{code:e},...De(r?.hint),...i}},"O"),Ca=Symbol.for("lunora.serverVerdict"),Pe=n(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,e[Ca]=!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"),Oa=n(t=>Object.freeze(Object.fromEntries([...t].filter(([e])=>e!=="set-cookie"))),"b"),H=n((t,e)=>Object.defineProperty(t,"headers",{value:Oa(e)}),"w"),Yt=n((t,e)=>{let s=Pe(t),r=Ea(s,e.get("retry-after"));return r!==void 0&&(s.data=r),H(s,e)},"j"),Xt=n(t=>{let e=be(t);return e===void 0?zt():Pe(e)},"M"),yr=new WeakSet,rt=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 yr.add(e),e},"N"),Me=n(t=>t instanceof Error&&yr.has(t),"T");var it=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 nt=n(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),Zt=n(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),j=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"),Ia="http://same-origin.invalid",Fe=n(t=>new URL(t,Ia),"p"),ka=/^[a-z][a-z\d+.-]*:/iu,es=n((t,e)=>{if(ka.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var ts=0,ve,gr=n((t,e)=>{for(let s of t)try{s(e)}catch{}},"f"),Ra=n(t=>{let e=[...t.callbacks],s=t.lastValue;return()=>{for(let r of e){if(t.lastValue!==s)return;t.callbacks.has(r)&&gr([r],s)}}},"p"),br=n(t=>{ve===void 0?t():ve.add(t)},"k"),vr=n(()=>ts,"L"),Aa=n((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"y"),Sr=n((t,e)=>{e!==t.lastValue&&(t.lastValue=e,ve===void 0?gr(t.callbacks,e):ve.add(t))},"d"),at=n((t,e=()=>!0)=>{let s=new Set;ve=s;try{t()}finally{ve=void 0;let r=[...s].map(i=>typeof i=="function"?i:Ra(i));for(let i of r){if(!e())break;try{i()}catch{}}}},"v"),ae=n((t,e)=>{Sr(t,Aa(e,t.optimisticLayers))},"m"),ot=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),Sr(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)},"s"),o=n(()=>{ae(t,t.serverBase)},"a");return{confirm:n(c=>{if(c===void 0){a();return}r.commitCursor=c,ts+=1,r.acknowledgedAt=ts,t.serverCursor!==void 0&&t.serverCursor>=c&&a()&&o()},"confirm"),rollback:n(()=>{i||(i=!0,a(),o())},"rollback")}},"b"),ct=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},"h"),wr=n((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"g"),ce=n(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"w");var Tr=0,_a="lunora-bridge",La=1e3,Na=3e3,ut=class{static{n(this,"u")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;pendingData=new Map;heldData=new Map;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(Tr+=1,this.tabId=`tab_${String(Tr)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??La,this.leaderTimeout=e.leaderTimeout??Na,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??_a),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)return;let s,r=!0;for(let[i,a]of e.entries()){let o=i<e.length-1;try{this.bc?.postMessage(o?{...a,more:!0}:a),s=a,r=!o}catch{}}!r&&s!==void 0&&this.bc?.postMessage(s)}applySubscriptionData(e){let s=this.heldData.get(e.tabId)??[];if(s.push(e),e.more===!0){this.heldData.set(e.tabId,s);return}this.heldData.delete(e.tabId),at(()=>{for(let r of s)this.onSubscriptionData?.(r.key,r.data,r.cursor,r.epoch,r.identity)},()=>this.running)}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.applySubscriptionData(e);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.heldData.delete(e.tabId),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.heldData.delete(this.knownLeader),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 Ue=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 Da=1024,dt=n(t=>{let e=t.maxBuffer??Da,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 Se=n(t=>t.reason??Object.assign(new Error("The operation was aborted"),{name:"AbortError"}),"c"),ue=n(async(t,e,s,r=()=>new x(`LunoraClient: request timed out after ${t.toString()}ms`))=>{if(e?.aborted)throw Se(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(Se(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"),ss=n(async(t,e)=>{if(e===void 0)return t;if(e.aborted)throw t.catch(()=>{}),Se(e);let s=n(()=>{},"o"),r=new Promise((i,a)=>{s=n(()=>{a(Se(e))},"o"),e.addEventListener("abort",s,{once:!0})});t.catch(()=>{});try{return await Promise.race([t,r])}finally{e.removeEventListener("abort",s)}},"E"),Er=n(async(t,e)=>!Number.isFinite(e)||e<=0?t.read():ue(e,void 0,async()=>t.read(),()=>new g("STREAM_IDLE",`stream received nothing for ${e.toString()}ms`)),"y");var ht=/^ /u,Pa=/^\d+$/u,Ma=2147483647,Fa=10,Ua=1e3,Cr=n(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"O"),xa=n(t=>{let e="",s,r,i=[];for(let a of t.split(`
|
|
16
|
+
`))if(a.startsWith("event:"))e=a.slice(6).replace(ht,"");else if(a.startsWith("data:"))i.push(a.slice(5).replace(ht,""));else if(a.startsWith("id:")){let o=a.slice(3).replace(ht,"");o.includes("\0")||(s=o)}else if(a.startsWith("retry:")){let o=a.slice(6).replace(ht,"");Pa.test(o)&&Number.isSafeInteger(Number(o))&&(r=Math.min(Number(o),Ma))}return{data:i.join(`
|
|
17
|
+
`),event:e,id:s,retry:r}},"U"),Ha=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(Cr(h))}).join("/"),a=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&a.set(c,Cr(u));let o=a.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"Y"),Qa=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,De(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"),Ir=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=xa(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),Qa(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"),ja=n(async(t,e,s,r,i=0)=>{let a=t.getReader(),o=new TextDecoder,c=Ir(e,s),u=n(()=>a.cancel().then(()=>{},()=>{}),"a");try{for(;;){let{done:h,value:d}=await Er(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"),kr=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"),Ka=n(async(t,e,s,r)=>{let i=Ir(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 kr(0,r.signal)}},"K"),qa=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"),Ba=n(async(t,e)=>{let s,r=new Promise(a=>{s=setTimeout(()=>{a(void 0)},Ua)}),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"),Wa=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"),Or=n(t=>t instanceof Error&&"code"in t?t:new g("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"M"),Rr=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=Ha(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}=dt({maxBuffer:s.maxBuffer,onCancel:n(()=>{a.abort()},"onCancel"),onFail:n(()=>{a.abort()},"onFail")}),d=s.reconnect??!1,l=Ue(),{lastEventId:p}=s,f,y=0,m=n(()=>{l.reset(),y=0},"x"),v={},S=n(w=>{try{w()}catch(k){throw v.value={error:k},k}},"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=Wa(s.headers,p),k=new g("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"),se=n(R=>{if(a.signal.aborted){u.complete();return}return{completed:R,error:k}},"_"),D=new AbortController,A=n(()=>{D.abort()},"A");a.signal.addEventListener("abort",A,{once:!0});try{let R=await r(i,{headers:w,method:t.method,signal:D.signal});if(!R.ok){let Y=await Ba(R,a.signal);u.fail(qa(Y,R.status)??new g("HTTP_STREAM_STATUS",`httpStream: request failed (status ${R.status.toString()})`,{status:R.status}));return}if(!R.body){if(typeof R.text!="function"){u.fail(new g("HTTP_STREAM_NO_BODY","httpStream: response exposes neither a body stream nor a text() read",{hint:Rt}));return}return se(await Ka(R,u,E,D))}return se(await ja(R.body,u,E,D,s.idleTimeoutMs))}catch(R){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:Or(R)}}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>=Fa){w.completed||u.fail(w.error);return}y+=1,await kr(f??l.next(),a.signal)}}finally{c()}})().catch(w=>{if(a.signal.aborted){u.complete();return}u.fail(Or(w))}),h},"ne");var N=class t{static{n(this,"y")}static key(e,s,r){return`${e}::${q(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"),lt=n(t=>{t.ack==="inflight"&&z(t,"idle")},"b");function pt(t){if(t!==void 0)return e=>{t(e)}}n(pt,"o");var ee=n((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Ar=n((t,e)=>{let s=[],r=[],i=n((a,o)=>t.get(N.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=ot(u,()=>c);h&&(s.push(h.confirm),r.push(h.rollback))},"setQuery")}}},"g");var _r=0,Ga=n(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();_r+=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)}_${_r.toString(36)}_${t}`},"d"),rs=n((t,e)=>t!==void 0&&e!==t,"l"),mt=Ga,we=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"),ft=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??=mt();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=>{we(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 we(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(rs(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{we(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=>{we(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),we(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){we(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"),yt=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"),gt=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 $a="lunora-outbox",Va="offline-mutations",is="by_id",za=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??$a,r=t.storeName??Va,i=yt(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(is,"id",{unique:!0})}),a=gt(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(is).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(is).getKey(o.id));u!==void 0&&await M(c.put(o,u))})},"replace")}},"w"),Lr=n((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return za()}},"b");var de=n((t,e,s)=>`${t}::${e}::${s??""}`,"T"),Ja=500,Ya=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 Xa="lunora-query-cache",Za="query-cache",Nr="by_ts",eo=1,to=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??Xa,r=t.storeName??Za,i=Ya(t.maxEntries??Ja,"createIndexedDbQueryCache"),a=yt(e,s,eo,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(Nr,"ts",{unique:!1})}),o=gt(a,r),c=n(async u=>{let h=await M(u.count())-i;h<=0||await new Promise((d,l)=>{let p=u.index(Nr).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"),Dr=n(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return to()}},"L");var Pr=new WeakMap,ns=n((t,e)=>{Pr.set(t,e)},"i"),as=n(t=>t===void 0?void 0:Pr.get(t),"d"),Mr=n((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),a=i.present&&i.answered?q(i.value):void 0,o=n(()=>{let c=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!i.answered||!c.present||!c.answered?!0:q(c.value)===a},"c");return a!==void 0&&ns(o,{args:s,functionPath:e.__lunoraRef,shardKey:r}),o},"h");var io="/_lunora/rpc",os="/_lunora/rpc-batch",cs="/_lunora/ws",Gr="/_lunora/admin/shard-traffic",no="/_lunora/admin/scheduled",ao="/_lunora/admin/scheduled/status",oo="/_lunora/admin/scheduled/ws",co="/_lunora/admin/scheduled/cancel",Fr="/_lunora/admin/scheduled/dead",uo="/_lunora/admin/scheduled/dead/retry",ho="/_lunora/admin/scheduled/dead/cancel",lo="/_lunora/admin/workflows/instances",po="/_lunora/admin/workflows/instance",fo="/_lunora/admin/workflows/status",vt="/_lunora/admin/storage",$r="/_lunora/admin/storage/url",Vr="/_lunora/admin/storage/buckets",zr="/_lunora/admin/functions",Jr="/_lunora/admin/cron-jobs",Yr="/_lunora/admin/cron-jobs/run",Xr="/_lunora/admin/architecture",Zr="/_lunora/admin/openapi",ei="/_lunora/admin/openrpc",ti="/_lunora/admin/global/tables",si="/_lunora/admin/global/table",ri="/_lunora/admin/global/facet",ii="/_lunora/admin/vector/indexes",ni="/_lunora/admin/vector/query",ai="/_lunora/admin/logs/archive",oi="/_lunora/admin/kv/namespaces",ci="/_lunora/admin/kv/keys",St="/_lunora/admin/kv/value",ui="/_lunora/admin/auth/users",di="/_lunora/admin/auth/sessions",hi="/_lunora/admin/auth/users/create",li="/_lunora/admin/auth/users/role",pi="/_lunora/admin/auth/users/ban",fi="/_lunora/admin/auth/users/unban",mi="/_lunora/admin/auth/users/password",yi="/_lunora/admin/auth/users/remove",gi="/_lunora/admin/auth/users/impersonate",bi="/_lunora/admin/auth/sessions/revoke",vi="/_lunora/admin/auth/sessions/revoke-all",Si="/_lunora/admin/auth/capabilities",wi="/_lunora/admin/auth/users/update",Ti="/_lunora/admin/auth/accounts",Ei="/_lunora/admin/auth/accounts/unlink",Ci="/_lunora/admin/auth/passkeys",Oi="/_lunora/admin/auth/passkeys/delete",Ii="/_lunora/admin/auth/two-factor/disable",ki="/_lunora/admin/auth/organizations",Ri="/_lunora/admin/auth/organizations/members",Ai="/_lunora/admin/auth/organizations/invitations",_i="/_lunora/admin/auth/organizations/members/remove",Li="/_lunora/admin/auth/organizations/invitations/cancel",Ni="/_lunora/admin/auth/config",Di="/_lunora/admin/auth/sign-up-invitations",Pi="/_lunora/admin/auth/sign-up-invitations/create",Mi="/_lunora/admin/auth/sign-up-invitations/revoke",Fi="/_lunora/admin/auth/organizations/create",Ui="/_lunora/admin/auth/organizations/update",xi="/_lunora/admin/auth/organizations/remove",Hi="/_lunora/admin/auth/organizations/members/add",Qi="/_lunora/admin/auth/organizations/members/invite",ji="/_lunora/admin/auth/organizations/members/role",Ki="/_lunora/admin/auth/organizations/teams",qi="/_lunora/admin/auth/organizations/teams/create",Bi="/_lunora/admin/auth/organizations/teams/update",Wi="/_lunora/admin/auth/organizations/teams/remove",Gi="/_lunora/admin/auth/organizations/teams/members",$i="/_lunora/admin/auth/organizations/teams/members/add",Vi="/_lunora/admin/auth/organizations/teams/members/remove",zi="/_lunora/admin/auth/organizations/roles",Ji="/_lunora/admin/auth/organizations/roles/create",Yi="/_lunora/admin/auth/organizations/roles/update",Xi="/_lunora/admin/auth/organizations/roles/remove",mo="/api/auth",yo="/get-session",go="lunora-ping",us=500,Zi=n((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Le");new TextDecoder;var bo=new TextEncoder,vo=n(t=>qt(bo.encode(t)),"Dt"),So=n(t=>vo(JSON.stringify(t)),"Qt"),wo="x-lunora-expect-subject",To=n(t=>So({subject:t}),"qt"),Eo="refreshBatch",Ur=Symbol.for("lunora:session-change"),Co="lunora:session-change",Oo="better-auth.message",Io="signout",en=n(()=>{let t=globalThis,e=t[Ur];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[Ur]=e),e},"Pe"),ko=n(()=>"document"in globalThis,"Vt"),Ro=n(async()=>{let t=[];for(let e of en().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"zt"),Ao=n((t,e)=>{if(t!==Oo||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===Io}catch{return!1}},"Jt"),_o=n(t=>{let e=[],s=n(()=>{Ro().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(Co):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=>{Ao(o.key,o.newValue)&&s()},"r");i.addEventListener("storage",a),e.push(()=>{i.removeEventListener?.("storage",a)})}return()=>{for(let a of e)a()}},"Yt"),Lo=n(t=>{let e=en();return e.listeners.add(t),e.detach===void 0&&ko()&&(e.detach=_o(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"Xt"),xr="/_lunora/ws/reauth",No="lunora",Do="lunora.bearer.",Po=n(t=>`${Do}${qt(new TextEncoder().encode(t))}`,"ts"),Mo=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}},"ss"),gs=n(t=>"args"in t?{...t,args:C(t.args)}:t,"oe"),tn=n(async t=>(t.assertOpen(),((await t.adminFetch(no,"GET")).records??[]).map(e=>gs(e))),"gr"),sn=n(async t=>{t.assertOpen();let e=await t.adminFetch(ao,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"wr"),rn=n(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(co,"POST",{id:e})).cancelled===!0}),"Tr"),nn=n(async t=>(t.assertOpen(),(await Mo(async e=>await t.adminFetch(e===void 0?Fr:`${Fr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>gs(e))),"kr"),an=n(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(uo,"POST",{id:e})).retried===!0}),"Cr"),on=n(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(ho,"POST",{id:e})).removed===!0}),"Ar"),cn=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(`${lo}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"Er"),un=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${po}?${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??[]}},"_r"),dn=n(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(fo,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"Ir"),J=n((t,e)=>{try{return K(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"),ls=n(t=>{try{return K(t),!0}catch{return!1}},"ee"),hn=n(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Me"),Fo=n((t,e,s)=>{let r=Array.from({length:e}),i=n(a=>({error:H(Xt(a),s),ok:!1}),"i");for(let a of t){if(typeof a.id!="number"||a.id<0||a.id>=e)continue;if(!hn(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(rt(c),s),ok:!1}}}return r.map(a=>a??{error:H(new Error("batch call returned no result"),s),ok:!1})},"is"),ds=n((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"Y"),xe=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}},"k"),Uo=n(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)W(t,s)},"rs"),xo=new TextDecoder,Ho=n(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return xo.decode(t)},"os"),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()}},Te=n(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"H"),Qo=n((t,e,s)=>{Te(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(go)}catch{}},e))},"as"),Hr=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(()=>{Te(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&&Qo(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()})},"Te"),jo=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}},"cs"),Ko=1e4,Qr=n(async t=>ue(Ko,void 0,t,()=>new TypeError("LunoraClient: poll timed out")),"ke"),ln=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),jr=n(t=>{if(t instanceof x)return!0;let e=t?.code;return e===void 0||ln.has(e)||$t.has(e)},"Ce"),qo=1e3,pn=6e4,Bo={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},He=n((t,e,s)=>{let r=Vt(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(Bo[t]??"BAD_REQUEST",a,{data:i});return H(o,s)},"B"),ps=n((t,e=Math.random)=>{let s=Math.min(qo*2**Math.max(t-1,0),pn);return Math.round(s*(.5+e()*.5))},"te"),Wo=n(t=>{let e=t?.code;return t instanceof x||e===void 0||ln.has(e)},"ls"),Go=n((t,e,s)=>{let r=st(t);return r!==void 0&&r>0?Math.min(r,pn):Wo(t)?ps(e,s):void 0},"fs"),$o=983040,Vo=n(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"ms"),zo=n(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&hn(s.body)&&e.set(s.id,s.body);return e},"ys"),Jo=n((t,e)=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:H(Xt(t),e),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:C(t.result)}}catch(s){return{commitCursor:t.commitCursor,error:H(rt(s),e),kind:"undecodable"}}},"Ss"),hs=n((t,e)=>`${b(t)}\0${e}`,"X"),Yo=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)},"vs"),fs=class{static{n(this,"bs")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){Zi(this.buffers,this.maxBuffers),this.buffers.set(hs(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(hs(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=hs(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},Xo=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(),Yo(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"},"gs"),Kr=n(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"Ae"),Zo=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)}`})}},"ws"),ms=n((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"se"),ys=n((t,e=!1)=>{let s=t.serverCursor,r=t.lastMutationId;br(()=>{for(let i of t.checkpointCallbacks)i({checkpoint:s,mutationId:r,...e&&{rowsFollow:!0}})})},"ie"),fn=n((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Ue"),ec=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,"Ts"),tc=n(t=>t.type==="delta"&&t.more===!0,"ks"),wt=n((t,e)=>t!==void 0&&t!==e,"j"),sc=n((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","Cs"),rc=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()},"As"),ic=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()},"Es"),nc=n((t,e,s)=>{if(wt(s,t.identityFingerprint()))return;let r=t.leader,i=sc(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&(t.awaitLeaderAnswers(),t.flushOfflineQueues())},"_s"),ac=n(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Is"),oc=n((t,e,s,r,i,a)=>{if(wt(a,t.identityFingerprint()))return;let o=t.subscription(e);if(!o)return;t.dropCacheSeed(e);let c=!o.valueReceived;o.valueReceived=!0,fn(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&ct(o,r),ae(o,s),c&&t.emitConnectionStatus(),t.settleAwaitedAnswer(o,!0)},"Rs"),cc=n((t,e,s,r)=>{if(wt(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)}},"Os"),uc=n((t,e,s,r,i,a,o)=>{if(wt(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&a===t.clientIdentifier()&&ms(c,i),ys(c))},"Ls"),dc=n((t,e,s)=>t!==null||e&&s===null,"Ps"),hc=n(t=>t.sensitive===!0,"Ms"),lc=n((t,e)=>{if(!hc(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}},"Fs"),pc=[hr,Eo],fc=n(t=>t.type==="data"||t.type==="delta"||t.type==="settled"||t.type==="resume"||t.type==="error"&&typeof t.id=="string","Us"),mc=100,mn=1e4,yc=1e4,gc=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)})},"Bs"),qr=n(async t=>typeof t=="function"?await t():t,"Ee"),Br=n(async(t,e,s,r)=>{let i=new AbortController,a=setTimeout(()=>{i.abort()},mn);try{let o=await t(e,{body:s,credentials:"include",headers:r,method:"POST",signal:i.signal});return{status:o.status,text:await o.text()}}finally{clearTimeout(a)}},"_e"),Wr=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:kt}),"Ie"),bc=n((t,e)=>t instanceof TypeError&&ls(e),"Ds"),vc=n((t,e,s,r)=>e||t===!0&&s&&!r,"Qs"),Sc=Promise.resolve(),bt=class t{static{n(this,"We")}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 N;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 fs(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??j(Zt(e.url),cs),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;let s=e.authBasePath??mo;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??pr(),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=Lr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Dr(e.queryCache),this.clientQueryStore=new it,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=Sc),this.offlineQueue=new ft(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-${mt()}`,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=Lo(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&&xe(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(!Me(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&&(Zi(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(j(this.url,`${this.authBasePath}${yo}`),{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>=mc?!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:xe(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=Fe(this.wsUrl),i=n(o=>{let c=Fe(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 Mr(this,e,s,r)}whenReady(e={}){return e.signal===void 0?this.readyPromise:ss(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,q(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=N.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 ue(this.rpcTimeoutMs,void 0,async s=>this.sendBatch(e,s))}async mutation(e,s,r={}){if(r.signal?.aborted)throw Se(r.signal);let{value:i}=await ss(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(j(Zt(this.url),oo),{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=>gs(a))))},"onMessage")});return s.close}subscribe(e,s,r,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};let a=s??{},o=N.key(e.__lunoraRef,a,i.shardKey),c=this.subscriptions.get(o),u=pt(r),h=pt(i.onError),d=pt(i.onCheckpoint);if(!c){this.nextSubId+=1;let y=`sub_${this.nextSubId.toString()}`,m=q(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()&&xe(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(N.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}=dt({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 Rr(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),dc(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?[No,Po(this.authToken)]:void 0}applyUpgradeBearer(e){e==="cold"?(this.resetRoomSends(),this.reconnectCold()):e==="warm"&&this.bounceShardSockets(!0)}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,Te(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 ut({channelName:e,onBecomeLeader:n(()=>{rc(s)},"onBecomeLeader"),onStopBeingLeader:n(()=>{ic(s)},"onStopBeingLeader"),onConnectionStatus:n((r,i)=>{nc(s,r,i)},"onConnectionStatus"),onSubscriptionData:n((r,i,a,o,c)=>{oc(s,r,i,a,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:n(()=>{ac(s)},"onLeaderClaimAnswered"),onSubscriptionError:n((r,i,a)=>{cc(s,r,i,a)},"onSubscriptionError"),onSubscriptionSettled:n((r,i,a,o,c,u)=>{uc(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(j(this.url,os),{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(Pe(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 Fo(a.results??[],e.length,r.headers)}async runMutation(e,s,r){this.assertOpen();let i=lc(e,r),a=s,o=i.mutationId??mt();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(k=>{I=k},"onCommitCursor")});for(let k of d)k(I);return{committed:!0,value:w}}catch(w){let k=bc(w,a),se=f&&m&&k,D=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(w instanceof TypeError||w instanceof x)&&ls(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),vc(i.onlineOnly,se,k,D)?Wr(e.__lunoraRef,w):w}}refuseOnlineOnlyWhenDown(e,s,r=[]){if(!s.onlineOnly)return;let i=this.writeQueueGate(s.shardKey);if(i.socketDown||i.midReconnect)throw ce(r),Wr(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),Me(e)){for(let o of r)o(s);return}ce(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(()=>{ce(o)},"onRejected")},shardKey:r})}catch(m){throw ce(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),Me(S)||ce(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(rs(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&&(ls(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=vr(),a=this.identityFingerprint(),o;try{o=await Qr(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:K(h.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await Qr(async s=>e(j(this.url,os),{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=N.key(e,s,r),u=this.subscriptions.get(c);if(u){let h=ot(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}=Ar(this.subscriptions,r);try{e(u,s)}catch{ce(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:jo({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:Ue(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=Ue(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||Hr(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 gc(m,yc)}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),Te(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),Te(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=Fe(this.wsUrl),r=s.pathname.endsWith(cs)?s.pathname.slice(0,-cs.length):s.pathname;return s.pathname=j(r,e),es(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){let i=Fe(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("&"),es(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[wo]=To(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 ue(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{let y=await a(j(this.url,io),{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 He(d.status,d.statusText,d.headers);let l=h;if(typeof l!="object"||l===null||Array.isArray(l))throw He(d.status,d.statusText,d.headers);let p=be(h);if(p!==void 0)throw Yt(p,d.headers);if(!d.ok)throw He(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(rt(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(j(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 Pe({...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:pc,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 ue(this.connectTimeoutMs,void 0,async()=>({session:await qr(this.wsToken),ticket:await qr(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;Hr(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.heldFrames=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)}Uo(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(),Te(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.heldFrames=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),lt(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):lt(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=Ho(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}let a=this.getConnection(s);if(i.type!=="error"&&a?.reconnect.reset(),a&&typeof i.id=="string"&&this.settleSubscribeWatchdog(a,i.id),i.type==="batchStart")a&&(a.heldFrames=[]);else if(i.type==="batchEnd"){let o=a?.heldFrames;if(a&&o){let{socket:c}=a;a.heldFrames=void 0,at(()=>{for(let u of o){if(a.retired===!0||a.socket!==c)break;this.dispatchServerMessage(u,s)}},()=>!this.closed)}}else a?.heldFrames&&fc(i)?a.heldFrames.push(i):this.dispatchServerMessage(i,s)}dispatchServerMessage(e,s){switch(e.type){case"ack":{let r=this.subscriptions.getById(e.id);r&&this.ackAndAdvanceCursor(r,void 0,void 0);return}case"chunk":{let{data:r,generation:i,id:a,seq:o}=e,c=this.streams.get(a);c&&typeof o=="number"&&(c.lastSeq=o,typeof i=="number"&&(c.generation=i),c.durable=!0),c?.handle.push(C(r));return}case"complete":{this.handleCompleteMessage(e.id);return}case"data":case"delta":{this.handleDataMessage(e);return}case"error":{this.handleErrorMessage(e);break}case"identity":{this.handleIdentityFrame(e,s),this.adoptSocketConnectionId(e,s),this.confirmShardIdentity(s);break}case"live":{this.dispatchLive(e,s);break}case"pokeEnd":{this.handlePokeEnd(e,s);break}case"pokePart":{this.pokeAssembler.part(s,e);break}case"pokeStart":{this.pokeAssembler.start(s,e);break}case"resume":{this.handleResumeMessage(e);break}case"settled":{this.handleSettledMessage(e);break}case"whisper":{this.dispatchWhisper(e,s);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(b(s),e.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(mr(e)),this.forgetStream(r);return}let a=r===void 0?void 0:this.subscriptions.getById(r);if(a){lt(a);let c=Jt(e),u=this.identityFingerprint(),h=N.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,Jt(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){Zo(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=Xo(e,s,r);if(e.answered!==i&&this.emitSyncStatus(),Kr(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"&&ec(i,e))return;let a,o=i.pendingDeltaRun;try{a=lr(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===Gt){this.resnapshotSubscription(i);return}if(tc(e)){i.pendingDeltaRun={payload:a};return}i.pendingDeltaRun=void 0,this.dropCacheSeed(N.keyOf(i));let c=s!==void 0&&!i.valueReceived;if(fn(i,a,{cursor:e.cursor,epoch:e.epoch}),c&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(ms(i,e.lastMutationId),ys(i,!0)),this.persistQueryValue(i),ct(i,i.serverCursor),s!==void 0&&wr(i,s),ae(i,a),this.tabCoordinator?.isLeader()){let u=N.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(N.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&&ms(s,e.lastMutationId),ys(s),this.tabCoordinator?.isLeader())){let r=N.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),ct(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()},mn),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(()=>Br(a,j(this.url,e),o,c)).then(({status: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&&xe(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,Kr(e);this.emitSyncStatus(),this.bounceShardSockets()}bounceShardSockets(e=!1){let{authToken:s,fetchImpl:r}=this;for(let i of this.connections.values()){let{connectionId:a}=i;e&&s!==null&&r!==void 0&&i.socket!==void 0&&a!==void 0&&i.retired!==!0?Br(r,j(this.url,i.shardKey===void 0?xr:`${xr}?shard=${encodeURIComponent(i.shardKey)}`),JSON.stringify({connectionId:a}),{authorization:`Bearer ${s}`,"content-type":"application/json"}).then(({text:o})=>JSON.parse(o)?.ok===!0).catch(()=>!1).then(o=>{!o&&!this.closed&&this.authToken===s&&i.connectionId===a&&this.bounceShardSocket(i)}).catch(()=>{}):this.bounceShardSocket(i)}for(let i of this.supplementaryBounces)i()}bounceShardSocket(e){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)})}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&&xe(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=as(e),r=s&&this.subscriptions.get(N.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=as(e);if(e===void 0||s===void 0)return e;let r=n(()=>this.snapshotAnswer(e)!==void 0||e(),"s");return ns(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+=us){let l=u.slice(d,d+us),p=await this.replayBatched(l,e,s);if(h.push(...p.requeue),p.stop||p.requeue.length>0){h.push(...u.slice(d+us));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,ps(i))})}noteReplayRetryDelay(e,s,r){let i=b(e),a=this.replayRetryState.get(i),o=(a?.attempts??0)+1,c=Go(s,o)??(r===null&&Ne(s)?ps(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)||jr(e)}noteReplayAuthRefusal(e,s){if(!Ne(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,...ds(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||Ne(s)||r==="RATE_LIMITED"||r==="TOO_MANY_REQUESTS"||!jr(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,...ds(a.identity,r),mutationId:a.id,onCommitCursor:n(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(a,c,o)}catch(c){if(Me(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&&Vo(i)>$o)return await this.replayBatchedHalves(e,s,r);let{fetchImpl:a}=this,o,c;try{({payload:c,response:o}=await ue(this.rpcTimeoutMs,void 0,async h=>{let d=await a(j(this.url,os),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...ds(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,He(o.status,o.statusText,o.headers),s,r);if(!Array.isArray(c.results)){let h=be(c),d=h===void 0?He(o.status,o.statusText,o.headers):Yt(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=zo(s),c=[],u=!1,h=!1;for(let[d,l]of e.entries()){let p=Jo(o.get(d),a);switch(p.kind){case"committed":{u=!0,this.settleReplaySuccess(l,p.value,p.commitCursor);break}case"errored":{h||=Ne(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(zt(),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 wc=n(async t=>(t.assertOpen(),(await t.adminFetch(zr,"GET")).functions??[]),"Rt"),Tc=n(async t=>(t.assertOpen(),(await t.adminFetch(Jr,"GET")).jobs??[]),"gt"),Ec=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Yr,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Gt"),Cc=n(async t=>(t.assertOpen(),await t.adminFetch(Zr,"GET")),"Ct"),Oc=n(async t=>(t.assertOpen(),await t.adminFetch(Xr,"GET")),"Nt"),Ic=n(async t=>(t.assertOpen(),await t.adminFetch(ei,"GET")),"Mt"),kc=n(async t=>(t.assertOpen(),await t.adminFetch(ti,"GET")),"kt"),Rc=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(K(e.filters))),C(await t.adminFetch(`${si}?${s.toString()}`,"GET"))},"vt"),Ac=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(K(e.filters))),C(await t.adminFetch(`${ri}?${s.toString()}`,"GET"))},"Lt"),_c=n(async t=>(t.assertOpen(),(await t.adminFetch(oi,"GET")).namespaces??[]),"Vt"),Lc=n(async(t,e)=>{t.assertOpen();let s=L(ci,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"Kt"),Nc=n(async(t,e)=>{t.assertOpen();let s=L(St,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Bt"),Dc=n(async(t,e)=>{t.assertOpen(),await t.adminFetch(St,"PUT",e)},"Dt"),Pc=n(async(t,e)=>{t.assertOpen();let s=L(St,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"Jt"),Mc=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Gr,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"xt"),Fc=n(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(ai,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"$t"),Uc=n(async(t,e={})=>{t.assertOpen();let s=L(vt,{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"),xc=n(async(t,e,s)=>{t.assertOpen();let r=`${vt}?key=${encodeURIComponent(e)}${nt(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"jt"),Hc=n(async t=>(t.assertOpen(),(await t.adminFetch(Vr,"GET")).buckets??[]),"Wt"),Qc=n(async(t,e)=>{t.assertOpen();let s=`${vt}?key=${encodeURIComponent(e.key)}${nt(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"qt"),jc=n(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,a=`${$r}?key=${encodeURIComponent(e)}${i}${nt(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"),Kc=n(async t=>(t.assertOpen(),(await t.adminFetch(ii,"GET")).indexes??[]),"Yt"),qc=n(async(t,e)=>(t.assertOpen(),(await t.adminFetch(ni,"POST",e)).matches??[]),"Xt"),bs=class extends bt{static{n(this,"sa")}async shardTraffic(e){return Mc(this.adminHost,e)}async listScheduledJobs(){return tn(this.adminHost)}async schedulerStatus(){return sn(this.adminHost)}async cancelScheduledJob(e){return rn(this.adminHost,e)}async listDeadJobs(){return nn(this.adminHost)}async retryDeadJob(e){return an(this.adminHost,e)}async removeDeadJob(e){return on(this.adminHost,e)}async listWorkflowInstances(e){return cn(this.adminHost,e)}async getWorkflowInstance(e){return un(this.adminHost,e)}async setWorkflowInstanceStatus(e){return dn(this.adminHost,e)}async listFunctions(){return wc(this.adminHost)}async getCronJobs(){return Tc(this.adminHost)}async runCronJob(e){return Ec(this.adminHost,e)}async fetchOpenApi(){return Cc(this.adminHost)}async fetchArchitecture(){return Oc(this.adminHost)}async fetchOpenRpc(){return Ic(this.adminHost)}async listStorageObjects(e={}){return Uc(this.adminHost,e)}async deleteStorageObject(e,s){return xc(this.adminHost,e,s)}async listStorageBuckets(){return Hc(this.adminHost)}async uploadStorageObject(e){return Qc(this.adminHost,e)}async signedStorageUrl(e,s){return jc(this.adminHost,e,s)}async listGlobalTables(){return kc(this.adminHost)}async readGlobalTablePage(e){return Rc(this.adminHost,e)}async facetGlobalColumn(e){return Ac(this.adminHost,e)}async listVectorIndexes(){return Kc(this.adminHost)}async queryVectorIndex(e){return qc(this.adminHost,e)}async queryLogArchive(e={}){return Fc(this.adminHost,e)}async listKvNamespaces(){return _c(this.adminHost)}async listKvKeys(e){return Lc(this.adminHost,e)}async getKvValue(e){return Nc(this.adminHost,e)}async putKvValue(e){return Dc(this.adminHost,e)}async deleteKvKey(e){return Pc(this.adminHost,e)}async listAuthUsers(e={}){this.adminHost.assertOpen();let s=L(ui,{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(hi,"POST",e)}async setAuthUserRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(li,"POST",e)}async banAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(pi,"POST",e)}async unbanAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(fi,"POST",e)}async setAuthUserPassword(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(mi,"POST",e)}async removeAuthUser(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(yi,"POST",e)}async impersonateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(gi,"POST",e)}async revokeAuthSession(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(bi,"POST",e)}async revokeAuthUserSessions(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(vi,"POST",e)}async getAuthCapabilities(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Si,"GET")}async updateAuthUser(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(wi,"POST",e)}async listAuthAccounts(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(Ti,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ei,"POST",e)}async listAuthPasskeys(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(Ci,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Oi,"POST",e)}async disableAuthTwoFactor(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ii,"POST",e)}async listAuthOrganizations(e={}){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(L(ki,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.adminHost.assertOpen();let s=L(Ri,{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(Ai,{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(Di,{limit:e.limit,offset:e.offset});return await this.adminHost.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Pi,"POST",e)}async revokeAuthSignUpInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Mi,"POST",e)}async removeAuthOrgMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(_i,"POST",e)}async cancelAuthOrgInvitation(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Li,"POST",e)}async getAuthConfig(){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ni,"GET")}async createAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Fi,"POST",e)}async updateAuthOrganization(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Ui,"POST",e)}async deleteAuthOrganization(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(xi,"POST",e)}async addAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Hi,"POST",e)}async inviteAuthOrgMember(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Qi,"POST",e)}async setAuthOrgMemberRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(ji,"POST",e)}async listAuthOrgTeams(e){this.adminHost.assertOpen();let s=L(Ki,{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(qi,"POST",e)}async updateAuthOrgTeam(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Bi,"POST",e)}async removeAuthOrgTeam(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Wi,"POST",e)}async listAuthOrgTeamMembers(e){this.adminHost.assertOpen();let s=L(Gi,{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($i,"POST",e)}async removeAuthOrgTeamMember(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Vi,"POST",e)}async listAuthOrgRoles(e){this.adminHost.assertOpen();let s=L(zi,{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(Ji,"POST",e)}async updateAuthOrgRole(e){return this.adminHost.assertOpen(),await this.adminHost.adminFetch(Yi,"POST",e)}async deleteAuthOrgRole(e){this.adminHost.assertOpen(),await this.adminHost.adminFetch(Xi,"POST",e)}async listAuthSessions(e={}){this.adminHost.assertOpen();let s=L(di,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminHost.adminFetch(s,"GET")}},vs=n(t=>"listAuthUsers"in t,"ea");var vn=U(Os(),1);var F=U(re(),1);var Tt=U(Et(),1);var Ss=n(t=>q(t),"b");var yn=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"),ws={status:"idle"},gn=n((t,e)=>{for(let s of t.waiters)s(e);t.waiters.clear()},"F"),Bc=1e4,Wc=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)},Bc),t.waiters.add(h),e.addEventListener("abort",u,{once:!0}),o=s(()=>{h(!1)}),t.waiters.has(h)||o()}),"U"),Es=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(Ss(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=Ss(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 Wc(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"]}))yn(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,a,o={}){let c=Ss(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=ws;for(let m of p.clients.keys())yn(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},gn(y,!0)},{onError:n(f=>{let y=this.liveFor(c);y.state.status!=="pushed"&&(y.state={status:"errored"},gn(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:ws,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=ws)}},bn=new WeakMap,Ts=n(t=>{let e=bn.get(t);return e||(e=new Es(t),bn.set(t,e)),e},"L"),Sn=(0,F.createContext)(null),Gc=(0,F.createContext)(!1),$c=n(()=>new jt({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"B"),Vc=n(t=>{let e=(0,vn.c)(20),{children:s,client:r,queryClient:i}=t,a=(0,F.use)(Oe),o;e[0]!==a||e[1]!==i?(o=n(()=>i??a??$c(),"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(()=>{Ts(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&&(Ts(l.current).stopClearingOnIdentityChange(u),l.current=r,Ts(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,Tt.jsx)(Gc,{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,Tt.jsx)(Sn,{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,Tt.jsx)(_t,{client:u,children:E}),e[17]=E,e[18]=u,e[19]=I):I=e[19],I},"X");var Qe=n(()=>{let t=(0,F.use)(Sn);if(!t)throw new g("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var wn=U(Os(),1),Tn=U(re(),1);var zc=n(()=>{let t=(0,wn.c)(4),e=Qe(),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,Tn.useSyncExternalStore)(s,r,i)},"S");var Ef=n(()=>{let t=Qe();if(!vs(t))throw new g("INTERNAL","The Studio needs a LunoraAdminClient (`@lunora/client/admin`), not a plain LunoraClient.");return t},"a");export{g as a,Rn as b,An as c,Ce as d,qe as e,K as f,C as g,Yn as h,bs as i,sa as j,Ie as k,la as l,pa as m,Vc as n,zc as o,Ef as p};
|