fetchium 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +12 -5
  2. package/README.md +1 -1
  3. package/dist/cjs/development/QueryAdapter-DUo338ga.js +2 -0
  4. package/dist/cjs/development/QueryAdapter-DUo338ga.js.map +1 -0
  5. package/dist/cjs/development/QueryClient-m7BzCIe9.js +2 -0
  6. package/dist/cjs/development/QueryClient-m7BzCIe9.js.map +1 -0
  7. package/dist/cjs/development/index.js +1 -1
  8. package/dist/cjs/development/index.js.map +1 -1
  9. package/dist/cjs/development/mutation-wUhcGxKl.js +2 -0
  10. package/dist/cjs/development/mutation-wUhcGxKl.js.map +1 -0
  11. package/dist/cjs/development/react/index.js +1 -1
  12. package/dist/cjs/development/rest/index.js +2 -0
  13. package/dist/cjs/development/rest/index.js.map +1 -0
  14. package/dist/cjs/development/topic/index.js +2 -0
  15. package/dist/cjs/development/topic/index.js.map +1 -0
  16. package/dist/cjs/production/QueryAdapter-DUo338ga.js +2 -0
  17. package/dist/cjs/production/QueryAdapter-DUo338ga.js.map +1 -0
  18. package/dist/cjs/production/QueryClient-4T90peFN.js +2 -0
  19. package/dist/cjs/production/QueryClient-4T90peFN.js.map +1 -0
  20. package/dist/cjs/production/index.js +1 -1
  21. package/dist/cjs/production/index.js.map +1 -1
  22. package/dist/cjs/production/mutation-Dk0gznwX.js +2 -0
  23. package/dist/cjs/production/mutation-Dk0gznwX.js.map +1 -0
  24. package/dist/cjs/production/react/index.js +1 -1
  25. package/dist/cjs/production/rest/index.js +2 -0
  26. package/dist/cjs/production/rest/index.js.map +1 -0
  27. package/dist/cjs/production/topic/index.js +2 -0
  28. package/dist/cjs/production/topic/index.js.map +1 -0
  29. package/dist/esm/MutationResult.d.ts +0 -1
  30. package/dist/esm/MutationResult.d.ts.map +1 -1
  31. package/dist/esm/QueryAdapter.d.ts +49 -0
  32. package/dist/esm/QueryAdapter.d.ts.map +1 -0
  33. package/dist/esm/QueryClient.d.ts +26 -4
  34. package/dist/esm/QueryClient.d.ts.map +1 -1
  35. package/dist/esm/QueryResult.d.ts +11 -11
  36. package/dist/esm/QueryResult.d.ts.map +1 -1
  37. package/dist/esm/development/QueryAdapter-Bu5UJjE4.js +14 -0
  38. package/dist/esm/development/QueryAdapter-Bu5UJjE4.js.map +1 -0
  39. package/dist/esm/development/QueryClient-BajBmpnA.js +2572 -0
  40. package/dist/esm/development/QueryClient-BajBmpnA.js.map +1 -0
  41. package/dist/esm/development/index.js +29 -100
  42. package/dist/esm/development/index.js.map +1 -1
  43. package/dist/esm/development/mutation-DAOZE4Ok.js +58 -0
  44. package/dist/esm/development/mutation-DAOZE4Ok.js.map +1 -0
  45. package/dist/esm/development/react/index.js +1 -1
  46. package/dist/esm/development/rest/index.js +142 -0
  47. package/dist/esm/development/rest/index.js.map +1 -0
  48. package/dist/esm/development/{shared-Dq2yW78d.js → shared-DcuVH8Pf.js} +5 -5
  49. package/dist/esm/development/{shared-Dq2yW78d.js.map → shared-DcuVH8Pf.js.map} +1 -1
  50. package/dist/esm/development/stores/async.js +6 -6
  51. package/dist/esm/development/stores/sync.js +5 -5
  52. package/dist/esm/development/topic/index.js +86 -0
  53. package/dist/esm/development/topic/index.js.map +1 -0
  54. package/dist/esm/index.d.ts +5 -4
  55. package/dist/esm/index.d.ts.map +1 -1
  56. package/dist/esm/mutation.d.ts +6 -19
  57. package/dist/esm/mutation.d.ts.map +1 -1
  58. package/dist/esm/production/QueryAdapter-Bu5UJjE4.js +14 -0
  59. package/dist/esm/production/QueryAdapter-Bu5UJjE4.js.map +1 -0
  60. package/dist/esm/production/{QueryClient-BP0Z1rQV.js → QueryClient-KH0Ex_8m.js} +595 -591
  61. package/dist/esm/production/QueryClient-KH0Ex_8m.js.map +1 -0
  62. package/dist/esm/production/index.js +29 -100
  63. package/dist/esm/production/index.js.map +1 -1
  64. package/dist/esm/production/mutation-C7BOChR2.js +58 -0
  65. package/dist/esm/production/mutation-C7BOChR2.js.map +1 -0
  66. package/dist/esm/production/react/index.js +1 -1
  67. package/dist/esm/production/rest/index.js +142 -0
  68. package/dist/esm/production/rest/index.js.map +1 -0
  69. package/dist/esm/production/{shared-Dq2yW78d.js → shared-DcuVH8Pf.js} +5 -5
  70. package/dist/esm/production/{shared-Dq2yW78d.js.map → shared-DcuVH8Pf.js.map} +1 -1
  71. package/dist/esm/production/stores/async.js +6 -6
  72. package/dist/esm/production/stores/sync.js +5 -5
  73. package/dist/esm/production/topic/index.js +86 -0
  74. package/dist/esm/production/topic/index.js.map +1 -0
  75. package/dist/esm/query-types.d.ts +2 -4
  76. package/dist/esm/query-types.d.ts.map +1 -1
  77. package/dist/esm/query.d.ts +17 -39
  78. package/dist/esm/query.d.ts.map +1 -1
  79. package/dist/esm/rest/RESTMutation.d.ts +18 -0
  80. package/dist/esm/rest/RESTMutation.d.ts.map +1 -0
  81. package/dist/esm/rest/RESTQuery.d.ts +24 -0
  82. package/dist/esm/rest/RESTQuery.d.ts.map +1 -0
  83. package/dist/esm/rest/RESTQueryAdapter.d.ts +34 -0
  84. package/dist/esm/rest/RESTQueryAdapter.d.ts.map +1 -0
  85. package/dist/esm/rest/index.d.ts +5 -0
  86. package/dist/esm/rest/index.d.ts.map +1 -0
  87. package/dist/esm/stores/shared.d.ts.map +1 -1
  88. package/dist/esm/testing/MockClient.d.ts +64 -0
  89. package/dist/esm/testing/MockClient.d.ts.map +1 -0
  90. package/dist/esm/testing/auto-generate.d.ts +20 -0
  91. package/dist/esm/testing/auto-generate.d.ts.map +1 -0
  92. package/dist/esm/testing/entity-factory.d.ts +13 -0
  93. package/dist/esm/testing/entity-factory.d.ts.map +1 -0
  94. package/dist/esm/testing/index.d.ts +6 -0
  95. package/dist/esm/testing/index.d.ts.map +1 -0
  96. package/dist/esm/testing/types.d.ts +37 -0
  97. package/dist/esm/testing/types.d.ts.map +1 -0
  98. package/dist/esm/topic/TopicQuery.d.ts +10 -0
  99. package/dist/esm/topic/TopicQuery.d.ts.map +1 -0
  100. package/dist/esm/topic/TopicQueryAdapter.d.ts +43 -0
  101. package/dist/esm/topic/TopicQueryAdapter.d.ts.map +1 -0
  102. package/dist/esm/topic/index.d.ts +3 -0
  103. package/dist/esm/topic/index.d.ts.map +1 -0
  104. package/dist/esm/typeDefs.d.ts +1 -1
  105. package/dist/esm/types.d.ts +9 -4
  106. package/dist/esm/types.d.ts.map +1 -1
  107. package/package.json +51 -4
  108. package/plugin/.claude-plugin/plugin.json +10 -0
  109. package/plugin/agents/fetchium.md +168 -0
  110. package/plugin/docs/api/fetchium-react.md +135 -0
  111. package/plugin/docs/api/fetchium.md +674 -0
  112. package/plugin/docs/api/stores-async.md +219 -0
  113. package/plugin/docs/api/stores-sync.md +133 -0
  114. package/plugin/docs/core/entities.md +351 -0
  115. package/plugin/docs/core/queries.md +600 -0
  116. package/plugin/docs/core/streaming.md +550 -0
  117. package/plugin/docs/core/types.md +374 -0
  118. package/plugin/docs/data/caching.md +298 -0
  119. package/plugin/docs/data/live-data.md +435 -0
  120. package/plugin/docs/data/mutations.md +465 -0
  121. package/plugin/docs/guides/auth.md +318 -0
  122. package/plugin/docs/guides/error-handling.md +351 -0
  123. package/plugin/docs/guides/offline.md +270 -0
  124. package/plugin/docs/guides/testing.md +301 -0
  125. package/plugin/docs/quickstart.md +170 -0
  126. package/plugin/docs/reference/pagination.md +519 -0
  127. package/plugin/docs/reference/rest-queries.md +107 -0
  128. package/plugin/docs/reference/why-signalium.md +364 -0
  129. package/plugin/docs/setup/project-setup.md +319 -0
  130. package/plugin/install.mjs +88 -0
  131. package/plugin/skills/design/SKILL.md +140 -0
  132. package/plugin/skills/teach/SKILL.md +105 -0
  133. package/dist/cjs/development/QueryClient-CpmwggOn.js +0 -2
  134. package/dist/cjs/development/QueryClient-CpmwggOn.js.map +0 -1
  135. package/dist/cjs/production/QueryClient-qi3bR0eD.js +0 -2
  136. package/dist/cjs/production/QueryClient-qi3bR0eD.js.map +0 -1
  137. package/dist/esm/development/QueryClient-DRZtPKFD.js +0 -2568
  138. package/dist/esm/development/QueryClient-DRZtPKFD.js.map +0 -1
  139. package/dist/esm/production/QueryClient-BP0Z1rQV.js.map +0 -1
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./QueryClient-CpmwggOn.js"),y=require("signalium");class p{params;result;optimisticUpdates;config;effects;constructor(){return t.createDefinitionProxy(this)}}class M extends p{path;method="POST";body;headers;requestOptions;getStorageKey(){return`${this.method??"POST"}:${this.path??""}`}async send(){const e=this.getPath?this.getPath():this.path,n=this.getMethod?this.getMethod():this.method,a=this.getBody?this.getBody():this.body,c=this.getRequestOptions?this.getRequestOptions():this.requestOptions;if(!e)throw new Error("RESTMutation requires a path. Define `path` as a field or override `getPath()`.");const s=a??this.params,i=t.resolveBaseUrl(c?.baseUrl)??t.resolveBaseUrl(this.context.baseUrl),f=i?`${i}${e}`:e,{baseUrl:u,signal:g,...r}=c??{},d={"Content-Type":"application/json",...this.headers},l=await this.context.fetch(f,{method:n,headers:d,body:JSON.stringify(s),signal:this.signal,...r});return this.response=l,l.json()}}const h=new WeakMap,C=o=>{const e=h.get(o);if(e===void 0)throw new Error("Mutation definition not found");return e().id};function m(o){let e=h.get(o);if(e!==void 0)return e;let n;const a=()=>{if(n!==void 0)return n;const c=new o,s=t.extractDefinition(c),{fields:i}=s,f=`mutation:${String(s.methods.getStorageKey.call(i))}`,u=i.params??{},g=u instanceof t.ValidatorDef?u:t.t.object(u),r=i.result,d=r!==void 0?r instanceof t.ValidatorDef?r:t.t.object(r):void 0;return n={id:f,requestShape:g,responseShape:d,captured:s,optimisticUpdates:i.optimisticUpdates??!1,config:i.config,effects:i.effects,hasGetEffects:typeof s.methods.getEffects=="function"},n};return h.set(o,a),a}function E(o){const e=m(o),n=y.getContext(t.QueryClientContext);if(n===void 0)throw new Error("QueryClient not found");return n.getMutation(e())}exports.ARRAY_KEY=t.ARRAY_KEY;exports.Entity=t.Entity;exports.GcManager=t.GcManager;exports.LiveFieldConfig=t.LiveFieldConfig;exports.LiveFieldType=t.LiveFieldType;exports.Mask=t.Mask;exports.NetworkManager=t.NetworkManager;exports.NetworkManagerContext=t.NetworkManagerContext;exports.NetworkMode=t.NetworkMode;exports.NoOpGcManager=t.NoOpGcManager;exports.NoOpNetworkManager=t.NoOpNetworkManager;exports.QUERY_ID=t.QUERY_ID;exports.Query=t.Query;exports.QueryClient=t.QueryClient;exports.QueryClientContext=t.QueryClientContext;exports.RECORD_KEY=t.RECORD_KEY;exports.RESTQuery=t.RESTQuery;exports.defaultNetworkManager=t.defaultNetworkManager;exports.draft=t.draft;exports.fetchQuery=t.fetchQuery;exports.queryKeyForClass=t.queryKeyForClass;exports.registerFormat=t.registerFormat;exports.t=t.t;exports.Mutation=p;exports.RESTMutation=M;exports.getMutation=E;exports.mutationKeyForClass=C;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./QueryClient-m7BzCIe9.js"),r=require("./QueryAdapter-DUo338ga.js"),t=require("./mutation-wUhcGxKl.js");exports.ARRAY_KEY=e.ARRAY_KEY;exports.Entity=e.Entity;exports.GcManager=e.GcManager;exports.LiveFieldConfig=e.LiveFieldConfig;exports.LiveFieldType=e.LiveFieldType;exports.Mask=e.Mask;exports.NetworkManager=e.NetworkManager;exports.NetworkManagerContext=e.NetworkManagerContext;exports.NetworkMode=e.NetworkMode;exports.NoOpGcManager=e.NoOpGcManager;exports.NoOpNetworkManager=e.NoOpNetworkManager;exports.QUERY_ID=e.QUERY_ID;exports.Query=e.Query;exports.QueryClient=e.QueryClient;exports.QueryClientContext=e.QueryClientContext;exports.RECORD_KEY=e.RECORD_KEY;exports.defaultNetworkManager=e.defaultNetworkManager;exports.draft=e.draft;exports.fetchQuery=e.fetchQuery;exports.queryKeyForClass=e.queryKeyForClass;exports.registerFormat=e.registerFormat;exports.t=e.t;exports.QueryAdapter=r.QueryAdapter;exports.Mutation=t.Mutation;exports.getMutation=t.getMutation;exports.mutationKeyForClass=t.mutationKeyForClass;
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/mutation.ts"],"sourcesContent":["import { getContext, ReactiveTask } from 'signalium';\nimport {\n ExtractType,\n InternalTypeDef,\n MutationEffects,\n TypeDef,\n RetryConfig,\n TypeDefShape,\n QueryRequestOptions,\n} from './types.js';\nimport { QueryClientContext, QueryContext, resolveBaseUrl } from './QueryClient.js';\nimport { ValidatorDef, t } from './typeDefs.js';\nimport { createDefinitionProxy, extractDefinition, type CapturedDefinition } from './fieldRef.js';\n\n// ================================\n// Mutation Definition Types\n// ================================\n\nexport interface MutationConfigOptions {\n retry?: RetryConfig | number | false;\n}\n\nexport interface MutationDefinition<Request, Response> {\n id: string;\n requestShape: InternalTypeDef;\n responseShape: InternalTypeDef | undefined;\n captured: CapturedDefinition<Mutation>;\n optimisticUpdates: boolean;\n config?: MutationConfigOptions;\n effects?: MutationEffects;\n hasGetEffects: boolean;\n}\n\n// ================================\n// Mutation base class\n// ================================\n\nexport abstract class Mutation {\n readonly params?: TypeDefShape;\n readonly result?: TypeDefShape;\n readonly optimisticUpdates?: boolean;\n readonly config?: MutationConfigOptions;\n readonly effects?: Readonly<MutationEffects>;\n\n declare context: QueryContext;\n declare response: Response | undefined;\n declare signal: AbortSignal;\n\n abstract send(): Promise<unknown>;\n abstract getStorageKey(): unknown;\n\n getEffects?(): MutationEffects;\n\n constructor() {\n return createDefinitionProxy(this);\n }\n}\n\n// ================================\n// RESTMutation\n// ================================\n\nexport abstract class RESTMutation extends Mutation {\n path?: string;\n method: 'POST' | 'PUT' | 'DELETE' | 'PATCH' = 'POST';\n body?: Record<string, unknown>;\n headers?: HeadersInit;\n requestOptions?: QueryRequestOptions;\n\n getStorageKey(): string {\n return `${this.method ?? 'POST'}:${this.path ?? ''}`;\n }\n\n getPath?(): string | undefined;\n getMethod?(): string;\n getBody?(): Record<string, unknown> | undefined;\n getRequestOptions?(): QueryRequestOptions | undefined;\n\n async send(): Promise<unknown> {\n const path = this.getPath ? this.getPath() : this.path;\n const method = this.getMethod ? this.getMethod() : this.method;\n const body = this.getBody ? this.getBody() : this.body;\n const requestOptions = this.getRequestOptions ? this.getRequestOptions() : this.requestOptions;\n\n if (!path) {\n throw new Error('RESTMutation requires a path. Define `path` as a field or override `getPath()`.');\n }\n\n const bodyData = body ?? (this.params as Record<string, unknown>);\n\n const baseUrl = resolveBaseUrl(requestOptions?.baseUrl) ?? resolveBaseUrl(this.context.baseUrl);\n const fullUrl = baseUrl ? `${baseUrl}${path}` : path;\n\n const { baseUrl: _baseUrl, signal: _signal, ...fetchOptions } = requestOptions ?? ({} as Record<string, unknown>);\n\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n ...(this.headers as Record<string, string>),\n };\n\n const fetchResponse = await this.context.fetch(fullUrl, {\n method,\n headers,\n body: JSON.stringify(bodyData),\n signal: this.signal,\n ...fetchOptions,\n });\n\n this.response = fetchResponse;\n return fetchResponse.json();\n }\n}\n\n// ================================\n// Mutation definition cache and lookup\n// ================================\n\nconst mutationDefCache = new WeakMap<new () => Mutation, () => MutationDefinition<any, any>>();\n\nexport const mutationKeyForClass = (cls: new () => Mutation): string => {\n const getMutationDef = mutationDefCache.get(cls);\n\n if (getMutationDef === undefined) {\n throw new Error('Mutation definition not found');\n }\n\n return getMutationDef().id;\n};\n\n// ================================\n// Internal: build mutation definition from class\n// ================================\n\nfunction buildMutationDefinition(MutationClass: new () => Mutation): () => MutationDefinition<any, any> {\n let cached = mutationDefCache.get(MutationClass);\n\n if (cached !== undefined) {\n return cached;\n }\n\n let mutationDefinition: MutationDefinition<any, any> | undefined;\n\n const getter = (): MutationDefinition<any, any> => {\n if (mutationDefinition !== undefined) {\n return mutationDefinition;\n }\n\n const instance = new MutationClass();\n const captured = extractDefinition(instance);\n const { fields } = captured;\n\n const id = `mutation:${String(captured.methods.getStorageKey.call(fields))}`;\n\n const requestDef = fields.params ?? {};\n const requestShape = (requestDef instanceof ValidatorDef\n ? requestDef\n : t.object(requestDef)) as unknown as InternalTypeDef;\n const responseDef = fields.result;\n const responseShape =\n responseDef !== undefined\n ? ((responseDef instanceof ValidatorDef ? responseDef : t.object(responseDef)) as unknown as InternalTypeDef)\n : undefined;\n\n mutationDefinition = {\n id,\n requestShape,\n responseShape,\n captured,\n optimisticUpdates: fields.optimisticUpdates ?? false,\n config: fields.config,\n effects: fields.effects,\n hasGetEffects: typeof captured.methods.getEffects === 'function',\n };\n\n return mutationDefinition;\n };\n\n mutationDefCache.set(MutationClass, getter);\n return getter;\n}\n\n// ================================\n// Public API\n// ================================\n\nexport function getMutation<T extends Mutation>(\n MutationClass: new () => T,\n): ReactiveTask<Readonly<ExtractType<T['result']>>, [ExtractType<T['params']>]> {\n const getMutationDef = buildMutationDefinition(MutationClass);\n\n const queryClient = getContext(QueryClientContext);\n\n if (queryClient === undefined) {\n throw new Error('QueryClient not found');\n }\n\n return queryClient.getMutation<any, any>(getMutationDef());\n}\n"],"names":["Mutation","createDefinitionProxy","RESTMutation","path","method","body","requestOptions","bodyData","baseUrl","resolveBaseUrl","fullUrl","_baseUrl","_signal","fetchOptions","headers","fetchResponse","mutationDefCache","mutationKeyForClass","cls","getMutationDef","buildMutationDefinition","MutationClass","cached","mutationDefinition","getter","instance","captured","extractDefinition","fields","id","requestDef","requestShape","ValidatorDef","t","responseDef","responseShape","getMutation","queryClient","getContext","QueryClientContext"],"mappings":"oJAqCO,MAAeA,CAAS,CACpB,OACA,OACA,kBACA,OACA,QAWT,aAAc,CACZ,OAAOC,EAAAA,sBAAsB,IAAI,CACnC,CACF,CAMO,MAAeC,UAAqBF,CAAS,CAClD,KACA,OAA8C,OAC9C,KACA,QACA,eAEA,eAAwB,CACtB,MAAO,GAAG,KAAK,QAAU,MAAM,IAAI,KAAK,MAAQ,EAAE,EACpD,CAOA,MAAM,MAAyB,CAC7B,MAAMG,EAAO,KAAK,QAAU,KAAK,QAAA,EAAY,KAAK,KAC5CC,EAAS,KAAK,UAAY,KAAK,UAAA,EAAc,KAAK,OAClDC,EAAO,KAAK,QAAU,KAAK,QAAA,EAAY,KAAK,KAC5CC,EAAiB,KAAK,kBAAoB,KAAK,kBAAA,EAAsB,KAAK,eAEhF,GAAI,CAACH,EACH,MAAM,IAAI,MAAM,iFAAiF,EAGnG,MAAMI,EAAWF,GAAS,KAAK,OAEzBG,EAAUC,EAAAA,eAAeH,GAAgB,OAAO,GAAKG,iBAAe,KAAK,QAAQ,OAAO,EACxFC,EAAUF,EAAU,GAAGA,CAAO,GAAGL,CAAI,GAAKA,EAE1C,CAAE,QAASQ,EAAU,OAAQC,EAAS,GAAGC,CAAA,EAAiBP,GAAmB,CAAA,EAE7EQ,EAAuB,CAC3B,eAAgB,mBAChB,GAAI,KAAK,OAAA,EAGLC,EAAgB,MAAM,KAAK,QAAQ,MAAML,EAAS,CACtD,OAAAN,EACA,QAAAU,EACA,KAAM,KAAK,UAAUP,CAAQ,EAC7B,OAAQ,KAAK,OACb,GAAGM,CAAA,CACJ,EAED,YAAK,SAAWE,EACTA,EAAc,KAAA,CACvB,CACF,CAMA,MAAMC,MAAuB,QAEhBC,EAAuBC,GAAoC,CACtE,MAAMC,EAAiBH,EAAiB,IAAIE,CAAG,EAE/C,GAAIC,IAAmB,OACrB,MAAM,IAAI,MAAM,+BAA+B,EAGjD,OAAOA,IAAiB,EAC1B,EAMA,SAASC,EAAwBC,EAAuE,CACtG,IAAIC,EAASN,EAAiB,IAAIK,CAAa,EAE/C,GAAIC,IAAW,OACb,OAAOA,EAGT,IAAIC,EAEJ,MAAMC,EAAS,IAAoC,CACjD,GAAID,IAAuB,OACzB,OAAOA,EAGT,MAAME,EAAW,IAAIJ,EACfK,EAAWC,EAAAA,kBAAkBF,CAAQ,EACrC,CAAE,OAAAG,GAAWF,EAEbG,EAAK,YAAY,OAAOH,EAAS,QAAQ,cAAc,KAAKE,CAAM,CAAC,CAAC,GAEpEE,EAAaF,EAAO,QAAU,CAAA,EAC9BG,EAAgBD,aAAsBE,EAAAA,aACxCF,EACAG,EAAAA,EAAE,OAAOH,CAAU,EACjBI,EAAcN,EAAO,OACrBO,EACJD,IAAgB,OACVA,aAAuBF,EAAAA,aAAeE,EAAcD,IAAE,OAAOC,CAAW,EAC1E,OAEN,OAAAX,EAAqB,CACnB,GAAAM,EACA,aAAAE,EACA,cAAAI,EACA,SAAAT,EACA,kBAAmBE,EAAO,mBAAqB,GAC/C,OAAQA,EAAO,OACf,QAASA,EAAO,QAChB,cAAe,OAAOF,EAAS,QAAQ,YAAe,UAAA,EAGjDH,CACT,EAEA,OAAAP,EAAiB,IAAIK,EAAeG,CAAM,EACnCA,CACT,CAMO,SAASY,EACdf,EAC8E,CAC9E,MAAMF,EAAiBC,EAAwBC,CAAa,EAEtDgB,EAAcC,EAAAA,WAAWC,oBAAkB,EAEjD,GAAIF,IAAgB,OAClB,MAAM,IAAI,MAAM,uBAAuB,EAGzC,OAAOA,EAAY,YAAsBlB,GAAgB,CAC3D"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+ "use strict";const g=require("signalium"),o=require("./QueryClient-m7BzCIe9.js");class y{static adapter;params;result;optimisticUpdates;config;effects;constructor(){return o.createDefinitionProxy(this)}}const c=new WeakMap,h=t=>{const e=c.get(t);if(e===void 0)throw new Error("Mutation definition not found");return e().id};function D(t){let e=c.get(t);if(e!==void 0)return e;let n;const f=()=>{if(n!==void 0)return n;const d=new t,r=o.extractDefinition(d),{fields:i}=r,p=`mutation:${String(r.methods.getIdentityKey.call(i))}`,a=i.params??{},l=a instanceof o.ValidatorDef?a:o.t.object(a),s=i.result,m=s!==void 0?s instanceof o.ValidatorDef?s:o.t.object(s):void 0,u=t.adapter;if(!u)throw new Error(`Mutation class "${t.name}" must define a static \`adapter\` property. Extend RESTMutation (from fetchium/rest) or set \`static adapter = MyAdapter\` on your mutation class.`);return n={id:p,requestShape:l,responseShape:m,captured:r,optimisticUpdates:i.optimisticUpdates??!1,config:i.config,effects:i.effects,hasGetEffects:typeof r.methods.getEffects=="function",adapterClass:u},n};return c.set(t,f),f}function M(t){const e=D(t),n=g.getContext(o.QueryClientContext);if(n===void 0)throw new Error("QueryClient not found");return n.getMutation(e())}exports.Mutation=y;exports.getMutation=M;exports.mutationKeyForClass=h;
2
+ //# sourceMappingURL=mutation-wUhcGxKl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mutation-wUhcGxKl.js","sources":["../../../src/mutation.ts"],"sourcesContent":["import { getContext, ReactiveTask } from 'signalium';\nimport { ExtractType, InternalTypeDef, MutationEffects, TypeDef, RetryConfig, TypeDefShape } from './types.js';\nimport { QueryClientContext, type QueryContext } from './QueryClient.js';\nimport { ValidatorDef, t } from './typeDefs.js';\nimport { createDefinitionProxy, extractDefinition, type CapturedDefinition } from './fieldRef.js';\nimport type { QueryAdapter } from './QueryAdapter.js';\n\n// ================================\n// Mutation Definition Types\n// ================================\n\nexport interface MutationConfigOptions {\n retry?: RetryConfig | number | false;\n}\n\nexport interface MutationDefinition<Request, Response> {\n id: string;\n requestShape: InternalTypeDef;\n responseShape: InternalTypeDef | undefined;\n captured: CapturedDefinition<Mutation>;\n optimisticUpdates: boolean;\n config?: MutationConfigOptions;\n effects?: MutationEffects;\n hasGetEffects: boolean;\n adapterClass: typeof QueryAdapter;\n}\n\n// ================================\n// Mutation base class\n// ================================\n\nexport abstract class Mutation {\n static adapter?: typeof QueryAdapter;\n\n readonly params?: TypeDefShape;\n readonly result?: TypeDefShape;\n readonly optimisticUpdates?: boolean;\n readonly config?: MutationConfigOptions;\n readonly effects?: Readonly<MutationEffects>;\n\n declare context: QueryContext;\n\n abstract getIdentityKey(): unknown;\n\n getEffects?(): MutationEffects;\n\n constructor() {\n return createDefinitionProxy(this);\n }\n}\n\n// ================================\n// Mutation definition cache and lookup\n// ================================\n\nconst mutationDefCache = new WeakMap<new () => Mutation, () => MutationDefinition<any, any>>();\n\nexport const mutationKeyForClass = (cls: new () => Mutation): string => {\n const getMutationDef = mutationDefCache.get(cls);\n\n if (getMutationDef === undefined) {\n throw new Error('Mutation definition not found');\n }\n\n return getMutationDef().id;\n};\n\n// ================================\n// Internal: build mutation definition from class\n// ================================\n\nfunction buildMutationDefinition(MutationClass: new () => Mutation): () => MutationDefinition<any, any> {\n let cached = mutationDefCache.get(MutationClass);\n\n if (cached !== undefined) {\n return cached;\n }\n\n let mutationDefinition: MutationDefinition<any, any> | undefined;\n\n const getter = (): MutationDefinition<any, any> => {\n if (mutationDefinition !== undefined) {\n return mutationDefinition;\n }\n\n const instance = new MutationClass();\n const captured = extractDefinition(instance);\n const { fields } = captured;\n\n const id = `mutation:${String(captured.methods.getIdentityKey.call(fields))}`;\n\n const requestDef = fields.params ?? {};\n const requestShape = (requestDef instanceof ValidatorDef\n ? requestDef\n : t.object(requestDef)) as unknown as InternalTypeDef;\n const responseDef = fields.result;\n const responseShape =\n responseDef !== undefined\n ? ((responseDef instanceof ValidatorDef ? responseDef : t.object(responseDef)) as unknown as InternalTypeDef)\n : undefined;\n\n const adapterClass = (MutationClass as typeof Mutation).adapter;\n if (!adapterClass) {\n throw new Error(\n `Mutation class \"${MutationClass.name}\" must define a static \\`adapter\\` property. ` +\n `Extend RESTMutation (from fetchium/rest) or set \\`static adapter = MyAdapter\\` on your mutation class.`,\n );\n }\n\n mutationDefinition = {\n id,\n requestShape,\n responseShape,\n captured,\n optimisticUpdates: fields.optimisticUpdates ?? false,\n config: fields.config,\n effects: fields.effects,\n hasGetEffects: typeof captured.methods.getEffects === 'function',\n adapterClass,\n };\n\n return mutationDefinition;\n };\n\n mutationDefCache.set(MutationClass, getter);\n return getter;\n}\n\n// ================================\n// Public API\n// ================================\n\nexport function getMutation<T extends Mutation>(\n MutationClass: new () => T,\n): ReactiveTask<Readonly<ExtractType<T['result']>>, [ExtractType<T['params']>]> {\n const getMutationDef = buildMutationDefinition(MutationClass);\n\n const queryClient = getContext(QueryClientContext);\n\n if (queryClient === undefined) {\n throw new Error('QueryClient not found');\n }\n\n return queryClient.getMutation<any, any>(getMutationDef());\n}\n"],"names":["Mutation","createDefinitionProxy","mutationDefCache","mutationKeyForClass","cls","getMutationDef","buildMutationDefinition","MutationClass","cached","mutationDefinition","getter","instance","captured","extractDefinition","fields","id","requestDef","requestShape","ValidatorDef","t","responseDef","responseShape","adapterClass","getMutation","queryClient","getContext","QueryClientContext"],"mappings":"iFA+BO,MAAeA,CAAS,CAC7B,OAAO,QAEE,OACA,OACA,kBACA,OACA,QAQT,aAAc,CACZ,OAAOC,EAAAA,sBAAsB,IAAI,CACnC,CACF,CAMA,MAAMC,MAAuB,QAEhBC,EAAuBC,GAAoC,CACtE,MAAMC,EAAiBH,EAAiB,IAAIE,CAAG,EAE/C,GAAIC,IAAmB,OACrB,MAAM,IAAI,MAAM,+BAA+B,EAGjD,OAAOA,IAAiB,EAC1B,EAMA,SAASC,EAAwBC,EAAuE,CACtG,IAAIC,EAASN,EAAiB,IAAIK,CAAa,EAE/C,GAAIC,IAAW,OACb,OAAOA,EAGT,IAAIC,EAEJ,MAAMC,EAAS,IAAoC,CACjD,GAAID,IAAuB,OACzB,OAAOA,EAGT,MAAME,EAAW,IAAIJ,EACfK,EAAWC,EAAAA,kBAAkBF,CAAQ,EACrC,CAAE,OAAAG,GAAWF,EAEbG,EAAK,YAAY,OAAOH,EAAS,QAAQ,eAAe,KAAKE,CAAM,CAAC,CAAC,GAErEE,EAAaF,EAAO,QAAU,CAAA,EAC9BG,EAAgBD,aAAsBE,EAAAA,aACxCF,EACAG,EAAAA,EAAE,OAAOH,CAAU,EACjBI,EAAcN,EAAO,OACrBO,EACJD,IAAgB,OACVA,aAAuBF,EAAAA,aAAeE,EAAcD,IAAE,OAAOC,CAAW,EAC1E,OAEAE,EAAgBf,EAAkC,QACxD,GAAI,CAACe,EACH,MAAM,IAAI,MACR,mBAAmBf,EAAc,IAAI,qJAAA,EAKzC,OAAAE,EAAqB,CACnB,GAAAM,EACA,aAAAE,EACA,cAAAI,EACA,SAAAT,EACA,kBAAmBE,EAAO,mBAAqB,GAC/C,OAAQA,EAAO,OACf,QAASA,EAAO,QAChB,cAAe,OAAOF,EAAS,QAAQ,YAAe,WACtD,aAAAU,CAAA,EAGKb,CACT,EAEA,OAAAP,EAAiB,IAAIK,EAAeG,CAAM,EACnCA,CACT,CAMO,SAASa,EACdhB,EAC8E,CAC9E,MAAMF,EAAiBC,EAAwBC,CAAa,EAEtDiB,EAAcC,EAAAA,WAAWC,oBAAkB,EAEjD,GAAIF,IAAgB,OAClB,MAAM,IAAI,MAAM,uBAAuB,EAGzC,OAAOA,EAAY,YAAsBnB,GAAgB,CAC3D"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("signalium/react"),i=require("signalium"),f=require("../QueryClient-CpmwggOn.js");function n(e){if(Array.isArray(e))return e.map(n);if(e&&typeof e=="object"){if(e instanceof Date)return new Date(e);if(e instanceof RegExp)return new RegExp(e);if(e instanceof Map)return new Map(Array.from(e.entries()).map(([t,c])=>[n(t),n(c)]));if(e instanceof Set)return new Set(Array.from(e).map(n));const r=Object.create(Object.getPrototypeOf(e));for(const t of Object.keys(e))r[t]=n(e[t]);return r}return e}const y=i.reactive(e=>n(e.value)),a=i.reactive((e,...r)=>{const t=f.fetchQuery(e,...r);return new Proxy(t,{get(c,o,u){return o==="value"?y(c):Reflect.get(c,o,u)}})}),p=i.reactive(e=>e.value);function g(e,...r){const t=s.useReactive(a,e,...r);return s.useReactive(p,t),t}exports.useQuery=g;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("signalium/react"),i=require("signalium"),f=require("../QueryClient-m7BzCIe9.js");function n(e){if(Array.isArray(e))return e.map(n);if(e&&typeof e=="object"){if(e instanceof Date)return new Date(e);if(e instanceof RegExp)return new RegExp(e);if(e instanceof Map)return new Map(Array.from(e.entries()).map(([t,c])=>[n(t),n(c)]));if(e instanceof Set)return new Set(Array.from(e).map(n));const r=Object.create(Object.getPrototypeOf(e));for(const t of Object.keys(e))r[t]=n(e[t]);return r}return e}const y=i.reactive(e=>n(e.value)),a=i.reactive((e,...r)=>{const t=f.fetchQuery(e,...r);return new Proxy(t,{get(c,o,u){return o==="value"?y(c):Reflect.get(c,o,u)}})}),p=i.reactive(e=>e.value);function g(e,...r){const t=s.useReactive(a,e,...r);return s.useReactive(p,t),t}exports.useQuery=g;
2
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("../QueryClient-m7BzCIe9.js"),q=require("../QueryAdapter-DUo338ga.js"),T=require("../mutation-wUhcGxKl.js");class f extends q.QueryAdapter{_fetch;_baseUrl;constructor(e){super(),this._fetch=e?.fetch??globalThis.fetch,this._baseUrl=e?.baseUrl}async send(e,s){return this.executeRequest(e,s)}async sendNext(e,s){const t=this.resolveFetchNext(e);if(t===void 0)throw new Error("fetchNext is not configured for this query");return this.executeRequest(e,s,t)}hasNext(e){const s=this.resolveFetchNext(e);if(s===void 0)return!1;if(s.url!==void 0&&s.url!==null)return!0;if(s.searchParams!==void 0){const t=Object.keys(s.searchParams);if(t.length===0)return!1;for(const r of t)if(s.searchParams[r]===void 0||s.searchParams[r]===null)return!1;return!0}return!1}resolveFetchNext(e){const t=(e.getFetchNext?e.getFetchNext():void 0)??e.rawFetchNext;if(t===void 0)return;const r={params:e.params??{},result:e.resultData};return{url:t.url!==void 0?i.reifyValue(t.url,r):void 0,searchParams:t.searchParams!==void 0?i.reifyValue(t.searchParams,r):void 0}}buildUrl(e,s){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//"))return e;if(e.startsWith("/")){const t=i.resolveBaseUrl(s)??i.resolveBaseUrl(this._baseUrl)??globalThis.location?.origin;if(!t)throw new Error(`RESTQueryAdapter: cannot resolve URL for path "${e}". Set \`baseUrl\` on the query/mutation, pass it to \`new RESTQueryAdapter({ baseUrl })\`, or use an absolute URL.`);return`${t}${e}`}return e}async executeRequest(e,s,t){const r=t?.url??(e.getPath?e.getPath():e.path),u=e.getMethod?e.getMethod():e.method,a=e.getSearchParams?e.getSearchParams():e.searchParams,o=t?.searchParams?{...a,...t.searchParams}:a,n=e.getBody?e.getBody():e.body,h=e.getRequestOptions?e.getRequestOptions():e.requestOptions;if(!r)throw new Error("RESTQuery requires a path. Define `path` as a field or override `getPath()`.");let l=r;if(o){const m=new URLSearchParams;for(const U in o){const c=o[U];c!=null&&m.append(U,String(c))}const v=m.toString();v&&(l+="?"+v)}const p=h?.baseUrl??e.baseUrl,d=this.buildUrl(l,p),{baseUrl:g,signal:P,...R}=h??{},S=n||e.headers?{...n?{"Content-Type":"application/json"}:void 0,...e.headers}:void 0,b=await this._fetch(d,{method:u,headers:S,body:n?JSON.stringify(n):void 0,signal:s,...R});return e.response=b,b.json()}async sendMutation(e,s){const t=e,r=t.getPath?t.getPath():t.path,u=t.getMethod?t.getMethod():t.method,a=t.getBody?t.getBody():t.body,o=t.getRequestOptions?t.getRequestOptions():t.requestOptions;if(!r)throw new Error("RESTMutation requires a path. Define `path` as a field or override `getPath()`.");const n=o?.baseUrl??t.baseUrl,h=this.buildUrl(r,n),{baseUrl:l,signal:p,...d}=o??{},g={...a!==void 0?{"Content-Type":"application/json"}:{},...t.headers};return(await this._fetch(h,{method:u,headers:g,...a!==void 0?{body:JSON.stringify(a)}:{},signal:s,...d})).json()}}class O extends i.Query{static adapter=f;method="GET";path;baseUrl;searchParams;body;headers;requestOptions;fetchNext;getIdentityKey(){return`${this.method??"GET"}:${this.path??""}`}}class E extends T.Mutation{static adapter=f;path;baseUrl;method="POST";body;headers;requestOptions;getIdentityKey(){return`${this.method??"POST"}:${this.path??""}`}}exports.RESTMutation=E;exports.RESTQuery=O;exports.RESTQueryAdapter=f;
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../src/rest/RESTQueryAdapter.ts","../../../../src/rest/RESTQuery.ts","../../../../src/rest/RESTMutation.ts"],"sourcesContent":["import { QueryAdapter } from '../QueryAdapter.js';\nimport { resolveBaseUrl } from '../query-types.js';\nimport { reifyValue } from '../fieldRef.js';\nimport type { Query } from '../query.js';\nimport type { Mutation } from '../mutation.js';\nimport type { FetchNextConfig } from '../query-types.js';\nimport type { RESTQuery } from './RESTQuery.js';\nimport type { RESTMutation } from './RESTMutation.js';\nimport type { QueryRequestInit, BaseUrlValue, QueryRequestOptions } from '../types.js';\n\n// ================================\n// ResolvedFetchNext\n// ================================\n\nexport interface ResolvedFetchNext {\n url?: string;\n searchParams?: Record<string, unknown>;\n}\n\n// ================================\n// RESTQueryAdapter options\n// ================================\n\nexport interface RESTQueryAdapterOptions {\n fetch?: (url: string, init?: QueryRequestInit) => Promise<Response>;\n baseUrl?: BaseUrlValue;\n}\n\n// ================================\n// RESTQueryAdapter\n// ================================\n\nexport class RESTQueryAdapter extends QueryAdapter {\n private readonly _fetch: (url: string, init?: QueryRequestInit) => Promise<Response>;\n private readonly _baseUrl: BaseUrlValue | undefined;\n\n constructor(options?: RESTQueryAdapterOptions) {\n super();\n this._fetch =\n options?.fetch ?? (globalThis.fetch as unknown as (url: string, init?: QueryRequestInit) => Promise<Response>);\n this._baseUrl = options?.baseUrl;\n }\n\n override async send(ctx: Query, signal: AbortSignal): Promise<unknown> {\n return this.executeRequest(ctx as RESTQuery, signal);\n }\n\n override async sendNext(ctx: Query, signal: AbortSignal): Promise<unknown> {\n const resolved = this.resolveFetchNext(ctx as RESTQuery);\n if (resolved === undefined) {\n throw new Error('fetchNext is not configured for this query');\n }\n return this.executeRequest(ctx as RESTQuery, signal, resolved);\n }\n\n override hasNext(ctx: Query): boolean {\n const resolved = this.resolveFetchNext(ctx as RESTQuery);\n if (resolved === undefined) return false;\n\n if (resolved.url !== undefined && resolved.url !== null) {\n return true;\n }\n\n if (resolved.searchParams !== undefined) {\n const keys = Object.keys(resolved.searchParams);\n if (keys.length === 0) return false;\n for (const key of keys) {\n if (resolved.searchParams[key] === undefined || resolved.searchParams[key] === null) {\n return false;\n }\n }\n return true;\n }\n\n return false;\n }\n\n private resolveFetchNext(ctx: RESTQuery): ResolvedFetchNext | undefined {\n const dynamicConfig = ctx.getFetchNext ? ctx.getFetchNext() : undefined;\n const fetchNextConfig: FetchNextConfig | undefined = dynamicConfig ?? ctx.rawFetchNext;\n if (fetchNextConfig === undefined) return undefined;\n\n const resolveRoot: Record<string, unknown> = {\n params: ctx.params ?? {},\n result: ctx.resultData,\n };\n\n return {\n url: fetchNextConfig.url !== undefined ? (reifyValue(fetchNextConfig.url, resolveRoot) as string) : undefined,\n searchParams:\n fetchNextConfig.searchParams !== undefined\n ? (reifyValue(fetchNextConfig.searchParams, resolveRoot) as Record<string, unknown>)\n : undefined,\n };\n }\n\n /**\n * Resolves a path to a full URL.\n *\n * - Absolute URLs (`https://...`, `//...`) are returned as-is.\n * - Root-relative paths (`/foo`) are prepended with the resolved baseUrl.\n * The baseUrl priority is: per-query/mutation > adapter-level > `location.origin`.\n * If none is available and the path is root-relative, an error is thrown.\n * - Other paths (e.g. `example.com/foo`) are returned as-is.\n */\n private buildUrl(path: string, ctxBaseUrl: BaseUrlValue | undefined): string {\n // Absolute URL — use as-is regardless of any configured baseUrl\n if (path.startsWith('http://') || path.startsWith('https://') || path.startsWith('//')) {\n return path;\n }\n\n // Root-relative path — needs a base\n if (path.startsWith('/')) {\n const base = resolveBaseUrl(ctxBaseUrl) ?? resolveBaseUrl(this._baseUrl) ?? globalThis.location?.origin;\n\n if (!base) {\n throw new Error(\n `RESTQueryAdapter: cannot resolve URL for path \"${path}\". ` +\n `Set \\`baseUrl\\` on the query/mutation, pass it to \\`new RESTQueryAdapter({ baseUrl })\\`, ` +\n `or use an absolute URL.`,\n );\n }\n\n return `${base}${path}`;\n }\n\n // Relative path — use as-is\n return path;\n }\n\n private async executeRequest(\n ctx: RESTQuery,\n signal: AbortSignal,\n next?: { url?: string; searchParams?: Record<string, unknown> },\n ): Promise<unknown> {\n const path = next?.url ?? (ctx.getPath ? ctx.getPath() : ctx.path);\n const method = ctx.getMethod ? ctx.getMethod() : ctx.method;\n const baseSearchParams = ctx.getSearchParams ? ctx.getSearchParams() : ctx.searchParams;\n const searchParams = next?.searchParams ? { ...baseSearchParams, ...next.searchParams } : baseSearchParams;\n const body = ctx.getBody ? ctx.getBody() : ctx.body;\n const requestOptions = ctx.getRequestOptions ? ctx.getRequestOptions() : ctx.requestOptions;\n\n if (!path) {\n throw new Error('RESTQuery requires a path. Define `path` as a field or override `getPath()`.');\n }\n\n let url = path;\n\n if (searchParams) {\n const sp = new URLSearchParams();\n for (const key in searchParams) {\n const val = searchParams[key];\n if (val !== undefined && val !== null) {\n sp.append(key, String(val));\n }\n }\n const qs = sp.toString();\n if (qs) {\n url += '?' + qs;\n }\n }\n\n const ctxBaseUrl = requestOptions?.baseUrl ?? ctx.baseUrl;\n const fullUrl = this.buildUrl(url, ctxBaseUrl);\n\n const { baseUrl: _baseUrl, signal: _signal, ...fetchOptions } = requestOptions ?? ({} as Record<string, unknown>);\n\n const hasHeaders = body || ctx.headers;\n const headers: HeadersInit | undefined = hasHeaders\n ? {\n ...(body ? { 'Content-Type': 'application/json' } : undefined),\n ...(ctx.headers as Record<string, string>),\n }\n : undefined;\n\n const fetchResponse = await this._fetch(fullUrl, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal,\n ...fetchOptions,\n });\n\n ctx.response = fetchResponse as unknown as Response;\n\n return fetchResponse.json();\n }\n\n override async sendMutation(ctx: Mutation, signal: AbortSignal): Promise<unknown> {\n const restCtx = ctx as RESTMutation;\n const path = restCtx.getPath ? restCtx.getPath() : restCtx.path;\n const method = restCtx.getMethod ? restCtx.getMethod() : restCtx.method;\n const body = restCtx.getBody ? restCtx.getBody() : restCtx.body;\n const requestOptions = restCtx.getRequestOptions ? restCtx.getRequestOptions() : restCtx.requestOptions;\n\n if (!path) {\n throw new Error('RESTMutation requires a path. Define `path` as a field or override `getPath()`.');\n }\n\n const ctxBaseUrl = (requestOptions as QueryRequestOptions | undefined)?.baseUrl ?? restCtx.baseUrl;\n const fullUrl = this.buildUrl(path, ctxBaseUrl);\n\n const { baseUrl: _baseUrl, signal: _signal, ...fetchOptions } = (requestOptions ?? {}) as Record<string, unknown>;\n\n const headers: HeadersInit = {\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...(restCtx.headers as Record<string, string>),\n };\n\n const fetchResponse = await this._fetch(fullUrl, {\n method,\n headers,\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n signal,\n ...fetchOptions,\n });\n\n return fetchResponse.json();\n }\n}\n","import { Query } from '../query.js';\nimport { RESTQueryAdapter } from './RESTQueryAdapter.js';\nimport type { FetchNextConfig } from '../query-types.js';\nimport type { BaseUrlValue, QueryRequestOptions } from '../types.js';\n\n// ================================\n// RESTQuery — declarative HTTP query definition\n// ================================\n\nexport abstract class RESTQuery extends Query {\n static override adapter = RESTQueryAdapter;\n\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' = 'GET';\n path?: string;\n baseUrl?: BaseUrlValue;\n searchParams?: Record<string, unknown>;\n body?: Record<string, unknown>;\n headers?: HeadersInit;\n requestOptions?: QueryRequestOptions;\n fetchNext?: FetchNextConfig;\n\n declare response: Response | undefined;\n\n getIdentityKey(): string {\n return `${this.method ?? 'GET'}:${this.path ?? ''}`;\n }\n\n // User-overridable getters — the adapter reads these from the execution context\n getPath?(): string | undefined;\n getMethod?(): string;\n getSearchParams?(): Record<string, unknown> | undefined;\n getBody?(): Record<string, unknown> | undefined;\n getRequestOptions?(): QueryRequestOptions | undefined;\n getFetchNext?(): FetchNextConfig | undefined;\n}\n","import { Mutation } from '../mutation.js';\nimport type { BaseUrlValue, QueryRequestOptions } from '../types.js';\nimport { RESTQueryAdapter } from './RESTQueryAdapter.js';\n\nexport abstract class RESTMutation extends Mutation {\n static override adapter = RESTQueryAdapter;\n\n path?: string;\n baseUrl?: BaseUrlValue;\n method: 'POST' | 'PUT' | 'DELETE' | 'PATCH' = 'POST';\n body?: Record<string, unknown>;\n headers?: HeadersInit;\n requestOptions?: QueryRequestOptions;\n\n getIdentityKey(): string {\n return `${this.method ?? 'POST'}:${this.path ?? ''}`;\n }\n\n getPath?(): string | undefined;\n getMethod?(): string;\n getBody?(): Record<string, unknown> | undefined;\n getRequestOptions?(): QueryRequestOptions | undefined;\n}\n"],"names":["RESTQueryAdapter","QueryAdapter","options","ctx","signal","resolved","keys","key","fetchNextConfig","resolveRoot","reifyValue","path","ctxBaseUrl","base","resolveBaseUrl","next","method","baseSearchParams","searchParams","body","requestOptions","url","sp","val","qs","fullUrl","_baseUrl","_signal","fetchOptions","headers","fetchResponse","restCtx","RESTQuery","Query","RESTMutation","Mutation"],"mappings":"4MAgCO,MAAMA,UAAyBC,EAAAA,YAAa,CAChC,OACA,SAEjB,YAAYC,EAAmC,CAC7C,MAAA,EACA,KAAK,OACHA,GAAS,OAAU,WAAW,MAChC,KAAK,SAAWA,GAAS,OAC3B,CAEA,MAAe,KAAKC,EAAYC,EAAuC,CACrE,OAAO,KAAK,eAAeD,EAAkBC,CAAM,CACrD,CAEA,MAAe,SAASD,EAAYC,EAAuC,CACzE,MAAMC,EAAW,KAAK,iBAAiBF,CAAgB,EACvD,GAAIE,IAAa,OACf,MAAM,IAAI,MAAM,4CAA4C,EAE9D,OAAO,KAAK,eAAeF,EAAkBC,EAAQC,CAAQ,CAC/D,CAES,QAAQF,EAAqB,CACpC,MAAME,EAAW,KAAK,iBAAiBF,CAAgB,EACvD,GAAIE,IAAa,OAAW,MAAO,GAEnC,GAAIA,EAAS,MAAQ,QAAaA,EAAS,MAAQ,KACjD,MAAO,GAGT,GAAIA,EAAS,eAAiB,OAAW,CACvC,MAAMC,EAAO,OAAO,KAAKD,EAAS,YAAY,EAC9C,GAAIC,EAAK,SAAW,EAAG,MAAO,GAC9B,UAAWC,KAAOD,EAChB,GAAID,EAAS,aAAaE,CAAG,IAAM,QAAaF,EAAS,aAAaE,CAAG,IAAM,KAC7E,MAAO,GAGX,MAAO,EACT,CAEA,MAAO,EACT,CAEQ,iBAAiBJ,EAA+C,CAEtE,MAAMK,GADgBL,EAAI,aAAeA,EAAI,eAAiB,SACQA,EAAI,aAC1E,GAAIK,IAAoB,OAAW,OAEnC,MAAMC,EAAuC,CAC3C,OAAQN,EAAI,QAAU,CAAA,EACtB,OAAQA,EAAI,UAAA,EAGd,MAAO,CACL,IAAKK,EAAgB,MAAQ,OAAaE,EAAAA,WAAWF,EAAgB,IAAKC,CAAW,EAAe,OACpG,aACED,EAAgB,eAAiB,OAC5BE,EAAAA,WAAWF,EAAgB,aAAcC,CAAW,EACrD,MAAA,CAEV,CAWQ,SAASE,EAAcC,EAA8C,CAE3E,GAAID,EAAK,WAAW,SAAS,GAAKA,EAAK,WAAW,UAAU,GAAKA,EAAK,WAAW,IAAI,EACnF,OAAOA,EAIT,GAAIA,EAAK,WAAW,GAAG,EAAG,CACxB,MAAME,EAAOC,iBAAeF,CAAU,GAAKE,EAAAA,eAAe,KAAK,QAAQ,GAAK,WAAW,UAAU,OAEjG,GAAI,CAACD,EACH,MAAM,IAAI,MACR,kDAAkDF,CAAI,qHAAA,EAM1D,MAAO,GAAGE,CAAI,GAAGF,CAAI,EACvB,CAGA,OAAOA,CACT,CAEA,MAAc,eACZR,EACAC,EACAW,EACkB,CAClB,MAAMJ,EAAOI,GAAM,MAAQZ,EAAI,QAAUA,EAAI,QAAA,EAAYA,EAAI,MACvDa,EAASb,EAAI,UAAYA,EAAI,UAAA,EAAcA,EAAI,OAC/Cc,EAAmBd,EAAI,gBAAkBA,EAAI,gBAAA,EAAoBA,EAAI,aACrEe,EAAeH,GAAM,aAAe,CAAE,GAAGE,EAAkB,GAAGF,EAAK,YAAA,EAAiBE,EACpFE,EAAOhB,EAAI,QAAUA,EAAI,QAAA,EAAYA,EAAI,KACzCiB,EAAiBjB,EAAI,kBAAoBA,EAAI,kBAAA,EAAsBA,EAAI,eAE7E,GAAI,CAACQ,EACH,MAAM,IAAI,MAAM,8EAA8E,EAGhG,IAAIU,EAAMV,EAEV,GAAIO,EAAc,CAChB,MAAMI,EAAK,IAAI,gBACf,UAAWf,KAAOW,EAAc,CAC9B,MAAMK,EAAML,EAAaX,CAAG,EACHgB,GAAQ,MAC/BD,EAAG,OAAOf,EAAK,OAAOgB,CAAG,CAAC,CAE9B,CACA,MAAMC,EAAKF,EAAG,SAAA,EACVE,IACFH,GAAO,IAAMG,EAEjB,CAEA,MAAMZ,EAAaQ,GAAgB,SAAWjB,EAAI,QAC5CsB,EAAU,KAAK,SAASJ,EAAKT,CAAU,EAEvC,CAAE,QAASc,EAAU,OAAQC,EAAS,GAAGC,CAAA,EAAiBR,GAAmB,CAAA,EAG7ES,EADaV,GAAQhB,EAAI,QAE3B,CACE,GAAIgB,EAAO,CAAE,eAAgB,oBAAuB,OACpD,GAAIhB,EAAI,OAAA,EAEV,OAEE2B,EAAgB,MAAM,KAAK,OAAOL,EAAS,CAC/C,OAAAT,EACA,QAAAa,EACA,KAAMV,EAAO,KAAK,UAAUA,CAAI,EAAI,OACpC,OAAAf,EACA,GAAGwB,CAAA,CACJ,EAED,OAAAzB,EAAI,SAAW2B,EAERA,EAAc,KAAA,CACvB,CAEA,MAAe,aAAa3B,EAAeC,EAAuC,CAChF,MAAM2B,EAAU5B,EACVQ,EAAOoB,EAAQ,QAAUA,EAAQ,QAAA,EAAYA,EAAQ,KACrDf,EAASe,EAAQ,UAAYA,EAAQ,UAAA,EAAcA,EAAQ,OAC3DZ,EAAOY,EAAQ,QAAUA,EAAQ,QAAA,EAAYA,EAAQ,KACrDX,EAAiBW,EAAQ,kBAAoBA,EAAQ,kBAAA,EAAsBA,EAAQ,eAEzF,GAAI,CAACpB,EACH,MAAM,IAAI,MAAM,iFAAiF,EAGnG,MAAMC,EAAcQ,GAAoD,SAAWW,EAAQ,QACrFN,EAAU,KAAK,SAASd,EAAMC,CAAU,EAExC,CAAE,QAASc,EAAU,OAAQC,EAAS,GAAGC,CAAA,EAAkBR,GAAkB,CAAA,EAE7ES,EAAuB,CAC3B,GAAIV,IAAS,OAAY,CAAE,eAAgB,kBAAA,EAAuB,CAAA,EAClE,GAAIY,EAAQ,OAAA,EAWd,OARsB,MAAM,KAAK,OAAON,EAAS,CAC/C,OAAAT,EACA,QAAAa,EACA,GAAIV,IAAS,OAAY,CAAE,KAAM,KAAK,UAAUA,CAAI,CAAA,EAAM,CAAA,EAC1D,OAAAf,EACA,GAAGwB,CAAA,CACJ,GAEoB,KAAA,CACvB,CACF,CClNO,MAAeI,UAAkBC,EAAAA,KAAM,CAC5C,OAAgB,QAAUjC,EAE1B,OAAsD,MACtD,KACA,QACA,aACA,KACA,QACA,eACA,UAIA,gBAAyB,CACvB,MAAO,GAAG,KAAK,QAAU,KAAK,IAAI,KAAK,MAAQ,EAAE,EACnD,CASF,CC9BO,MAAekC,UAAqBC,EAAAA,QAAS,CAClD,OAAgB,QAAUnC,EAE1B,KACA,QACA,OAA8C,OAC9C,KACA,QACA,eAEA,gBAAyB,CACvB,MAAO,GAAG,KAAK,QAAU,MAAM,IAAI,KAAK,MAAQ,EAAE,EACpD,CAMF"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("../QueryClient-m7BzCIe9.js"),d=require("../QueryAdapter-DUo338ga.js");class h extends l.Query{static adapter;getIdentityKey(){return`topic:${this.topic}`}getConfig(){return{staleTime:0,subscribe:()=>()=>{this._topicAdapter?.unsubscribe(this.topic)}}}}class f extends d.QueryAdapter{_topics=new Map;fulfillTopic(e,s){const t=this._topics.get(e);if(t===void 0){this._topics.set(e,{status:"fulfilled",data:s});return}t.status==="pending"&&(t.status="fulfilled",t.data=s,t.resolve(s))}rejectTopic(e,s){const t=this._topics.get(e);if(t===void 0){this._topics.set(e,{status:"rejected",error:s});return}t.status==="pending"&&(t.status="rejected",t.error=s,t.reject(s))}clearTopic(e){this._topics.delete(e)}clearAll(){this._topics.clear()}async send(e,s){const t=e;t._topicAdapter=this;const r=t.topic,i=this._topics.get(r);if(i)switch(i.status){case"fulfilled":return i.data;case"rejected":throw i.error;case"pending":return i.promise}let c,o;const n=new Promise((a,u)=>{c=a,o=u});return this._topics.set(r,{status:"pending",promise:n,resolve:c,reject:o}),this.subscribe(r),n}sendMutationEvent(e){this.queryClient.applyMutationEvent(e)}}exports.TopicQuery=h;exports.TopicQueryAdapter=f;
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../../../src/topic/TopicQuery.ts","../../../../src/topic/TopicQueryAdapter.ts"],"sourcesContent":["import { Query } from '../query.js';\nimport type { TopicQueryAdapter } from './TopicQueryAdapter.js';\nimport type { QueryConfigOptions } from '../query-types.js';\n\n// ================================\n// TopicQuery — declarative topic-based query definition\n// ================================\n\nexport abstract class TopicQuery extends Query {\n static override adapter: typeof TopicQueryAdapter;\n\n abstract topic: string;\n\n getIdentityKey(): string {\n return `topic:${this.topic}`;\n }\n\n getConfig(): QueryConfigOptions {\n return {\n staleTime: 0,\n subscribe: () => {\n return () => {\n const adapter = (this as Record<string, any>)._topicAdapter as TopicQueryAdapter | undefined;\n adapter?.unsubscribe(this.topic);\n };\n },\n };\n }\n}\n","import { QueryAdapter } from '../QueryAdapter.js';\nimport type { Query } from '../query.js';\nimport type { MutationEvent } from '../types.js';\n\n// ================================\n// TopicQueryAdapter — abstract adapter for topic-based subscriptions\n// ================================\n\ninterface TopicCtx extends Query {\n topic: string;\n _topicAdapter?: TopicQueryAdapter;\n}\n\ninterface TopicState {\n status: 'pending' | 'fulfilled' | 'rejected';\n promise?: Promise<unknown>;\n resolve?: (data: unknown) => void;\n reject?: (error: unknown) => void;\n data?: unknown;\n error?: unknown;\n}\n\nexport abstract class TopicQueryAdapter extends QueryAdapter {\n private _topics = new Map<string, TopicState>();\n\n /**\n * Called when a query activates for a given topic.\n * Implementations should start delivering data for this topic,\n * calling `fulfillTopic()` when initial data is available and\n * `sendMutationEvent()` for ongoing updates.\n */\n abstract subscribe(topic: string): void;\n\n /**\n * Called when the query deactivates. Implementations should\n * tear down any resources for this topic.\n */\n abstract unsubscribe(topic: string): void;\n\n /**\n * Resolve the pending promise for a topic with initial data.\n * Can be called before `send()` — the data will be picked up\n * when the query activates.\n */\n protected fulfillTopic(topic: string, data: unknown): void {\n const state = this._topics.get(topic);\n\n if (state === undefined) {\n this._topics.set(topic, { status: 'fulfilled', data });\n return;\n }\n\n if (state.status === 'pending') {\n state.status = 'fulfilled';\n state.data = data;\n state.resolve!(data);\n }\n }\n\n /**\n * Reject the pending promise for a topic.\n * Can be called before `send()` — the error will be propagated\n * when the query activates.\n */\n protected rejectTopic(topic: string, error: unknown): void {\n const state = this._topics.get(topic);\n\n if (state === undefined) {\n this._topics.set(topic, { status: 'rejected', error });\n return;\n }\n\n if (state.status === 'pending') {\n state.status = 'rejected';\n state.error = error;\n state.reject!(error);\n }\n }\n\n /**\n * Clears internal state for a topic. Called automatically by\n * `unsubscribe` — subclasses generally don't need to call this.\n */\n protected clearTopic(topic: string): void {\n this._topics.delete(topic);\n }\n\n protected clearAll(): void {\n this._topics.clear();\n }\n\n override async send(ctx: Query, _signal: AbortSignal): Promise<unknown> {\n const topicCtx = ctx as TopicCtx;\n topicCtx._topicAdapter = this;\n const topic = topicCtx.topic;\n\n const existing = this._topics.get(topic);\n\n if (existing) {\n switch (existing.status) {\n case 'fulfilled':\n return existing.data;\n case 'rejected':\n throw existing.error;\n case 'pending':\n return existing.promise;\n }\n }\n\n // No state yet — create a deferred and subscribe\n let resolve!: (data: unknown) => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<unknown>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n this._topics.set(topic, { status: 'pending', promise, resolve, reject });\n this.subscribe(topic);\n\n return promise;\n }\n\n /**\n * Convenience wrapper — pushes a mutation event through the QueryClient\n * so that entities and live collections are updated reactively.\n */\n protected sendMutationEvent(event: MutationEvent): void {\n this.queryClient!.applyMutationEvent(event);\n }\n}\n"],"names":["TopicQuery","Query","TopicQueryAdapter","QueryAdapter","topic","data","state","error","ctx","_signal","topicCtx","existing","resolve","reject","promise","res","rej","event"],"mappings":"uKAQO,MAAeA,UAAmBC,EAAAA,KAAM,CAC7C,OAAgB,QAIhB,gBAAyB,CACvB,MAAO,SAAS,KAAK,KAAK,EAC5B,CAEA,WAAgC,CAC9B,MAAO,CACL,UAAW,EACX,UAAW,IACF,IAAM,CACM,KAA6B,eACrC,YAAY,KAAK,KAAK,CACjC,CACF,CAEJ,CACF,CCNO,MAAeC,UAA0BC,EAAAA,YAAa,CACnD,YAAc,IAqBZ,aAAaC,EAAeC,EAAqB,CACzD,MAAMC,EAAQ,KAAK,QAAQ,IAAIF,CAAK,EAEpC,GAAIE,IAAU,OAAW,CACvB,KAAK,QAAQ,IAAIF,EAAO,CAAE,OAAQ,YAAa,KAAAC,EAAM,EACrD,MACF,CAEIC,EAAM,SAAW,YACnBA,EAAM,OAAS,YACfA,EAAM,KAAOD,EACbC,EAAM,QAASD,CAAI,EAEvB,CAOU,YAAYD,EAAeG,EAAsB,CACzD,MAAMD,EAAQ,KAAK,QAAQ,IAAIF,CAAK,EAEpC,GAAIE,IAAU,OAAW,CACvB,KAAK,QAAQ,IAAIF,EAAO,CAAE,OAAQ,WAAY,MAAAG,EAAO,EACrD,MACF,CAEID,EAAM,SAAW,YACnBA,EAAM,OAAS,WACfA,EAAM,MAAQC,EACdD,EAAM,OAAQC,CAAK,EAEvB,CAMU,WAAWH,EAAqB,CACxC,KAAK,QAAQ,OAAOA,CAAK,CAC3B,CAEU,UAAiB,CACzB,KAAK,QAAQ,MAAA,CACf,CAEA,MAAe,KAAKI,EAAYC,EAAwC,CACtE,MAAMC,EAAWF,EACjBE,EAAS,cAAgB,KACzB,MAAMN,EAAQM,EAAS,MAEjBC,EAAW,KAAK,QAAQ,IAAIP,CAAK,EAEvC,GAAIO,EACF,OAAQA,EAAS,OAAA,CACf,IAAK,YACH,OAAOA,EAAS,KAClB,IAAK,WACH,MAAMA,EAAS,MACjB,IAAK,UACH,OAAOA,EAAS,OAAA,CAKtB,IAAIC,EACAC,EACJ,MAAMC,EAAU,IAAI,QAAiB,CAACC,EAAKC,IAAQ,CACjDJ,EAAUG,EACVF,EAASG,CACX,CAAC,EAED,YAAK,QAAQ,IAAIZ,EAAO,CAAE,OAAQ,UAAW,QAAAU,EAAS,QAAAF,EAAS,OAAAC,EAAQ,EACvE,KAAK,UAAUT,CAAK,EAEbU,CACT,CAMU,kBAAkBG,EAA4B,CACtD,KAAK,YAAa,mBAAmBA,CAAK,CAC5C,CACF"}
@@ -0,0 +1,2 @@
1
+ "use strict";class r{queryClient;register(e){this.queryClient=e}}exports.QueryAdapter=r;
2
+ //# sourceMappingURL=QueryAdapter-DUo338ga.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"QueryAdapter-DUo338ga.js","sources":["../../../src/QueryAdapter.ts"],"sourcesContent":["import { type QueryContext } from './query-types.js';\nimport type { Query } from './query.js';\nimport type { Mutation } from './mutation.js';\n\n// ================================\n// IQueryClient — minimal interface QueryAdapter needs from the client\n// (avoids circular import: QueryClient → QueryAdapter → QueryClient)\n// ================================\n\nexport interface IQueryClientForAdapter {\n getContext(): QueryContext;\n applyMutationEvent(event: import('./types.js').MutationEvent): void;\n}\n\n// ================================\n// QueryAdapter base class\n// ================================\n\nexport abstract class QueryAdapter {\n protected queryClient: IQueryClientForAdapter | undefined;\n\n /**\n * Called once by QueryClient when this adapter is registered.\n * Subclasses can override to do setup (e.g. open a WebSocket connection).\n */\n register(queryClient: IQueryClientForAdapter): void {\n this.queryClient = queryClient;\n }\n\n /**\n * Called when the network comes online or goes offline.\n * Subclasses can override to reconnect persistent connections (e.g. WebSocket).\n */\n onNetworkStatusChange?(isOnline: boolean): void;\n\n /**\n * Called when the QueryClient is destroyed.\n * Subclasses can override to clean up connections or timers.\n */\n destroy?(): void;\n\n /**\n * Send the query and return the raw response data.\n * @param ctx The query execution context (a reified Query instance with params applied).\n * @param signal AbortSignal to cancel the in-flight request.\n */\n abstract send(ctx: Query, signal: AbortSignal): Promise<unknown>;\n\n /**\n * Fetch the next page of results. Only implement if the adapter supports pagination.\n * @param ctx The query execution context. `ctx.resultData` contains the current page's data.\n * @param signal AbortSignal to cancel the in-flight request.\n */\n sendNext?(ctx: Query, signal: AbortSignal): Promise<unknown>;\n\n /**\n * Return true if more pages are available for the current result.\n * Called reactively — do not perform async work here.\n */\n hasNext?(ctx: Query): boolean;\n\n /**\n * Send a mutation and return the raw response data.\n * @param ctx The mutation execution context (a reified Mutation instance with params applied).\n * @param signal AbortSignal to cancel the in-flight request.\n */\n sendMutation?(ctx: Mutation, signal: AbortSignal): Promise<unknown>;\n}\n"],"names":["QueryAdapter","queryClient"],"mappings":"aAkBO,MAAeA,CAAa,CACvB,YAMV,SAASC,EAA2C,CAClD,KAAK,YAAcA,CACrB,CAwCF"}
@@ -0,0 +1,2 @@
1
+ "use strict";const b=require("signalium"),A=require("signalium/utils"),Lt=require("./shared-Ct5zKrt4.js"),Rt=require("./stores/sync.js");var P=(i=>(i.Always="always",i.Online="online",i.OfflineFirst="offlineFirst",i))(P||{}),d=(i=>(i[i.UNDEFINED=1]="UNDEFINED",i[i.NULL=2]="NULL",i[i.NUMBER=4]="NUMBER",i[i.STRING=8]="STRING",i[i.BOOLEAN=16]="BOOLEAN",i[i.OBJECT=32]="OBJECT",i[i.ARRAY=64]="ARRAY",i[i.ID=128]="ID",i[i.RECORD=256]="RECORD",i[i.UNION=512]="UNION",i[i.ENTITY=1024]="ENTITY",i[i.HAS_FORMAT=4096]="HAS_FORMAT",i[i.IS_EAGER_FORMAT=8192]="IS_EAGER_FORMAT",i[i.PARSE_RESULT=16384]="PARSE_RESULT",i[i.LIVE=32768]="LIVE",i))(d||{});const U=Symbol("array"),V=Symbol("record"),ft=Symbol("QUERY_ID");var H=(i=>(i[i.Array=0]="Array",i[i.Value=1]="Value",i))(H||{});class L{type;entityDefs;constraintFieldRefs;sort;valueType;onCreate;onUpdate;onDelete;constructor(t,e,n,s,r,o,a,c){this.type=t,this.entityDefs=e,this.constraintFieldRefs=n,this.sort=s,this.valueType=r,this.onCreate=o,this.onUpdate=a,this.onDelete=c}static array(t,e,n){return new L(0,t,e,n,void 0,void 0,void 0,void 0)}static value(t,e,n,s,r,o){return new L(1,t,e,void 0,n,s,r,o)}}const O=new WeakMap;function F(i){return O.get(i)}var J=(i=>(i[i.Query=0]="Query",i[i.Entity=1]="Entity",i))(J||{});class _e{constructor(t,e,n){this._onEvict=e,this._intervalId=setInterval(this._tick,t*6e4*n)}_currentFlush=new Map;_nextFlush=new Map;_intervalId;schedule(t,e){this._nextFlush.set(t,e)}cancel(t){this._currentFlush.delete(t),this._nextFlush.delete(t)}_tick=()=>{const{_currentFlush:t,_nextFlush:e,_onEvict:n}=this;for(const[s,r]of t)n(s,r);this._currentFlush=e,this._nextFlush=new Map};destroy(){clearInterval(this._intervalId)}}class qt{_buckets=new Map;_nextTickEntries=new Map;_nextTickScheduled=!1;_onEvict;_multiplier;constructor(t,e=1){this._onEvict=t,this._multiplier=e}schedule(t,e,n){if(e===1/0)return;if(e===0){const{_nextTickEntries:o}=this;o.set(t,n),this._nextTickScheduled||(this._nextTickScheduled=!0,setTimeout(this._flushNextTick,0));return}const{_buckets:s}=this;let r=s.get(e);r||(r=new _e(e,this._onEvict,this._multiplier),s.set(e,r)),r.schedule(t,n)}cancel(t,e){if(e!==1/0){if(e===0){this._nextTickEntries.delete(t);return}this._buckets.get(e)?.cancel(t)}}_flushNextTick=()=>{const{_nextTickEntries:t,_onEvict:e}=this;this._nextTickScheduled=!1;for(const[n,s]of t)e(n,s);t.clear()};destroy(){const{_buckets:t,_nextTickEntries:e}=this;for(const n of t.values())n.destroy();t.clear(),e.clear()}}class jt{schedule(t,e,n){}cancel(t,e){}destroy(){}}const W=Symbol("fieldRef"),M=Symbol("fieldRefPath"),ut=Symbol("DEFINITION_TARGET"),z=Symbol("CANCEL_PROXY"),me=/\[([^\]]+)\]/g;function Ut(i){const t={[W]:!0,[M]:i};return new Proxy(t,we)}const we={get(i,t){if(t===W)return!0;if(t===M)return i[M];if(t===Symbol.toPrimitive||t==="toString"||t==="valueOf"){const n=i[M];return()=>`[${n.join(".")}]`}if(typeof t=="symbol")return;const e=i[M];return Ut([...e,t])},has(i,t){return t===W||t===M}};function Vt(i){return typeof i=="object"&&i!==null&&i[W]===!0}function Kt(i){return i[M]}function dt(i){return new Proxy(i,{set(t,e,n){return t[e]=n,!0},get(t,e){return e===ut?t:e===z?()=>{}:typeof e=="symbol"?t[e]:Ut([e])}})}function $t(i){const t=i[ut];i[z]();const e={};for(const r of Object.getOwnPropertyNames(t))e[r]=t[r];const n={};let s=Object.getPrototypeOf(t);for(;s&&s!==Object.prototype;){for(const r of Object.getOwnPropertyNames(s)){if(r==="constructor")continue;const o=Object.getOwnPropertyDescriptor(s,r);typeof o.value=="function"&&!(r in n)&&(n[r]=o.value)}s=Object.getPrototypeOf(s)}return{fields:e,methods:n}}function lt(i,t){let e=t;for(const n of i){if(e==null)return;e=e[n]}return e}function Ee(i,t){return i.replace(me,(e,n)=>{const s=n.split("."),r=lt(s,t);return r!=null?encodeURIComponent(String(r)):""})}function K(i,t){if(Vt(i))return lt(Kt(i),t);if(typeof i=="string")return Ee(i,t);if(Array.isArray(i))return i.map(e=>K(e,t));if(typeof i=="object"&&i!==null&&Object.getPrototypeOf(i)===Object.prototype){const e={};for(const n of Object.keys(i))e[n]=K(i[n],t);return e}return i}function nt(i,t,e){const n=i.fields,s=i.methods,r={params:t},o={};for(const[a,c]of Object.entries(n))o[a]=K(c,r);o.params=t,o.context=e;for(const[a,c]of Object.entries(s))o[a]=c.bind(o);return o}class ht{static cache;constructor(){return dt(this)}}const Qt=Object.entries,st=Object.keys;function St(i){return typeof i=="number"?i|d.UNDEFINED:i instanceof _?(i.mask&d.UNDEFINED)!==0?i:_.cloneWith(i,d.UNDEFINED):i}function Ce(i){return i instanceof _&&(i.mask&d.OBJECT)!==0&&(i.mask&(d.ENTITY|d.ARRAY|d.UNION|d.RECORD|d.LIVE))===0}function Bt(i,t,e){const n=new Set;for(const r of i)if(r!==void 0)for(const o of Object.keys(r))n.add(o);const s={};for(const r of n){let o=0,a;const c=[];let f=!0;for(const l of i){const u=l?.[r];u!==void 0?(o++,a===void 0&&(a=u),Ce(u)?c.push(u.shape):(f=!1,c.push(void 0))):(f=!1,c.push(void 0))}if(f&&o>0){const l=Bt(c,t),u=new _(d.OBJECT,l);s[r]=o<t?St(u):u}else s[r]=o<t?St(a):a}return s}class _{mask;shape;typenameField=void 0;typenameValue=void 0;idField=void 0;values=void 0;_methods=void 0;_entityConfig=void 0;_entityClass=void 0;_entityCache=void 0;_liveConfig=void 0;constructor(t,e,n,s,r,o){this.mask=t,this.shape=e,this.values=n,this.typenameField=s,this.typenameValue=r,this.idField=o}static merge(t){if(t.length===1)return t[0];const e=t.length,n=t.map(c=>c.shape);t[0].typenameValue;const s=Bt(n,e);let r,o,a;for(const c of t){if(r===void 0&&c.idField!==void 0)r=c.idField;else if(r!==void 0&&c.idField!==void 0&&c.idField!==r)throw new Error(`[fetchium] Entity typename '${c.typenameValue}' has conflicting id fields: '${String(r)}' vs '${String(c.idField)}'`);o===void 0&&(o=c.typenameField),a===void 0&&(a=c.typenameValue)}return new _(d.ENTITY|d.OBJECT,s,void 0,o,a,r)}static cloneWith(t,e){const n=new _(e|t.mask,t.shape,t.values,t.typenameField,t.typenameValue,t.idField);return n._methods=t._methods,n._entityConfig=t._entityConfig,n._entityClass=t._entityClass,n._entityCache=t._entityCache,n._liveConfig=t._liveConfig,n}}class X extends Set{lowercaseMap;constructor(t){super(t),this.lowercaseMap=new Map;for(const e of t)if(typeof e=="string"){const n=e.toLowerCase(),s=this.lowercaseMap.get(n);if(s!==void 0)throw new Error(`Case-insensitive enum cannot have multiple values with the same lowercase form: '${s}' and '${e}' both become '${n}'`);this.lowercaseMap.set(n,e)}}has(t){return this.get(t)!==void 0}get(t){if(typeof t=="string")return this.lowercaseMap.get(t.toLowerCase());if(super.has(t))return t}}const be=1128875347;A.registerCustomHash(X,i=>{let t=be;for(const e of i)t+=A.hashValue(e);return t>>>0});function yt(i,t){return new _(i,t)}function xe(i){return yt(d.ARRAY,i)}function Oe(i){return yt(d.RECORD|d.OBJECT,i)}function Re(i){return yt(d.PARSE_RESULT,i)}function Yt(i,t){let e=i,n,s,r;for(const[o,a]of Qt(t))switch(typeof a){case"number":if((a&d.ID)!==0){if(n!==void 0)throw new Error(`Duplicate id field: ${o}`);n=o}break;case"string":if(s!==void 0&&s!==o)throw new Error(`Duplicate typename field: ${o}`);s=o,r=a;break;case"object":if(a instanceof X||a instanceof Set)break;a.mask&d.LIVE&&(e|=d.LIVE);break}return new _(e,t,void 0,s,r,n)}function Se(i){return Yt(d.OBJECT,i)}function At(i,t,e){const n=i.mask;if((n&d.UNION)!==0){const s=i;if(s.typenameField!==void 0){if(e!==void 0&&e!==s.typenameField)throw new Error(`Union typename field conflict: Cannot merge unions with different typename fields ('${e}' vs '${s.typenameField}')`);e=s.typenameField}const r=s.shape;if(r!==void 0)for(const o of[...st(r),U,V]){const a=r[o];if(t[o]!==void 0&&t[o]!==a)throw new Error(`Union merge conflict: Duplicate typename value '${String(o)}' found when merging nested unions (${String(t[o])} vs ${String(a)})`);t[o]=a}}else if((n&d.ARRAY)!==0){if(t[U]!==void 0)throw new Error("Array shape already defined");t[U]=i.shape}else if((n&d.RECORD)!==0){if(t[V]!==void 0)throw new Error("Record shape already defined");t[V]=i.shape}else{const s=i.typenameField,r=i.typenameValue;if(r===void 0)throw new Error("Object definitions must have a typename to be in a union with other objects, records, or arrays");if(e!==void 0&&s!==e)throw new Error("Object definitions must have the same typename field to be in the same union");e=s,t[r]=i}return e}function pt(...i){const t=i;let e=0,n=0,s,r,o,a,c=0;for(const l of t){if(typeof l=="number"){e|=l;continue}if(l instanceof Set){if(r===void 0)r=new Set(l);else for(const u of l)r.add(u);continue}if(n++,c|=l.mask,n===1){s=l;continue}n===2&&(o=Object.create(null),a=At(s,o,a)),a=At(l,o,a)}if(n===0)return r===void 0?e:e===0?r:new _(e|d.UNION,void 0,r);if(n===1)return _.cloneWith(s,e);const f=e|c|d.UNION;return new _(f,o,r,a)}function gt(i,t,e){const n=i;if(typeof n=="number")return n|t;if(n instanceof Set)return pt(i,t);let s=e.get(n);return s===void 0&&(s=_.cloneWith(n,t),e.set(n,s)),s}const Ae=new WeakMap,De=new WeakMap,Ne=new WeakMap;function Ie(i){return gt(i,d.UNDEFINED|d.NULL,Ne)}function Me(i){return gt(i,d.UNDEFINED,Ae)}function ke(i){return gt(i,d.NULL,De)}function Fe(i){return i}function Te(i){return new Set([i])}const Gt=((...i)=>new Set(i));Gt.caseInsensitive=(...i)=>new X(i);const Wt=16;let Pe=0;const rt=[],zt=[],Ht=new Map,Z=new WeakSet;class ${_raw;_formatted;_parsed;_formatId;constructor(t,e,n){this._raw=t,this._formatId=e,n?(this._formatted=rt[e](t),this._parsed=!0):this._parsed=!1,Z.add(this)}getValue(){return this._parsed||(this._formatted=rt[this._formatId](this._raw),this._parsed=!0),this._formatted}toJSON(){return this._parsed?zt[this._formatId](this._formatted):this._raw}}function Le(i){const t=Ht.get(i);if(t===void 0)throw new Error(`Format ${i} not registered`);return t}function vt(i,t,e,n,s){const r=Pe++;rt[r]=e,zt[r]=n;const o=s?.eager??!0,c=r<<Wt|t|d.HAS_FORMAT|(o?d.IS_EAGER_FORMAT:0);Ht.set(i,c)}vt("date",d.STRING,i=>{const t=i.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)throw new Error(`Invalid date string: ${i}. Expected YYYY-MM-DD format.`);const[,e,n,s]=t,r=new Date(Date.UTC(parseInt(e,10),parseInt(n,10)-1,parseInt(s,10)));if(isNaN(r.getTime()))throw new Error(`Invalid date string: ${i}`);return r},i=>{const t=i.getUTCFullYear(),e=String(i.getUTCMonth()+1).padStart(2,"0"),n=String(i.getUTCDate()).padStart(2,"0");return`${t}-${e}-${n}`});vt("date-time",d.STRING,i=>{const t=new Date(i);if(isNaN(t.getTime()))throw new Error(`Invalid date-time string: ${i}`);return t},i=>i.toISOString());const Dt=new WeakMap;function q(i){let t=Dt.get(i);if(t===void 0){const e=new i,n=e[ut]??e;e[z]&&e[z]();const s={};for(const[f,l]of Qt(n))s[f]=l;const r=Object.getPrototypeOf(i.prototype);if(r!=null){const f=r.constructor;if(f!==ht&&typeof f=="function"){const u=q(f).shape;for(const y of st(u))if(y in s&&s[y]!==u[y])throw new Error(`Cannot extend: field '${y}' already exists in type definition`)}}const o={},a=i.prototype;for(const f of Object.getOwnPropertyNames(a))f!=="constructor"&&typeof a[f]=="function"&&(o[f]=a[f]);t=Yt(d.ENTITY|d.OBJECT,s),t._entityClass=i,st(o).length>0&&(t._methods=o),typeof o.__subscribe=="function"&&(t._entityConfig={hasSubscribe:!0});const c=i;c.cache&&(t._entityCache=c.cache),Dt.set(i,t)}return t}function qe(i){return q(i)}function Jt(i,t){if(t==null)return;const e=new Map;if(Array.isArray(t))for(const n of t){const[s,r]=n,a=q(s).typenameValue;if(a===void 0)continue;const c=[];for(const[f,l]of Object.entries(r))c.push([f,l]);c.length>0&&e.set(a,c)}else{const s=Object.entries(t);if(s.length===0)return;const r=s.map(([o,a])=>[o,a]);for(const o of i){const a=o.typenameValue;a!==void 0&&e.set(a,r)}}return e.size>0?e:void 0}function Xt(i){return Array.isArray(i)?i.map(t=>q(t)):[q(i)]}function je(i,t){const e=Xt(i),n=e.length===1?e[0]:pt(...e.map(o=>o)),s=d.ARRAY|d.LIVE,r=new _(s,n);return r._liveConfig=L.array(e,Jt(e,t?.constraints),t?.sort),r}function Ue(i,t,e){const n=Xt(t),s=i,r=d.LIVE,o=new _(r,void 0);return o._liveConfig=L.value(n,Jt(n,e?.constraints),s,e.onCreate,e.onUpdate,e.onDelete),o}const Zt={format:Le,typename:Fe,const:Te,enum:Gt,id:d.ID|d.STRING|d.NUMBER,string:d.STRING,number:d.NUMBER,boolean:d.BOOLEAN,null:d.NULL,undefined:d.UNDEFINED,array:xe,object:Se,record:Oe,union:pt,nullish:Ie,optional:Me,nullable:ke,result:Re,entity:qe,liveArray:je,liveValue:Ue};function j(i,t,e){return new TypeError(`Validation error at ${i}`)}const te=Array.isArray;function Nt(i){if(i===null)return d.NULL;switch(typeof i){case"number":return d.NUMBER;case"string":return d.STRING;case"boolean":return d.BOOLEAN;case"undefined":return d.UNDEFINED;case"object":return te(i)?d.ARRAY:d.OBJECT;default:throw new Error(`Invalid type: ${typeof i}`)}}function Ve(i){return T(i)}function T(i){if(i===null||typeof i!="object")return i;if(te(i))return i.map(e=>T(e));if(i instanceof Date)return new Date(i.getTime());if(i instanceof Map){const e=new Map;for(const[n,s]of i)e.set(T(n),T(s));return e}if(i instanceof Set){const e=new Set;for(const n of i)e.add(T(n));return e}const t={};for(const e of Object.keys(i))t[e]=T(i[e]);return t}const _t=Object.entries,Ke=()=>{};class ot{queryClient=void 0;preloadedEntities=void 0;warn=Ke;isPartialEvent=!1;seen=void 0;seenByKey=void 0;reset(t,e,n,s=!1){this.queryClient=t,this.preloadedEntities=e,this.warn=n,this.isPartialEvent=s,t!==void 0&&(this.seen===void 0?(this.seen=new Map,this.seenByKey=new Map):(this.seen.clear(),this.seenByKey.clear()))}}function ee(i,t,e){return k(i,t,e,"")}function $e(i,t,e){return mt(i,t,e)}function It(i,t,e,n){const s=i>>Wt;if((i&d.IS_EAGER_FORMAT)!==0)try{return new $(t,s,!0)}catch(o){if((i&d.UNDEFINED)!==0){e.warn("Invalid formatted value for optional type, defaulting to undefined",{value:t,path:n,error:o instanceof Error?o.message:String(o)});return}throw o}return new $(t,s,!1)}function k(i,t,e,n){const s=t;if(s instanceof X){const c=s.get(i);if(c===void 0)throw j(n);return c}if(s instanceof Set){if(!s.has(i))throw j(n);return i}if(typeof s=="string"){if(i==null)return s;if(i!==s)throw j(n);return i}if(typeof s=="number"){const c=Nt(i);if((s&c)===0){if((s&d.UNDEFINED)!==0){e.warn("Invalid value for optional type, defaulting to undefined",{value:i,path:n});return}throw j(n)}return(s&d.HAS_FORMAT)!==0&&i!==null&&i!==void 0?It(s,i,e,n):i}const r=s.mask,o=s._liveConfig;if(o!==void 0&&o.type===H.Value)return o.valueType!==void 0?k(i,o.valueType,e,n):i;if((r&d.PARSE_RESULT)!==0)try{return{success:!0,value:k(i,s.shape,e,n)}}catch(c){return{success:!1,error:c instanceof Error?c:new Error(String(c))}}const a=Nt(i);if((r&a)===0&&!s.values?.has(i)){if((r&d.UNDEFINED)!==0){e.warn("Invalid value for optional type, defaulting to undefined",{value:i,path:n});return}throw j(n)}return a<d.OBJECT?(r&d.HAS_FORMAT)!==0&&i!==null&&i!==void 0?It(r,i,e,n):i:(r&d.UNION)!==0?Qe(a,i,s,e,n):a===d.ARRAY?ie(i,s.shape,e,n):(r&d.RECORD)!==0?ne(i,s.shape,e,n):(r&d.ENTITY)!==0&&e.queryClient!==void 0?mt(i,s,e):se(i,s,e,n)}function Qe(i,t,e,n,s){if(i===d.ARRAY){const r=e.shape[U];return r===void 0||typeof r=="number"?t:ie(t,r,n,s)}else{const r=e.typenameField,o=r?t[r]:void 0;if(o===void 0||typeof o!="string"){const c=e.shape[V];if(c===void 0)throw new Error(`Typename field '${r}' is required for union discrimination but was not found in the data`);return ne(t,c,n,s)}const a=e.shape[o];if(a===void 0||typeof a=="number")throw new Error(`Unknown typename '${o}' in union`);return a.mask&d.ENTITY&&n.queryClient!==void 0?mt(t,a,n):se(t,a,n,s)}}function ie(i,t,e,n){const s=[];for(let r=0;r<i.length;r++)try{s.push(k(i[r],t,e,`${n}[${r}]`))}catch(o){e.warn("Failed to parse array item, filtering out",{index:r,value:i[r],error:o instanceof Error?o.message:String(o)})}return s}function ne(i,t,e,n){for(const[s,r]of _t(i))i[s]=k(r,t,e,`${n}["${s}"]`);return i}function se(i,t,e,n){if(O.has(i))return i;const s=t.shape;for(const[r,o]of _t(s))i[r]=k(i[r],o,e,`${n}.${r}`);return i}function mt(i,t,e){const n=e.queryClient,s=e.preloadedEntities;let r,o;if(s!==void 0)r=i.__entityRef,o=r;else{const p=i[t.idField];if(p==null||typeof p!="string"&&typeof p!="number")throw new Error(`Entity id must be a string or number: ${t.typenameValue} (got ${typeof p})`);o=p,r=A.hashValue([t.typenameValue,o])}const a=e.seenByKey.get(r);if(a!==void 0)return a.data;if(s!==void 0){const g=n.entityMap.getEntity(r)?.data??s.get(r);if(g===void 0)throw new Error(`Cached entity ${r} not found in preloaded map`);i=g}const c={};typeof t.idField=="symbol"&&(c[t.idField]=o);const f=n.entityMap.getEntity(r),l=e.isPartialEvent&&f!==void 0,u={key:r,shape:t,data:c,rawKeys:l?new Set(Object.keys(i)):void 0};e.seen.set(c,u),e.seenByKey.set(r,u);const y=`[[${t.typenameValue}:${o}]]`,v=t.shape;for(const[p,g]of _t(v))l&&!(p in i)||(c[p]=k(i[p],g,e,`${y}.${p}`));return c}function Be(i,t){return Ye(i,t.shape,t.typenameField)}function Ye(i,t,e){if(t===void 0)return!0;for(const n of Object.keys(t)){if(n===e)continue;const s=t[n];if(s instanceof _){if((s.mask&d.UNDEFINED)!==0)continue;if(!(n in i)||i[n]===void 0)return!1}else if(typeof s=="number"){if((s&d.UNDEFINED)!==0)continue;if(!(n in i)||i[n]===void 0)return!1}else if(!(n in i)||i[n]===void 0)return!1}return!0}const Ge=Object.prototype,G=new WeakMap;function N(i){if(typeof i!="object"||i===null)return i;if(Z.has(i))return N(i.getValue());if(O.has(i))return i;if(Array.isArray(i)){let t=G.get(i);return t===void 0&&(t=new Proxy(i,We),G.set(i,t)),t}if(Object.getPrototypeOf(i)===Ge){let t=G.get(i);return t===void 0&&(t=new Proxy(i,ze),G.set(i,t)),t}return i}const We={get(i,t,e){if(typeof t=="string"){const n=Number(t);if(Number.isInteger(n)&&n>=0&&n<i.length)return N(i[n])}return Reflect.get(i,t,e)},set(){return!1},deleteProperty(){return!1}},ze={get(i,t,e){return typeof t=="string"?N(i[t]):Reflect.get(i,t,e)},set(){return!1},deleteProperty(){return!1},has(i,t){return t in i},ownKeys(i){return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,t){return Object.getOwnPropertyDescriptor(i,t)}};class He{_notifier;_queryClient;_proxies=new Map;key;typename;id;idField;data;refCount=0;entityRefs;liveCollections=[];satisfiedDefs=new WeakSet;parseId=-1;_entityCache;_extraMethods;_extraGetters;constructor(t,e,n,s,r,o){this._notifier=b.notifier(),this._queryClient=o,this.key=t,this.typename=e,this.id=n,this.idField=s,this.data=r,this.entityRefs=void 0}retain(){this.refCount++;const t=this._entityCache?.gcTime;t!==void 0&&this._queryClient.gcManager.cancel(this.key,t)}release(){if(--this.refCount>0||this.refCount<0)return;const t=this._entityCache?.gcTime;t!==void 0?this._queryClient.gcManager.schedule(this.key,t,J.Entity):this.evict()}evict(){const t=this.liveCollections.slice();this.liveCollections.length=0;for(const n of t)n.destroy();this._queryClient.entityMap.remove(this.key);const e=this.entityRefs;if(this.entityRefs=void 0,e)for(const n of e.keys())n.release()}setChildRefs(t,e){const n=this.entityRefs;if(t!==void 0&&t.size>0)for(const s of t.keys())(n===void 0||!n.has(s))&&s.retain();if(n!==void 0&&n.size>0)for(const s of n.keys())(t===void 0||!t.has(s))&&s.release();this.entityRefs=t,e&&this.save()}addChildRef(t){this.entityRefs===void 0&&(this.entityRefs=new Map);const e=this.entityRefs.get(t)??0;this.entityRefs.set(t,e+1),e===0&&t.retain(),this.save()}removeChildRef(t){if(this.entityRefs===void 0)return;const e=this.entityRefs.get(t);e!==void 0&&(e<=1?(this.entityRefs.delete(t),t.release()):this.entityRefs.set(t,e-1),this.save())}getProxy(t){const e=t;let n=this._proxies.get(e);return n===void 0&&(n=Xe(this,this.key,t,this._notifier,this._queryClient),this._proxies.set(e,n)),n}get proxy(){return this._proxies.values().next().value}satisfiesDef(t){return this.satisfiedDefs.has(t)?!0:Be(this.data,t)?(this.satisfiedDefs.add(t),!0):!1}save(){this._queryClient.entityMap.save(this)}notify(){this._notifier.notify()}consume(){this._notifier.consume()}}function Je(i,t,e){const n=[];for(const s of i){if(typeof s!="object"||s===null)continue;const r=O.get(s);if(r===void 0)continue;const o=e.entityMap.getEntity(r);o!==void 0&&o.satisfiesDef(t)&&n.push(s)}return n}function Xe(i,t,e,n,s){const r=e.shape??{},o=e,a=o._methods,c=o._entityClass,f=o._entityConfig,l=c?c.prototype:ht.prototype;e.typenameField;const u=new Map,y=new Map,v=()=>({__entityRef:t});let p;f?.hasSubscribe&&a&&"__subscribe"in a&&(p=b.relay(E=>{const h=C=>{C.__eventSource=t,s.applyMutationEvent(C)},m=a.__subscribe.call(g,h);return E.value=g,m}));let g;const w=Object.keys(r);if(w.includes("__typename")||w.push("__typename"),a)for(const E of Object.keys(a))w.includes(E)||w.push(E);let I,R=w;function Y(){const E=i._extraMethods;if(E!==I){if(I=E,R=w.slice(),E!==void 0)for(const m of Object.keys(E))R.includes(m)||R.push(m);const h=i._extraGetters;if(h!==void 0)for(const m of Object.keys(h))R.includes(m)||R.push(m)}return R}const S={getPrototypeOf(){return l},get(E,h){if(typeof h=="symbol")return;if(h==="toJSON")return v;if(h==="__context")return s.getContext();if(h==="__typename")return i.typename;if(p?.value,n.consume(),typeof h=="string"){const C=i._extraGetters;if(C!==void 0&&h in C)return C[h]();const D=i._extraMethods;if(D!==void 0&&h in D){let x=u.get(h);return x||(x=D[h].bind(g),u.set(h,x)),x}if(a&&h in a){let x=u.get(h);return x||(x=b.reactiveMethod(g,a[h].bind(g)),u.set(h,x)),x}}const m=i.data[h];if(typeof m=="object"&&m!==null&&Z.has(m))return N(m.getValue());if(Array.isArray(m)&&typeof h=="string"){const C=r[h];if(C instanceof _&&(C.mask&d.ARRAY)!==0){const D=C.shape;if(D instanceof _&&(D.mask&d.ENTITY)!==0){const x=D.typenameValue;if(x!==void 0){const xt=s.getEntityDefsForTypename(x);if(xt!==void 0&&xt.length>1){const tt=y.get(h);if(tt!==void 0&&tt.source===m)return N(tt.filtered);const Ot=Je(m,D,s);return y.set(h,{source:m,filtered:Ot}),N(Ot)}}}}return N(m)}return N(m)},set(){return!1},has(E,h){if(h==="__typename")return!0;if(typeof h=="string"){const m=i._extraGetters;if(m&&h in m)return!0;const C=i._extraMethods;if(C&&h in C||a&&h in a)return!0}return h in r},ownKeys(){return Y()},getOwnPropertyDescriptor(E,h){if(h==="__typename")return{enumerable:!0,configurable:!0,value:i.typename,writable:!1};if(h in r)return{enumerable:!0,configurable:!0,value:S.get(E,h,g),writable:!1};if(typeof h=="string"){const m=i._extraGetters;if(m&&h in m)return{enumerable:!0,configurable:!0,value:S.get(E,h,g),writable:!1};const C=i._extraMethods;if(C&&h in C)return{enumerable:!0,configurable:!0,value:S.get(E,h,g),writable:!1};if(a&&h in a)return{enumerable:!1,configurable:!0,value:S.get(E,h,g),writable:!1}}}};return g=new Proxy({},S),O.set(g,t),b.setScopeOwner(g,s),g}class Ze{instances=new Map;persistEntity;constructor(t){this.persistEntity=t}hasEntity(t){return this.instances.has(t)}getEntity(t){return this.instances.get(t)}getOrCreateEntity(t,e,n,s){let r=this.instances.get(t);if(r===void 0){const o=n.idField;if(o===void 0)throw new Error(`Entity id field is required ${n.typenameValue}`);const a=e[o];if(typeof a!="string"&&typeof a!="number")throw new Error(`Entity id must be string or number: ${n.typenameValue}`);const c=n;r=new He(t,n.typenameValue,a,o,e,s),r._entityCache=c._entityCache,this.instances.set(t,r)}return r.parseId=s.currentParseId,r}remove(t){this.instances.delete(t)}save(t){let e;if(t.entityRefs){e=new Set;for(const n of t.entityRefs.keys())e.add(n.key)}this.persistEntity(t.key,t.data,e)}}class wt{onlineSignal;manualOverride=void 0;eventListenersAttached=!1;constructor(t){const e=t??this.detectOnlineStatus();this.onlineSignal=b.signal(e),this.canAttachListeners()&&this.attachEventListeners()}get isOnline(){return this.manualOverride!==void 0?this.manualOverride:this.onlineSignal.value}setNetworkStatus(t){this.manualOverride=t,this.onlineSignal.value=t}clearManualOverride(){this.manualOverride=void 0,this.onlineSignal.value=this.detectOnlineStatus()}getOnlineSignal(){return this.onlineSignal}detectOnlineStatus(){return typeof navigator<"u"&&"onLine"in navigator?navigator.onLine:!0}canAttachListeners(){return typeof window<"u"&&typeof window.addEventListener=="function"}destroy(){this.eventListenersAttached&&this.handleOnline&&this.handleOffline&&(window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline),this.eventListenersAttached=!1)}handleOnline=void 0;handleOffline=void 0;attachEventListeners(){this.eventListenersAttached||(this.handleOnline=()=>{this.manualOverride===void 0&&(this.onlineSignal.value=!0)},this.handleOffline=()=>{this.manualOverride===void 0&&(this.onlineSignal.value=!1)},window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline),this.eventListenersAttached=!0)}}class Et{static onlineSignal=b.signal(!0);get isOnline(){return!0}setNetworkStatus(t){}clearManualOverride(){}getOnlineSignal(){return Et.onlineSignal}destroy(){}}const re=new wt,ti=b.context(re);function Ct(i,t=typeof window>"u"){let e;i===!1?e=0:i===void 0||i===!0?e=t?0:3:typeof i=="number"?e=i:e=i.retries;const n=typeof i=="object"&&i.retryDelay?i.retryDelay:s=>1e3*Math.pow(2,s);return{retries:e,retryDelay:n}}class ei{static cache;static adapter;params;config;constructor(){return dt(this)}}const Mt=new WeakMap;class B{constructor(t,e){this.captured=e,this.statics=t}statics;createExecutionContext(t,e){return nt(this.captured,t,e)}resolveOptions(t){const{methods:e}=this.captured,n=e.getConfig?e.getConfig.call(t):t.config,s=Ct(n?.retry);return{config:n,retryConfig:s}}static for(t){let e=Mt.get(t);if(e!==void 0)return e;const n=new t,s=$t(n),r=String(s.methods.getIdentityKey.call(s.fields)),o=s.fields.result,a=o instanceof _?o:Zt.object(o),c=(a.mask&d.ENTITY)!==0,f=t.cache,l=s.fields.fetchNext,u=t.adapter;if(!u)throw new Error(`Query class "${t.name}" must define a static \`adapter\` property. Extend RESTQuery (from fetchium/rest) or set \`static adapter = MyAdapter\` on your query class.`);const y=typeof u.prototype.sendNext=="function",v=c?a:new _(d.ENTITY|d.OBJECT,a.shape,void 0,void 0,r,ft);return e=new B({id:r,shape:v,cache:f,rawFetchNext:l,hasSendNext:y,isEntityResult:c,adapterClass:u},s),Mt.set(t,e),e}}const ii=(i,t)=>{const e=B.for(i);return bt(e,t)};function ni(i,...t){const e=B.for(i),n=b.getContext(ve);if(n===void 0)throw new Error("QueryClient not found");const s=t[0];return n.getQuery(e,s)}function oe(i,t){return new Promise((e,n)=>{if(t?.aborted){n(t.reason);return}const s=setTimeout(e,i);t?.addEventListener("abort",()=>{clearTimeout(s),n(t.reason)},{once:!0})})}async function at(i,t,e){const n=Math.max(0,t.retries);let s;for(let r=0;r<=n;r++){e?.throwIfAborted();try{return await i()}catch(o){if(s=o,r>=n)throw o;await oe(t.retryDelay(r),e)}}throw s}class si{def;queryKey;storageKey=-1;relay;queryClient;initialized=!1;updatedAt=void 0;params=void 0;unsubscribe=void 0;_relayState=void 0;wasPaused=!1;currentParams=void 0;debounceTimer=void 0;config=void 0;retryConfig=Ct(void 0);_abortController=void 0;_executionCtx=void 0;_executionCtxKey=-1;rootEntity;_extraMethods={};_queryId=0;get key(){return this.queryKey}get relayState(){return this._relayState}constructor(t,e,n,s){this.def=t,this.queryClient=e,this.queryKey=n,this.params=s,this._extraMethods={__refetch:this.refetch},t.statics.hasSendNext&&(this._extraMethods.__fetchNext=this.fetchNext);const r=Pt(s);this._queryId=r!==void 0?A.hashValue(r):0,this.relay=b.relay(o=>{this._relayState=o;const a=()=>{clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this._abortController?.abort(),this._abortController=void 0,this._fetchNextAbort?.abort(),this._fetchNextAbort=void 0,this._fetchNextPromise=void 0,this.unsubscribe?.(),this.unsubscribe=void 0;const f=this.config?.gcTime??Lt.DEFAULT_GC_TIME;this.queryClient.gcManager.schedule(this.queryKey,f,J.Query)},c=(f=!1)=>{const{wasPaused:l,isPaused:u,initialized:y}=this;if(this.wasPaused=u,u&&!l&&y){a();return}const v=Pt(this.params),p=bt(this.def,v),g=p!==this.storageKey;g&&(this.currentParams=v,this.storageKey=p),this.getOrCreateExecutionContext(),this.initialized?l||f?(this.queryClient.activateQuery(this),f&&this.updatedAt!==void 0&&this.setupSubscription(),(this.config?.refreshStaleOnReconnect??!0)&&this.isStale&&this.runDebounced()):g&&(this.setupSubscription(),this.runDebounced()):(this.queryClient.activateQuery(this),this.initialize())};return c(!0),{update:c,deactivate:a}},{desc:`Query(${t.statics.id})`})}applyData(t,e,n=!1,s){const r=this.def;return this.rootEntity=this.queryClient.parseAndApplyRootEntity(t,this._queryId,r.statics.shape,e,n,s),this.rootEntity._extraMethods===void 0&&(this.rootEntity._extraMethods=this._extraMethods,this.rootEntity._extraGetters={__hasNext:()=>this.hasNext,__isFetchingNext:()=>this._fetchNextPromise!==void 0}),this.rootEntity.getProxy(r.statics.shape)}saveQueryMetadata(){if(this.rootEntity===void 0||this.updatedAt===void 0)return;const t=new Map(this.rootEntity.entityRefs??[]);t.set(this.rootEntity,1),this.queryClient.saveQueryData(this.def,this.storageKey,{__entityRef:this.rootEntity.key},this.updatedAt,t)}async initialize(){const t=this.queryClient,e=this.relayState;this.initialized=!0;let n;try{n=await t.loadCachedQuery(this.def,this.storageKey),n!==void 0&&(this.updatedAt=n.updatedAt,e.value=this.applyData(n.value,!1,!1,n.preloadedEntities))}catch(s){t.store.deleteQuery(this.storageKey),t.getContext().log?.warn?.("Failed to initialize query, the query cache may be corrupted or invalid",s)}if(!this.isPaused)try{if(n!==void 0&&this.setupSubscription(),n===void 0||this.isStale){if(await oe(0),this.isPaused)return;this.runQueryImmediately()}}catch(s){e.setError(s)}}setupSubscription(){this.unsubscribe?.(),this.unsubscribe=void 0;const t=this.config?.subscribe;if(!t)return;const e=this._executionCtx;this.unsubscribe=t.call(e,n=>{n.__eventSource=this.queryKey,this.queryClient.applyMutationEvent(n)})}getOrCreateExecutionContext(){return(this._executionCtx===void 0||this._executionCtxKey!==this.storageKey)&&(this._executionCtxKey=this.storageKey,this._executionCtx=this.def.createExecutionContext(this.currentParams??{},this.queryClient.getContext()),this._executionCtx.refetch=()=>this.refetch(),this._executionCtx.rawFetchNext=this.def.statics.rawFetchNext),this.resolveAndApplyOptions(),this._executionCtx}resolveAndApplyOptions(){const t=this.def.resolveOptions(this._executionCtx);this.config=t.config,this.retryConfig=t.retryConfig}async runQuery(){const t=this.def;if(this.isPaused)throw new Error("Query is paused due to network status");const e=this.getOrCreateExecutionContext(),n=this.queryClient.getAdapter(t.statics.adapterClass),s=this._abortController?.signal??new AbortController().signal;return at(async()=>{const r=await n.send(e,s);this.updatedAt=Date.now();const o=this.applyData(r,!0);return this.saveQueryMetadata(),this.unsubscribe===void 0&&this.setupSubscription(),o},this.retryConfig,s)}runQueryImmediately(){this._abortController?.abort(),this._abortController=new AbortController,this._fetchNextAbort?.abort(),this._fetchNextAbort=void 0,this._fetchNextPromise=void 0,this.relayState.setPromise(this.runQuery())}runDebounced(){if(this.relayState.isPending)return;const t=this.config?.debounce??0;clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runQueryImmediately()},t)}refetch=()=>this.relayState.isPending?this.relay:(this.runQueryImmediately(),this.relay);markStale(){this.updatedAt=0}get resolvedParams(){return this.currentParams}_fetchNextPromise=void 0;_fetchNextAbort=void 0;fetchNext=()=>{if(this.updatedAt===void 0)throw new Error("Cannot call __fetchNext before initial data has loaded");return this._fetchNextPromise!==void 0?this._fetchNextPromise:(queueMicrotask(()=>this.rootEntity?.notify()),this._fetchNextPromise=this.runFetchNext().then(t=>(this._fetchNextPromise=void 0,this.rootEntity?.notify(),t),t=>{throw this._fetchNextPromise=void 0,this.rootEntity?.notify(),t}),this._fetchNextPromise)};get hasNext(){if(this.rootEntity===void 0||!this._executionCtx)return!1;const t=this.queryClient.getAdapter(this.def.statics.adapterClass);return t.hasNext?(this._executionCtx.resultData=this.rootEntity.data,t.hasNext(this._executionCtx)):!1}async runFetchNext(){const t=this.def;this._fetchNextAbort=new AbortController;const e=this._fetchNextAbort.signal,n=this.getOrCreateExecutionContext();n.resultData=this.rootEntity.data;const s=this.queryClient.getAdapter(t.statics.adapterClass);return at(async()=>{const r=await s.sendNext(n,e);this.updatedAt=Date.now();const o=this.applyData(r,!0,!0);return this.saveQueryMetadata(),o},this.retryConfig,e)}get isStale(){if(this.updatedAt===void 0)return!0;const t=this.config?.staleTime??0;return Date.now()-this.updatedAt>=t}get isPaused(){const t=this.config?.networkMode??P.Online;if(t===P.Always)return!1;const e=this.queryClient.networkManager.getOnlineSignal().value;switch(t){case P.Online:return!e;case P.OfflineFirst:return!e&&this.updatedAt===void 0;default:return!1}}}class ri{def;queryClient;_inFlight=!1;task;constructor(t,e){this.def=t,this.queryClient=e,this.task=this.createTask()}createTask(){return b.task(async t=>{if(this._inFlight)throw new Error("A mutation is already in progress. Await the previous call before starting a new one.");this._inFlight=!0;try{const e=await this.executeWithRetry(t),n=this.validateResponse(e);return this.processEffects(t,n),n}finally{this._inFlight=!1}},{desc:`Mutation(${this.def.id})`})}validateResponse(t){const e=this.def.responseShape;if(!(e instanceof _))return t;const n=this.queryClient.getContext().log?.warn??(()=>{}),s=new ot;return s.reset(void 0,void 0,n),ee(t,e,s)}processEffects(t,e){let n;if(this.def.hasGetEffects){const r=nt(this.def.captured,t??{},this.queryClient.getContext());r.result=e,n=r.getEffects()}else if(this.def.effects!==void 0){const r={params:t,result:e};n=K(this.def.effects,r)}if(n===void 0)return;const s=this.queryClient;et(n.creates,"create",s),et(n.updates,"update",s),et(n.deletes,"delete",s),n.invalidates&&s.invalidateQueries(n.invalidates)}executeWithRetry(t){const e=Ct(this.def.config?.retry,!0),n=this.queryClient.getAdapter(this.def.adapterClass);if(!n.sendMutation)throw new Error(`Adapter "${this.def.adapterClass.name}" does not implement sendMutation(). Add a sendMutation() method to handle mutations.`);return at(async()=>{const s=new AbortController,r=nt(this.def.captured,t??{},this.queryClient.getContext());return await n.sendMutation(r,s.signal)},e)}}function oi(i){return typeof i=="string"?i:q(i).typenameValue}function et(i,t,e){if(i)for(const[n,s]of i){const r=oi(n);r!==void 0&&e.applyMutationEvent({type:t,typename:r,data:s})}}const ae="__eventSource";function ce(i){return{field:i,segments:i.indexOf(".")!==-1?i.split("."):void 0}}function ai(i){return i.map(ce)}function ci(i,t){if(t.segments===void 0)return i[t.field];let e=i;for(const n of t.segments){if(e==null)return;e=e[n]}return e}function fe(i,t){const e=[];for(let n=0;n<t.length;n++){const s=t[n],r=ci(i,s);if(r===void 0)return;e.push(s.field,r)}return A.hashValue(e)}function fi(i,t){if(i===void 0)return;const e=new Map;for(const[n,s]of i){const r=s.slice().sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0),o=[];let a=!0;for(const[c,f]of r){let l;if(Vt(f)){const u=Kt(f);l=lt(u,t)}else l=f;if(l===void 0){a=!1;break}o.push(c,l)}a&&e.set(n,A.hashValue(o))}return e.size>0?e:void 0}function kt(i,t){const e=i.get(t);if(e!==void 0)return e.map(([n])=>n).sort()}class ui{fields;fieldPaths;_bindings=new Map;constructor(t){this.fields=t,this.fieldPaths=t.map(ce)}register(t,e){let n=this._bindings.get(t);n===void 0&&(n=new Set,this._bindings.set(t,n)),n.add(e)}unregister(t,e){const n=this._bindings.get(t);n!==void 0&&(n.delete(e),n.size===0&&this._bindings.delete(t))}getMatching(t){return this._bindings.get(t)}get isEmpty(){return this._bindings.size===0}}function Ft(i){return A.hashValue(i)}class di{_groups=new Map;getOrCreateGroup(t){const e=Ft(t);let n=this._groups.get(e);return n===void 0&&(n=new ui(t),this._groups.set(e,n)),n}register(t,e,n){this.getOrCreateGroup(e).register(t,n)}unregister(t,e,n){const s=Ft(e),r=this._groups.get(s);r!==void 0&&(r.unregister(t,n),r.isEmpty&&this._groups.delete(s))}registerBinding(t,e){const n=t._constraintHashes.get(e);if(n===void 0)return;const s=kt(t._constraintFieldRefs,e);s!==void 0&&this.register(n,s,t)}unregisterBinding(t,e){const n=t._constraintHashes.get(e);if(n===void 0)return;const s=kt(t._constraintFieldRefs,e);s!==void 0&&this.unregister(n,s,t)}routeEvent(t,e,n,s,r,o){for(const a of this._groups.values()){const c=fe(e,a.fieldPaths);if(c===void 0)continue;const f=a.getMatching(c);if(f!==void 0)for(const l of f)l.onEvent(t,n,s,r,o)}}}function Tt(i){const t=new Set;for(const e of i)if(typeof e=="object"&&e!==null){const n=F(e);n!==void 0&&t.add(n)}return t}class ue{_queryClient;_parent;_constraintHashes;_entityDefsByTypename;_constraintFieldRefs;instance;constructor(t,e,n,s,r,o){this._queryClient=n,this._parent=s,this._constraintHashes=r,this._constraintFieldRefs=e,this.instance=o,this._entityDefsByTypename=new Map;for(const a of t)a.typenameValue!==void 0&&this._entityDefsByTypename.set(a.typenameValue,a);Z.add(this)}getValue(){return this.instance.getValue()}toJSON(){return this.instance.getRawValue()}reset(t){this.instance.reset(t)}append(t){this.instance.append(t)}onEvent(t,e,n,s,r){const o=this._entityDefsByTypename.get(t);if(o===void 0)return;const a=this._queryClient.entityMap.getEntity(e);if(n==="delete"){const f=a!==void 0?a.getProxy(o):r;f!==void 0&&(this.instance.onEvent(e,f,r??a?.data??{},"delete"),s?.());return}if(a===void 0||!a.satisfiesDef(o))return;s?.();const c=a.getProxy(o);this.instance.onEvent(e,c,a.data,n)}destroy(){this._queryClient.unregisterLiveCollection(this);const t=this._parent.liveCollections,e=t.indexOf(this);e!==-1&&t.splice(e,1)}}class li{_notifier;_items;_keys;_outputSignal;_queryClient;_parent;constructor(t,e,n,s,r,o){this._notifier=b.notifier(),this._items=n,this._keys=Tt(n),this._queryClient=t,this._parent=e;const a=s!==void 0&&r!==void 0,c=o!==void 0;(a||c)&&(this._outputSignal=b.reactiveSignal(()=>{this._notifier.consume();let f=this._items;if(a){const l=[];for(const u of f){if(typeof u!="object"||u===null){l.push(u);continue}const y=F(u);if(y===void 0){l.push(u);continue}const v=t.entityMap.getEntity(y);if(v===void 0){l.push(u);continue}v.consume(),fe(v.data,s)===r&&l.push(u)}f=l}return c&&(f=(f===this._items?f.slice():f).sort(o)),f}))}onEvent(t,e,n,s){switch(s){case"create":this.add(t,e);break;case"update":!this.has(t)&&e!==void 0&&this.add(t,e);break;case"delete":this.remove(t);break}}getValue(){return this._outputSignal!==void 0?this._outputSignal.value:(this._notifier.consume(),this._items)}getRawValue(){return this._items}add(t,e){if(this._keys.has(t))return!1;this._keys.add(t),this._items.push(e);const n=this._queryClient.entityMap.getEntity(t);return n!==void 0&&(this._parent.addChildRef(n),n.save()),this._notifier.notify(),!0}remove(t){if(!this._keys.has(t))return!1;this._keys.delete(t);const e=this._findIndex(t);e!==-1&&this._items.splice(e,1);const n=this._queryClient.entityMap.getEntity(t);return n!==void 0&&this._parent.removeChildRef(n),this._notifier.notify(),!0}has(t){return this._keys.has(t)}reset(t){const e=this._items,n=Array.isArray(t)?t:[];this._items=n,this._keys=Tt(n);for(const s of n)if(typeof s=="object"&&s!==null){const r=F(s);if(r!==void 0){const o=this._queryClient.entityMap.getEntity(r);o!==void 0&&this._parent.addChildRef(o)}}for(const s of e)if(typeof s=="object"&&s!==null){const r=F(s);if(r!==void 0){const o=this._queryClient.entityMap.getEntity(r);o!==void 0&&this._parent.removeChildRef(o)}}this._notifier.notify()}append(t){if(Array.isArray(t))for(const e of t){if(typeof e!="object"||e===null)continue;const n=F(e);n!==void 0&&this.add(n,e)}}_findIndex(t){for(let e=0;e<this._items.length;e++){const n=this._items[e];if(typeof n=="object"&&n!==null&&F(n)===t)return e}return-1}}class hi{_notifier;_value;_createdKeys;_deletedKeys;_queryClient;_parent;_onCreate;_onUpdate;_onDelete;constructor(t,e,n,s,r,o){this._notifier=b.notifier(),this._value=n,this._createdKeys=new Set,this._deletedKeys=new Set,this._queryClient=t,this._parent=e,this._onCreate=s,this._onUpdate=r,this._onDelete=o}onEvent(t,e,n,s){switch(s){case"create":if(this._createdKeys.has(t))return;this._createdKeys.add(t),this._value=this._onCreate(this._value,e);break;case"update":this._value=this._onUpdate(this._value,e??n);break;case"delete":if(this._deletedKeys.has(t))return;this._deletedKeys.add(t),this._value=this._onDelete(this._value,e??n);break}this._notifier.notify()}getValue(){return this._notifier.consume(),this._value}getRawValue(){return this._value}reset(t){this._value=t,this._createdKeys.clear(),this._deletedKeys.clear(),this._notifier.notify()}append(t){}}function de(i,t,e,n,s){let r=i.constraintFieldRefs;if(r===void 0){r=new Map;for(const f of i.entityDefs){const l=f.typenameValue;l!==void 0&&r.set(l,[[ae,e.key]])}}const o=fi(r,n)??new Map;let a;if(i.type===H.Array){let f,l;if(i.constraintFieldRefs!==void 0&&o.size>0&&o.size===1)for(const[u]of i.constraintFieldRefs){const y=o.get(u);if(y!==void 0){l=y;const v=i.constraintFieldRefs.get(u);v!==void 0&&(f=ai(v.map(([p])=>p)));break}}a=new li(s,e,Array.isArray(t)?t:[],f,l,i.sort)}else a=new hi(s,e,t,i.onCreate,i.onUpdate,i.onDelete);const c=new ue(i.entityDefs,r,s,e,o,a);return e.liveCollections.push(c),s.registerLiveCollection(c),c}const le=Object.entries,he=Object.prototype;function it(i,t,e,n=!1){const s=i.queryClient;s.currentParseId++;const r=i.seen,o=new Map;return{data:Q(t,r,s,e,o,n),entityRefs:o}}function Q(i,t,e,n,s,r){if(typeof i!="object"||i===null)return i;const o=t.get(i);if(o!==void 0)return yi(o,t,e,n,s,r);if(Array.isArray(i)){for(let a=0;a<i.length;a++){const c=i[a];typeof c=="object"&&c!==null&&!(c instanceof $)&&!O.has(c)&&(i[a]=Q(c,t,e,n,s,r))}return i}if(Object.getPrototypeOf(i)===he&&!O.has(i)){const a=i;for(const c of Object.keys(a)){const f=a[c];typeof f=="object"&&f!==null&&!(f instanceof $)&&!O.has(f)&&(a[c]=Q(f,t,e,n,s,r))}}return i}function ye(i){return typeof i=="object"&&i!==null&&!(i instanceof $)&&!O.has(i)}function yi(i,t,e,n,s,r){const{key:o,data:a,shape:c,rawKeys:f}=i,l=c.shape,u=e.prepareEntity(o,a,c),y=u.data,v=y!==a,p=v&&f!==void 0&&u.entityRefs!==void 0?new Map(u.entityRefs):new Map;if(v?(pe(l,a,y,f,u,y,t,e,n,p,r),u.notify()):ge(l,a,u,a,t,e,n,p,r),r&&u.liveCollections.length>0)for(const w of u.liveCollections){const I=w.instance.getRawValue();if(Array.isArray(I))for(const R of I){if(typeof R!="object"||R===null)continue;const Y=O.get(R);if(Y===void 0)continue;const S=e.entityMap.getEntity(Y);S!==void 0&&p.set(S,(p.get(S)??0)+1)}}u.setChildRefs(p.size>0?p:void 0,n);const g=u.getProxy(c);return s.set(u,(s.get(u)??0)+1),g}function pe(i,t,e,n,s,r,o,a,c,f,l){for(const[u,y]of le(i))if(!(n!==void 0&&!n.has(u)))if(ye(t[u])&&(t[u]=Q(t[u],o,a,c,f,l)),y instanceof _&&y._liveConfig!==void 0){const v=e[u];v instanceof ue?l?v.append(t[u]):v.reset(t[u]):e[u]=de(y._liveConfig,t[u],s,r,a)}else{const v=t[u],p=e[u];if(ct(v)&&ct(p)){const g=y instanceof _&&y.shape!==void 0?y.shape:void 0;if(g!==void 0)pe(g,v,p,void 0,s,r,o,a,c,f,l);else for(const w of Object.keys(v))p[w]=v[w];e[u]=p}else e[u]=v}}function ge(i,t,e,n,s,r,o,a,c){for(const[f,l]of le(i))if(f in t)if(ye(t[f])&&(t[f]=Q(t[f],s,r,o,a,c)),l instanceof _&&l._liveConfig!==void 0)t[f]=de(l._liveConfig,t[f],e,n,r);else{const u=t[f];if(ct(u)){const y=l instanceof _&&l.shape!==void 0?l.shape:void 0;y!==void 0&&ge(y,u,e,n,s,r,o,a,c)}}}function ct(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.getPrototypeOf(i)===he&&!O.has(i)}function pi(i){if(i!==void 0)return typeof i=="string"?i:typeof i=="function"?i():i.value}function gi(i){return b.isSignal(i)}function Pt(i){if(i===void 0)return;const t={};for(const[e,n]of Object.entries(i))gi(n)?t[e]=n.value:t[e]=n;return t}const bt=(i,t)=>A.hashValue([i.statics.id,t]);class vi{entityMap;queryInstances=new Map;mutationInstances=new Map;gcManager;networkManager;isServer;store;currentParseId=0;context;typenameRegistry=new Map;constraintRegistry=new Map;mergedDefCache=new Map;adapters=new Map;networkUnsubscribe;constructor(t={}){const{store:e=new Rt.SyncQueryStore(new Rt.MemoryPersistentStore),log:n,evictionMultiplier:s,adapters:r,networkManager:o,gcManager:a,...c}=t;this.isServer=typeof window>"u",this.store=e,this.context={...c,log:n??console,evictionMultiplier:s},this.gcManager=t.gcManager??(this.isServer?new jt:new qt(this.handleEviction,s)),this.networkManager=t.networkManager??new wt,this.entityMap=new Ze((u,y,v)=>this.store.saveEntity(u,y,v));for(const u of t.adapters??[])this.adapters.set(u.constructor,u),u.register(this);const f=this.networkManager.getOnlineSignal(),l=b.watcher(()=>f.value);this.networkUnsubscribe=l.addListener(()=>{const u=f.value;for(const y of this.adapters.values())y.onNetworkStatusChange?.(u)},{skipInitial:!0}),this.store.purgeStaleQueries?.()}getAdapter(t){let e=this.adapters.get(t);if(!e){try{e=new t}catch{throw new Error(`No adapter registered for ${t.name} and auto-instantiation failed. Pass an instance via QueryClient config: new QueryClient({ store, adapters: [new ${t.name}(...)] })`)}this.adapters.set(t,e),e.register(this)}return e}getContext(){return this.context}registerEntityDef(t){const e=t.typenameValue;if(e===void 0||t._entityClass===void 0)return;const n=this.typenameRegistry.get(e);if(n!==void 0){if(n.indexOf(t)!==-1)return;n.push(t),this.mergedDefCache.delete(e),this.getMergedDef(e)}else this.typenameRegistry.set(e,[t])}getEntityDefsForTypename(t){return this.typenameRegistry.get(t)}getMergedDef(t){let e=this.mergedDefCache.get(t);if(e!==void 0)return e;const n=this.typenameRegistry.get(t);if(n!==void 0)return e=_.merge(n),this.mergedDefCache.set(t,e),e}saveQueryData(t,e,n,s,r){const o=r!==void 0&&r.size>0?new Set([...r.keys()].map(a=>a.key)):void 0;this.store.saveQuery(t,e,n,s,o)}activateQuery(t){const{def:e,queryKey:n,storageKey:s,config:r}=t;this.store.activateQuery(e,s);const o=r?.gcTime??Lt.DEFAULT_GC_TIME;this.gcManager.cancel(n,o)}loadCachedQuery(t,e){return this.store.loadQuery(t,e)}getQuery(t,e){const n=bt(t,e);let s=this.queryInstances.get(n);return s===void 0&&(s=new si(t,this,n,e),this.queryInstances.set(n,s)),s.relay}getMutation(t){const e=t.id;let n=this.mutationInstances.get(e);return n===void 0&&(n=new ri(t,this),this.mutationInstances.set(e,n)),n.task}parseData(t,e,n){const s=this.context.log?.warn??(()=>{}),r=new ot;return r.reset(this,n,s),{data:ee(t,e,r),ctx:r}}applyRefs(t,e=!0,n=!1){return it(t.ctx,t.data,e,n)}parseAndApplyRootEntity(t,e,n,s,r=!1,o){typeof n.idField=="symbol"&&typeof t=="object"&&t!==null&&!("__entityRef"in t)&&(t[ft]=e);const a=this.parseData(t,n,o),c=it(a.ctx,a.data,s,r),f=O.get(c.data);return this.entityMap.getEntity(f)}prepareEntity(t,e,n){return this.registerEntityDef(n),this.entityMap.getOrCreateEntity(t,e,n,this)}applyMutationEvent(t){const{type:e,typename:n}=t,s=this.getMergedDef(n);if(s===void 0)return;const r=s.idField;if(r===void 0||typeof r=="symbol")return;const o=t.data,a=t.id!==void 0?t.id:e==="delete"&&(typeof o=="string"||typeof o=="number")?o:o[r];if(a===void 0)return;const c=A.hashValue([n,a]),f=t.__eventSource,l=typeof o=="object"&&o!==null?o:{},u=this.entityMap.getEntity(c);if(e==="delete"){const g=u!==void 0?u.data:l;this.routeEvent(n,g,c,e,f,void 0,g);return}try{const g=this.context.log?.warn??(()=>{}),w=new ot;w.reset(this,void 0,g,!0);const I=$e(l,s,w);it(w,I,!0)}catch(g){if(this.context.log?.warn?.("Failed to apply mutation event",g),u===void 0){const w=this.entityMap.getEntity(c);w!==void 0&&w.evict()}return}const y=this.entityMap.getEntity(c);if(y===void 0)return;this.entityMap.save(y);const v=u===void 0;let p=!1;this.routeEvent(n,y.data,c,e,f,()=>{p=!0}),v&&!p&&y.evict()}invalidateQueries(t){for(const e of t){const n=Array.isArray(e),s=n?e[0]:e,r=n?e[1]:void 0,a=B.for(s).statics.id;for(const[,c]of this.queryInstances)c.def.statics.id===a&&(r===void 0||_i(c.resolvedParams,r))&&c.markStale()}}handleEviction=(t,e)=>{if(e===J.Query){const s=this.queryInstances.get(t);if(s===void 0)return;s.rootEntity?.evict(),this.queryInstances.delete(t);return}const n=this.entityMap.getEntity(t);n!==void 0&&n.evict()};getOrCreateMatcher(t){let e=this.constraintRegistry.get(t);return e===void 0&&(e=new di,this.constraintRegistry.set(t,e)),e}registerLiveCollection(t){for(const[e,n]of t._entityDefsByTypename)this.registerEntityDef(n),this.getOrCreateMatcher(e).registerBinding(t,e)}unregisterLiveCollection(t){for(const e of t._entityDefsByTypename.keys()){const n=this.constraintRegistry.get(e);n!==void 0&&n.unregisterBinding(t,e)}}routeEvent(t,e,n,s,r,o,a){const c=this.constraintRegistry.get(t);if(c===void 0)return;const f=r!==void 0?{...e,[ae]:r}:e;c.routeEvent(t,f,n,s,o,a)}destroy(){this.networkUnsubscribe?.(),this.gcManager.destroy(),this.networkManager.destroy();for(const t of this.adapters.values())t.destroy?.();this.adapters.clear(),this.queryInstances.clear(),this.mutationInstances.clear(),this.constraintRegistry.clear(),this.typenameRegistry.clear(),this.mergedDefCache.clear()}}const ve=b.context(void 0);function _i(i,t){if(i===void 0)return!1;for(const e in t)if(i[e]!==t[e])return!1;return!0}exports.ARRAY_KEY=U;exports.Entity=ht;exports.GcManager=qt;exports.LiveFieldConfig=L;exports.LiveFieldType=H;exports.Mask=d;exports.NetworkManager=wt;exports.NetworkManagerContext=ti;exports.NetworkMode=P;exports.NoOpGcManager=jt;exports.NoOpNetworkManager=Et;exports.QUERY_ID=ft;exports.Query=ei;exports.QueryClient=vi;exports.QueryClientContext=ve;exports.RECORD_KEY=V;exports.ValidatorDef=_;exports.createDefinitionProxy=dt;exports.defaultNetworkManager=re;exports.draft=Ve;exports.extractDefinition=$t;exports.fetchQuery=ni;exports.queryKeyForClass=ii;exports.registerFormat=vt;exports.reifyValue=K;exports.resolveBaseUrl=pi;exports.t=Zt;
2
+ //# sourceMappingURL=QueryClient-4T90peFN.js.map