@logixjs/query 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Engine.ts","../src/internal/middleware/middleware.ts"],"sourcesContent":["import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Context, Effect, Layer, Option } from 'effect'\nimport { middleware as middlewareImpl, type MiddlewareConfig } from './internal/middleware/middleware.js'\n\nexport type InvalidateRequest =\n | { readonly kind: 'byResource'; readonly resourceId: string }\n | { readonly kind: 'byParams'; readonly resourceId: string; readonly keyHash: string }\n | { readonly kind: 'byTag'; readonly tag: string }\n\nexport interface Engine {\n readonly fetch: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n readonly effect: Effect.Effect<A, unknown, any>\n /**\n * MUST be serializable and slim; recommended default is undefined (lazy),\n * and only populate it when diagnostics/devtools require it.\n */\n readonly meta?: unknown\n }) => Effect.Effect<A, unknown, any>\n\n /**\n * perf: optional fast path to avoid allocations on the hot path.\n * Semantics must match `fetch({ ... })`.\n */\n readonly fetchFast?: <A>(\n resourceId: string,\n keyHash: string,\n effect: Effect.Effect<A, unknown, any>,\n meta?: unknown,\n ) => Effect.Effect<A, unknown, any>\n\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void, unknown, any>\n\n /**\n * Read-only fast path: must not trigger IO; used to short-circuit to success before refresh,\n * avoiding loading jitter.\n */\n readonly peekFresh?: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n }) => Effect.Effect<Option.Option<A>, never, any>\n}\n\nclass EngineTagImpl extends Context.Tag('@logixjs/query/Engine')<EngineTagImpl, Engine>() {}\n\nexport const Engine = Object.assign(EngineTagImpl, {\n layer: (engine: Engine): Layer.Layer<EngineTagImpl, never, never> => Layer.succeed(EngineTagImpl, engine),\n middleware: (config?: MiddlewareConfig): EffectOp.Middleware => middlewareImpl(config),\n})\n\nexport type { MiddlewareConfig }\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Effect, Option } from 'effect'\nimport { Engine } from '../../Engine.js'\nimport type { Engine as EngineService } from '../../Engine.js'\n\nexport interface MiddlewareConfig {\n /**\n * Default: only applies to EffectOp that carries resourceId+keyHash (from StateTrait.source).\n * Optional: further filter by resourceId.\n */\n readonly useFor?: (resourceId: string) => boolean\n}\n\n/**\n * Query middleware (EffectOp): external engine takeover point.\n * - Delegates ResourceSpec.load execution to Engine (cache / in-flight dedupe / invalidation, etc.)\n * - Still preserves Logix Runtime's keyHash gating and ResourceSnapshot source-of-truth semantics\n */\nexport const middleware = (config?: MiddlewareConfig): EffectOp.Middleware =>\n (() => {\n // perf: within the same Runtime instance, Engine injection is stable.\n // Cache it in the middleware closure to avoid a Context lookup on every fetch.\n let cachedEngine: EngineService | undefined\n\n return (op) => {\n if ((op.kind !== 'service' && op.kind !== 'trait-source') || !op.meta?.resourceId || !op.meta.keyHash) {\n return op.effect as any\n }\n\n const resourceId = op.meta.resourceId\n if (config?.useFor && !config.useFor(resourceId)) {\n return op.effect as any\n }\n\n const keyHash = op.meta.keyHash as string\n\n if (cachedEngine) {\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }\n\n return Effect.serviceOption(Engine).pipe(\n Effect.flatMap((engineOpt) => {\n if (Option.isNone(engineOpt)) {\n return Effect.fail(\n new Error(\n `[Query.Engine.middleware] Missing Query.Engine in the Runtime scope; please provide Query.Engine.layer(Query.TanStack.engine(new QueryClient())) (recommended) or Query.Engine.layer(customEngine).`,\n ),\n )\n }\n cachedEngine = engineOpt.value\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyH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,qBAAM,QAAQ,eAAe,MAAM;AAAA,EACxG,YAAY,CAAC,WAAmD,WAAe,MAAM;AACvF,CAAC;","names":["import_effect"]}
1
+ {"version":3,"sources":["../src/Engine.ts","../src/internal/middleware/middleware.ts"],"sourcesContent":["import type * as EffectOp from '@logixjs/core/EffectOp'\nimport type { JsonValue } from '@logixjs/core/Observability'\nimport { Context, Effect, Layer, Option } from 'effect'\nimport { middleware as middlewareImpl, type MiddlewareConfig } from './internal/middleware/middleware.js'\n\nexport type InvalidateRequest =\n | { readonly kind: 'byResource'; readonly resourceId: string }\n | { readonly kind: 'byParams'; readonly resourceId: string; readonly keyHash: string }\n | { readonly kind: 'byTag'; readonly tag: string }\n\nexport interface Engine {\n readonly fetch: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n readonly effect: Effect.Effect<A, unknown, any>\n /**\n * MUST be serializable and slim; recommended default is undefined (lazy),\n * and only populate it when diagnostics/devtools require it.\n */\n readonly meta?: JsonValue\n }) => Effect.Effect<A, unknown, any>\n\n /**\n * perf: optional fast path to avoid allocations on the hot path.\n * Semantics must match `fetch({ ... })`.\n */\n readonly fetchFast?: <A>(\n resourceId: string,\n keyHash: string,\n effect: Effect.Effect<A, unknown, any>,\n meta?: JsonValue,\n ) => Effect.Effect<A, unknown, any>\n\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void, unknown, any>\n\n /**\n * Read-only fast path: must not trigger IO; used to short-circuit to success before refresh,\n * avoiding loading jitter.\n */\n readonly peekFresh?: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n }) => Effect.Effect<Option.Option<A>, never, any>\n}\n\nclass EngineTagImpl extends Context.Tag('@logixjs/query/Engine')<EngineTagImpl, Engine>() {}\n\nexport const Engine = Object.assign(EngineTagImpl, {\n layer: (engine: Engine): Layer.Layer<EngineTagImpl, never, never> => Layer.succeed(EngineTagImpl, engine),\n middleware: (config?: MiddlewareConfig): EffectOp.Middleware => middlewareImpl(config),\n})\n\nexport type { MiddlewareConfig }\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Effect, Option } from 'effect'\nimport { Engine } from '../../Engine.js'\nimport type { Engine as EngineService } from '../../Engine.js'\n\nexport interface MiddlewareConfig {\n /**\n * Default: only applies to EffectOp that carries resourceId+keyHash (from StateTrait.source).\n * Optional: further filter by resourceId.\n */\n readonly useFor?: (resourceId: string) => boolean\n}\n\n/**\n * Query middleware (EffectOp): external engine takeover point.\n * - Delegates ResourceSpec.load execution to Engine (cache / in-flight dedupe / invalidation, etc.)\n * - Still preserves Logix Runtime's keyHash gating and ResourceSnapshot source-of-truth semantics\n */\nexport const middleware = (config?: MiddlewareConfig): EffectOp.Middleware =>\n (() => {\n // perf: within the same Runtime instance, Engine injection is stable.\n // Cache it in the middleware closure to avoid a Context lookup on every fetch.\n let cachedEngine: EngineService | undefined\n\n return (op) => {\n if ((op.kind !== 'service' && op.kind !== 'trait-source') || !op.meta?.resourceId || !op.meta.keyHash) {\n return op.effect as any\n }\n\n const resourceId = op.meta.resourceId\n if (config?.useFor && !config.useFor(resourceId)) {\n return op.effect as any\n }\n\n const keyHash = op.meta.keyHash as string\n\n if (cachedEngine) {\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }\n\n return Effect.serviceOption(Engine).pipe(\n Effect.flatMap((engineOpt) => {\n if (Option.isNone(engineOpt)) {\n return Effect.fail(\n new Error(\n `[Query.Engine.middleware] Missing Query.Engine in the Runtime scope; please provide Query.Engine.layer(Query.TanStack.engine(new QueryClient())) (recommended) or Query.Engine.layer(customEngine).`,\n ),\n )\n }\n cachedEngine = engineOpt.value\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }),\n ) as any\n }\n })()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AA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names":["import_effect"]}
package/dist/Engine.d.cts CHANGED
@@ -1,4 +1,5 @@
1
1
  import * as EffectOp from '@logixjs/core/EffectOp';
2
+ import { JsonValue } from '@logixjs/core/Observability';
2
3
  import { Effect, Option, Context, Layer } from 'effect';
3
4
 
4
5
  interface MiddlewareConfig {
@@ -32,13 +33,13 @@ interface Engine {
32
33
  * MUST be serializable and slim; recommended default is undefined (lazy),
33
34
  * and only populate it when diagnostics/devtools require it.
34
35
  */
35
- readonly meta?: unknown;
36
+ readonly meta?: JsonValue;
36
37
  }) => Effect.Effect<A, unknown, any>;
37
38
  /**
38
39
  * perf: optional fast path to avoid allocations on the hot path.
39
40
  * Semantics must match `fetch({ ... })`.
40
41
  */
41
- readonly fetchFast?: <A>(resourceId: string, keyHash: string, effect: Effect.Effect<A, unknown, any>, meta?: unknown) => Effect.Effect<A, unknown, any>;
42
+ readonly fetchFast?: <A>(resourceId: string, keyHash: string, effect: Effect.Effect<A, unknown, any>, meta?: JsonValue) => Effect.Effect<A, unknown, any>;
42
43
  readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void, unknown, any>;
43
44
  /**
44
45
  * Read-only fast path: must not trigger IO; used to short-circuit to success before refresh,
package/dist/Engine.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import * as EffectOp from '@logixjs/core/EffectOp';
2
+ import { JsonValue } from '@logixjs/core/Observability';
2
3
  import { Effect, Option, Context, Layer } from 'effect';
3
4
 
4
5
  interface MiddlewareConfig {
@@ -32,13 +33,13 @@ interface Engine {
32
33
  * MUST be serializable and slim; recommended default is undefined (lazy),
33
34
  * and only populate it when diagnostics/devtools require it.
34
35
  */
35
- readonly meta?: unknown;
36
+ readonly meta?: JsonValue;
36
37
  }) => Effect.Effect<A, unknown, any>;
37
38
  /**
38
39
  * perf: optional fast path to avoid allocations on the hot path.
39
40
  * Semantics must match `fetch({ ... })`.
40
41
  */
41
- readonly fetchFast?: <A>(resourceId: string, keyHash: string, effect: Effect.Effect<A, unknown, any>, meta?: unknown) => Effect.Effect<A, unknown, any>;
42
+ readonly fetchFast?: <A>(resourceId: string, keyHash: string, effect: Effect.Effect<A, unknown, any>, meta?: JsonValue) => Effect.Effect<A, unknown, any>;
42
43
  readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void, unknown, any>;
43
44
  /**
44
45
  * Read-only fast path: must not trigger IO; used to short-circuit to success before refresh,
package/dist/Engine.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Engine
3
- } from "./chunk-THVAADR2.js";
3
+ } from "./chunk-7IVR4THQ.js";
4
4
  import "./chunk-PZ5AY32C.js";
5
5
  export {
6
6
  Engine
package/dist/Query.cjs CHANGED
@@ -309,7 +309,8 @@ var toStateTraitSpec = (input) => {
309
309
  triggers,
310
310
  debounceMs: q.debounceMs,
311
311
  concurrency: q.concurrency === "exhaust" ? "exhaust-trailing" : q.concurrency,
312
- key: (...depsValues) => q.key(...depsValues)
312
+ key: (...depsValues) => q.key(...depsValues),
313
+ meta: q.meta
313
314
  });
314
315
  }
315
316
  return out;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Query.ts","../src/internal/logics/auto-trigger.ts","../src/Engine.ts","../src/internal/middleware/middleware.ts","../src/internal/logics/invalidate.ts","../src/Traits.ts"],"sourcesContent":["import * as Logix from '@logixjs/core'\nimport { Effect, Schema } from 'effect'\nimport { autoTrigger } from './internal/logics/auto-trigger.js'\nimport { invalidate } from './internal/logics/invalidate.js'\nimport type { InvalidateRequest } from './Engine.js'\nimport { toStateTraitSpec, type QueryBuilder, type QuerySourceConfig, type QueryResourceData, type QueryResourceError } from './Traits.js'\n\ntype AnyQuerySourceConfig<TParams, TUI> = QuerySourceConfig<TParams, TUI, any, any>\n\ntype EnsureQueries<TParams, TUI, TQueries> = TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>>\n ? {}\n : {\n readonly __queries_must_be_QuerySourceConfig__: never\n }\n\ntype QueriesOf<TParams, TUI, TQueries> = TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> ? TQueries : never\n\nexport type QueryState<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly params: TParams\n readonly ui: TUI\n readonly queries: {\n readonly [K in keyof TQueries]: Logix.Resource.ResourceSnapshot<\n QueryResourceData<TQueries[K]['resource']>,\n QueryResourceError<TQueries[K]['resource']>\n >\n }\n}\n\nexport type QueryName<TQueries extends Record<string, any>> = Extract<keyof TQueries, string>\n\ntype ForbiddenQueryName = 'params' | 'ui' | 'queries'\ntype ForbidQueryNames = {\n readonly [K in ForbiddenQueryName]?: never\n}\n\nexport type QueryActions<TParams, TUI = unknown, TQueries extends Record<string, any> = {}> = {\n readonly setParams: Schema.Schema<TParams, any>\n readonly setUi: Schema.Schema<TUI, any>\n readonly refresh: Schema.Schema<QueryName<TQueries> | undefined, any>\n readonly invalidate: Schema.Schema<InvalidateRequest, any>\n}\n\nexport type QueryShape<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.Shape<Schema.Schema<QueryState<TParams, TUI, TQueries>, any>, QueryActions<TParams, TUI, TQueries>>\n\nexport type QueryAction<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.ActionOf<QueryShape<TParams, TUI, TQueries>>\n\nexport interface QueryMakeConfig<\n TParams,\n TUI = unknown,\n TQueries = {},\n> {\n readonly params: Schema.Schema<TParams, any>\n readonly initialParams: TParams\n readonly ui?: TUI\n readonly queries?: (q: QueryBuilder<TParams, TUI>) => TQueries & ForbidQueryNames\n readonly traits?: unknown\n}\n\nexport interface QueryController<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> {\n readonly runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, TQueries>, QueryAction<TParams, TUI, TQueries>>\n readonly getState: Effect.Effect<QueryState<TParams, TUI, TQueries>>\n readonly dispatch: (action: QueryAction<TParams, TUI, TQueries>) => Effect.Effect<void>\n\n readonly controller: {\n readonly setParams: (params: TParams) => Effect.Effect<void>\n readonly setUi: (ui: TUI) => Effect.Effect<void>\n readonly refresh: (target?: QueryName<TQueries>) => Effect.Effect<void>\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void>\n }\n}\n\nexport type QueryModuleController<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly make: (\n runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, TQueries>, QueryAction<TParams, TUI, TQueries>>,\n ) => QueryController<TParams, TUI, TQueries>\n}\n\nexport type QueryHandleExt<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly controller: QueryController<TParams, TUI, TQueries>['controller']\n}\n\nexport type QueryModule<\n Id extends string,\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.Module.Module<Id, QueryShape<TParams, TUI, TQueries>, QueryHandleExt<TParams, TUI, TQueries>, any> & {\n readonly controller: QueryModuleController<TParams, TUI, TQueries>\n}\n\nconst InvalidateRequestSchema = Schema.Union(\n Schema.Struct({\n kind: Schema.Literal('byResource'),\n resourceId: Schema.String,\n }),\n Schema.Struct({\n kind: Schema.Literal('byParams'),\n resourceId: Schema.String,\n keyHash: Schema.String,\n }),\n Schema.Struct({\n kind: Schema.Literal('byTag'),\n tag: Schema.String,\n }),\n) as Schema.Schema<InvalidateRequest, any>\n\nconst assertQueryName = (name: string): void => {\n if (!name) {\n throw new Error(`[Query.make] query name must be non-empty`)\n }\n if (name.includes('.')) {\n throw new Error(`[Query.make] query name must not include \".\"; got \"${name}\"`)\n }\n if (name === 'params' || name === 'ui' || name === 'queries') {\n throw new Error(`[Query.make] query name \"${name}\" is reserved`)\n }\n}\n\nexport const make = <\n Id extends string,\n TParams,\n TUI = unknown,\n const TQueries = {},\n>(\n id: Id,\n config: QueryMakeConfig<TParams, TUI, TQueries> & EnsureQueries<TParams, TUI, TQueries>,\n): QueryModule<Id, TParams, TUI, QueriesOf<TParams, TUI, TQueries>> => {\n type Queries = QueriesOf<TParams, TUI, TQueries>\n const queryBuilder: QueryBuilder<TParams, TUI> = {\n source: (q: any) => q,\n }\n\n\t const queries = ((): Queries => {\n\t const raw = config.queries\n\t if (!raw) return {} as Queries\n\t return raw(queryBuilder) as Queries\n\t })()\n\n const queriesForTraits: Readonly<Record<string, AnyQuerySourceConfig<TParams, TUI>>> = queries\n for (const name of Object.keys(queries)) {\n assertQueryName(name)\n }\n\n\t const RefreshTargetSchema = (() => {\n\t const names = Object.keys(queries) as Array<QueryName<Queries>>\n\t if (names.length === 0) return Schema.Never as unknown as Schema.Schema<QueryName<Queries>, any>\n\t if (names.length === 1) {\n\t return Schema.Literal(names[0] as any) as unknown as Schema.Schema<QueryName<Queries>, any>\n\t }\n const asUnionMembers = <A>(items: ReadonlyArray<A>): readonly [A, A, ...Array<A>] => {\n if (items.length < 2) {\n throw new Error(`[Query.make] internal error: expected at least 2 query names for union`)\n }\n return items as unknown as readonly [A, A, ...Array<A>]\n }\n\n\t const members = names.map((n) => Schema.Literal(n as any))\n\t return Schema.Union(...asUnionMembers(members)) as unknown as Schema.Schema<QueryName<Queries>, any>\n\t })()\n\n const UiSchema = Schema.Unknown as Schema.Schema<TUI, any>\n\n\t const QueriesSchema = Schema.Struct(\n\t Object.fromEntries((Object.keys(queries) as Array<keyof Queries>).map((k) => [k, Schema.Unknown])) as Record<\n\t string,\n\t Schema.Schema<any, any>\n\t >,\n\t )\n\n const StateSchema = Schema.Struct({\n params: config.params,\n ui: UiSchema,\n queries: QueriesSchema,\n }) as unknown as Schema.Schema<QueryState<TParams, TUI, Queries>, any>\n\n const Actions = {\n setParams: config.params,\n setUi: UiSchema,\n refresh: Schema.UndefinedOr(RefreshTargetSchema),\n invalidate: InvalidateRequestSchema,\n } satisfies QueryActions<TParams, TUI, Queries>\n\n type Reducers = Logix.ReducersFromMap<typeof StateSchema, typeof Actions>\n\n const reducers: Reducers = {\n setParams: (state, action, sink) => {\n sink?.('params')\n return { ...state, params: action.payload ?? state.params }\n },\n setUi: (state, action, sink) => {\n sink?.('ui')\n return { ...state, ui: action.payload ?? state.ui }\n },\n refresh: (state) => state,\n invalidate: (state) => state,\n } satisfies Reducers\n\n const queryTraits =\n Object.keys(queriesForTraits).length > 0 ? toStateTraitSpec<TParams, TUI>({ queries: queriesForTraits }) : undefined\n\n const traits =\n queryTraits || config.traits\n ? ({\n ...(queryTraits as any),\n ...(config.traits as any),\n } as any)\n : undefined\n\n const module = Logix.Module.make(id, {\n state: StateSchema,\n actions: Actions,\n reducers,\n traits,\n })\n\n const logics = [\n autoTrigger<any, TParams, TUI>(module.tag as any, { queries: queriesForTraits }),\n invalidate<any, TParams, TUI>(module.tag as any, { queries: queriesForTraits }),\n ] satisfies ReadonlyArray<Logix.ModuleLogic<any, any, any>>\n\n const initial = (params?: TParams): QueryState<TParams, TUI, Queries> =>\n ({\n params: params ?? config.initialParams,\n ui: (config.ui ?? ({} as unknown as TUI)) as TUI,\n queries: Object.fromEntries(\n (Object.keys(queries) as Array<keyof Queries>).map((k) => [k, Logix.Resource.Snapshot.idle()]),\n ),\n }) as QueryState<TParams, TUI, Queries>\n\n\t const controller: QueryModuleController<TParams, TUI, Queries> = {\n\t make: (\n\t runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, Queries>, QueryAction<TParams, TUI, Queries>>,\n\t ): QueryController<TParams, TUI, Queries> => {\n\t const dispatch = runtime.dispatch\n\t const actions = module.actions as unknown as {\n\t readonly setParams: (params: TParams) => QueryAction<TParams, TUI, Queries>\n\t readonly setUi: (ui: TUI) => QueryAction<TParams, TUI, Queries>\n\t readonly refresh: (target: QueryName<Queries> | undefined) => QueryAction<TParams, TUI, Queries>\n\t readonly invalidate: (request: InvalidateRequest) => QueryAction<TParams, TUI, Queries>\n\t }\n\t\t return {\n\t\t runtime,\n\t\t getState: runtime.getState as Effect.Effect<QueryState<TParams, TUI, Queries>>,\n\t\t dispatch,\n\t controller: {\n\t setParams: (params: TParams) => dispatch(actions.setParams(params)),\n\t setUi: (ui: TUI) => dispatch(actions.setUi(ui)),\n\t refresh: (target?: QueryName<Queries>) => dispatch(actions.refresh(target)),\n\t\t invalidate: (request: InvalidateRequest) => dispatch(actions.invalidate(request)),\n\t\t },\n\t\t } as QueryController<TParams, TUI, Queries>\n\t\t },\n\t\t }\n\n ;(module as any).controller = controller\n\n const EXTEND_HANDLE = Symbol.for('logix.module.handle.extend')\n ;(module.tag as any)[EXTEND_HANDLE] = (\n runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, Queries>, QueryAction<TParams, TUI, Queries>>,\n base: Logix.ModuleHandle<any>,\n ) => {\n const c = controller.make(runtime)\n return {\n ...base,\n controller: c.controller,\n }\n }\n\n return module.implement({\n initial: initial(),\n logics: [...logics],\n }) as unknown as QueryModule<Id, TParams, TUI, Queries>\n}\n","import * as Logix from '@logixjs/core'\nimport { Duration, Effect, Fiber } from 'effect'\nimport type { QuerySourceConfig, QueryTrigger } from '../../Traits.js'\nimport { Engine } from '../../Engine.js'\n\nconst defaultTriggers = ['onMount', 'onKeyChange'] as const\n\nconst getTriggers = (triggers: ReadonlyArray<QueryTrigger> | undefined): ReadonlyArray<QueryTrigger> =>\n triggers ?? defaultTriggers\n\nconst isManualOnly = (triggers: ReadonlyArray<QueryTrigger>): boolean =>\n triggers.length === 1 && triggers[0] === 'manual'\n\nconst getSnapshotKeyHash = (snapshot: unknown): string | undefined => {\n if (!snapshot || typeof snapshot !== 'object') return undefined\n const keyHash = (snapshot as any).keyHash\n return typeof keyHash === 'string' ? keyHash : undefined\n}\n\nconst getSnapshotStatus = (snapshot: unknown): string | undefined => {\n if (!snapshot || typeof snapshot !== 'object') return undefined\n const status = (snapshot as any).status\n return typeof status === 'string' ? status : undefined\n}\n\nexport interface AutoTriggerLogicConfig<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>\n}\n\n/**\n * Query auto-trigger logic:\n * - onMount: triggers once on initialization (if the key is valid and current snapshot does not match the same keyHash).\n * - onKeyChange: triggers after params/ui state changes (can debounce; only when keyHash changes or current is idle).\n * - manual-only: when triggers=[\"manual\"], disable onMount/onKeyChange auto triggering.\n */\nexport const autoTrigger = <Sh extends Logix.AnyModuleShape, TParams, TUI>(\n module: Logix.ModuleTagType<any, Sh>,\n config: AutoTriggerLogicConfig<TParams, TUI>,\n): Logix.ModuleLogic<Sh, any, never> =>\n module.logic(($) => {\n type _State = Logix.StateOf<Sh> & { readonly queries: Record<string, unknown> }\n type QueryName = Extract<keyof typeof config.queries, string>\n\n const pending = new Map<string, Fiber.RuntimeFiber<void, any>>()\n const lastKeyHash = new Map<string, string | undefined>()\n\n const hydrateFromFreshCache = (\n name: QueryName,\n q: QuerySourceConfig<TParams, TUI>,\n keyHash: string,\n ): Effect.Effect<boolean, never, any> =>\n Effect.gen(function* () {\n const engineOpt = yield* Effect.serviceOption(Engine)\n if (engineOpt._tag === 'None') return false\n\n const engine = engineOpt.value\n if (!engine.peekFresh) return false\n\n const dataOpt = yield* engine.peekFresh({\n resourceId: q.resource.id,\n keyHash,\n })\n if (dataOpt._tag === 'None') return false\n\n const snapshot = Logix.Resource.Snapshot.success({\n keyHash,\n data: dataOpt.value,\n })\n yield* $.state.mutate((draft) => {\n ;(draft as Logix.Logic.Draft<_State>).queries[name] = snapshot\n })\n\n return true\n })\n\n const cancelPending = (name: string): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n const prev = pending.get(name)\n if (!prev) return\n pending.delete(name)\n yield* Fiber.interruptFork(prev)\n })\n\n const sourcePathOf = (name: QueryName): string => `queries.${name}`\n\n const refresh = (name: QueryName, options?: { readonly force?: boolean }): Effect.Effect<void, never, any> =>\n $.traits.source.refresh(sourcePathOf(name) as any, options as any) as Effect.Effect<void, never, any>\n\n const scheduleDebounced = (name: QueryName, ms: number): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n yield* cancelPending(name)\n const fiber = yield* Effect.forkScoped(\n Effect.sleep(Duration.millis(ms)).pipe(\n Effect.zipRight(refresh(name)),\n Effect.ensuring(Effect.sync(() => pending.delete(name))),\n Effect.catchAllCause(() => Effect.void),\n ),\n )\n pending.set(name, fiber)\n })\n\n const computeKeyHash = (state: any, q: QuerySourceConfig<TParams, TUI>): string | undefined => {\n const getAtPath = (root: any, path: string): unknown => {\n const parts = path.split('.')\n let cur = root\n for (const p of parts) {\n if (cur == null) return undefined\n cur = cur[p]\n }\n return cur\n }\n\n try {\n const keyState = { params: state.params as any, ui: state.ui as any } as any\n const args = (q.deps as ReadonlyArray<string>).map((dep) => getAtPath(keyState, dep))\n const key = (q.key as any)(...args)\n if (key === undefined) return undefined\n return Logix.Resource.keyHash(key)\n } catch {\n return undefined\n }\n }\n\n const maybeAutoRefresh = (\n phase: 'mount' | 'keyChange',\n stateOverride?: unknown,\n ): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n const state = (stateOverride ?? (yield* $.state.read)) as any\n\n for (const [name, q] of Object.entries(config.queries)) {\n const queryName = name as QueryName\n const triggers = getTriggers(q.triggers)\n if (isManualOnly(triggers)) {\n continue\n }\n\n if (phase === 'mount' && !triggers.includes('onMount')) {\n continue\n }\n\n if (phase === 'keyChange' && !triggers.includes('onKeyChange')) {\n continue\n }\n\n const keyHash = computeKeyHash(state, q)\n const snapshot = state?.queries?.[queryName]\n const snapshotKeyHash = getSnapshotKeyHash(snapshot)\n const snapshotStatus = getSnapshotStatus(snapshot)\n\n // Key is unavailable: do not refresh (idle reaping is guaranteed by kernel syncIdleInTransaction).\n if (keyHash === undefined) {\n lastKeyHash.set(queryName, undefined)\n continue\n }\n\n // keyHash unchanged and we already have a non-idle snapshot: avoid re-entering loading (reuse existing result).\n const last = lastKeyHash.get(queryName)\n if (snapshotStatus && snapshotStatus !== 'idle' && snapshotKeyHash === keyHash && last === keyHash) {\n continue\n }\n\n // If current snapshot is already success/error/loading with the same keyHash: update lastKeyHash and skip.\n if (snapshotStatus && snapshotStatus !== 'idle' && snapshotKeyHash === keyHash) {\n lastKeyHash.set(queryName, keyHash)\n continue\n }\n\n lastKeyHash.set(queryName, keyHash)\n\n // TanStack Query scenario: if we can hit the fresh cache, write a success snapshot directly,\n // skipping source.refresh (avoids UI jitter and extra transactions like \"cache hit but still loading -> success\").\n const hydrated = yield* hydrateFromFreshCache(queryName, q, keyHash)\n if (hydrated) {\n yield* cancelPending(queryName)\n continue\n }\n\n const debounceMs = q.debounceMs ?? 0\n if (phase === 'keyChange' && debounceMs > 0) {\n yield* scheduleDebounced(queryName, debounceMs)\n } else {\n // mount / no debounce: trigger immediately\n yield* cancelPending(queryName)\n yield* refresh(queryName)\n }\n }\n })\n\n const refreshAll = (options?: { readonly force?: boolean }): Effect.Effect<void, never, any> =>\n Effect.forEach(Object.keys(config.queries), (name) =>\n cancelPending(name).pipe(Effect.zipRight(refresh(name as QueryName, options))),\n ).pipe(Effect.asVoid)\n\n const setup = $.lifecycle.onStart(maybeAutoRefresh('mount'))\n\n const run = Effect.suspend(() =>\n Effect.all(\n [\n // params/ui changes: handled by Query's default logic, avoiding scattered UI-side useEffect triggers.\n $.onAction('setParams').runFork((action: any) =>\n Effect.gen(function* () {\n const state = (yield* $.state.read) as any\n const next = { ...state, params: action.payload }\n yield* maybeAutoRefresh('keyChange', next)\n }),\n ),\n $.onAction('setUi').runFork((action: any) =>\n Effect.gen(function* () {\n const state = (yield* $.state.read) as any\n const next = { ...state, ui: action.payload }\n yield* maybeAutoRefresh('keyChange', next)\n }),\n ),\n\n // Manual refresh: not restricted by triggers (manual-only still allows explicit refresh).\n $.onAction('refresh').runFork((action: any) =>\n Effect.gen(function* () {\n const target = action.payload as QueryName | undefined\n if (typeof target === 'string' && target.length > 0) {\n yield* cancelPending(target)\n yield* refresh(target, { force: true })\n } else {\n yield* refreshAll({ force: true })\n }\n }),\n ),\n ],\n { concurrency: 'unbounded' },\n ).pipe(Effect.asVoid),\n )\n\n return { setup, run }\n }) as Logix.ModuleLogic<Sh, any, never>\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Context, Effect, Layer, Option } from 'effect'\nimport { middleware as middlewareImpl, type MiddlewareConfig } from './internal/middleware/middleware.js'\n\nexport type InvalidateRequest =\n | { readonly kind: 'byResource'; readonly resourceId: string }\n | { readonly kind: 'byParams'; readonly resourceId: string; readonly keyHash: string }\n | { readonly kind: 'byTag'; readonly tag: string }\n\nexport interface Engine {\n readonly fetch: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n readonly effect: Effect.Effect<A, unknown, any>\n /**\n * MUST be serializable and slim; recommended default is undefined (lazy),\n * and only populate it when diagnostics/devtools require it.\n */\n readonly meta?: unknown\n }) => Effect.Effect<A, unknown, any>\n\n /**\n * perf: optional fast path to avoid allocations on the hot path.\n * Semantics must match `fetch({ ... })`.\n */\n readonly fetchFast?: <A>(\n resourceId: string,\n keyHash: string,\n effect: Effect.Effect<A, unknown, any>,\n meta?: unknown,\n ) => Effect.Effect<A, unknown, any>\n\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void, unknown, any>\n\n /**\n * Read-only fast path: must not trigger IO; used to short-circuit to success before refresh,\n * avoiding loading jitter.\n */\n readonly peekFresh?: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n }) => Effect.Effect<Option.Option<A>, never, any>\n}\n\nclass EngineTagImpl extends Context.Tag('@logixjs/query/Engine')<EngineTagImpl, Engine>() {}\n\nexport const Engine = Object.assign(EngineTagImpl, {\n layer: (engine: Engine): Layer.Layer<EngineTagImpl, never, never> => Layer.succeed(EngineTagImpl, engine),\n middleware: (config?: MiddlewareConfig): EffectOp.Middleware => middlewareImpl(config),\n})\n\nexport type { MiddlewareConfig }\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Effect, Option } from 'effect'\nimport { Engine } from '../../Engine.js'\nimport type { Engine as EngineService } from '../../Engine.js'\n\nexport interface MiddlewareConfig {\n /**\n * Default: only applies to EffectOp that carries resourceId+keyHash (from StateTrait.source).\n * Optional: further filter by resourceId.\n */\n readonly useFor?: (resourceId: string) => boolean\n}\n\n/**\n * Query middleware (EffectOp): external engine takeover point.\n * - Delegates ResourceSpec.load execution to Engine (cache / in-flight dedupe / invalidation, etc.)\n * - Still preserves Logix Runtime's keyHash gating and ResourceSnapshot source-of-truth semantics\n */\nexport const middleware = (config?: MiddlewareConfig): EffectOp.Middleware =>\n (() => {\n // perf: within the same Runtime instance, Engine injection is stable.\n // Cache it in the middleware closure to avoid a Context lookup on every fetch.\n let cachedEngine: EngineService | undefined\n\n return (op) => {\n if ((op.kind !== 'service' && op.kind !== 'trait-source') || !op.meta?.resourceId || !op.meta.keyHash) {\n return op.effect as any\n }\n\n const resourceId = op.meta.resourceId\n if (config?.useFor && !config.useFor(resourceId)) {\n return op.effect as any\n }\n\n const keyHash = op.meta.keyHash as string\n\n if (cachedEngine) {\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }\n\n return Effect.serviceOption(Engine).pipe(\n Effect.flatMap((engineOpt) => {\n if (Option.isNone(engineOpt)) {\n return Effect.fail(\n new Error(\n `[Query.Engine.middleware] Missing Query.Engine in the Runtime scope; please provide Query.Engine.layer(Query.TanStack.engine(new QueryClient())) (recommended) or Query.Engine.layer(customEngine).`,\n ),\n )\n }\n cachedEngine = engineOpt.value\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }),\n ) as any\n }\n })()\n","import * as Logix from '@logixjs/core'\nimport { Effect } from 'effect'\nimport { Engine, type InvalidateRequest } from '../../Engine.js'\nimport type { QuerySourceConfig } from '../../Traits.js'\n\nexport interface InvalidateLogicConfig<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>\n}\n\nconst toInvalidateTargets = <TParams, TUI>(\n request: InvalidateRequest,\n queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>,\n): ReadonlyArray<{ readonly name: string; readonly resourceId: string }> => {\n if (request.kind === 'byResource') {\n return Object.entries(queries)\n .filter(([, q]) => q.resource.id === request.resourceId)\n .map(([name, q]) => ({ name, resourceId: q.resource.id }))\n }\n\n if (request.kind === 'byParams') {\n return Object.entries(queries)\n .filter(([, q]) => q.resource.id === request.resourceId)\n .map(([name, q]) => ({ name, resourceId: q.resource.id }))\n }\n\n // byTag: prefer QuerySourceConfig.tags for static filtering; if tags are missing, conservatively fall back to refreshing all.\n const entries = Object.entries(queries)\n const tagged = entries.filter(([, q]) => Array.isArray(q.tags) && q.tags.includes(request.tag))\n const selected = tagged.length > 0 ? tagged : entries\n return selected.map(([name, q]) => ({ name, resourceId: q.resource.id }))\n}\n\nexport const invalidate = <Sh extends Logix.AnyModuleShape, TParams, TUI>(\n module: Logix.ModuleTagType<any, Sh>,\n config: InvalidateLogicConfig<TParams, TUI>,\n): Logix.ModuleLogic<Sh, any, never> =>\n module.logic(($) =>\n Effect.gen(function* () {\n yield* $.onAction('invalidate').runFork((action: any) =>\n Effect.gen(function* () {\n const request = action.payload as InvalidateRequest\n\n // 1) Eventize: goes into ReplayLog (kernel-owned).\n yield* Logix.TraitLifecycle.scopedExecute($ as any, {\n kind: 'query:invalidate',\n request,\n })\n\n // 2) Call external engine (optional): does not block the fallback path.\n const engineOpt = yield* Effect.serviceOption(Engine)\n if (engineOpt._tag !== 'None') {\n yield* engineOpt.value.invalidate(request)\n }\n\n // 3) Immediately refresh related sources (write-back gating is still guaranteed by kernel keyHash).\n const targets = toInvalidateTargets<TParams, TUI>(request, config.queries)\n const sourcePathOf = (name: string): string => `queries.${name}`\n yield* Effect.forEach(\n targets,\n (t) =>\n $.traits.source.refresh(sourcePathOf(t.name) as any, { force: true }) as Effect.Effect<void, never, any>,\n ).pipe(Effect.asVoid)\n }),\n )\n }),\n ) as Logix.ModuleLogic<Sh, any, never>\n","import * as Logix from '@logixjs/core'\n\nexport type QueryTrigger = 'onMount' | 'onKeyChange' | 'manual'\n\nexport type QueryConcurrency = 'switch' | 'exhaust'\n\nexport type QueryResourceRef = { readonly id: string }\n\nexport type QueryResource = QueryResourceRef | Logix.Resource.ResourceSpec<any, any, any, any>\n\nexport type QueryResourceKey<R> = R extends Logix.Resource.ResourceSpec<infer Key, any, any, any> ? Key : unknown\n\nexport type QueryResourceData<R> = R extends Logix.Resource.ResourceSpec<any, infer Data, any, any> ? Data : unknown\n\nexport type QueryResourceError<R> = R extends Logix.Resource.ResourceSpec<any, any, infer Err, any> ? Err : unknown\n\nexport type QueryKeyState<TParams, TUI> = Readonly<{\n readonly params: TParams\n readonly ui: TUI\n}>\n\nexport type QueryDepsPath<TParams, TUI> = Logix.StateTrait.StateFieldPath<QueryKeyState<TParams, TUI>>\n\ntype DepsArgs<S extends object, Deps extends ReadonlyArray<string>> = {\n readonly [K in keyof Deps]: Deps[K] extends Logix.StateTrait.StateFieldPath<S>\n ? Logix.StateTrait.StateAtPath<S, Deps[K]>\n : any\n}\n\ntype BivariantCallback<Args extends ReadonlyArray<any>, R> = {\n bivarianceHack(...args: Args): R\n}['bivarianceHack']\n\nexport interface QuerySourceConfig<\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n> {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n /**\n * Optional static tags for invalidate(byTag), used to narrow byTag from \"refresh all\" to a matched subset.\n * - Must be serializable (recommend: string constants only)\n * - If omitted, byTag conservatively falls back to refreshing everything\n */\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: BivariantCallback<DepsArgs<QueryKeyState<TParams, TUI>, Deps>, QueryResourceKey<R> | undefined>\n}\n\nexport type QueryBuilder<TParams, TUI> = {\n readonly source: <\n R extends QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n >(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n }) => QuerySourceConfig<TParams, TUI, R, Deps>\n}\n\n/**\n * Query.source:\n * - Strongly typed helper to preserve `deps` as a tuple and infer `key(...depsValues)` argument types from it.\n * - Recommended usage inside `Query.make(..., { queries: { name: Query.source({ ... }) } })`.\n */\nexport const source = <\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n>(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n}): QuerySourceConfig<TParams, TUI, R, Deps> => config as QuerySourceConfig<TParams, TUI, R, Deps>\n\nexport interface QueryTraitsInput<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI, any>>>\n}\n\n/**\n * Lowering rules (Query -> StateTrait):\n * - Each Query rule maps to a `StateTrait.source`, writing back to `queries.<name>` (isomorphic to module state).\n * - keySelector computes key from `{ params; ui }`; keyHash/race gating is guaranteed by the kernel source runtime.\n *\n * Notes:\n * - deps uses module-root paths (e.g. \"params.q\" / \"ui.query.autoEnabled\"), aligned with the constraints in 007/004.\n * - concurrency \"exhaust\" is represented as \"exhaust-trailing\" in the kernel.\n */\nexport const toStateTraitSpec = <TParams, TUI>(\n input: QueryTraitsInput<TParams, TUI>,\n): Logix.StateTrait.StateTraitSpec<any> => {\n const out: Record<string, Logix.StateTrait.StateTraitEntry<any, any>> = {}\n\n for (const [name, q] of Object.entries(input.queries)) {\n const triggers = q.triggers ?? (['onMount', 'onKeyChange'] as const)\n\n // \"manual\" must be exclusive to avoid ambiguous semantics (configuration error).\n if (triggers.includes('manual') && triggers.length > 1) {\n throw new Error(\n `[Query.traits] \"manual\" must be exclusive, but got triggers=[${triggers.join(', ')}] for query \"${name}\".`,\n )\n }\n\n out[`queries.${name}`] = Logix.StateTrait.source({\n // deps: used for graph building/diagnostics/future reverse-closure; Query also reuses deps to converge triggers.\n deps: q.deps as any,\n resource: q.resource.id,\n triggers,\n debounceMs: q.debounceMs,\n concurrency: q.concurrency === 'exhaust' ? 'exhaust-trailing' : q.concurrency,\n key: (...depsValues: ReadonlyArray<any>) => (q.key as any)(...depsValues),\n })\n }\n\n return out as Logix.StateTrait.StateTraitSpec<any>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,SAAuB;AACvB,IAAAC,iBAA+B;;;ACD/B,YAAuB;AACvB,IAAAC,iBAAwC;;;ACAxC,IAAAC,iBAA+C;;;ACA/C,oBAA+B;AAiBxB,IAAM,aAAa,CAAC,WACxB,uBAAM;AAGL,MAAI;AAEJ,SAAO,CAAC,OAAO;AACb,QAAK,GAAG,SAAS,aAAa,GAAG,SAAS,kBAAmB,CAAC,GAAG,MAAM,cAAc,CAAC,GAAG,KAAK,SAAS;AACrG,aAAO,GAAG;AAAA,IACZ;AAEA,UAAM,aAAa,GAAG,KAAK;AAC3B,QAAI,QAAQ,UAAU,CAAC,OAAO,OAAO,UAAU,GAAG;AAChD,aA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A,UAAU,QAAQ;AAAA,QAClB;AAAA,QACD,YAAY;AAAA,UACV,WAAW,CAAC,WAAoB,SAAS,QAAQ,UAAU,MAAM,CAAC;AAAA,UAClE,OAAO,CAAC,OAAY,SAAS,QAAQ,MAAM,EAAE,CAAC;AAAA,UAC9C,SAAS,CAAC,WAAgC,SAAS,QAAQ,QAAQ,MAAM,CAAC;AAAA,UACzE,YAAY,CAAC,YAA+B,SAAS,QAAQ,WAAW,OAAO,CAAC;AAAA,QAClF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAED,EAACA,QAAe,aAAa;AAE9B,QAAM,gBAAgB,uBAAO,IAAI,4BAA4B;AAC5D,EAACA,QAAO,IAAY,aAAa,IAAI,CACpC,SACA,SACG;AACH,UAAM,IAAI,WAAW,KAAK,OAAO;AACjC,WAAO;AAAA,MACL,GAAG;AAAA,MACH,YAAY,EAAE;AAAA,IAChB;AAAA,EACF;AAEA,SAAOA,QAAO,UAAU;AAAA,IACtB,SAAS,QAAQ;AAAA,IACjB,QAAQ,CAAC,GAAG,MAAM;AAAA,EACpB,CAAC;AACH;","names":["Logix","import_effect","import_effect","import_effect","module","Logix","import_effect","module","Logix","module"]}
1
+ {"version":3,"sources":["../src/Query.ts","../src/internal/logics/auto-trigger.ts","../src/Engine.ts","../src/internal/middleware/middleware.ts","../src/internal/logics/invalidate.ts","../src/Traits.ts"],"sourcesContent":["import * as Logix from '@logixjs/core'\nimport { Effect, Schema } from 'effect'\nimport { autoTrigger } from './internal/logics/auto-trigger.js'\nimport { invalidate } from './internal/logics/invalidate.js'\nimport type { InvalidateRequest } from './Engine.js'\nimport { toStateTraitSpec, type QueryBuilder, type QuerySourceConfig, type QueryResourceData, type QueryResourceError } from './Traits.js'\n\ntype AnyQuerySourceConfig<TParams, TUI> = QuerySourceConfig<TParams, TUI, any, any>\n\ntype EnsureQueries<TParams, TUI, TQueries> = TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>>\n ? {}\n : {\n readonly __queries_must_be_QuerySourceConfig__: never\n }\n\ntype QueriesOf<TParams, TUI, TQueries> = TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> ? TQueries : never\n\nexport type QueryState<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly params: TParams\n readonly ui: TUI\n readonly queries: {\n readonly [K in keyof TQueries]: Logix.Resource.ResourceSnapshot<\n QueryResourceData<TQueries[K]['resource']>,\n QueryResourceError<TQueries[K]['resource']>\n >\n }\n}\n\nexport type QueryName<TQueries extends Record<string, any>> = Extract<keyof TQueries, string>\n\ntype ForbiddenQueryName = 'params' | 'ui' | 'queries'\ntype ForbidQueryNames = {\n readonly [K in ForbiddenQueryName]?: never\n}\n\nexport type QueryActions<TParams, TUI = unknown, TQueries extends Record<string, any> = {}> = {\n readonly setParams: Schema.Schema<TParams, any>\n readonly setUi: Schema.Schema<TUI, any>\n readonly refresh: Schema.Schema<QueryName<TQueries> | undefined, any>\n readonly invalidate: Schema.Schema<InvalidateRequest, any>\n}\n\nexport type QueryShape<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.Shape<Schema.Schema<QueryState<TParams, TUI, TQueries>, any>, QueryActions<TParams, TUI, TQueries>>\n\nexport type QueryAction<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.ActionOf<QueryShape<TParams, TUI, TQueries>>\n\nexport interface QueryMakeConfig<\n TParams,\n TUI = unknown,\n TQueries = {},\n> {\n readonly params: Schema.Schema<TParams, any>\n readonly initialParams: TParams\n readonly ui?: TUI\n readonly queries?: (q: QueryBuilder<TParams, TUI>) => TQueries & ForbidQueryNames\n readonly traits?: unknown\n}\n\nexport interface QueryController<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> {\n readonly runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, TQueries>, QueryAction<TParams, TUI, TQueries>>\n readonly getState: Effect.Effect<QueryState<TParams, TUI, TQueries>>\n readonly dispatch: (action: QueryAction<TParams, TUI, TQueries>) => Effect.Effect<void>\n\n readonly controller: {\n readonly setParams: (params: TParams) => Effect.Effect<void>\n readonly setUi: (ui: TUI) => Effect.Effect<void>\n readonly refresh: (target?: QueryName<TQueries>) => Effect.Effect<void>\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void>\n }\n}\n\nexport type QueryModuleController<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly make: (\n runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, TQueries>, QueryAction<TParams, TUI, TQueries>>,\n ) => QueryController<TParams, TUI, TQueries>\n}\n\nexport type QueryHandleExt<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly controller: QueryController<TParams, TUI, TQueries>['controller']\n}\n\nexport type QueryModule<\n Id extends string,\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.Module.Module<Id, QueryShape<TParams, TUI, TQueries>, QueryHandleExt<TParams, TUI, TQueries>, any> & {\n readonly controller: QueryModuleController<TParams, TUI, TQueries>\n}\n\nconst InvalidateRequestSchema = Schema.Union(\n Schema.Struct({\n kind: Schema.Literal('byResource'),\n resourceId: Schema.String,\n }),\n Schema.Struct({\n kind: Schema.Literal('byParams'),\n resourceId: Schema.String,\n keyHash: Schema.String,\n }),\n Schema.Struct({\n kind: Schema.Literal('byTag'),\n tag: Schema.String,\n }),\n) as Schema.Schema<InvalidateRequest, any>\n\nconst assertQueryName = (name: string): void => {\n if (!name) {\n throw new Error(`[Query.make] query name must be non-empty`)\n }\n if (name.includes('.')) {\n throw new Error(`[Query.make] query name must not include \".\"; got \"${name}\"`)\n }\n if (name === 'params' || name === 'ui' || name === 'queries') {\n throw new Error(`[Query.make] query name \"${name}\" is reserved`)\n }\n}\n\nexport const make = <\n Id extends string,\n TParams,\n TUI = unknown,\n const TQueries = {},\n>(\n id: Id,\n config: QueryMakeConfig<TParams, TUI, TQueries> & EnsureQueries<TParams, TUI, TQueries>,\n): QueryModule<Id, TParams, TUI, QueriesOf<TParams, TUI, TQueries>> => {\n type Queries = QueriesOf<TParams, TUI, TQueries>\n const queryBuilder: QueryBuilder<TParams, TUI> = {\n source: (q: any) => q,\n }\n\n\t const queries = ((): Queries => {\n\t const raw = config.queries\n\t if (!raw) return {} as Queries\n\t return raw(queryBuilder) as Queries\n\t })()\n\n const queriesForTraits: Readonly<Record<string, AnyQuerySourceConfig<TParams, TUI>>> = queries\n for (const name of Object.keys(queries)) {\n assertQueryName(name)\n }\n\n\t const RefreshTargetSchema = (() => {\n\t const names = Object.keys(queries) as Array<QueryName<Queries>>\n\t if (names.length === 0) return Schema.Never as unknown as Schema.Schema<QueryName<Queries>, any>\n\t if (names.length === 1) {\n\t return Schema.Literal(names[0] as any) as unknown as Schema.Schema<QueryName<Queries>, any>\n\t }\n const asUnionMembers = <A>(items: ReadonlyArray<A>): readonly [A, A, ...Array<A>] => {\n if (items.length < 2) {\n throw new Error(`[Query.make] internal error: expected at least 2 query names for union`)\n }\n return items as unknown as readonly [A, A, ...Array<A>]\n }\n\n\t const members = names.map((n) => Schema.Literal(n as any))\n\t return Schema.Union(...asUnionMembers(members)) as unknown as Schema.Schema<QueryName<Queries>, any>\n\t })()\n\n const UiSchema = Schema.Unknown as Schema.Schema<TUI, any>\n\n\t const QueriesSchema = Schema.Struct(\n\t Object.fromEntries((Object.keys(queries) as Array<keyof Queries>).map((k) => [k, Schema.Unknown])) as Record<\n\t string,\n\t Schema.Schema<any, any>\n\t >,\n\t )\n\n const StateSchema = Schema.Struct({\n params: config.params,\n ui: UiSchema,\n queries: QueriesSchema,\n }) as unknown as Schema.Schema<QueryState<TParams, TUI, Queries>, any>\n\n const Actions = {\n setParams: config.params,\n setUi: UiSchema,\n refresh: Schema.UndefinedOr(RefreshTargetSchema),\n invalidate: InvalidateRequestSchema,\n } satisfies QueryActions<TParams, TUI, Queries>\n\n type Reducers = Logix.ReducersFromMap<typeof StateSchema, typeof Actions>\n\n const reducers: Reducers = {\n setParams: (state, action, sink) => {\n sink?.('params')\n return { ...state, params: action.payload ?? state.params }\n },\n setUi: (state, action, sink) => {\n sink?.('ui')\n return { ...state, ui: action.payload ?? state.ui }\n },\n refresh: (state) => state,\n invalidate: (state) => state,\n } satisfies Reducers\n\n const queryTraits =\n Object.keys(queriesForTraits).length > 0 ? toStateTraitSpec<TParams, TUI>({ queries: queriesForTraits }) : undefined\n\n const traits =\n queryTraits || config.traits\n ? ({\n ...(queryTraits as any),\n ...(config.traits as any),\n } as any)\n : undefined\n\n const module = Logix.Module.make(id, {\n state: StateSchema,\n actions: Actions,\n reducers,\n traits,\n })\n\n const logics = [\n autoTrigger<any, TParams, TUI>(module.tag as any, { queries: queriesForTraits }),\n invalidate<any, TParams, TUI>(module.tag as any, { queries: queriesForTraits }),\n ] satisfies ReadonlyArray<Logix.ModuleLogic<any, any, any>>\n\n const initial = (params?: TParams): QueryState<TParams, TUI, Queries> =>\n ({\n params: params ?? config.initialParams,\n ui: (config.ui ?? ({} as unknown as TUI)) as TUI,\n queries: Object.fromEntries(\n (Object.keys(queries) as Array<keyof Queries>).map((k) => [k, Logix.Resource.Snapshot.idle()]),\n ),\n }) as QueryState<TParams, TUI, Queries>\n\n\t const controller: QueryModuleController<TParams, TUI, Queries> = {\n\t make: (\n\t runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, Queries>, QueryAction<TParams, TUI, Queries>>,\n\t ): QueryController<TParams, TUI, Queries> => {\n\t const dispatch = runtime.dispatch\n\t const actions = module.actions as unknown as {\n\t readonly setParams: (params: TParams) => QueryAction<TParams, TUI, Queries>\n\t readonly setUi: (ui: TUI) => QueryAction<TParams, TUI, Queries>\n\t readonly refresh: (target: QueryName<Queries> | undefined) => QueryAction<TParams, TUI, Queries>\n\t readonly invalidate: (request: InvalidateRequest) => QueryAction<TParams, TUI, Queries>\n\t }\n\t\t return {\n\t\t runtime,\n\t\t getState: runtime.getState as Effect.Effect<QueryState<TParams, TUI, Queries>>,\n\t\t dispatch,\n\t controller: {\n\t setParams: (params: TParams) => dispatch(actions.setParams(params)),\n\t setUi: (ui: TUI) => dispatch(actions.setUi(ui)),\n\t refresh: (target?: QueryName<Queries>) => dispatch(actions.refresh(target)),\n\t\t invalidate: (request: InvalidateRequest) => dispatch(actions.invalidate(request)),\n\t\t },\n\t\t } as QueryController<TParams, TUI, Queries>\n\t\t },\n\t\t }\n\n ;(module as any).controller = controller\n\n const EXTEND_HANDLE = Symbol.for('logix.module.handle.extend')\n ;(module.tag as any)[EXTEND_HANDLE] = (\n runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, Queries>, QueryAction<TParams, TUI, Queries>>,\n base: Logix.ModuleHandle<any>,\n ) => {\n const c = controller.make(runtime)\n return {\n ...base,\n controller: c.controller,\n }\n }\n\n return module.implement({\n initial: initial(),\n logics: [...logics],\n }) as unknown as QueryModule<Id, TParams, TUI, Queries>\n}\n","import * as Logix from '@logixjs/core'\nimport { Duration, Effect, Fiber } from 'effect'\nimport type { QuerySourceConfig, QueryTrigger } from '../../Traits.js'\nimport { Engine } from '../../Engine.js'\n\nconst defaultTriggers = ['onMount', 'onKeyChange'] as const\n\nconst getTriggers = (triggers: ReadonlyArray<QueryTrigger> | undefined): ReadonlyArray<QueryTrigger> =>\n triggers ?? defaultTriggers\n\nconst isManualOnly = (triggers: ReadonlyArray<QueryTrigger>): boolean =>\n triggers.length === 1 && triggers[0] === 'manual'\n\nconst getSnapshotKeyHash = (snapshot: unknown): string | undefined => {\n if (!snapshot || typeof snapshot !== 'object') return undefined\n const keyHash = (snapshot as any).keyHash\n return typeof keyHash === 'string' ? keyHash : undefined\n}\n\nconst getSnapshotStatus = (snapshot: unknown): string | undefined => {\n if (!snapshot || typeof snapshot !== 'object') return undefined\n const status = (snapshot as any).status\n return typeof status === 'string' ? status : undefined\n}\n\nexport interface AutoTriggerLogicConfig<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>\n}\n\n/**\n * Query auto-trigger logic:\n * - onMount: triggers once on initialization (if the key is valid and current snapshot does not match the same keyHash).\n * - onKeyChange: triggers after params/ui state changes (can debounce; only when keyHash changes or current is idle).\n * - manual-only: when triggers=[\"manual\"], disable onMount/onKeyChange auto triggering.\n */\nexport const autoTrigger = <Sh extends Logix.AnyModuleShape, TParams, TUI>(\n module: Logix.ModuleTagType<any, Sh>,\n config: AutoTriggerLogicConfig<TParams, TUI>,\n): Logix.ModuleLogic<Sh, any, never> =>\n module.logic(($) => {\n type _State = Logix.StateOf<Sh> & { readonly queries: Record<string, unknown> }\n type QueryName = Extract<keyof typeof config.queries, string>\n\n const pending = new Map<string, Fiber.RuntimeFiber<void, any>>()\n const lastKeyHash = new Map<string, string | undefined>()\n\n const hydrateFromFreshCache = (\n name: QueryName,\n q: QuerySourceConfig<TParams, TUI>,\n keyHash: string,\n ): Effect.Effect<boolean, never, any> =>\n Effect.gen(function* () {\n const engineOpt = yield* Effect.serviceOption(Engine)\n if (engineOpt._tag === 'None') return false\n\n const engine = engineOpt.value\n if (!engine.peekFresh) return false\n\n const dataOpt = yield* engine.peekFresh({\n resourceId: q.resource.id,\n keyHash,\n })\n if (dataOpt._tag === 'None') return false\n\n const snapshot = Logix.Resource.Snapshot.success({\n keyHash,\n data: dataOpt.value,\n })\n yield* $.state.mutate((draft) => {\n ;(draft as Logix.Logic.Draft<_State>).queries[name] = snapshot\n })\n\n return true\n })\n\n const cancelPending = (name: string): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n const prev = pending.get(name)\n if (!prev) return\n pending.delete(name)\n yield* Fiber.interruptFork(prev)\n })\n\n const sourcePathOf = (name: QueryName): string => `queries.${name}`\n\n const refresh = (name: QueryName, options?: { readonly force?: boolean }): Effect.Effect<void, never, any> =>\n $.traits.source.refresh(sourcePathOf(name) as any, options as any) as Effect.Effect<void, never, any>\n\n const scheduleDebounced = (name: QueryName, ms: number): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n yield* cancelPending(name)\n const fiber = yield* Effect.forkScoped(\n Effect.sleep(Duration.millis(ms)).pipe(\n Effect.zipRight(refresh(name)),\n Effect.ensuring(Effect.sync(() => pending.delete(name))),\n Effect.catchAllCause(() => Effect.void),\n ),\n )\n pending.set(name, fiber)\n })\n\n const computeKeyHash = (state: any, q: QuerySourceConfig<TParams, TUI>): string | undefined => {\n const getAtPath = (root: any, path: string): unknown => {\n const parts = path.split('.')\n let cur = root\n for (const p of parts) {\n if (cur == null) return undefined\n cur = cur[p]\n }\n return cur\n }\n\n try {\n const keyState = { params: state.params as any, ui: state.ui as any } as any\n const args = (q.deps as ReadonlyArray<string>).map((dep) => getAtPath(keyState, dep))\n const key = (q.key as any)(...args)\n if (key === undefined) return undefined\n return Logix.Resource.keyHash(key)\n } catch {\n return undefined\n }\n }\n\n const maybeAutoRefresh = (\n phase: 'mount' | 'keyChange',\n stateOverride?: unknown,\n ): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n const state = (stateOverride ?? (yield* $.state.read)) as any\n\n for (const [name, q] of Object.entries(config.queries)) {\n const queryName = name as QueryName\n const triggers = getTriggers(q.triggers)\n if (isManualOnly(triggers)) {\n continue\n }\n\n if (phase === 'mount' && !triggers.includes('onMount')) {\n continue\n }\n\n if (phase === 'keyChange' && !triggers.includes('onKeyChange')) {\n continue\n }\n\n const keyHash = computeKeyHash(state, q)\n const snapshot = state?.queries?.[queryName]\n const snapshotKeyHash = getSnapshotKeyHash(snapshot)\n const snapshotStatus = getSnapshotStatus(snapshot)\n\n // Key is unavailable: do not refresh (idle reaping is guaranteed by kernel syncIdleInTransaction).\n if (keyHash === undefined) {\n lastKeyHash.set(queryName, undefined)\n continue\n }\n\n // keyHash unchanged and we already have a non-idle snapshot: avoid re-entering loading (reuse existing result).\n const last = lastKeyHash.get(queryName)\n if (snapshotStatus && snapshotStatus !== 'idle' && snapshotKeyHash === keyHash && last === keyHash) {\n continue\n }\n\n // If current snapshot is already success/error/loading with the same keyHash: update lastKeyHash and skip.\n if (snapshotStatus && snapshotStatus !== 'idle' && snapshotKeyHash === keyHash) {\n lastKeyHash.set(queryName, keyHash)\n continue\n }\n\n lastKeyHash.set(queryName, keyHash)\n\n // TanStack Query scenario: if we can hit the fresh cache, write a success snapshot directly,\n // skipping source.refresh (avoids UI jitter and extra transactions like \"cache hit but still loading -> success\").\n const hydrated = yield* hydrateFromFreshCache(queryName, q, keyHash)\n if (hydrated) {\n yield* cancelPending(queryName)\n continue\n }\n\n const debounceMs = q.debounceMs ?? 0\n if (phase === 'keyChange' && debounceMs > 0) {\n yield* scheduleDebounced(queryName, debounceMs)\n } else {\n // mount / no debounce: trigger immediately\n yield* cancelPending(queryName)\n yield* refresh(queryName)\n }\n }\n })\n\n const refreshAll = (options?: { readonly force?: boolean }): Effect.Effect<void, never, any> =>\n Effect.forEach(Object.keys(config.queries), (name) =>\n cancelPending(name).pipe(Effect.zipRight(refresh(name as QueryName, options))),\n ).pipe(Effect.asVoid)\n\n const setup = $.lifecycle.onStart(maybeAutoRefresh('mount'))\n\n const run = Effect.suspend(() =>\n Effect.all(\n [\n // params/ui changes: handled by Query's default logic, avoiding scattered UI-side useEffect triggers.\n $.onAction('setParams').runFork((action: any) =>\n Effect.gen(function* () {\n const state = (yield* $.state.read) as any\n const next = { ...state, params: action.payload }\n yield* maybeAutoRefresh('keyChange', next)\n }),\n ),\n $.onAction('setUi').runFork((action: any) =>\n Effect.gen(function* () {\n const state = (yield* $.state.read) as any\n const next = { ...state, ui: action.payload }\n yield* maybeAutoRefresh('keyChange', next)\n }),\n ),\n\n // Manual refresh: not restricted by triggers (manual-only still allows explicit refresh).\n $.onAction('refresh').runFork((action: any) =>\n Effect.gen(function* () {\n const target = action.payload as QueryName | undefined\n if (typeof target === 'string' && target.length > 0) {\n yield* cancelPending(target)\n yield* refresh(target, { force: true })\n } else {\n yield* refreshAll({ force: true })\n }\n }),\n ),\n ],\n { concurrency: 'unbounded' },\n ).pipe(Effect.asVoid),\n )\n\n return { setup, run }\n }) as Logix.ModuleLogic<Sh, any, never>\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport type { JsonValue } from '@logixjs/core/Observability'\nimport { Context, Effect, Layer, Option } from 'effect'\nimport { middleware as middlewareImpl, type MiddlewareConfig } from './internal/middleware/middleware.js'\n\nexport type InvalidateRequest =\n | { readonly kind: 'byResource'; readonly resourceId: string }\n | { readonly kind: 'byParams'; readonly resourceId: string; readonly keyHash: string }\n | { readonly kind: 'byTag'; readonly tag: string }\n\nexport interface Engine {\n readonly fetch: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n readonly effect: Effect.Effect<A, unknown, any>\n /**\n * MUST be serializable and slim; recommended default is undefined (lazy),\n * and only populate it when diagnostics/devtools require it.\n */\n readonly meta?: JsonValue\n }) => Effect.Effect<A, unknown, any>\n\n /**\n * perf: optional fast path to avoid allocations on the hot path.\n * Semantics must match `fetch({ ... })`.\n */\n readonly fetchFast?: <A>(\n resourceId: string,\n keyHash: string,\n effect: Effect.Effect<A, unknown, any>,\n meta?: JsonValue,\n ) => Effect.Effect<A, unknown, any>\n\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void, unknown, any>\n\n /**\n * Read-only fast path: must not trigger IO; used to short-circuit to success before refresh,\n * avoiding loading jitter.\n */\n readonly peekFresh?: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n }) => Effect.Effect<Option.Option<A>, never, any>\n}\n\nclass EngineTagImpl extends Context.Tag('@logixjs/query/Engine')<EngineTagImpl, Engine>() {}\n\nexport const Engine = Object.assign(EngineTagImpl, {\n layer: (engine: Engine): Layer.Layer<EngineTagImpl, never, never> => Layer.succeed(EngineTagImpl, engine),\n middleware: (config?: MiddlewareConfig): EffectOp.Middleware => middlewareImpl(config),\n})\n\nexport type { MiddlewareConfig }\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Effect, Option } from 'effect'\nimport { Engine } from '../../Engine.js'\nimport type { Engine as EngineService } from '../../Engine.js'\n\nexport interface MiddlewareConfig {\n /**\n * Default: only applies to EffectOp that carries resourceId+keyHash (from StateTrait.source).\n * Optional: further filter by resourceId.\n */\n readonly useFor?: (resourceId: string) => boolean\n}\n\n/**\n * Query middleware (EffectOp): external engine takeover point.\n * - Delegates ResourceSpec.load execution to Engine (cache / in-flight dedupe / invalidation, etc.)\n * - Still preserves Logix Runtime's keyHash gating and ResourceSnapshot source-of-truth semantics\n */\nexport const middleware = (config?: MiddlewareConfig): EffectOp.Middleware =>\n (() => {\n // perf: within the same Runtime instance, Engine injection is stable.\n // Cache it in the middleware closure to avoid a Context lookup on every fetch.\n let cachedEngine: EngineService | undefined\n\n return (op) => {\n if ((op.kind !== 'service' && op.kind !== 'trait-source') || !op.meta?.resourceId || !op.meta.keyHash) {\n return op.effect as any\n }\n\n const resourceId = op.meta.resourceId\n if (config?.useFor && !config.useFor(resourceId)) {\n return op.effect as any\n }\n\n const keyHash = op.meta.keyHash as string\n\n if (cachedEngine) {\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }\n\n return Effect.serviceOption(Engine).pipe(\n Effect.flatMap((engineOpt) => {\n if (Option.isNone(engineOpt)) {\n return Effect.fail(\n new Error(\n `[Query.Engine.middleware] Missing Query.Engine in the Runtime scope; please provide Query.Engine.layer(Query.TanStack.engine(new QueryClient())) (recommended) or Query.Engine.layer(customEngine).`,\n ),\n )\n }\n cachedEngine = engineOpt.value\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }),\n ) as any\n }\n })()\n","import * as Logix from '@logixjs/core'\nimport { Effect } from 'effect'\nimport { Engine, type InvalidateRequest } from '../../Engine.js'\nimport type { QuerySourceConfig } from '../../Traits.js'\n\nexport interface InvalidateLogicConfig<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>\n}\n\nconst toInvalidateTargets = <TParams, TUI>(\n request: InvalidateRequest,\n queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>,\n): ReadonlyArray<{ readonly name: string; readonly resourceId: string }> => {\n if (request.kind === 'byResource') {\n return Object.entries(queries)\n .filter(([, q]) => q.resource.id === request.resourceId)\n .map(([name, q]) => ({ name, resourceId: q.resource.id }))\n }\n\n if (request.kind === 'byParams') {\n return Object.entries(queries)\n .filter(([, q]) => q.resource.id === request.resourceId)\n .map(([name, q]) => ({ name, resourceId: q.resource.id }))\n }\n\n // byTag: prefer QuerySourceConfig.tags for static filtering; if tags are missing, conservatively fall back to refreshing all.\n const entries = Object.entries(queries)\n const tagged = entries.filter(([, q]) => Array.isArray(q.tags) && q.tags.includes(request.tag))\n const selected = tagged.length > 0 ? tagged : entries\n return selected.map(([name, q]) => ({ name, resourceId: q.resource.id }))\n}\n\nexport const invalidate = <Sh extends Logix.AnyModuleShape, TParams, TUI>(\n module: Logix.ModuleTagType<any, Sh>,\n config: InvalidateLogicConfig<TParams, TUI>,\n): Logix.ModuleLogic<Sh, any, never> =>\n module.logic(($) =>\n Effect.gen(function* () {\n yield* $.onAction('invalidate').runFork((action: any) =>\n Effect.gen(function* () {\n const request = action.payload as InvalidateRequest\n\n // 1) Eventize: goes into ReplayLog (kernel-owned).\n yield* Logix.TraitLifecycle.scopedExecute($ as any, {\n kind: 'query:invalidate',\n request,\n })\n\n // 2) Call external engine (optional): does not block the fallback path.\n const engineOpt = yield* Effect.serviceOption(Engine)\n if (engineOpt._tag !== 'None') {\n yield* engineOpt.value.invalidate(request)\n }\n\n // 3) Immediately refresh related sources (write-back gating is still guaranteed by kernel keyHash).\n const targets = toInvalidateTargets<TParams, TUI>(request, config.queries)\n const sourcePathOf = (name: string): string => `queries.${name}`\n yield* Effect.forEach(\n targets,\n (t) =>\n $.traits.source.refresh(sourcePathOf(t.name) as any, { force: true }) as Effect.Effect<void, never, any>,\n ).pipe(Effect.asVoid)\n }),\n )\n }),\n ) as Logix.ModuleLogic<Sh, any, never>\n","import * as Logix from '@logixjs/core'\n\nexport type QueryTrigger = 'onMount' | 'onKeyChange' | 'manual'\n\nexport type QueryConcurrency = 'switch' | 'exhaust'\n\nexport type QueryResourceRef = { readonly id: string }\n\nexport type QueryResource = QueryResourceRef | Logix.Resource.ResourceSpec<any, any, any, any>\n\nexport type QueryResourceKey<R> = R extends Logix.Resource.ResourceSpec<infer Key, any, any, any> ? Key : unknown\n\nexport type QueryResourceData<R> = R extends Logix.Resource.ResourceSpec<any, infer Data, any, any> ? Data : unknown\n\nexport type QueryResourceError<R> = R extends Logix.Resource.ResourceSpec<any, any, infer Err, any> ? Err : unknown\n\nexport type QueryKeyState<TParams, TUI> = Readonly<{\n readonly params: TParams\n readonly ui: TUI\n}>\n\nexport type QueryDepsPath<TParams, TUI> = Logix.StateTrait.StateFieldPath<QueryKeyState<TParams, TUI>>\n\ntype DepsArgs<S extends object, Deps extends ReadonlyArray<string>> = {\n readonly [K in keyof Deps]: Deps[K] extends Logix.StateTrait.StateFieldPath<S>\n ? Logix.StateTrait.StateAtPath<S, Deps[K]>\n : any\n}\n\ntype BivariantCallback<Args extends ReadonlyArray<any>, R> = {\n bivarianceHack(...args: Args): R\n}['bivarianceHack']\n\nexport interface QuerySourceConfig<\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n> {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n /**\n * Optional exportable trait meta (Devtools / Static IR / docs).\n *\n * Constraints:\n * - Must be serializable (JsonValue only); no closures/functions/Effect/DOM objects.\n * - Keep it slim; use `annotations` with `x-*` keys for extension hints.\n */\n readonly meta?: Logix.StateTrait.TraitMeta\n /**\n * Optional static tags for invalidate(byTag), used to narrow byTag from \"refresh all\" to a matched subset.\n * - Must be serializable (recommend: string constants only)\n * - If omitted, byTag conservatively falls back to refreshing everything\n */\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: BivariantCallback<DepsArgs<QueryKeyState<TParams, TUI>, Deps>, QueryResourceKey<R> | undefined>\n}\n\nexport type QueryBuilder<TParams, TUI> = {\n readonly source: <\n R extends QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n >(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly meta?: Logix.StateTrait.TraitMeta\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n }) => QuerySourceConfig<TParams, TUI, R, Deps>\n}\n\n/**\n * Query.source:\n * - Strongly typed helper to preserve `deps` as a tuple and infer `key(...depsValues)` argument types from it.\n * - Recommended usage inside `Query.make(..., { queries: { name: Query.source({ ... }) } })`.\n */\nexport const source = <\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n>(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly meta?: Logix.StateTrait.TraitMeta\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n}): QuerySourceConfig<TParams, TUI, R, Deps> => config as QuerySourceConfig<TParams, TUI, R, Deps>\n\nexport interface QueryTraitsInput<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI, any>>>\n}\n\n/**\n * Lowering rules (Query -> StateTrait):\n * - Each Query rule maps to a `StateTrait.source`, writing back to `queries.<name>` (isomorphic to module state).\n * - keySelector computes key from `{ params; ui }`; keyHash/race gating is guaranteed by the kernel source runtime.\n *\n * Notes:\n * - deps uses module-root paths (e.g. \"params.q\" / \"ui.query.autoEnabled\"), aligned with the constraints in 007/004.\n * - concurrency \"exhaust\" is represented as \"exhaust-trailing\" in the kernel.\n */\nexport const toStateTraitSpec = <TParams, TUI>(\n input: QueryTraitsInput<TParams, TUI>,\n): Logix.StateTrait.StateTraitSpec<any> => {\n const out: Record<string, Logix.StateTrait.StateTraitEntry<any, any>> = {}\n\n for (const [name, q] of Object.entries(input.queries)) {\n const triggers = q.triggers ?? (['onMount', 'onKeyChange'] as const)\n\n // \"manual\" must be exclusive to avoid ambiguous semantics (configuration error).\n if (triggers.includes('manual') && triggers.length > 1) {\n throw new Error(\n `[Query.traits] \"manual\" must be exclusive, but got triggers=[${triggers.join(', ')}] for query \"${name}\".`,\n )\n }\n\n out[`queries.${name}`] = Logix.StateTrait.source({\n // deps: used for graph building/diagnostics/future reverse-closure; Query also reuses deps to converge triggers.\n deps: q.deps as any,\n resource: q.resource.id,\n triggers,\n debounceMs: q.debounceMs,\n concurrency: q.concurrency === 'exhaust' ? 'exhaust-trailing' : q.concurrency,\n key: (...depsValues: ReadonlyArray<any>) => (q.key as any)(...depsValues),\n meta: q.meta,\n })\n }\n\n return out as Logix.StateTrait.StateTraitSpec<any>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,SAAuB;AACvB,IAAAC,iBAA+B;;;ACD/B,YAAuB;AACvB,IAAAC,iBAAwC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M,UAAU,CAAC,YACd;AAAA,IACC,QAAQ,UAAU,OAAO;AAAA,IACzB,IAAK,OAAO,MAAO,CAAC;AAAA,IACpB,SAAS,OAAO;AAAA,MACb,OAAO,KAAK,OAAO,EAA2B,IAAI,CAAC,MAAM,CAAC,GAAS,gBAAS,SAAS,KAAK,CAAC,CAAC;AAAA,IAC/F;AAAA,EACF;AAED,QAAM,aAA2D;AAAA,IAC/D,MAAM,CACJ,YAC2C;AAC3C,YAAM,WAAW,QAAQ;AACzB,YAAM,UAAUA,QAAO;AAMtB,aAAO;AAAA,QACL;AAAA,QACA,UAAU,QAAQ;AAAA,QAClB;AAAA,QACD,YAAY;AAAA,UACV,WAAW,CAAC,WAAoB,SAAS,QAAQ,UAAU,MAAM,CAAC;AAAA,UAClE,OAAO,CAAC,OAAY,SAAS,QAAQ,MAAM,EAAE,CAAC;AAAA,UAC9C,SAAS,CAAC,WAAgC,SAAS,QAAQ,QAAQ,MAAM,CAAC;AAAA,UACzE,YAAY,CAAC,YAA+B,SAAS,QAAQ,WAAW,OAAO,CAAC;AAAA,QAClF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAED,EAACA,QAAe,aAAa;AAE9B,QAAM,gBAAgB,uBAAO,IAAI,4BAA4B;AAC5D,EAACA,QAAO,IAAY,aAAa,IAAI,CACpC,SACA,SACG;AACH,UAAM,IAAI,WAAW,KAAK,OAAO;AACjC,WAAO;AAAA,MACL,GAAG;AAAA,MACH,YAAY,EAAE;AAAA,IAChB;AAAA,EACF;AAEA,SAAOA,QAAO,UAAU;AAAA,IACtB,SAAS,QAAQ;AAAA,IACjB,QAAQ,CAAC,GAAG,MAAM;AAAA,EACpB,CAAC;AACH;","names":["Logix","import_effect","import_effect","import_effect","module","Logix","import_effect","module","Logix","module"]}
package/dist/Query.d.cts CHANGED
@@ -3,6 +3,7 @@ import { Schema, Effect } from 'effect';
3
3
  import { InvalidateRequest } from './Engine.cjs';
4
4
  import { QuerySourceConfig, QueryResourceData, QueryResourceError, QueryBuilder } from './Traits.cjs';
5
5
  import '@logixjs/core/EffectOp';
6
+ import '@logixjs/core/Observability';
6
7
 
7
8
  type AnyQuerySourceConfig<TParams, TUI> = QuerySourceConfig<TParams, TUI, any, any>;
8
9
  type EnsureQueries<TParams, TUI, TQueries> = TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> ? {} : {
package/dist/Query.d.ts CHANGED
@@ -3,6 +3,7 @@ import { Schema, Effect } from 'effect';
3
3
  import { InvalidateRequest } from './Engine.js';
4
4
  import { QuerySourceConfig, QueryResourceData, QueryResourceError, QueryBuilder } from './Traits.js';
5
5
  import '@logixjs/core/EffectOp';
6
+ import '@logixjs/core/Observability';
6
7
 
7
8
  type AnyQuerySourceConfig<TParams, TUI> = QuerySourceConfig<TParams, TUI, any, any>;
8
9
  type EnsureQueries<TParams, TUI, TQueries> = TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> ? {} : {
package/dist/Query.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  make
3
- } from "./chunk-NXFX6RIH.js";
4
- import "./chunk-THVAADR2.js";
5
- import "./chunk-V3F5KWNH.js";
3
+ } from "./chunk-DMEHDC55.js";
4
+ import "./chunk-7IVR4THQ.js";
5
+ import "./chunk-BERAWANA.js";
6
6
  import "./chunk-PZ5AY32C.js";
7
7
  export {
8
8
  make
@@ -2,4 +2,5 @@ export { a as TanStackEngineConfig, e as engine, o as observe } from './TanStack
2
2
  import '@tanstack/query-core';
3
3
  import './Engine.cjs';
4
4
  import '@logixjs/core/EffectOp';
5
+ import '@logixjs/core/Observability';
5
6
  import 'effect';
@@ -2,4 +2,5 @@ export { a as TanStackEngineConfig, e as engine, o as observe } from './TanStack
2
2
  import '@tanstack/query-core';
3
3
  import './Engine.js';
4
4
  import '@logixjs/core/EffectOp';
5
+ import '@logixjs/core/Observability';
5
6
  import 'effect';
package/dist/Traits.cjs CHANGED
@@ -52,7 +52,8 @@ var toStateTraitSpec = (input) => {
52
52
  triggers,
53
53
  debounceMs: q.debounceMs,
54
54
  concurrency: q.concurrency === "exhaust" ? "exhaust-trailing" : q.concurrency,
55
- key: (...depsValues) => q.key(...depsValues)
55
+ key: (...depsValues) => q.key(...depsValues),
56
+ meta: q.meta
56
57
  });
57
58
  }
58
59
  return out;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Traits.ts"],"sourcesContent":["import * as Logix from '@logixjs/core'\n\nexport type QueryTrigger = 'onMount' | 'onKeyChange' | 'manual'\n\nexport type QueryConcurrency = 'switch' | 'exhaust'\n\nexport type QueryResourceRef = { readonly id: string }\n\nexport type QueryResource = QueryResourceRef | Logix.Resource.ResourceSpec<any, any, any, any>\n\nexport type QueryResourceKey<R> = R extends Logix.Resource.ResourceSpec<infer Key, any, any, any> ? Key : unknown\n\nexport type QueryResourceData<R> = R extends Logix.Resource.ResourceSpec<any, infer Data, any, any> ? Data : unknown\n\nexport type QueryResourceError<R> = R extends Logix.Resource.ResourceSpec<any, any, infer Err, any> ? Err : unknown\n\nexport type QueryKeyState<TParams, TUI> = Readonly<{\n readonly params: TParams\n readonly ui: TUI\n}>\n\nexport type QueryDepsPath<TParams, TUI> = Logix.StateTrait.StateFieldPath<QueryKeyState<TParams, TUI>>\n\ntype DepsArgs<S extends object, Deps extends ReadonlyArray<string>> = {\n readonly [K in keyof Deps]: Deps[K] extends Logix.StateTrait.StateFieldPath<S>\n ? Logix.StateTrait.StateAtPath<S, Deps[K]>\n : any\n}\n\ntype BivariantCallback<Args extends ReadonlyArray<any>, R> = {\n bivarianceHack(...args: Args): R\n}['bivarianceHack']\n\nexport interface QuerySourceConfig<\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n> {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n /**\n * Optional static tags for invalidate(byTag), used to narrow byTag from \"refresh all\" to a matched subset.\n * - Must be serializable (recommend: string constants only)\n * - If omitted, byTag conservatively falls back to refreshing everything\n */\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: BivariantCallback<DepsArgs<QueryKeyState<TParams, TUI>, Deps>, QueryResourceKey<R> | undefined>\n}\n\nexport type QueryBuilder<TParams, TUI> = {\n readonly source: <\n R extends QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n >(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n }) => QuerySourceConfig<TParams, TUI, R, Deps>\n}\n\n/**\n * Query.source:\n * - Strongly typed helper to preserve `deps` as a tuple and infer `key(...depsValues)` argument types from it.\n * - Recommended usage inside `Query.make(..., { queries: { name: Query.source({ ... }) } })`.\n */\nexport const source = <\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n>(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n}): QuerySourceConfig<TParams, TUI, R, Deps> => config as QuerySourceConfig<TParams, TUI, R, Deps>\n\nexport interface QueryTraitsInput<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI, any>>>\n}\n\n/**\n * Lowering rules (Query -> StateTrait):\n * - Each Query rule maps to a `StateTrait.source`, writing back to `queries.<name>` (isomorphic to module state).\n * - keySelector computes key from `{ params; ui }`; keyHash/race gating is guaranteed by the kernel source runtime.\n *\n * Notes:\n * - deps uses module-root paths (e.g. \"params.q\" / \"ui.query.autoEnabled\"), aligned with the constraints in 007/004.\n * - concurrency \"exhaust\" is represented as \"exhaust-trailing\" in the kernel.\n */\nexport const toStateTraitSpec = <TParams, TUI>(\n input: QueryTraitsInput<TParams, TUI>,\n): Logix.StateTrait.StateTraitSpec<any> => {\n const out: Record<string, Logix.StateTrait.StateTraitEntry<any, any>> = {}\n\n for (const [name, q] of Object.entries(input.queries)) {\n const triggers = q.triggers ?? (['onMount', 'onKeyChange'] as const)\n\n // \"manual\" must be exclusive to avoid ambiguous semantics (configuration error).\n if (triggers.includes('manual') && triggers.length > 1) {\n throw new Error(\n `[Query.traits] \"manual\" must be exclusive, but got triggers=[${triggers.join(', ')}] for query \"${name}\".`,\n )\n }\n\n out[`queries.${name}`] = Logix.StateTrait.source({\n // deps: used for graph building/diagnostics/future reverse-closure; Query also reuses deps to converge triggers.\n deps: q.deps as any,\n resource: q.resource.id,\n triggers,\n debounceMs: q.debounceMs,\n concurrency: q.concurrency === 'exhaust' ? 'exhaust-trailing' : q.concurrency,\n key: (...depsValues: ReadonlyArray<any>) => (q.key as any)(...depsValues),\n })\n }\n\n return out as Logix.StateTrait.StateTraitSpec<any>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAAuB;AAyEhB,IAAM,SAAS,CAKpB,WAQ8C;AAezC,IAAM,mBAAmB,CAC9B,UACyC;AACzC,QAAM,MAAkE,CAAC;AAEzE,aAAW,CAAC,MAAM,CAAC,KAAK,OAAO,QAAQ,MAAM,OAAO,GAAG;AACrD,UAAM,WAAW,EAAE,YAAa,CAAC,WAAW,aAAa;AAGzD,QAAI,SAAS,SAAS,QAAQ,KAAK,SAAS,SAAS,GAAG;AACtD,YAAM,IAAI;AAAA,QACR,gEAAgE,SAAS,KAAK,IAAI,CAAC,gBAAgB,IAAI;AAAA,MACzG;AAAA,IACF;AAEA,QAAI,WAAW,IAAI,EAAE,IAAU,iBAAW,OAAO;AAAA;AAAA,MAE/C,MAAM,EAAE;AAAA,MACR,UAAU,EAAE,SAAS;AAAA,MACrB;AAAA,MACA,YAAY,EAAE;AAAA,MACd,aAAa,EAAE,gBAAgB,YAAY,qBAAqB,EAAE;AAAA,MAClE,KAAK,IAAI,eAAoC,EAAE,IAAY,GAAG,UAAU;AAAA,IAC1E,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/Traits.ts"],"sourcesContent":["import * as Logix from '@logixjs/core'\n\nexport type QueryTrigger = 'onMount' | 'onKeyChange' | 'manual'\n\nexport type QueryConcurrency = 'switch' | 'exhaust'\n\nexport type QueryResourceRef = { readonly id: string }\n\nexport type QueryResource = QueryResourceRef | Logix.Resource.ResourceSpec<any, any, any, any>\n\nexport type QueryResourceKey<R> = R extends Logix.Resource.ResourceSpec<infer Key, any, any, any> ? Key : unknown\n\nexport type QueryResourceData<R> = R extends Logix.Resource.ResourceSpec<any, infer Data, any, any> ? Data : unknown\n\nexport type QueryResourceError<R> = R extends Logix.Resource.ResourceSpec<any, any, infer Err, any> ? Err : unknown\n\nexport type QueryKeyState<TParams, TUI> = Readonly<{\n readonly params: TParams\n readonly ui: TUI\n}>\n\nexport type QueryDepsPath<TParams, TUI> = Logix.StateTrait.StateFieldPath<QueryKeyState<TParams, TUI>>\n\ntype DepsArgs<S extends object, Deps extends ReadonlyArray<string>> = {\n readonly [K in keyof Deps]: Deps[K] extends Logix.StateTrait.StateFieldPath<S>\n ? Logix.StateTrait.StateAtPath<S, Deps[K]>\n : any\n}\n\ntype BivariantCallback<Args extends ReadonlyArray<any>, R> = {\n bivarianceHack(...args: Args): R\n}['bivarianceHack']\n\nexport interface QuerySourceConfig<\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n> {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n /**\n * Optional exportable trait meta (Devtools / Static IR / docs).\n *\n * Constraints:\n * - Must be serializable (JsonValue only); no closures/functions/Effect/DOM objects.\n * - Keep it slim; use `annotations` with `x-*` keys for extension hints.\n */\n readonly meta?: Logix.StateTrait.TraitMeta\n /**\n * Optional static tags for invalidate(byTag), used to narrow byTag from \"refresh all\" to a matched subset.\n * - Must be serializable (recommend: string constants only)\n * - If omitted, byTag conservatively falls back to refreshing everything\n */\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: BivariantCallback<DepsArgs<QueryKeyState<TParams, TUI>, Deps>, QueryResourceKey<R> | undefined>\n}\n\nexport type QueryBuilder<TParams, TUI> = {\n readonly source: <\n R extends QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n >(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly meta?: Logix.StateTrait.TraitMeta\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n }) => QuerySourceConfig<TParams, TUI, R, Deps>\n}\n\n/**\n * Query.source:\n * - Strongly typed helper to preserve `deps` as a tuple and infer `key(...depsValues)` argument types from it.\n * - Recommended usage inside `Query.make(..., { queries: { name: Query.source({ ... }) } })`.\n */\nexport const source = <\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n>(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly meta?: Logix.StateTrait.TraitMeta\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n}): QuerySourceConfig<TParams, TUI, R, Deps> => config as QuerySourceConfig<TParams, TUI, R, Deps>\n\nexport interface QueryTraitsInput<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI, any>>>\n}\n\n/**\n * Lowering rules (Query -> StateTrait):\n * - Each Query rule maps to a `StateTrait.source`, writing back to `queries.<name>` (isomorphic to module state).\n * - keySelector computes key from `{ params; ui }`; keyHash/race gating is guaranteed by the kernel source runtime.\n *\n * Notes:\n * - deps uses module-root paths (e.g. \"params.q\" / \"ui.query.autoEnabled\"), aligned with the constraints in 007/004.\n * - concurrency \"exhaust\" is represented as \"exhaust-trailing\" in the kernel.\n */\nexport const toStateTraitSpec = <TParams, TUI>(\n input: QueryTraitsInput<TParams, TUI>,\n): Logix.StateTrait.StateTraitSpec<any> => {\n const out: Record<string, Logix.StateTrait.StateTraitEntry<any, any>> = {}\n\n for (const [name, q] of Object.entries(input.queries)) {\n const triggers = q.triggers ?? (['onMount', 'onKeyChange'] as const)\n\n // \"manual\" must be exclusive to avoid ambiguous semantics (configuration error).\n if (triggers.includes('manual') && triggers.length > 1) {\n throw new Error(\n `[Query.traits] \"manual\" must be exclusive, but got triggers=[${triggers.join(', ')}] for query \"${name}\".`,\n )\n }\n\n out[`queries.${name}`] = Logix.StateTrait.source({\n // deps: used for graph building/diagnostics/future reverse-closure; Query also reuses deps to converge triggers.\n deps: q.deps as any,\n resource: q.resource.id,\n triggers,\n debounceMs: q.debounceMs,\n concurrency: q.concurrency === 'exhaust' ? 'exhaust-trailing' : q.concurrency,\n key: (...depsValues: ReadonlyArray<any>) => (q.key as any)(...depsValues),\n meta: q.meta,\n })\n }\n\n return out as Logix.StateTrait.StateTraitSpec<any>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAAuB;AAkFhB,IAAM,SAAS,CAKpB,WAS8C;AAezC,IAAM,mBAAmB,CAC9B,UACyC;AACzC,QAAM,MAAkE,CAAC;AAEzE,aAAW,CAAC,MAAM,CAAC,KAAK,OAAO,QAAQ,MAAM,OAAO,GAAG;AACrD,UAAM,WAAW,EAAE,YAAa,CAAC,WAAW,aAAa;AAGzD,QAAI,SAAS,SAAS,QAAQ,KAAK,SAAS,SAAS,GAAG;AACtD,YAAM,IAAI;AAAA,QACR,gEAAgE,SAAS,KAAK,IAAI,CAAC,gBAAgB,IAAI;AAAA,MACzG;AAAA,IACF;AAEA,QAAI,WAAW,IAAI,EAAE,IAAU,iBAAW,OAAO;AAAA;AAAA,MAE/C,MAAM,EAAE;AAAA,MACR,UAAU,EAAE,SAAS;AAAA,MACrB;AAAA,MACA,YAAY,EAAE;AAAA,MACd,aAAa,EAAE,gBAAgB,YAAY,qBAAqB,EAAE;AAAA,MAClE,KAAK,IAAI,eAAoC,EAAE,IAAY,GAAG,UAAU;AAAA,MACxE,MAAM,EAAE;AAAA,IACV,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
package/dist/Traits.d.cts CHANGED
@@ -24,6 +24,14 @@ interface QuerySourceConfig<TParams, TUI = unknown, R extends QueryResource = Qu
24
24
  readonly resource: R;
25
25
  readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>;
26
26
  readonly triggers?: ReadonlyArray<QueryTrigger>;
27
+ /**
28
+ * Optional exportable trait meta (Devtools / Static IR / docs).
29
+ *
30
+ * Constraints:
31
+ * - Must be serializable (JsonValue only); no closures/functions/Effect/DOM objects.
32
+ * - Keep it slim; use `annotations` with `x-*` keys for extension hints.
33
+ */
34
+ readonly meta?: Logix.StateTrait.TraitMeta;
27
35
  /**
28
36
  * Optional static tags for invalidate(byTag), used to narrow byTag from "refresh all" to a matched subset.
29
37
  * - Must be serializable (recommend: string constants only)
@@ -39,6 +47,7 @@ type QueryBuilder<TParams, TUI> = {
39
47
  readonly resource: R;
40
48
  readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>;
41
49
  readonly triggers?: ReadonlyArray<QueryTrigger>;
50
+ readonly meta?: Logix.StateTrait.TraitMeta;
42
51
  readonly tags?: ReadonlyArray<string>;
43
52
  readonly debounceMs?: number;
44
53
  readonly concurrency?: QueryConcurrency;
@@ -54,6 +63,7 @@ declare const source: <TParams, TUI = unknown, R extends QueryResource = QueryRe
54
63
  readonly resource: R;
55
64
  readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>;
56
65
  readonly triggers?: ReadonlyArray<QueryTrigger>;
66
+ readonly meta?: Logix.StateTrait.TraitMeta;
57
67
  readonly tags?: ReadonlyArray<string>;
58
68
  readonly debounceMs?: number;
59
69
  readonly concurrency?: QueryConcurrency;
package/dist/Traits.d.ts CHANGED
@@ -24,6 +24,14 @@ interface QuerySourceConfig<TParams, TUI = unknown, R extends QueryResource = Qu
24
24
  readonly resource: R;
25
25
  readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>;
26
26
  readonly triggers?: ReadonlyArray<QueryTrigger>;
27
+ /**
28
+ * Optional exportable trait meta (Devtools / Static IR / docs).
29
+ *
30
+ * Constraints:
31
+ * - Must be serializable (JsonValue only); no closures/functions/Effect/DOM objects.
32
+ * - Keep it slim; use `annotations` with `x-*` keys for extension hints.
33
+ */
34
+ readonly meta?: Logix.StateTrait.TraitMeta;
27
35
  /**
28
36
  * Optional static tags for invalidate(byTag), used to narrow byTag from "refresh all" to a matched subset.
29
37
  * - Must be serializable (recommend: string constants only)
@@ -39,6 +47,7 @@ type QueryBuilder<TParams, TUI> = {
39
47
  readonly resource: R;
40
48
  readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>;
41
49
  readonly triggers?: ReadonlyArray<QueryTrigger>;
50
+ readonly meta?: Logix.StateTrait.TraitMeta;
42
51
  readonly tags?: ReadonlyArray<string>;
43
52
  readonly debounceMs?: number;
44
53
  readonly concurrency?: QueryConcurrency;
@@ -54,6 +63,7 @@ declare const source: <TParams, TUI = unknown, R extends QueryResource = QueryRe
54
63
  readonly resource: R;
55
64
  readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>;
56
65
  readonly triggers?: ReadonlyArray<QueryTrigger>;
66
+ readonly meta?: Logix.StateTrait.TraitMeta;
57
67
  readonly tags?: ReadonlyArray<string>;
58
68
  readonly debounceMs?: number;
59
69
  readonly concurrency?: QueryConcurrency;
package/dist/Traits.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  source,
3
3
  toStateTraitSpec
4
- } from "./chunk-V3F5KWNH.js";
4
+ } from "./chunk-BERAWANA.js";
5
5
  import "./chunk-PZ5AY32C.js";
6
6
  export {
7
7
  source,
@@ -50,4 +50,4 @@ var Engine = Object.assign(EngineTagImpl, {
50
50
  export {
51
51
  Engine
52
52
  };
53
- //# sourceMappingURL=chunk-THVAADR2.js.map
53
+ //# sourceMappingURL=chunk-7IVR4THQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Engine.ts","../src/internal/middleware/middleware.ts"],"sourcesContent":["import type * as EffectOp from '@logixjs/core/EffectOp'\nimport type { JsonValue } from '@logixjs/core/Observability'\nimport { Context, Effect, Layer, Option } from 'effect'\nimport { middleware as middlewareImpl, type MiddlewareConfig } from './internal/middleware/middleware.js'\n\nexport type InvalidateRequest =\n | { readonly kind: 'byResource'; readonly resourceId: string }\n | { readonly kind: 'byParams'; readonly resourceId: string; readonly keyHash: string }\n | { readonly kind: 'byTag'; readonly tag: string }\n\nexport interface Engine {\n readonly fetch: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n readonly effect: Effect.Effect<A, unknown, any>\n /**\n * MUST be serializable and slim; recommended default is undefined (lazy),\n * and only populate it when diagnostics/devtools require it.\n */\n readonly meta?: JsonValue\n }) => Effect.Effect<A, unknown, any>\n\n /**\n * perf: optional fast path to avoid allocations on the hot path.\n * Semantics must match `fetch({ ... })`.\n */\n readonly fetchFast?: <A>(\n resourceId: string,\n keyHash: string,\n effect: Effect.Effect<A, unknown, any>,\n meta?: JsonValue,\n ) => Effect.Effect<A, unknown, any>\n\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void, unknown, any>\n\n /**\n * Read-only fast path: must not trigger IO; used to short-circuit to success before refresh,\n * avoiding loading jitter.\n */\n readonly peekFresh?: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n }) => Effect.Effect<Option.Option<A>, never, any>\n}\n\nclass EngineTagImpl extends Context.Tag('@logixjs/query/Engine')<EngineTagImpl, Engine>() {}\n\nexport const Engine = Object.assign(EngineTagImpl, {\n layer: (engine: Engine): Layer.Layer<EngineTagImpl, never, never> => Layer.succeed(EngineTagImpl, engine),\n middleware: (config?: MiddlewareConfig): EffectOp.Middleware => middlewareImpl(config),\n})\n\nexport type { MiddlewareConfig }\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Effect, Option } from 'effect'\nimport { Engine } from '../../Engine.js'\nimport type { Engine as EngineService } from '../../Engine.js'\n\nexport interface MiddlewareConfig {\n /**\n * Default: only applies to EffectOp that carries resourceId+keyHash (from StateTrait.source).\n * Optional: further filter by resourceId.\n */\n readonly useFor?: (resourceId: string) => boolean\n}\n\n/**\n * Query middleware (EffectOp): external engine takeover point.\n * - Delegates ResourceSpec.load execution to Engine (cache / in-flight dedupe / invalidation, etc.)\n * - Still preserves Logix Runtime's keyHash gating and ResourceSnapshot source-of-truth semantics\n */\nexport const middleware = (config?: MiddlewareConfig): EffectOp.Middleware =>\n (() => {\n // perf: within the same Runtime instance, Engine injection is stable.\n // Cache it in the middleware closure to avoid a Context lookup on every fetch.\n let cachedEngine: EngineService | undefined\n\n return (op) => {\n if ((op.kind !== 'service' && op.kind !== 'trait-source') || !op.meta?.resourceId || !op.meta.keyHash) {\n return op.effect as any\n }\n\n const resourceId = op.meta.resourceId\n if (config?.useFor && !config.useFor(resourceId)) {\n return op.effect as any\n }\n\n const keyHash = op.meta.keyHash as string\n\n if (cachedEngine) {\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }\n\n return Effect.serviceOption(Engine).pipe(\n Effect.flatMap((engineOpt) => {\n if (Option.isNone(engineOpt)) {\n return Effect.fail(\n new Error(\n `[Query.Engine.middleware] Missing Query.Engine in the Runtime scope; please provide Query.Engine.layer(Query.TanStack.engine(new QueryClient())) (recommended) or Query.Engine.layer(customEngine).`,\n ),\n )\n }\n cachedEngine = engineOpt.value\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }),\n ) as any\n }\n })()\n"],"mappings":";AAEA,SAAS,SAAiB,aAAqB;;;ACD/C,SAAS,QAAQ,cAAc;AAiBxB,IAAM,aAAa,CAAC,WACxB,uBAAM;AAGL,MAAI;AAEJ,SAAO,CAAC,OAAO;AACb,QAAK,GAAG,SAAS,aAAa,GAAG,SAAS,kBAAmB,CAAC,GAAG,MAAM,cAAc,CAAC,GAAG,KAAK,SAAS;AACrG,aAAO,GAAG;AAAA,IACZ;AAEA,UAAM,aAAa,GAAG,KAAK;AAC3B,QAAI,QAAQ,UAAU,CAAC,OAAO,OAAO,UAAU,GAAG;AAChD,aAAO,GAAG;AAAA,IACZ;AAEA,UAAM,UAAU,GAAG,KAAK;AAExB,QAAI,cAAc;AAChB,UAAI,aAAa,WAAW;AAC1B,eAAO,aAAa,UAAU,YAAY,SAAS,GAAG,MAAa;AAAA,MACrE;AACA,aAAO,aAAa,MAAM,EAAE,YAAY,SAAS,QAAQ,GAAG,OAAc,CAAC;AAAA,IAC7E;AAEA,WAAO,OAAO,cAAc,MAAM,EAAE;AAAA,MAClC,OAAO,QAAQ,CAAC,cAAc;AAC5B,YAAI,OAAO,OAAO,SAAS,GAAG;AAC5B,iBAAO,OAAO;AAAA,YACZ,IAAI;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,QACF;AACA,uBAAe,UAAU;AACzB,YAAI,aAAa,WAAW;AAC1B,iBAAO,aAAa,UAAU,YAAY,SAAS,GAAG,MAAa;AAAA,QACrE;AACA,eAAO,aAAa,MAAM,EAAE,YAAY,SAAS,QAAQ,GAAG,OAAc,CAAC;AAAA,MAC7E,CAAC;AAAA,IACH;AAAA,EACF;AACF,GAAG;;;ADfL,IAAM,gBAAN,cAA4B,QAAQ,IAAI,uBAAuB,EAAyB,EAAE;AAAC;AAEpF,IAAM,SAAS,OAAO,OAAO,eAAe;AAAA,EACjD,OAAO,CAAC,WAA6D,MAAM,QAAQ,eAAe,MAAM;AAAA,EACxG,YAAY,CAAC,WAAmD,WAAe,MAAM;AACvF,CAAC;","names":[]}
@@ -17,7 +17,8 @@ var toStateTraitSpec = (input) => {
17
17
  triggers,
18
18
  debounceMs: q.debounceMs,
19
19
  concurrency: q.concurrency === "exhaust" ? "exhaust-trailing" : q.concurrency,
20
- key: (...depsValues) => q.key(...depsValues)
20
+ key: (...depsValues) => q.key(...depsValues),
21
+ meta: q.meta
21
22
  });
22
23
  }
23
24
  return out;
@@ -27,4 +28,4 @@ export {
27
28
  source,
28
29
  toStateTraitSpec
29
30
  };
30
- //# sourceMappingURL=chunk-V3F5KWNH.js.map
31
+ //# sourceMappingURL=chunk-BERAWANA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/Traits.ts"],"sourcesContent":["import * as Logix from '@logixjs/core'\n\nexport type QueryTrigger = 'onMount' | 'onKeyChange' | 'manual'\n\nexport type QueryConcurrency = 'switch' | 'exhaust'\n\nexport type QueryResourceRef = { readonly id: string }\n\nexport type QueryResource = QueryResourceRef | Logix.Resource.ResourceSpec<any, any, any, any>\n\nexport type QueryResourceKey<R> = R extends Logix.Resource.ResourceSpec<infer Key, any, any, any> ? Key : unknown\n\nexport type QueryResourceData<R> = R extends Logix.Resource.ResourceSpec<any, infer Data, any, any> ? Data : unknown\n\nexport type QueryResourceError<R> = R extends Logix.Resource.ResourceSpec<any, any, infer Err, any> ? Err : unknown\n\nexport type QueryKeyState<TParams, TUI> = Readonly<{\n readonly params: TParams\n readonly ui: TUI\n}>\n\nexport type QueryDepsPath<TParams, TUI> = Logix.StateTrait.StateFieldPath<QueryKeyState<TParams, TUI>>\n\ntype DepsArgs<S extends object, Deps extends ReadonlyArray<string>> = {\n readonly [K in keyof Deps]: Deps[K] extends Logix.StateTrait.StateFieldPath<S>\n ? Logix.StateTrait.StateAtPath<S, Deps[K]>\n : any\n}\n\ntype BivariantCallback<Args extends ReadonlyArray<any>, R> = {\n bivarianceHack(...args: Args): R\n}['bivarianceHack']\n\nexport interface QuerySourceConfig<\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n> {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n /**\n * Optional exportable trait meta (Devtools / Static IR / docs).\n *\n * Constraints:\n * - Must be serializable (JsonValue only); no closures/functions/Effect/DOM objects.\n * - Keep it slim; use `annotations` with `x-*` keys for extension hints.\n */\n readonly meta?: Logix.StateTrait.TraitMeta\n /**\n * Optional static tags for invalidate(byTag), used to narrow byTag from \"refresh all\" to a matched subset.\n * - Must be serializable (recommend: string constants only)\n * - If omitted, byTag conservatively falls back to refreshing everything\n */\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: BivariantCallback<DepsArgs<QueryKeyState<TParams, TUI>, Deps>, QueryResourceKey<R> | undefined>\n}\n\nexport type QueryBuilder<TParams, TUI> = {\n readonly source: <\n R extends QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n >(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly meta?: Logix.StateTrait.TraitMeta\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n }) => QuerySourceConfig<TParams, TUI, R, Deps>\n}\n\n/**\n * Query.source:\n * - Strongly typed helper to preserve `deps` as a tuple and infer `key(...depsValues)` argument types from it.\n * - Recommended usage inside `Query.make(..., { queries: { name: Query.source({ ... }) } })`.\n */\nexport const source = <\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n>(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly meta?: Logix.StateTrait.TraitMeta\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n}): QuerySourceConfig<TParams, TUI, R, Deps> => config as QuerySourceConfig<TParams, TUI, R, Deps>\n\nexport interface QueryTraitsInput<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI, any>>>\n}\n\n/**\n * Lowering rules (Query -> StateTrait):\n * - Each Query rule maps to a `StateTrait.source`, writing back to `queries.<name>` (isomorphic to module state).\n * - keySelector computes key from `{ params; ui }`; keyHash/race gating is guaranteed by the kernel source runtime.\n *\n * Notes:\n * - deps uses module-root paths (e.g. \"params.q\" / \"ui.query.autoEnabled\"), aligned with the constraints in 007/004.\n * - concurrency \"exhaust\" is represented as \"exhaust-trailing\" in the kernel.\n */\nexport const toStateTraitSpec = <TParams, TUI>(\n input: QueryTraitsInput<TParams, TUI>,\n): Logix.StateTrait.StateTraitSpec<any> => {\n const out: Record<string, Logix.StateTrait.StateTraitEntry<any, any>> = {}\n\n for (const [name, q] of Object.entries(input.queries)) {\n const triggers = q.triggers ?? (['onMount', 'onKeyChange'] as const)\n\n // \"manual\" must be exclusive to avoid ambiguous semantics (configuration error).\n if (triggers.includes('manual') && triggers.length > 1) {\n throw new Error(\n `[Query.traits] \"manual\" must be exclusive, but got triggers=[${triggers.join(', ')}] for query \"${name}\".`,\n )\n }\n\n out[`queries.${name}`] = Logix.StateTrait.source({\n // deps: used for graph building/diagnostics/future reverse-closure; Query also reuses deps to converge triggers.\n deps: q.deps as any,\n resource: q.resource.id,\n triggers,\n debounceMs: q.debounceMs,\n concurrency: q.concurrency === 'exhaust' ? 'exhaust-trailing' : q.concurrency,\n key: (...depsValues: ReadonlyArray<any>) => (q.key as any)(...depsValues),\n meta: q.meta,\n })\n }\n\n return out as Logix.StateTrait.StateTraitSpec<any>\n}\n"],"mappings":";AAAA,YAAY,WAAW;AAkFhB,IAAM,SAAS,CAKpB,WAS8C;AAezC,IAAM,mBAAmB,CAC9B,UACyC;AACzC,QAAM,MAAkE,CAAC;AAEzE,aAAW,CAAC,MAAM,CAAC,KAAK,OAAO,QAAQ,MAAM,OAAO,GAAG;AACrD,UAAM,WAAW,EAAE,YAAa,CAAC,WAAW,aAAa;AAGzD,QAAI,SAAS,SAAS,QAAQ,KAAK,SAAS,SAAS,GAAG;AACtD,YAAM,IAAI;AAAA,QACR,gEAAgE,SAAS,KAAK,IAAI,CAAC,gBAAgB,IAAI;AAAA,MACzG;AAAA,IACF;AAEA,QAAI,WAAW,IAAI,EAAE,IAAU,iBAAW,OAAO;AAAA;AAAA,MAE/C,MAAM,EAAE;AAAA,MACR,UAAU,EAAE,SAAS;AAAA,MACrB;AAAA,MACA,YAAY,EAAE;AAAA,MACd,aAAa,EAAE,gBAAgB,YAAY,qBAAqB,EAAE;AAAA,MAClE,KAAK,IAAI,eAAoC,EAAE,IAAY,GAAG,UAAU;AAAA,MACxE,MAAM,EAAE;AAAA,IACV,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  Engine
3
- } from "./chunk-THVAADR2.js";
3
+ } from "./chunk-7IVR4THQ.js";
4
4
  import {
5
5
  toStateTraitSpec
6
- } from "./chunk-V3F5KWNH.js";
6
+ } from "./chunk-BERAWANA.js";
7
7
 
8
8
  // src/Query.ts
9
9
  import * as Logix3 from "@logixjs/core";
@@ -352,4 +352,4 @@ var make = (id, config) => {
352
352
  export {
353
353
  make
354
354
  };
355
- //# sourceMappingURL=chunk-NXFX6RIH.js.map
355
+ //# sourceMappingURL=chunk-DMEHDC55.js.map
package/dist/index.cjs CHANGED
@@ -316,7 +316,8 @@ var toStateTraitSpec = (input) => {
316
316
  triggers,
317
317
  debounceMs: q.debounceMs,
318
318
  concurrency: q.concurrency === "exhaust" ? "exhaust-trailing" : q.concurrency,
319
- key: (...depsValues) => q.key(...depsValues)
319
+ key: (...depsValues) => q.key(...depsValues),
320
+ meta: q.meta
320
321
  });
321
322
  }
322
323
  return out;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/Query.ts","../src/internal/logics/auto-trigger.ts","../src/Engine.ts","../src/internal/middleware/middleware.ts","../src/internal/logics/invalidate.ts","../src/Traits.ts","../src/TanStack.ts","../src/internal/engine/tanstack.ts","../src/internal/tanstack/observer.ts"],"sourcesContent":["// Public barrel for @logixjs/query\n// Recommended usage:\n// import * as Query from \"@logixjs/query\"\n// Then Query exposes namespaces like make / traits / Engine / TanStack.\n\nexport { make } from './Query.js'\nexport type * from './Query.js'\n\nexport { toStateTraitSpec as traits, source } from './Traits.js'\nexport type * from './Traits.js'\n\nexport { Engine } from './Engine.js'\nexport type { InvalidateRequest, MiddlewareConfig } from './Engine.js'\n\nexport * as TanStack from './TanStack.js'\n","import * as Logix from '@logixjs/core'\nimport { Effect, Schema } from 'effect'\nimport { autoTrigger } from './internal/logics/auto-trigger.js'\nimport { invalidate } from './internal/logics/invalidate.js'\nimport type { InvalidateRequest } from './Engine.js'\nimport { toStateTraitSpec, type QueryBuilder, type QuerySourceConfig, type QueryResourceData, type QueryResourceError } from './Traits.js'\n\ntype AnyQuerySourceConfig<TParams, TUI> = QuerySourceConfig<TParams, TUI, any, any>\n\ntype EnsureQueries<TParams, TUI, TQueries> = TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>>\n ? {}\n : {\n readonly __queries_must_be_QuerySourceConfig__: never\n }\n\ntype QueriesOf<TParams, TUI, TQueries> = TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> ? TQueries : never\n\nexport type QueryState<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly params: TParams\n readonly ui: TUI\n readonly queries: {\n readonly [K in keyof TQueries]: Logix.Resource.ResourceSnapshot<\n QueryResourceData<TQueries[K]['resource']>,\n QueryResourceError<TQueries[K]['resource']>\n >\n }\n}\n\nexport type QueryName<TQueries extends Record<string, any>> = Extract<keyof TQueries, string>\n\ntype ForbiddenQueryName = 'params' | 'ui' | 'queries'\ntype ForbidQueryNames = {\n readonly [K in ForbiddenQueryName]?: never\n}\n\nexport type QueryActions<TParams, TUI = unknown, TQueries extends Record<string, any> = {}> = {\n readonly setParams: Schema.Schema<TParams, any>\n readonly setUi: Schema.Schema<TUI, any>\n readonly refresh: Schema.Schema<QueryName<TQueries> | undefined, any>\n readonly invalidate: Schema.Schema<InvalidateRequest, any>\n}\n\nexport type QueryShape<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.Shape<Schema.Schema<QueryState<TParams, TUI, TQueries>, any>, QueryActions<TParams, TUI, TQueries>>\n\nexport type QueryAction<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.ActionOf<QueryShape<TParams, TUI, TQueries>>\n\nexport interface QueryMakeConfig<\n TParams,\n TUI = unknown,\n TQueries = {},\n> {\n readonly params: Schema.Schema<TParams, any>\n readonly initialParams: TParams\n readonly ui?: TUI\n readonly queries?: (q: QueryBuilder<TParams, TUI>) => TQueries & ForbidQueryNames\n readonly traits?: unknown\n}\n\nexport interface QueryController<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> {\n readonly runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, TQueries>, QueryAction<TParams, TUI, TQueries>>\n readonly getState: Effect.Effect<QueryState<TParams, TUI, TQueries>>\n readonly dispatch: (action: QueryAction<TParams, TUI, TQueries>) => Effect.Effect<void>\n\n readonly controller: {\n readonly setParams: (params: TParams) => Effect.Effect<void>\n readonly setUi: (ui: TUI) => Effect.Effect<void>\n readonly refresh: (target?: QueryName<TQueries>) => Effect.Effect<void>\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void>\n }\n}\n\nexport type QueryModuleController<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly make: (\n runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, TQueries>, QueryAction<TParams, TUI, TQueries>>,\n ) => QueryController<TParams, TUI, TQueries>\n}\n\nexport type QueryHandleExt<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly controller: QueryController<TParams, TUI, TQueries>['controller']\n}\n\nexport type QueryModule<\n Id extends string,\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.Module.Module<Id, QueryShape<TParams, TUI, TQueries>, QueryHandleExt<TParams, TUI, TQueries>, any> & {\n readonly controller: QueryModuleController<TParams, TUI, TQueries>\n}\n\nconst InvalidateRequestSchema = Schema.Union(\n Schema.Struct({\n kind: Schema.Literal('byResource'),\n resourceId: Schema.String,\n }),\n Schema.Struct({\n kind: Schema.Literal('byParams'),\n resourceId: Schema.String,\n keyHash: Schema.String,\n }),\n Schema.Struct({\n kind: Schema.Literal('byTag'),\n tag: Schema.String,\n }),\n) as Schema.Schema<InvalidateRequest, any>\n\nconst assertQueryName = (name: string): void => {\n if (!name) {\n throw new Error(`[Query.make] query name must be non-empty`)\n }\n if (name.includes('.')) {\n throw new Error(`[Query.make] query name must not include \".\"; got \"${name}\"`)\n }\n if (name === 'params' || name === 'ui' || name === 'queries') {\n throw new Error(`[Query.make] query name \"${name}\" is reserved`)\n }\n}\n\nexport const make = <\n Id extends string,\n TParams,\n TUI = unknown,\n const TQueries = {},\n>(\n id: Id,\n config: QueryMakeConfig<TParams, TUI, TQueries> & EnsureQueries<TParams, TUI, TQueries>,\n): QueryModule<Id, TParams, TUI, QueriesOf<TParams, TUI, TQueries>> => {\n type Queries = QueriesOf<TParams, TUI, TQueries>\n const queryBuilder: QueryBuilder<TParams, TUI> = {\n source: (q: any) => q,\n }\n\n\t const queries = ((): Queries => {\n\t const raw = config.queries\n\t if (!raw) return {} as Queries\n\t return raw(queryBuilder) as Queries\n\t })()\n\n const queriesForTraits: Readonly<Record<string, AnyQuerySourceConfig<TParams, TUI>>> = queries\n for (const name of Object.keys(queries)) {\n assertQueryName(name)\n }\n\n\t const RefreshTargetSchema = (() => {\n\t const names = Object.keys(queries) as Array<QueryName<Queries>>\n\t if (names.length === 0) return Schema.Never as unknown as Schema.Schema<QueryName<Queries>, any>\n\t if (names.length === 1) {\n\t return Schema.Literal(names[0] as any) as unknown as Schema.Schema<QueryName<Queries>, any>\n\t }\n const asUnionMembers = <A>(items: ReadonlyArray<A>): readonly [A, A, ...Array<A>] => {\n if (items.length < 2) {\n throw new Error(`[Query.make] internal error: expected at least 2 query names for union`)\n }\n return items as unknown as readonly [A, A, ...Array<A>]\n }\n\n\t const members = names.map((n) => Schema.Literal(n as any))\n\t return Schema.Union(...asUnionMembers(members)) as unknown as Schema.Schema<QueryName<Queries>, any>\n\t })()\n\n const UiSchema = Schema.Unknown as Schema.Schema<TUI, any>\n\n\t const QueriesSchema = Schema.Struct(\n\t Object.fromEntries((Object.keys(queries) as Array<keyof Queries>).map((k) => [k, Schema.Unknown])) as Record<\n\t string,\n\t Schema.Schema<any, any>\n\t >,\n\t )\n\n const StateSchema = Schema.Struct({\n params: config.params,\n ui: UiSchema,\n queries: QueriesSchema,\n }) as unknown as Schema.Schema<QueryState<TParams, TUI, Queries>, any>\n\n const Actions = {\n setParams: config.params,\n setUi: UiSchema,\n refresh: Schema.UndefinedOr(RefreshTargetSchema),\n invalidate: InvalidateRequestSchema,\n } satisfies QueryActions<TParams, TUI, Queries>\n\n type Reducers = Logix.ReducersFromMap<typeof StateSchema, typeof Actions>\n\n const reducers: Reducers = {\n setParams: (state, action, sink) => {\n sink?.('params')\n return { ...state, params: action.payload ?? state.params }\n },\n setUi: (state, action, sink) => {\n sink?.('ui')\n return { ...state, ui: action.payload ?? state.ui }\n },\n refresh: (state) => state,\n invalidate: (state) => state,\n } satisfies Reducers\n\n const queryTraits =\n Object.keys(queriesForTraits).length > 0 ? toStateTraitSpec<TParams, TUI>({ queries: queriesForTraits }) : undefined\n\n const traits =\n queryTraits || config.traits\n ? ({\n ...(queryTraits as any),\n ...(config.traits as any),\n } as any)\n : undefined\n\n const module = Logix.Module.make(id, {\n state: StateSchema,\n actions: Actions,\n reducers,\n traits,\n })\n\n const logics = [\n autoTrigger<any, TParams, TUI>(module.tag as any, { queries: queriesForTraits }),\n invalidate<any, TParams, TUI>(module.tag as any, { queries: queriesForTraits }),\n ] satisfies ReadonlyArray<Logix.ModuleLogic<any, any, any>>\n\n const initial = (params?: TParams): QueryState<TParams, TUI, Queries> =>\n ({\n params: params ?? config.initialParams,\n ui: (config.ui ?? ({} as unknown as TUI)) as TUI,\n queries: Object.fromEntries(\n (Object.keys(queries) as Array<keyof Queries>).map((k) => [k, Logix.Resource.Snapshot.idle()]),\n ),\n }) as QueryState<TParams, TUI, Queries>\n\n\t const controller: QueryModuleController<TParams, TUI, Queries> = {\n\t make: (\n\t runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, Queries>, QueryAction<TParams, TUI, Queries>>,\n\t ): QueryController<TParams, TUI, Queries> => {\n\t const dispatch = runtime.dispatch\n\t const actions = module.actions as unknown as {\n\t readonly setParams: (params: TParams) => QueryAction<TParams, TUI, Queries>\n\t readonly setUi: (ui: TUI) => QueryAction<TParams, TUI, Queries>\n\t readonly refresh: (target: QueryName<Queries> | undefined) => QueryAction<TParams, TUI, Queries>\n\t readonly invalidate: (request: InvalidateRequest) => QueryAction<TParams, TUI, Queries>\n\t }\n\t\t return {\n\t\t runtime,\n\t\t getState: runtime.getState as Effect.Effect<QueryState<TParams, TUI, Queries>>,\n\t\t dispatch,\n\t controller: {\n\t setParams: (params: TParams) => dispatch(actions.setParams(params)),\n\t setUi: (ui: TUI) => dispatch(actions.setUi(ui)),\n\t refresh: (target?: QueryName<Queries>) => dispatch(actions.refresh(target)),\n\t\t invalidate: (request: InvalidateRequest) => dispatch(actions.invalidate(request)),\n\t\t },\n\t\t } as QueryController<TParams, TUI, Queries>\n\t\t },\n\t\t }\n\n ;(module as any).controller = controller\n\n const EXTEND_HANDLE = Symbol.for('logix.module.handle.extend')\n ;(module.tag as any)[EXTEND_HANDLE] = (\n runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, Queries>, QueryAction<TParams, TUI, Queries>>,\n base: Logix.ModuleHandle<any>,\n ) => {\n const c = controller.make(runtime)\n return {\n ...base,\n controller: c.controller,\n }\n }\n\n return module.implement({\n initial: initial(),\n logics: [...logics],\n }) as unknown as QueryModule<Id, TParams, TUI, Queries>\n}\n","import * as Logix from '@logixjs/core'\nimport { Duration, Effect, Fiber } from 'effect'\nimport type { QuerySourceConfig, QueryTrigger } from '../../Traits.js'\nimport { Engine } from '../../Engine.js'\n\nconst defaultTriggers = ['onMount', 'onKeyChange'] as const\n\nconst getTriggers = (triggers: ReadonlyArray<QueryTrigger> | undefined): ReadonlyArray<QueryTrigger> =>\n triggers ?? defaultTriggers\n\nconst isManualOnly = (triggers: ReadonlyArray<QueryTrigger>): boolean =>\n triggers.length === 1 && triggers[0] === 'manual'\n\nconst getSnapshotKeyHash = (snapshot: unknown): string | undefined => {\n if (!snapshot || typeof snapshot !== 'object') return undefined\n const keyHash = (snapshot as any).keyHash\n return typeof keyHash === 'string' ? keyHash : undefined\n}\n\nconst getSnapshotStatus = (snapshot: unknown): string | undefined => {\n if (!snapshot || typeof snapshot !== 'object') return undefined\n const status = (snapshot as any).status\n return typeof status === 'string' ? status : undefined\n}\n\nexport interface AutoTriggerLogicConfig<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>\n}\n\n/**\n * Query auto-trigger logic:\n * - onMount: triggers once on initialization (if the key is valid and current snapshot does not match the same keyHash).\n * - onKeyChange: triggers after params/ui state changes (can debounce; only when keyHash changes or current is idle).\n * - manual-only: when triggers=[\"manual\"], disable onMount/onKeyChange auto triggering.\n */\nexport const autoTrigger = <Sh extends Logix.AnyModuleShape, TParams, TUI>(\n module: Logix.ModuleTagType<any, Sh>,\n config: AutoTriggerLogicConfig<TParams, TUI>,\n): Logix.ModuleLogic<Sh, any, never> =>\n module.logic(($) => {\n type _State = Logix.StateOf<Sh> & { readonly queries: Record<string, unknown> }\n type QueryName = Extract<keyof typeof config.queries, string>\n\n const pending = new Map<string, Fiber.RuntimeFiber<void, any>>()\n const lastKeyHash = new Map<string, string | undefined>()\n\n const hydrateFromFreshCache = (\n name: QueryName,\n q: QuerySourceConfig<TParams, TUI>,\n keyHash: string,\n ): Effect.Effect<boolean, never, any> =>\n Effect.gen(function* () {\n const engineOpt = yield* Effect.serviceOption(Engine)\n if (engineOpt._tag === 'None') return false\n\n const engine = engineOpt.value\n if (!engine.peekFresh) return false\n\n const dataOpt = yield* engine.peekFresh({\n resourceId: q.resource.id,\n keyHash,\n })\n if (dataOpt._tag === 'None') return false\n\n const snapshot = Logix.Resource.Snapshot.success({\n keyHash,\n data: dataOpt.value,\n })\n yield* $.state.mutate((draft) => {\n ;(draft as Logix.Logic.Draft<_State>).queries[name] = snapshot\n })\n\n return true\n })\n\n const cancelPending = (name: string): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n const prev = pending.get(name)\n if (!prev) return\n pending.delete(name)\n yield* Fiber.interruptFork(prev)\n })\n\n const sourcePathOf = (name: QueryName): string => `queries.${name}`\n\n const refresh = (name: QueryName, options?: { readonly force?: boolean }): Effect.Effect<void, never, any> =>\n $.traits.source.refresh(sourcePathOf(name) as any, options as any) as Effect.Effect<void, never, any>\n\n const scheduleDebounced = (name: QueryName, ms: number): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n yield* cancelPending(name)\n const fiber = yield* Effect.forkScoped(\n Effect.sleep(Duration.millis(ms)).pipe(\n Effect.zipRight(refresh(name)),\n Effect.ensuring(Effect.sync(() => pending.delete(name))),\n Effect.catchAllCause(() => Effect.void),\n ),\n )\n pending.set(name, fiber)\n })\n\n const computeKeyHash = (state: any, q: QuerySourceConfig<TParams, TUI>): string | undefined => {\n const getAtPath = (root: any, path: string): unknown => {\n const parts = path.split('.')\n let cur = root\n for (const p of parts) {\n if (cur == null) return undefined\n cur = cur[p]\n }\n return cur\n }\n\n try {\n const keyState = { params: state.params as any, ui: state.ui as any } as any\n const args = (q.deps as ReadonlyArray<string>).map((dep) => getAtPath(keyState, dep))\n const key = (q.key as any)(...args)\n if (key === undefined) return undefined\n return Logix.Resource.keyHash(key)\n } catch {\n return undefined\n }\n }\n\n const maybeAutoRefresh = (\n phase: 'mount' | 'keyChange',\n stateOverride?: unknown,\n ): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n const state = (stateOverride ?? (yield* $.state.read)) as any\n\n for (const [name, q] of Object.entries(config.queries)) {\n const queryName = name as QueryName\n const triggers = getTriggers(q.triggers)\n if (isManualOnly(triggers)) {\n continue\n }\n\n if (phase === 'mount' && !triggers.includes('onMount')) {\n continue\n }\n\n if (phase === 'keyChange' && !triggers.includes('onKeyChange')) {\n continue\n }\n\n const keyHash = computeKeyHash(state, q)\n const snapshot = state?.queries?.[queryName]\n const snapshotKeyHash = getSnapshotKeyHash(snapshot)\n const snapshotStatus = getSnapshotStatus(snapshot)\n\n // Key is unavailable: do not refresh (idle reaping is guaranteed by kernel syncIdleInTransaction).\n if (keyHash === undefined) {\n lastKeyHash.set(queryName, undefined)\n continue\n }\n\n // keyHash unchanged and we already have a non-idle snapshot: avoid re-entering loading (reuse existing result).\n const last = lastKeyHash.get(queryName)\n if (snapshotStatus && snapshotStatus !== 'idle' && snapshotKeyHash === keyHash && last === keyHash) {\n continue\n }\n\n // If current snapshot is already success/error/loading with the same keyHash: update lastKeyHash and skip.\n if (snapshotStatus && snapshotStatus !== 'idle' && snapshotKeyHash === keyHash) {\n lastKeyHash.set(queryName, keyHash)\n continue\n }\n\n lastKeyHash.set(queryName, keyHash)\n\n // TanStack Query scenario: if we can hit the fresh cache, write a success snapshot directly,\n // skipping source.refresh (avoids UI jitter and extra transactions like \"cache hit but still loading -> success\").\n const hydrated = yield* hydrateFromFreshCache(queryName, q, keyHash)\n if (hydrated) {\n yield* cancelPending(queryName)\n continue\n }\n\n const debounceMs = q.debounceMs ?? 0\n if (phase === 'keyChange' && debounceMs > 0) {\n yield* scheduleDebounced(queryName, debounceMs)\n } else {\n // mount / no debounce: trigger immediately\n yield* cancelPending(queryName)\n yield* refresh(queryName)\n }\n }\n })\n\n const refreshAll = (options?: { readonly force?: boolean }): Effect.Effect<void, never, any> =>\n Effect.forEach(Object.keys(config.queries), (name) =>\n cancelPending(name).pipe(Effect.zipRight(refresh(name as QueryName, options))),\n ).pipe(Effect.asVoid)\n\n const setup = $.lifecycle.onStart(maybeAutoRefresh('mount'))\n\n const run = Effect.suspend(() =>\n Effect.all(\n [\n // params/ui changes: handled by Query's default logic, avoiding scattered UI-side useEffect triggers.\n $.onAction('setParams').runFork((action: any) =>\n Effect.gen(function* () {\n const state = (yield* $.state.read) as any\n const next = { ...state, params: action.payload }\n yield* maybeAutoRefresh('keyChange', next)\n }),\n ),\n $.onAction('setUi').runFork((action: any) =>\n Effect.gen(function* () {\n const state = (yield* $.state.read) as any\n const next = { ...state, ui: action.payload }\n yield* maybeAutoRefresh('keyChange', next)\n }),\n ),\n\n // Manual refresh: not restricted by triggers (manual-only still allows explicit refresh).\n $.onAction('refresh').runFork((action: any) =>\n Effect.gen(function* () {\n const target = action.payload as QueryName | undefined\n if (typeof target === 'string' && target.length > 0) {\n yield* cancelPending(target)\n yield* refresh(target, { force: true })\n } else {\n yield* refreshAll({ force: true })\n }\n }),\n ),\n ],\n { concurrency: 'unbounded' },\n ).pipe(Effect.asVoid),\n )\n\n return { setup, run }\n }) as Logix.ModuleLogic<Sh, any, never>\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Context, Effect, Layer, Option } from 'effect'\nimport { middleware as middlewareImpl, type MiddlewareConfig } from './internal/middleware/middleware.js'\n\nexport type InvalidateRequest =\n | { readonly kind: 'byResource'; readonly resourceId: string }\n | { readonly kind: 'byParams'; readonly resourceId: string; readonly keyHash: string }\n | { readonly kind: 'byTag'; readonly tag: string }\n\nexport interface Engine {\n readonly fetch: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n readonly effect: Effect.Effect<A, unknown, any>\n /**\n * MUST be serializable and slim; recommended default is undefined (lazy),\n * and only populate it when diagnostics/devtools require it.\n */\n readonly meta?: unknown\n }) => Effect.Effect<A, unknown, any>\n\n /**\n * perf: optional fast path to avoid allocations on the hot path.\n * Semantics must match `fetch({ ... })`.\n */\n readonly fetchFast?: <A>(\n resourceId: string,\n keyHash: string,\n effect: Effect.Effect<A, unknown, any>,\n meta?: unknown,\n ) => Effect.Effect<A, unknown, any>\n\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void, unknown, any>\n\n /**\n * Read-only fast path: must not trigger IO; used to short-circuit to success before refresh,\n * avoiding loading jitter.\n */\n readonly peekFresh?: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n }) => Effect.Effect<Option.Option<A>, never, any>\n}\n\nclass EngineTagImpl extends Context.Tag('@logixjs/query/Engine')<EngineTagImpl, Engine>() {}\n\nexport const Engine = Object.assign(EngineTagImpl, {\n layer: (engine: Engine): Layer.Layer<EngineTagImpl, never, never> => Layer.succeed(EngineTagImpl, engine),\n middleware: (config?: MiddlewareConfig): EffectOp.Middleware => middlewareImpl(config),\n})\n\nexport type { MiddlewareConfig }\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Effect, Option } from 'effect'\nimport { Engine } from '../../Engine.js'\nimport type { Engine as EngineService } from '../../Engine.js'\n\nexport interface MiddlewareConfig {\n /**\n * Default: only applies to EffectOp that carries resourceId+keyHash (from StateTrait.source).\n * Optional: further filter by resourceId.\n */\n readonly useFor?: (resourceId: string) => boolean\n}\n\n/**\n * Query middleware (EffectOp): external engine takeover point.\n * - Delegates ResourceSpec.load execution to Engine (cache / in-flight dedupe / invalidation, etc.)\n * - Still preserves Logix Runtime's keyHash gating and ResourceSnapshot source-of-truth semantics\n */\nexport const middleware = (config?: MiddlewareConfig): EffectOp.Middleware =>\n (() => {\n // perf: within the same Runtime instance, Engine injection is stable.\n // Cache it in the middleware closure to avoid a Context lookup on every fetch.\n let cachedEngine: EngineService | undefined\n\n return (op) => {\n if ((op.kind !== 'service' && op.kind !== 'trait-source') || !op.meta?.resourceId || !op.meta.keyHash) {\n return op.effect as any\n }\n\n const resourceId = op.meta.resourceId\n if (config?.useFor && !config.useFor(resourceId)) {\n return op.effect as any\n }\n\n const keyHash = op.meta.keyHash as string\n\n if (cachedEngine) {\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }\n\n return Effect.serviceOption(Engine).pipe(\n Effect.flatMap((engineOpt) => {\n if (Option.isNone(engineOpt)) {\n return Effect.fail(\n new Error(\n `[Query.Engine.middleware] Missing Query.Engine in the Runtime scope; please provide Query.Engine.layer(Query.TanStack.engine(new QueryClient())) (recommended) or Query.Engine.layer(customEngine).`,\n ),\n )\n }\n cachedEngine = engineOpt.value\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }),\n ) as any\n }\n })()\n","import * as Logix from '@logixjs/core'\nimport { Effect } from 'effect'\nimport { Engine, type InvalidateRequest } from '../../Engine.js'\nimport type { QuerySourceConfig } from '../../Traits.js'\n\nexport interface InvalidateLogicConfig<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>\n}\n\nconst toInvalidateTargets = <TParams, TUI>(\n request: InvalidateRequest,\n queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>,\n): ReadonlyArray<{ readonly name: string; readonly resourceId: string }> => {\n if (request.kind === 'byResource') {\n return Object.entries(queries)\n .filter(([, q]) => q.resource.id === request.resourceId)\n .map(([name, q]) => ({ name, resourceId: q.resource.id }))\n }\n\n if (request.kind === 'byParams') {\n return Object.entries(queries)\n .filter(([, q]) => q.resource.id === request.resourceId)\n .map(([name, q]) => ({ name, resourceId: q.resource.id }))\n }\n\n // byTag: prefer QuerySourceConfig.tags for static filtering; if tags are missing, conservatively fall back to refreshing all.\n const entries = Object.entries(queries)\n const tagged = entries.filter(([, q]) => Array.isArray(q.tags) && q.tags.includes(request.tag))\n const selected = tagged.length > 0 ? tagged : entries\n return selected.map(([name, q]) => ({ name, resourceId: q.resource.id }))\n}\n\nexport const invalidate = <Sh extends Logix.AnyModuleShape, TParams, TUI>(\n module: Logix.ModuleTagType<any, Sh>,\n config: InvalidateLogicConfig<TParams, TUI>,\n): Logix.ModuleLogic<Sh, any, never> =>\n module.logic(($) =>\n Effect.gen(function* () {\n yield* $.onAction('invalidate').runFork((action: any) =>\n Effect.gen(function* () {\n const request = action.payload as InvalidateRequest\n\n // 1) Eventize: goes into ReplayLog (kernel-owned).\n yield* Logix.TraitLifecycle.scopedExecute($ as any, {\n kind: 'query:invalidate',\n request,\n })\n\n // 2) Call external engine (optional): does not block the fallback path.\n const engineOpt = yield* Effect.serviceOption(Engine)\n if (engineOpt._tag !== 'None') {\n yield* engineOpt.value.invalidate(request)\n }\n\n // 3) Immediately refresh related sources (write-back gating is still guaranteed by kernel keyHash).\n const targets = toInvalidateTargets<TParams, TUI>(request, config.queries)\n const sourcePathOf = (name: string): string => `queries.${name}`\n yield* Effect.forEach(\n targets,\n (t) =>\n $.traits.source.refresh(sourcePathOf(t.name) as any, { force: true }) as Effect.Effect<void, never, any>,\n ).pipe(Effect.asVoid)\n }),\n )\n }),\n ) as Logix.ModuleLogic<Sh, any, never>\n","import * as Logix from '@logixjs/core'\n\nexport type QueryTrigger = 'onMount' | 'onKeyChange' | 'manual'\n\nexport type QueryConcurrency = 'switch' | 'exhaust'\n\nexport type QueryResourceRef = { readonly id: string }\n\nexport type QueryResource = QueryResourceRef | Logix.Resource.ResourceSpec<any, any, any, any>\n\nexport type QueryResourceKey<R> = R extends Logix.Resource.ResourceSpec<infer Key, any, any, any> ? Key : unknown\n\nexport type QueryResourceData<R> = R extends Logix.Resource.ResourceSpec<any, infer Data, any, any> ? Data : unknown\n\nexport type QueryResourceError<R> = R extends Logix.Resource.ResourceSpec<any, any, infer Err, any> ? Err : unknown\n\nexport type QueryKeyState<TParams, TUI> = Readonly<{\n readonly params: TParams\n readonly ui: TUI\n}>\n\nexport type QueryDepsPath<TParams, TUI> = Logix.StateTrait.StateFieldPath<QueryKeyState<TParams, TUI>>\n\ntype DepsArgs<S extends object, Deps extends ReadonlyArray<string>> = {\n readonly [K in keyof Deps]: Deps[K] extends Logix.StateTrait.StateFieldPath<S>\n ? Logix.StateTrait.StateAtPath<S, Deps[K]>\n : any\n}\n\ntype BivariantCallback<Args extends ReadonlyArray<any>, R> = {\n bivarianceHack(...args: Args): R\n}['bivarianceHack']\n\nexport interface QuerySourceConfig<\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n> {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n /**\n * Optional static tags for invalidate(byTag), used to narrow byTag from \"refresh all\" to a matched subset.\n * - Must be serializable (recommend: string constants only)\n * - If omitted, byTag conservatively falls back to refreshing everything\n */\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: BivariantCallback<DepsArgs<QueryKeyState<TParams, TUI>, Deps>, QueryResourceKey<R> | undefined>\n}\n\nexport type QueryBuilder<TParams, TUI> = {\n readonly source: <\n R extends QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n >(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n }) => QuerySourceConfig<TParams, TUI, R, Deps>\n}\n\n/**\n * Query.source:\n * - Strongly typed helper to preserve `deps` as a tuple and infer `key(...depsValues)` argument types from it.\n * - Recommended usage inside `Query.make(..., { queries: { name: Query.source({ ... }) } })`.\n */\nexport const source = <\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n>(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n}): QuerySourceConfig<TParams, TUI, R, Deps> => config as QuerySourceConfig<TParams, TUI, R, Deps>\n\nexport interface QueryTraitsInput<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI, any>>>\n}\n\n/**\n * Lowering rules (Query -> StateTrait):\n * - Each Query rule maps to a `StateTrait.source`, writing back to `queries.<name>` (isomorphic to module state).\n * - keySelector computes key from `{ params; ui }`; keyHash/race gating is guaranteed by the kernel source runtime.\n *\n * Notes:\n * - deps uses module-root paths (e.g. \"params.q\" / \"ui.query.autoEnabled\"), aligned with the constraints in 007/004.\n * - concurrency \"exhaust\" is represented as \"exhaust-trailing\" in the kernel.\n */\nexport const toStateTraitSpec = <TParams, TUI>(\n input: QueryTraitsInput<TParams, TUI>,\n): Logix.StateTrait.StateTraitSpec<any> => {\n const out: Record<string, Logix.StateTrait.StateTraitEntry<any, any>> = {}\n\n for (const [name, q] of Object.entries(input.queries)) {\n const triggers = q.triggers ?? (['onMount', 'onKeyChange'] as const)\n\n // \"manual\" must be exclusive to avoid ambiguous semantics (configuration error).\n if (triggers.includes('manual') && triggers.length > 1) {\n throw new Error(\n `[Query.traits] \"manual\" must be exclusive, but got triggers=[${triggers.join(', ')}] for query \"${name}\".`,\n )\n }\n\n out[`queries.${name}`] = Logix.StateTrait.source({\n // deps: used for graph building/diagnostics/future reverse-closure; Query also reuses deps to converge triggers.\n deps: q.deps as any,\n resource: q.resource.id,\n triggers,\n debounceMs: q.debounceMs,\n concurrency: q.concurrency === 'exhaust' ? 'exhaust-trailing' : q.concurrency,\n key: (...depsValues: ReadonlyArray<any>) => (q.key as any)(...depsValues),\n })\n }\n\n return out as Logix.StateTrait.StateTraitSpec<any>\n}\n","export * from './internal/engine/tanstack.js'\nexport * from './internal/tanstack/observer.js'\n","import { Effect, Option } from 'effect'\nimport type { QueryClient } from '@tanstack/query-core'\nimport type { Engine, InvalidateRequest } from '../../Engine.js'\n\nconst makeQueryKey = (resourceId: string, keyHash: string) => [resourceId, keyHash] as const\n\nexport interface TanStackEngineConfig {\n /**\n * The max number of entries per resourceId in the local fast cache.\n * - Goal: prevent unbounded memory growth when the key space is unbounded.\n * - Semantics: evicts oldest entries in insertion order (FIFO); cache misses fall back to re-loading.\n * - Set to Infinity to disable the cap (not recommended for long-running processes).\n */\n readonly maxEntriesPerResource?: number\n}\n\n/**\n * TanStack engine:\n * - Uses QueryClient for invalidation (easy integration with TanStack ecosystem).\n * - fetch/peekFresh uses a slim in-memory cache to avoid frequently creating Query objects on the Logix runtime hot path.\n * - Still preserves Logix Runtime's keyHash gating and ResourceSnapshot source-of-truth semantics.\n */\nexport const engine = (queryClient: QueryClient, config?: TanStackEngineConfig): Engine => {\n const byResourceId = new Map<string, Map<string, unknown>>()\n const maxEntriesPerResource = config?.maxEntriesPerResource ?? 2000\n\n // Align with external QueryClient.clear(): when QueryCache is cleared, clear the local fast cache as well.\n try {\n const queryCache: any = (queryClient as any).getQueryCache?.()\n if (queryCache && typeof queryCache.clear === 'function') {\n const original = queryCache.clear.bind(queryCache)\n queryCache.clear = () => {\n byResourceId.clear()\n return original()\n }\n }\n } catch {\n // ignore\n }\n\n const ensureBucket = (resourceId: string): Map<string, unknown> => {\n let bucket = byResourceId.get(resourceId)\n if (!bucket) {\n bucket = new Map<string, unknown>()\n byResourceId.set(resourceId, bucket)\n }\n return bucket\n }\n\n const evictIfNeeded = (bucket: Map<string, unknown>): void => {\n if (maxEntriesPerResource === Infinity) return\n if (!Number.isFinite(maxEntriesPerResource) || maxEntriesPerResource <= 0) return\n while (bucket.size > maxEntriesPerResource) {\n const firstKey = bucket.keys().next().value as string | undefined\n if (firstKey === undefined) return\n bucket.delete(firstKey)\n }\n }\n\n const fetchFast: Engine['fetchFast'] = (resourceId, keyHash, effect) =>\n Effect.suspend(() => {\n const hit = byResourceId.get(resourceId)?.get(keyHash)\n if (hit !== undefined) {\n return Effect.succeed(hit as any)\n }\n\n return Effect.map(effect, (out) => {\n if (out !== undefined) {\n const bucket = ensureBucket(resourceId)\n bucket.set(keyHash, out)\n evictIfNeeded(bucket)\n }\n return out as any\n })\n })\n\n return {\n fetch: ({ resourceId, keyHash, effect }) => fetchFast!(resourceId, keyHash, effect),\n\n fetchFast,\n\n invalidate: (request: InvalidateRequest) =>\n Effect.gen(function* () {\n yield* Effect.sync(() => {\n if (request.kind === 'byParams') {\n const bucket = byResourceId.get(request.resourceId)\n if (!bucket) return\n bucket.delete(request.keyHash)\n if (bucket.size === 0) {\n byResourceId.delete(request.resourceId)\n }\n return\n }\n\n if (request.kind === 'byResource') {\n byResourceId.delete(request.resourceId)\n return\n }\n\n // byTag: we currently lack a serializable tags mapping; conservatively clear all (explainable but coarse).\n byResourceId.clear()\n })\n\n // Sync to QueryClient (if there are external observers/ecosystem consumers).\n yield* Effect.tryPromise({\n try: () => {\n if (request.kind === 'byResource') {\n return queryClient.invalidateQueries({\n queryKey: [request.resourceId],\n })\n }\n\n if (request.kind === 'byParams') {\n return queryClient.invalidateQueries({\n queryKey: makeQueryKey(request.resourceId, request.keyHash),\n })\n }\n\n return queryClient.invalidateQueries({\n predicate: (q) => {\n const tags = (q.meta as any)?.tags\n return Array.isArray(tags) && tags.includes(request.tag)\n },\n })\n },\n catch: (e) => e,\n }).pipe(Effect.asVoid)\n }),\n\n peekFresh: <A>({ resourceId, keyHash }: { readonly resourceId: string; readonly keyHash: string }) =>\n Effect.sync(() => {\n const hit = byResourceId.get(resourceId)?.get(keyHash) as A | undefined\n return hit === undefined ? Option.none<A>() : Option.some(hit)\n }),\n }\n}\n","import { Effect } from 'effect'\nimport type { QueryClient } from '@tanstack/query-core'\nimport { QueryObserver } from '@tanstack/query-core'\n\n/**\n * observe (subscribe within scope + cleanup):\n * - For scenarios where you want \"TanStack-like automatic tracking\" of enabled/queryKey changes.\n * - Provided as infrastructure; domain logic can choose to use it (no hard dependency).\n */\nexport const observe = <TData = unknown>(params: {\n readonly queryClient: QueryClient\n readonly options: ConstructorParameters<typeof QueryObserver<TData>>[1]\n readonly onResult: (result: unknown) => void\n}): Effect.Effect<QueryObserver<TData>, never, any> =>\n Effect.gen(function* () {\n const observer = new QueryObserver<TData>(params.queryClient, params.options as any)\n const unsubscribe = observer.subscribe(params.onResult as any)\n yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribe()))\n return observer\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,SAAuB;AACvB,IAAAC,iBAA+B;;;ACD/B,YAAuB;AACvB,IAAAC,iBAAwC;;;ACAxC,IAAAC,iBAA+C;;;ACA/C,oBAA+B;AAiBxB,IAAM,aAAa,CAAC,WACxB,uBAAM;AAGL,MAAI;AAEJ,SAAO,CAAC,OAAO;AACb,QAAK,GAAG,SAAS,aAAa,GAAG,SAAS,kBAAmB,CAAC,GAAG,MAAM,cAAc,CAAC,GAAG,KAAK,SAAS;AACrG,aAAO,GAAG;AAAA,IACZ;AAEA,UAAM,aAAa,GAAG,KAAK;AAC3B,QAAI,QAAQ,UAAU,CAAC,OAAO,OAAO,UAAU,GAAG;AAChD,aAAO,GAAG;AAAA,IACZ;AAEA,UAAM,UAAU,GAAG,KAAK;AAExB,QAAI,cAAc;AAChB,UAAI,aAAa,WAAW;AAC1B,eAAO,aAAa,UAAU,YAAY,SAAS,GAAG,MAAa;AAAA,MACrE;AACA,aAAO,aAAa,MAAM,EAAE,YAAY,SAAS,QAAQ,GAAG,OAAc,CAAC;AAAA,IAC7E;AAEA,WAAO,qBAAO,cAAc,MAAM,EAAE;AAAA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H;AAEA,cAAI,QAAQ,SAAS,YAAY;AAC/B,mBAAO,YAAY,kBAAkB;AAAA,cACnC,UAAU,aAAa,QAAQ,YAAY,QAAQ,OAAO;AAAA,YAC5D,CAAC;AAAA,UACH;AAEA,iBAAO,YAAY,kBAAkB;AAAA,YACnC,WAAW,CAAC,MAAM;AAChB,oBAAM,OAAQ,EAAE,MAAc;AAC9B,qBAAO,MAAM,QAAQ,IAAI,KAAK,KAAK,SAAS,QAAQ,GAAG;AAAA,YACzD;AAAA,UACF,CAAC;AAAA,QACH;AAAA,QACA,OAAO,CAAC,MAAM;AAAA,MAChB,CAAC,EAAE,KAAK,sBAAO,MAAM;AAAA,IACvB,CAAC;AAAA,IAEH,WAAW,CAAI,EAAE,YAAY,QAAQ,MACnC,sBAAO,KAAK,MAAM;AAChB,YAAM,MAAM,aAAa,IAAI,UAAU,GAAG,IAAI,OAAO;AACrD,aAAO,QAAQ,SAAY,sBAAO,KAAQ,IAAI,sBAAO,KAAK,GAAG;AAAA,IAC/D,CAAC;AAAA,EACL;AACF;;;ACvIA,IAAAC,iBAAuB;AAEvB,wBAA8B;AAOvB,IAAM,UAAU,CAAkB,WAKvC,sBAAO,IAAI,aAAa;AACtB,QAAM,WAAW,IAAI,gCAAqB,OAAO,aAAa,OAAO,OAAc;AACnF,QAAM,cAAc,SAAS,UAAU,OAAO,QAAe;AAC7D,SAAO,sBAAO,aAAa,MAAM,sBAAO,KAAK,MAAM,YAAY,CAAC,CAAC;AACjE,SAAO;AACT,CAAC;","names":["Logix","import_effect","import_effect","import_effect","engine","module","engine","Logix","import_effect","module","Logix","module","import_effect","import_effect"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/Query.ts","../src/internal/logics/auto-trigger.ts","../src/Engine.ts","../src/internal/middleware/middleware.ts","../src/internal/logics/invalidate.ts","../src/Traits.ts","../src/TanStack.ts","../src/internal/engine/tanstack.ts","../src/internal/tanstack/observer.ts"],"sourcesContent":["// Public barrel for @logixjs/query\n// Recommended usage:\n// import * as Query from \"@logixjs/query\"\n// Then Query exposes namespaces like make / traits / Engine / TanStack.\n\nexport { make } from './Query.js'\nexport type * from './Query.js'\n\nexport { toStateTraitSpec as traits, source } from './Traits.js'\nexport type * from './Traits.js'\n\nexport { Engine } from './Engine.js'\nexport type { InvalidateRequest, MiddlewareConfig } from './Engine.js'\n\nexport * as TanStack from './TanStack.js'\n","import * as Logix from '@logixjs/core'\nimport { Effect, Schema } from 'effect'\nimport { autoTrigger } from './internal/logics/auto-trigger.js'\nimport { invalidate } from './internal/logics/invalidate.js'\nimport type { InvalidateRequest } from './Engine.js'\nimport { toStateTraitSpec, type QueryBuilder, type QuerySourceConfig, type QueryResourceData, type QueryResourceError } from './Traits.js'\n\ntype AnyQuerySourceConfig<TParams, TUI> = QuerySourceConfig<TParams, TUI, any, any>\n\ntype EnsureQueries<TParams, TUI, TQueries> = TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>>\n ? {}\n : {\n readonly __queries_must_be_QuerySourceConfig__: never\n }\n\ntype QueriesOf<TParams, TUI, TQueries> = TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> ? TQueries : never\n\nexport type QueryState<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly params: TParams\n readonly ui: TUI\n readonly queries: {\n readonly [K in keyof TQueries]: Logix.Resource.ResourceSnapshot<\n QueryResourceData<TQueries[K]['resource']>,\n QueryResourceError<TQueries[K]['resource']>\n >\n }\n}\n\nexport type QueryName<TQueries extends Record<string, any>> = Extract<keyof TQueries, string>\n\ntype ForbiddenQueryName = 'params' | 'ui' | 'queries'\ntype ForbidQueryNames = {\n readonly [K in ForbiddenQueryName]?: never\n}\n\nexport type QueryActions<TParams, TUI = unknown, TQueries extends Record<string, any> = {}> = {\n readonly setParams: Schema.Schema<TParams, any>\n readonly setUi: Schema.Schema<TUI, any>\n readonly refresh: Schema.Schema<QueryName<TQueries> | undefined, any>\n readonly invalidate: Schema.Schema<InvalidateRequest, any>\n}\n\nexport type QueryShape<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.Shape<Schema.Schema<QueryState<TParams, TUI, TQueries>, any>, QueryActions<TParams, TUI, TQueries>>\n\nexport type QueryAction<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.ActionOf<QueryShape<TParams, TUI, TQueries>>\n\nexport interface QueryMakeConfig<\n TParams,\n TUI = unknown,\n TQueries = {},\n> {\n readonly params: Schema.Schema<TParams, any>\n readonly initialParams: TParams\n readonly ui?: TUI\n readonly queries?: (q: QueryBuilder<TParams, TUI>) => TQueries & ForbidQueryNames\n readonly traits?: unknown\n}\n\nexport interface QueryController<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> {\n readonly runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, TQueries>, QueryAction<TParams, TUI, TQueries>>\n readonly getState: Effect.Effect<QueryState<TParams, TUI, TQueries>>\n readonly dispatch: (action: QueryAction<TParams, TUI, TQueries>) => Effect.Effect<void>\n\n readonly controller: {\n readonly setParams: (params: TParams) => Effect.Effect<void>\n readonly setUi: (ui: TUI) => Effect.Effect<void>\n readonly refresh: (target?: QueryName<TQueries>) => Effect.Effect<void>\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void>\n }\n}\n\nexport type QueryModuleController<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly make: (\n runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, TQueries>, QueryAction<TParams, TUI, TQueries>>,\n ) => QueryController<TParams, TUI, TQueries>\n}\n\nexport type QueryHandleExt<\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = {\n readonly controller: QueryController<TParams, TUI, TQueries>['controller']\n}\n\nexport type QueryModule<\n Id extends string,\n TParams,\n TUI = unknown,\n TQueries extends Record<string, AnyQuerySourceConfig<TParams, TUI>> = {},\n> = Logix.Module.Module<Id, QueryShape<TParams, TUI, TQueries>, QueryHandleExt<TParams, TUI, TQueries>, any> & {\n readonly controller: QueryModuleController<TParams, TUI, TQueries>\n}\n\nconst InvalidateRequestSchema = Schema.Union(\n Schema.Struct({\n kind: Schema.Literal('byResource'),\n resourceId: Schema.String,\n }),\n Schema.Struct({\n kind: Schema.Literal('byParams'),\n resourceId: Schema.String,\n keyHash: Schema.String,\n }),\n Schema.Struct({\n kind: Schema.Literal('byTag'),\n tag: Schema.String,\n }),\n) as Schema.Schema<InvalidateRequest, any>\n\nconst assertQueryName = (name: string): void => {\n if (!name) {\n throw new Error(`[Query.make] query name must be non-empty`)\n }\n if (name.includes('.')) {\n throw new Error(`[Query.make] query name must not include \".\"; got \"${name}\"`)\n }\n if (name === 'params' || name === 'ui' || name === 'queries') {\n throw new Error(`[Query.make] query name \"${name}\" is reserved`)\n }\n}\n\nexport const make = <\n Id extends string,\n TParams,\n TUI = unknown,\n const TQueries = {},\n>(\n id: Id,\n config: QueryMakeConfig<TParams, TUI, TQueries> & EnsureQueries<TParams, TUI, TQueries>,\n): QueryModule<Id, TParams, TUI, QueriesOf<TParams, TUI, TQueries>> => {\n type Queries = QueriesOf<TParams, TUI, TQueries>\n const queryBuilder: QueryBuilder<TParams, TUI> = {\n source: (q: any) => q,\n }\n\n\t const queries = ((): Queries => {\n\t const raw = config.queries\n\t if (!raw) return {} as Queries\n\t return raw(queryBuilder) as Queries\n\t })()\n\n const queriesForTraits: Readonly<Record<string, AnyQuerySourceConfig<TParams, TUI>>> = queries\n for (const name of Object.keys(queries)) {\n assertQueryName(name)\n }\n\n\t const RefreshTargetSchema = (() => {\n\t const names = Object.keys(queries) as Array<QueryName<Queries>>\n\t if (names.length === 0) return Schema.Never as unknown as Schema.Schema<QueryName<Queries>, any>\n\t if (names.length === 1) {\n\t return Schema.Literal(names[0] as any) as unknown as Schema.Schema<QueryName<Queries>, any>\n\t }\n const asUnionMembers = <A>(items: ReadonlyArray<A>): readonly [A, A, ...Array<A>] => {\n if (items.length < 2) {\n throw new Error(`[Query.make] internal error: expected at least 2 query names for union`)\n }\n return items as unknown as readonly [A, A, ...Array<A>]\n }\n\n\t const members = names.map((n) => Schema.Literal(n as any))\n\t return Schema.Union(...asUnionMembers(members)) as unknown as Schema.Schema<QueryName<Queries>, any>\n\t })()\n\n const UiSchema = Schema.Unknown as Schema.Schema<TUI, any>\n\n\t const QueriesSchema = Schema.Struct(\n\t Object.fromEntries((Object.keys(queries) as Array<keyof Queries>).map((k) => [k, Schema.Unknown])) as Record<\n\t string,\n\t Schema.Schema<any, any>\n\t >,\n\t )\n\n const StateSchema = Schema.Struct({\n params: config.params,\n ui: UiSchema,\n queries: QueriesSchema,\n }) as unknown as Schema.Schema<QueryState<TParams, TUI, Queries>, any>\n\n const Actions = {\n setParams: config.params,\n setUi: UiSchema,\n refresh: Schema.UndefinedOr(RefreshTargetSchema),\n invalidate: InvalidateRequestSchema,\n } satisfies QueryActions<TParams, TUI, Queries>\n\n type Reducers = Logix.ReducersFromMap<typeof StateSchema, typeof Actions>\n\n const reducers: Reducers = {\n setParams: (state, action, sink) => {\n sink?.('params')\n return { ...state, params: action.payload ?? state.params }\n },\n setUi: (state, action, sink) => {\n sink?.('ui')\n return { ...state, ui: action.payload ?? state.ui }\n },\n refresh: (state) => state,\n invalidate: (state) => state,\n } satisfies Reducers\n\n const queryTraits =\n Object.keys(queriesForTraits).length > 0 ? toStateTraitSpec<TParams, TUI>({ queries: queriesForTraits }) : undefined\n\n const traits =\n queryTraits || config.traits\n ? ({\n ...(queryTraits as any),\n ...(config.traits as any),\n } as any)\n : undefined\n\n const module = Logix.Module.make(id, {\n state: StateSchema,\n actions: Actions,\n reducers,\n traits,\n })\n\n const logics = [\n autoTrigger<any, TParams, TUI>(module.tag as any, { queries: queriesForTraits }),\n invalidate<any, TParams, TUI>(module.tag as any, { queries: queriesForTraits }),\n ] satisfies ReadonlyArray<Logix.ModuleLogic<any, any, any>>\n\n const initial = (params?: TParams): QueryState<TParams, TUI, Queries> =>\n ({\n params: params ?? config.initialParams,\n ui: (config.ui ?? ({} as unknown as TUI)) as TUI,\n queries: Object.fromEntries(\n (Object.keys(queries) as Array<keyof Queries>).map((k) => [k, Logix.Resource.Snapshot.idle()]),\n ),\n }) as QueryState<TParams, TUI, Queries>\n\n\t const controller: QueryModuleController<TParams, TUI, Queries> = {\n\t make: (\n\t runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, Queries>, QueryAction<TParams, TUI, Queries>>,\n\t ): QueryController<TParams, TUI, Queries> => {\n\t const dispatch = runtime.dispatch\n\t const actions = module.actions as unknown as {\n\t readonly setParams: (params: TParams) => QueryAction<TParams, TUI, Queries>\n\t readonly setUi: (ui: TUI) => QueryAction<TParams, TUI, Queries>\n\t readonly refresh: (target: QueryName<Queries> | undefined) => QueryAction<TParams, TUI, Queries>\n\t readonly invalidate: (request: InvalidateRequest) => QueryAction<TParams, TUI, Queries>\n\t }\n\t\t return {\n\t\t runtime,\n\t\t getState: runtime.getState as Effect.Effect<QueryState<TParams, TUI, Queries>>,\n\t\t dispatch,\n\t controller: {\n\t setParams: (params: TParams) => dispatch(actions.setParams(params)),\n\t setUi: (ui: TUI) => dispatch(actions.setUi(ui)),\n\t refresh: (target?: QueryName<Queries>) => dispatch(actions.refresh(target)),\n\t\t invalidate: (request: InvalidateRequest) => dispatch(actions.invalidate(request)),\n\t\t },\n\t\t } as QueryController<TParams, TUI, Queries>\n\t\t },\n\t\t }\n\n ;(module as any).controller = controller\n\n const EXTEND_HANDLE = Symbol.for('logix.module.handle.extend')\n ;(module.tag as any)[EXTEND_HANDLE] = (\n runtime: Logix.ModuleRuntime<QueryState<TParams, TUI, Queries>, QueryAction<TParams, TUI, Queries>>,\n base: Logix.ModuleHandle<any>,\n ) => {\n const c = controller.make(runtime)\n return {\n ...base,\n controller: c.controller,\n }\n }\n\n return module.implement({\n initial: initial(),\n logics: [...logics],\n }) as unknown as QueryModule<Id, TParams, TUI, Queries>\n}\n","import * as Logix from '@logixjs/core'\nimport { Duration, Effect, Fiber } from 'effect'\nimport type { QuerySourceConfig, QueryTrigger } from '../../Traits.js'\nimport { Engine } from '../../Engine.js'\n\nconst defaultTriggers = ['onMount', 'onKeyChange'] as const\n\nconst getTriggers = (triggers: ReadonlyArray<QueryTrigger> | undefined): ReadonlyArray<QueryTrigger> =>\n triggers ?? defaultTriggers\n\nconst isManualOnly = (triggers: ReadonlyArray<QueryTrigger>): boolean =>\n triggers.length === 1 && triggers[0] === 'manual'\n\nconst getSnapshotKeyHash = (snapshot: unknown): string | undefined => {\n if (!snapshot || typeof snapshot !== 'object') return undefined\n const keyHash = (snapshot as any).keyHash\n return typeof keyHash === 'string' ? keyHash : undefined\n}\n\nconst getSnapshotStatus = (snapshot: unknown): string | undefined => {\n if (!snapshot || typeof snapshot !== 'object') return undefined\n const status = (snapshot as any).status\n return typeof status === 'string' ? status : undefined\n}\n\nexport interface AutoTriggerLogicConfig<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>\n}\n\n/**\n * Query auto-trigger logic:\n * - onMount: triggers once on initialization (if the key is valid and current snapshot does not match the same keyHash).\n * - onKeyChange: triggers after params/ui state changes (can debounce; only when keyHash changes or current is idle).\n * - manual-only: when triggers=[\"manual\"], disable onMount/onKeyChange auto triggering.\n */\nexport const autoTrigger = <Sh extends Logix.AnyModuleShape, TParams, TUI>(\n module: Logix.ModuleTagType<any, Sh>,\n config: AutoTriggerLogicConfig<TParams, TUI>,\n): Logix.ModuleLogic<Sh, any, never> =>\n module.logic(($) => {\n type _State = Logix.StateOf<Sh> & { readonly queries: Record<string, unknown> }\n type QueryName = Extract<keyof typeof config.queries, string>\n\n const pending = new Map<string, Fiber.RuntimeFiber<void, any>>()\n const lastKeyHash = new Map<string, string | undefined>()\n\n const hydrateFromFreshCache = (\n name: QueryName,\n q: QuerySourceConfig<TParams, TUI>,\n keyHash: string,\n ): Effect.Effect<boolean, never, any> =>\n Effect.gen(function* () {\n const engineOpt = yield* Effect.serviceOption(Engine)\n if (engineOpt._tag === 'None') return false\n\n const engine = engineOpt.value\n if (!engine.peekFresh) return false\n\n const dataOpt = yield* engine.peekFresh({\n resourceId: q.resource.id,\n keyHash,\n })\n if (dataOpt._tag === 'None') return false\n\n const snapshot = Logix.Resource.Snapshot.success({\n keyHash,\n data: dataOpt.value,\n })\n yield* $.state.mutate((draft) => {\n ;(draft as Logix.Logic.Draft<_State>).queries[name] = snapshot\n })\n\n return true\n })\n\n const cancelPending = (name: string): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n const prev = pending.get(name)\n if (!prev) return\n pending.delete(name)\n yield* Fiber.interruptFork(prev)\n })\n\n const sourcePathOf = (name: QueryName): string => `queries.${name}`\n\n const refresh = (name: QueryName, options?: { readonly force?: boolean }): Effect.Effect<void, never, any> =>\n $.traits.source.refresh(sourcePathOf(name) as any, options as any) as Effect.Effect<void, never, any>\n\n const scheduleDebounced = (name: QueryName, ms: number): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n yield* cancelPending(name)\n const fiber = yield* Effect.forkScoped(\n Effect.sleep(Duration.millis(ms)).pipe(\n Effect.zipRight(refresh(name)),\n Effect.ensuring(Effect.sync(() => pending.delete(name))),\n Effect.catchAllCause(() => Effect.void),\n ),\n )\n pending.set(name, fiber)\n })\n\n const computeKeyHash = (state: any, q: QuerySourceConfig<TParams, TUI>): string | undefined => {\n const getAtPath = (root: any, path: string): unknown => {\n const parts = path.split('.')\n let cur = root\n for (const p of parts) {\n if (cur == null) return undefined\n cur = cur[p]\n }\n return cur\n }\n\n try {\n const keyState = { params: state.params as any, ui: state.ui as any } as any\n const args = (q.deps as ReadonlyArray<string>).map((dep) => getAtPath(keyState, dep))\n const key = (q.key as any)(...args)\n if (key === undefined) return undefined\n return Logix.Resource.keyHash(key)\n } catch {\n return undefined\n }\n }\n\n const maybeAutoRefresh = (\n phase: 'mount' | 'keyChange',\n stateOverride?: unknown,\n ): Effect.Effect<void, never, any> =>\n Effect.gen(function* () {\n const state = (stateOverride ?? (yield* $.state.read)) as any\n\n for (const [name, q] of Object.entries(config.queries)) {\n const queryName = name as QueryName\n const triggers = getTriggers(q.triggers)\n if (isManualOnly(triggers)) {\n continue\n }\n\n if (phase === 'mount' && !triggers.includes('onMount')) {\n continue\n }\n\n if (phase === 'keyChange' && !triggers.includes('onKeyChange')) {\n continue\n }\n\n const keyHash = computeKeyHash(state, q)\n const snapshot = state?.queries?.[queryName]\n const snapshotKeyHash = getSnapshotKeyHash(snapshot)\n const snapshotStatus = getSnapshotStatus(snapshot)\n\n // Key is unavailable: do not refresh (idle reaping is guaranteed by kernel syncIdleInTransaction).\n if (keyHash === undefined) {\n lastKeyHash.set(queryName, undefined)\n continue\n }\n\n // keyHash unchanged and we already have a non-idle snapshot: avoid re-entering loading (reuse existing result).\n const last = lastKeyHash.get(queryName)\n if (snapshotStatus && snapshotStatus !== 'idle' && snapshotKeyHash === keyHash && last === keyHash) {\n continue\n }\n\n // If current snapshot is already success/error/loading with the same keyHash: update lastKeyHash and skip.\n if (snapshotStatus && snapshotStatus !== 'idle' && snapshotKeyHash === keyHash) {\n lastKeyHash.set(queryName, keyHash)\n continue\n }\n\n lastKeyHash.set(queryName, keyHash)\n\n // TanStack Query scenario: if we can hit the fresh cache, write a success snapshot directly,\n // skipping source.refresh (avoids UI jitter and extra transactions like \"cache hit but still loading -> success\").\n const hydrated = yield* hydrateFromFreshCache(queryName, q, keyHash)\n if (hydrated) {\n yield* cancelPending(queryName)\n continue\n }\n\n const debounceMs = q.debounceMs ?? 0\n if (phase === 'keyChange' && debounceMs > 0) {\n yield* scheduleDebounced(queryName, debounceMs)\n } else {\n // mount / no debounce: trigger immediately\n yield* cancelPending(queryName)\n yield* refresh(queryName)\n }\n }\n })\n\n const refreshAll = (options?: { readonly force?: boolean }): Effect.Effect<void, never, any> =>\n Effect.forEach(Object.keys(config.queries), (name) =>\n cancelPending(name).pipe(Effect.zipRight(refresh(name as QueryName, options))),\n ).pipe(Effect.asVoid)\n\n const setup = $.lifecycle.onStart(maybeAutoRefresh('mount'))\n\n const run = Effect.suspend(() =>\n Effect.all(\n [\n // params/ui changes: handled by Query's default logic, avoiding scattered UI-side useEffect triggers.\n $.onAction('setParams').runFork((action: any) =>\n Effect.gen(function* () {\n const state = (yield* $.state.read) as any\n const next = { ...state, params: action.payload }\n yield* maybeAutoRefresh('keyChange', next)\n }),\n ),\n $.onAction('setUi').runFork((action: any) =>\n Effect.gen(function* () {\n const state = (yield* $.state.read) as any\n const next = { ...state, ui: action.payload }\n yield* maybeAutoRefresh('keyChange', next)\n }),\n ),\n\n // Manual refresh: not restricted by triggers (manual-only still allows explicit refresh).\n $.onAction('refresh').runFork((action: any) =>\n Effect.gen(function* () {\n const target = action.payload as QueryName | undefined\n if (typeof target === 'string' && target.length > 0) {\n yield* cancelPending(target)\n yield* refresh(target, { force: true })\n } else {\n yield* refreshAll({ force: true })\n }\n }),\n ),\n ],\n { concurrency: 'unbounded' },\n ).pipe(Effect.asVoid),\n )\n\n return { setup, run }\n }) as Logix.ModuleLogic<Sh, any, never>\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport type { JsonValue } from '@logixjs/core/Observability'\nimport { Context, Effect, Layer, Option } from 'effect'\nimport { middleware as middlewareImpl, type MiddlewareConfig } from './internal/middleware/middleware.js'\n\nexport type InvalidateRequest =\n | { readonly kind: 'byResource'; readonly resourceId: string }\n | { readonly kind: 'byParams'; readonly resourceId: string; readonly keyHash: string }\n | { readonly kind: 'byTag'; readonly tag: string }\n\nexport interface Engine {\n readonly fetch: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n readonly effect: Effect.Effect<A, unknown, any>\n /**\n * MUST be serializable and slim; recommended default is undefined (lazy),\n * and only populate it when diagnostics/devtools require it.\n */\n readonly meta?: JsonValue\n }) => Effect.Effect<A, unknown, any>\n\n /**\n * perf: optional fast path to avoid allocations on the hot path.\n * Semantics must match `fetch({ ... })`.\n */\n readonly fetchFast?: <A>(\n resourceId: string,\n keyHash: string,\n effect: Effect.Effect<A, unknown, any>,\n meta?: JsonValue,\n ) => Effect.Effect<A, unknown, any>\n\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void, unknown, any>\n\n /**\n * Read-only fast path: must not trigger IO; used to short-circuit to success before refresh,\n * avoiding loading jitter.\n */\n readonly peekFresh?: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n }) => Effect.Effect<Option.Option<A>, never, any>\n}\n\nclass EngineTagImpl extends Context.Tag('@logixjs/query/Engine')<EngineTagImpl, Engine>() {}\n\nexport const Engine = Object.assign(EngineTagImpl, {\n layer: (engine: Engine): Layer.Layer<EngineTagImpl, never, never> => Layer.succeed(EngineTagImpl, engine),\n middleware: (config?: MiddlewareConfig): EffectOp.Middleware => middlewareImpl(config),\n})\n\nexport type { MiddlewareConfig }\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Effect, Option } from 'effect'\nimport { Engine } from '../../Engine.js'\nimport type { Engine as EngineService } from '../../Engine.js'\n\nexport interface MiddlewareConfig {\n /**\n * Default: only applies to EffectOp that carries resourceId+keyHash (from StateTrait.source).\n * Optional: further filter by resourceId.\n */\n readonly useFor?: (resourceId: string) => boolean\n}\n\n/**\n * Query middleware (EffectOp): external engine takeover point.\n * - Delegates ResourceSpec.load execution to Engine (cache / in-flight dedupe / invalidation, etc.)\n * - Still preserves Logix Runtime's keyHash gating and ResourceSnapshot source-of-truth semantics\n */\nexport const middleware = (config?: MiddlewareConfig): EffectOp.Middleware =>\n (() => {\n // perf: within the same Runtime instance, Engine injection is stable.\n // Cache it in the middleware closure to avoid a Context lookup on every fetch.\n let cachedEngine: EngineService | undefined\n\n return (op) => {\n if ((op.kind !== 'service' && op.kind !== 'trait-source') || !op.meta?.resourceId || !op.meta.keyHash) {\n return op.effect as any\n }\n\n const resourceId = op.meta.resourceId\n if (config?.useFor && !config.useFor(resourceId)) {\n return op.effect as any\n }\n\n const keyHash = op.meta.keyHash as string\n\n if (cachedEngine) {\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }\n\n return Effect.serviceOption(Engine).pipe(\n Effect.flatMap((engineOpt) => {\n if (Option.isNone(engineOpt)) {\n return Effect.fail(\n new Error(\n `[Query.Engine.middleware] Missing Query.Engine in the Runtime scope; please provide Query.Engine.layer(Query.TanStack.engine(new QueryClient())) (recommended) or Query.Engine.layer(customEngine).`,\n ),\n )\n }\n cachedEngine = engineOpt.value\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }),\n ) as any\n }\n })()\n","import * as Logix from '@logixjs/core'\nimport { Effect } from 'effect'\nimport { Engine, type InvalidateRequest } from '../../Engine.js'\nimport type { QuerySourceConfig } from '../../Traits.js'\n\nexport interface InvalidateLogicConfig<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>\n}\n\nconst toInvalidateTargets = <TParams, TUI>(\n request: InvalidateRequest,\n queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI>>>,\n): ReadonlyArray<{ readonly name: string; readonly resourceId: string }> => {\n if (request.kind === 'byResource') {\n return Object.entries(queries)\n .filter(([, q]) => q.resource.id === request.resourceId)\n .map(([name, q]) => ({ name, resourceId: q.resource.id }))\n }\n\n if (request.kind === 'byParams') {\n return Object.entries(queries)\n .filter(([, q]) => q.resource.id === request.resourceId)\n .map(([name, q]) => ({ name, resourceId: q.resource.id }))\n }\n\n // byTag: prefer QuerySourceConfig.tags for static filtering; if tags are missing, conservatively fall back to refreshing all.\n const entries = Object.entries(queries)\n const tagged = entries.filter(([, q]) => Array.isArray(q.tags) && q.tags.includes(request.tag))\n const selected = tagged.length > 0 ? tagged : entries\n return selected.map(([name, q]) => ({ name, resourceId: q.resource.id }))\n}\n\nexport const invalidate = <Sh extends Logix.AnyModuleShape, TParams, TUI>(\n module: Logix.ModuleTagType<any, Sh>,\n config: InvalidateLogicConfig<TParams, TUI>,\n): Logix.ModuleLogic<Sh, any, never> =>\n module.logic(($) =>\n Effect.gen(function* () {\n yield* $.onAction('invalidate').runFork((action: any) =>\n Effect.gen(function* () {\n const request = action.payload as InvalidateRequest\n\n // 1) Eventize: goes into ReplayLog (kernel-owned).\n yield* Logix.TraitLifecycle.scopedExecute($ as any, {\n kind: 'query:invalidate',\n request,\n })\n\n // 2) Call external engine (optional): does not block the fallback path.\n const engineOpt = yield* Effect.serviceOption(Engine)\n if (engineOpt._tag !== 'None') {\n yield* engineOpt.value.invalidate(request)\n }\n\n // 3) Immediately refresh related sources (write-back gating is still guaranteed by kernel keyHash).\n const targets = toInvalidateTargets<TParams, TUI>(request, config.queries)\n const sourcePathOf = (name: string): string => `queries.${name}`\n yield* Effect.forEach(\n targets,\n (t) =>\n $.traits.source.refresh(sourcePathOf(t.name) as any, { force: true }) as Effect.Effect<void, never, any>,\n ).pipe(Effect.asVoid)\n }),\n )\n }),\n ) as Logix.ModuleLogic<Sh, any, never>\n","import * as Logix from '@logixjs/core'\n\nexport type QueryTrigger = 'onMount' | 'onKeyChange' | 'manual'\n\nexport type QueryConcurrency = 'switch' | 'exhaust'\n\nexport type QueryResourceRef = { readonly id: string }\n\nexport type QueryResource = QueryResourceRef | Logix.Resource.ResourceSpec<any, any, any, any>\n\nexport type QueryResourceKey<R> = R extends Logix.Resource.ResourceSpec<infer Key, any, any, any> ? Key : unknown\n\nexport type QueryResourceData<R> = R extends Logix.Resource.ResourceSpec<any, infer Data, any, any> ? Data : unknown\n\nexport type QueryResourceError<R> = R extends Logix.Resource.ResourceSpec<any, any, infer Err, any> ? Err : unknown\n\nexport type QueryKeyState<TParams, TUI> = Readonly<{\n readonly params: TParams\n readonly ui: TUI\n}>\n\nexport type QueryDepsPath<TParams, TUI> = Logix.StateTrait.StateFieldPath<QueryKeyState<TParams, TUI>>\n\ntype DepsArgs<S extends object, Deps extends ReadonlyArray<string>> = {\n readonly [K in keyof Deps]: Deps[K] extends Logix.StateTrait.StateFieldPath<S>\n ? Logix.StateTrait.StateAtPath<S, Deps[K]>\n : any\n}\n\ntype BivariantCallback<Args extends ReadonlyArray<any>, R> = {\n bivarianceHack(...args: Args): R\n}['bivarianceHack']\n\nexport interface QuerySourceConfig<\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n> {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n /**\n * Optional exportable trait meta (Devtools / Static IR / docs).\n *\n * Constraints:\n * - Must be serializable (JsonValue only); no closures/functions/Effect/DOM objects.\n * - Keep it slim; use `annotations` with `x-*` keys for extension hints.\n */\n readonly meta?: Logix.StateTrait.TraitMeta\n /**\n * Optional static tags for invalidate(byTag), used to narrow byTag from \"refresh all\" to a matched subset.\n * - Must be serializable (recommend: string constants only)\n * - If omitted, byTag conservatively falls back to refreshing everything\n */\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: BivariantCallback<DepsArgs<QueryKeyState<TParams, TUI>, Deps>, QueryResourceKey<R> | undefined>\n}\n\nexport type QueryBuilder<TParams, TUI> = {\n readonly source: <\n R extends QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n >(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly meta?: Logix.StateTrait.TraitMeta\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n }) => QuerySourceConfig<TParams, TUI, R, Deps>\n}\n\n/**\n * Query.source:\n * - Strongly typed helper to preserve `deps` as a tuple and infer `key(...depsValues)` argument types from it.\n * - Recommended usage inside `Query.make(..., { queries: { name: Query.source({ ... }) } })`.\n */\nexport const source = <\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n>(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly meta?: Logix.StateTrait.TraitMeta\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n}): QuerySourceConfig<TParams, TUI, R, Deps> => config as QuerySourceConfig<TParams, TUI, R, Deps>\n\nexport interface QueryTraitsInput<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI, any>>>\n}\n\n/**\n * Lowering rules (Query -> StateTrait):\n * - Each Query rule maps to a `StateTrait.source`, writing back to `queries.<name>` (isomorphic to module state).\n * - keySelector computes key from `{ params; ui }`; keyHash/race gating is guaranteed by the kernel source runtime.\n *\n * Notes:\n * - deps uses module-root paths (e.g. \"params.q\" / \"ui.query.autoEnabled\"), aligned with the constraints in 007/004.\n * - concurrency \"exhaust\" is represented as \"exhaust-trailing\" in the kernel.\n */\nexport const toStateTraitSpec = <TParams, TUI>(\n input: QueryTraitsInput<TParams, TUI>,\n): Logix.StateTrait.StateTraitSpec<any> => {\n const out: Record<string, Logix.StateTrait.StateTraitEntry<any, any>> = {}\n\n for (const [name, q] of Object.entries(input.queries)) {\n const triggers = q.triggers ?? (['onMount', 'onKeyChange'] as const)\n\n // \"manual\" must be exclusive to avoid ambiguous semantics (configuration error).\n if (triggers.includes('manual') && triggers.length > 1) {\n throw new Error(\n `[Query.traits] \"manual\" must be exclusive, but got triggers=[${triggers.join(', ')}] for query \"${name}\".`,\n )\n }\n\n out[`queries.${name}`] = Logix.StateTrait.source({\n // deps: used for graph building/diagnostics/future reverse-closure; Query also reuses deps to converge triggers.\n deps: q.deps as any,\n resource: q.resource.id,\n triggers,\n debounceMs: q.debounceMs,\n concurrency: q.concurrency === 'exhaust' ? 'exhaust-trailing' : q.concurrency,\n key: (...depsValues: ReadonlyArray<any>) => (q.key as any)(...depsValues),\n meta: q.meta,\n })\n }\n\n return out as Logix.StateTrait.StateTraitSpec<any>\n}\n","export * from './internal/engine/tanstack.js'\nexport * from './internal/tanstack/observer.js'\n","import { Effect, Option } from 'effect'\nimport type { QueryClient } from '@tanstack/query-core'\nimport type { Engine, InvalidateRequest } from '../../Engine.js'\n\nconst makeQueryKey = (resourceId: string, keyHash: string) => [resourceId, keyHash] as const\n\nexport interface TanStackEngineConfig {\n /**\n * The max number of entries per resourceId in the local fast cache.\n * - Goal: prevent unbounded memory growth when the key space is unbounded.\n * - Semantics: evicts oldest entries in insertion order (FIFO); cache misses fall back to re-loading.\n * - Set to Infinity to disable the cap (not recommended for long-running processes).\n */\n readonly maxEntriesPerResource?: number\n}\n\n/**\n * TanStack engine:\n * - Uses QueryClient for invalidation (easy integration with TanStack ecosystem).\n * - fetch/peekFresh uses a slim in-memory cache to avoid frequently creating Query objects on the Logix runtime hot path.\n * - Still preserves Logix Runtime's keyHash gating and ResourceSnapshot source-of-truth semantics.\n */\nexport const engine = (queryClient: QueryClient, config?: TanStackEngineConfig): Engine => {\n const byResourceId = new Map<string, Map<string, unknown>>()\n const maxEntriesPerResource = config?.maxEntriesPerResource ?? 2000\n\n // Align with external QueryClient.clear(): when QueryCache is cleared, clear the local fast cache as well.\n try {\n const queryCache: any = (queryClient as any).getQueryCache?.()\n if (queryCache && typeof queryCache.clear === 'function') {\n const original = queryCache.clear.bind(queryCache)\n queryCache.clear = () => {\n byResourceId.clear()\n return original()\n }\n }\n } catch {\n // ignore\n }\n\n const ensureBucket = (resourceId: string): Map<string, unknown> => {\n let bucket = byResourceId.get(resourceId)\n if (!bucket) {\n bucket = new Map<string, unknown>()\n byResourceId.set(resourceId, bucket)\n }\n return bucket\n }\n\n const evictIfNeeded = (bucket: Map<string, unknown>): void => {\n if (maxEntriesPerResource === Infinity) return\n if (!Number.isFinite(maxEntriesPerResource) || maxEntriesPerResource <= 0) return\n while (bucket.size > maxEntriesPerResource) {\n const firstKey = bucket.keys().next().value as string | undefined\n if (firstKey === undefined) return\n bucket.delete(firstKey)\n }\n }\n\n const fetchFast: Engine['fetchFast'] = (resourceId, keyHash, effect) =>\n Effect.suspend(() => {\n const hit = byResourceId.get(resourceId)?.get(keyHash)\n if (hit !== undefined) {\n return Effect.succeed(hit as any)\n }\n\n return Effect.map(effect, (out) => {\n if (out !== undefined) {\n const bucket = ensureBucket(resourceId)\n bucket.set(keyHash, out)\n evictIfNeeded(bucket)\n }\n return out as any\n })\n })\n\n return {\n fetch: ({ resourceId, keyHash, effect }) => fetchFast!(resourceId, keyHash, effect),\n\n fetchFast,\n\n invalidate: (request: InvalidateRequest) =>\n Effect.gen(function* () {\n yield* Effect.sync(() => {\n if (request.kind === 'byParams') {\n const bucket = byResourceId.get(request.resourceId)\n if (!bucket) return\n bucket.delete(request.keyHash)\n if (bucket.size === 0) {\n byResourceId.delete(request.resourceId)\n }\n return\n }\n\n if (request.kind === 'byResource') {\n byResourceId.delete(request.resourceId)\n return\n }\n\n // byTag: we currently lack a serializable tags mapping; conservatively clear all (explainable but coarse).\n byResourceId.clear()\n })\n\n // Sync to QueryClient (if there are external observers/ecosystem consumers).\n yield* Effect.tryPromise({\n try: () => {\n if (request.kind === 'byResource') {\n return queryClient.invalidateQueries({\n queryKey: [request.resourceId],\n })\n }\n\n if (request.kind === 'byParams') {\n return queryClient.invalidateQueries({\n queryKey: makeQueryKey(request.resourceId, request.keyHash),\n })\n }\n\n return queryClient.invalidateQueries({\n predicate: (q) => {\n const tags = (q.meta as any)?.tags\n return Array.isArray(tags) && tags.includes(request.tag)\n },\n })\n },\n catch: (e) => e,\n }).pipe(Effect.asVoid)\n }),\n\n peekFresh: <A>({ resourceId, keyHash }: { readonly resourceId: string; readonly keyHash: string }) =>\n Effect.sync(() => {\n const hit = byResourceId.get(resourceId)?.get(keyHash) as A | undefined\n return hit === undefined ? Option.none<A>() : Option.some(hit)\n }),\n }\n}\n","import { Effect } from 'effect'\nimport type { QueryClient } from '@tanstack/query-core'\nimport { QueryObserver } from '@tanstack/query-core'\n\n/**\n * observe (subscribe within scope + cleanup):\n * - For scenarios where you want \"TanStack-like automatic tracking\" of enabled/queryKey changes.\n * - Provided as infrastructure; domain logic can choose to use it (no hard dependency).\n */\nexport const observe = <TData = unknown>(params: {\n readonly queryClient: QueryClient\n readonly options: ConstructorParameters<typeof QueryObserver<TData>>[1]\n readonly onResult: (result: unknown) => void\n}): Effect.Effect<QueryObserver<TData>, never, any> =>\n Effect.gen(function* () {\n const observer = new QueryObserver<TData>(params.queryClient, params.options as any)\n const unsubscribe = observer.subscribe(params.onResult as any)\n yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribe()))\n return observer\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,SAAuB;AACvB,IAAAC,iBAA+B;;;ACD/B,YAAuB;AACvB,IAAAC,iBAAwC;;;ACCxC,IAAAC,iBAA+C;;;ACD/C,oBAA+B;AAiBxB,IAAM,aAAa,CAAC,WACxB,uBAAM;AAGL,MAAI;AAEJ,SAAO,CAAC,OAAO;AACb,QAAK,GAAG,SAAS,aAAa,GAAG,SAAS,kBAAmB,CAAC,GAAG,MAAM,cAAc,CAAC,GAAG,KAAK,SAAS;AACrG,aAAO,GAAG;A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U,OAAO,QAAe;AAC7D,SAAO,sBAAO,aAAa,MAAM,sBAAO,KAAK,MAAM,YAAY,CAAC,CAAC;AACjE,SAAO;AACT,CAAC;","names":["Logix","import_effect","import_effect","import_effect","engine","module","engine","Logix","import_effect","module","Logix","module","import_effect","import_effect"]}
package/dist/index.d.cts CHANGED
@@ -5,4 +5,5 @@ export { T as TanStack } from './TanStack-C3mxN6Aj.cjs';
5
5
  import '@logixjs/core';
6
6
  import 'effect';
7
7
  import '@logixjs/core/EffectOp';
8
+ import '@logixjs/core/Observability';
8
9
  import '@tanstack/query-core';
package/dist/index.d.ts CHANGED
@@ -5,4 +5,5 @@ export { T as TanStack } from './TanStack-jQhqYG8i.js';
5
5
  import '@logixjs/core';
6
6
  import 'effect';
7
7
  import '@logixjs/core/EffectOp';
8
+ import '@logixjs/core/Observability';
8
9
  import '@tanstack/query-core';
package/dist/index.js CHANGED
@@ -1,16 +1,16 @@
1
1
  import {
2
2
  make
3
- } from "./chunk-NXFX6RIH.js";
3
+ } from "./chunk-DMEHDC55.js";
4
4
  import {
5
5
  Engine
6
- } from "./chunk-THVAADR2.js";
6
+ } from "./chunk-7IVR4THQ.js";
7
7
  import {
8
8
  TanStack_exports
9
9
  } from "./chunk-L745BR5P.js";
10
10
  import {
11
11
  source,
12
12
  toStateTraitSpec
13
- } from "./chunk-V3F5KWNH.js";
13
+ } from "./chunk-BERAWANA.js";
14
14
  import "./chunk-PZ5AY32C.js";
15
15
  export {
16
16
  Engine,
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@logixjs/query",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
+ "license": "Apache-2.0",
4
5
  "description": "Query domain package for Logix v3 Trait system",
5
6
  "files": [
6
7
  "dist/**"
@@ -29,7 +30,7 @@
29
30
  "dependencies": {
30
31
  "@tanstack/query-core": "^5.90.12",
31
32
  "effect": "^3.19.8",
32
- "@logixjs/core": "0.0.1"
33
+ "@logixjs/core": "0.0.2"
33
34
  },
34
35
  "devDependencies": {
35
36
  "@effect/vitest": "^0.27.0",
@@ -40,7 +41,7 @@
40
41
  "peerDependencies": {
41
42
  "effect": "^3.19.8",
42
43
  "react": ">=18.0.0",
43
- "@logixjs/core": "0.0.1"
44
+ "@logixjs/core": "0.0.2"
44
45
  },
45
46
  "scripts": {
46
47
  "build": "tsup",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/Engine.ts","../src/internal/middleware/middleware.ts"],"sourcesContent":["import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Context, Effect, Layer, Option } from 'effect'\nimport { middleware as middlewareImpl, type MiddlewareConfig } from './internal/middleware/middleware.js'\n\nexport type InvalidateRequest =\n | { readonly kind: 'byResource'; readonly resourceId: string }\n | { readonly kind: 'byParams'; readonly resourceId: string; readonly keyHash: string }\n | { readonly kind: 'byTag'; readonly tag: string }\n\nexport interface Engine {\n readonly fetch: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n readonly effect: Effect.Effect<A, unknown, any>\n /**\n * MUST be serializable and slim; recommended default is undefined (lazy),\n * and only populate it when diagnostics/devtools require it.\n */\n readonly meta?: unknown\n }) => Effect.Effect<A, unknown, any>\n\n /**\n * perf: optional fast path to avoid allocations on the hot path.\n * Semantics must match `fetch({ ... })`.\n */\n readonly fetchFast?: <A>(\n resourceId: string,\n keyHash: string,\n effect: Effect.Effect<A, unknown, any>,\n meta?: unknown,\n ) => Effect.Effect<A, unknown, any>\n\n readonly invalidate: (request: InvalidateRequest) => Effect.Effect<void, unknown, any>\n\n /**\n * Read-only fast path: must not trigger IO; used to short-circuit to success before refresh,\n * avoiding loading jitter.\n */\n readonly peekFresh?: <A>(args: {\n readonly resourceId: string\n readonly keyHash: string\n }) => Effect.Effect<Option.Option<A>, never, any>\n}\n\nclass EngineTagImpl extends Context.Tag('@logixjs/query/Engine')<EngineTagImpl, Engine>() {}\n\nexport const Engine = Object.assign(EngineTagImpl, {\n layer: (engine: Engine): Layer.Layer<EngineTagImpl, never, never> => Layer.succeed(EngineTagImpl, engine),\n middleware: (config?: MiddlewareConfig): EffectOp.Middleware => middlewareImpl(config),\n})\n\nexport type { MiddlewareConfig }\n","import type * as EffectOp from '@logixjs/core/EffectOp'\nimport { Effect, Option } from 'effect'\nimport { Engine } from '../../Engine.js'\nimport type { Engine as EngineService } from '../../Engine.js'\n\nexport interface MiddlewareConfig {\n /**\n * Default: only applies to EffectOp that carries resourceId+keyHash (from StateTrait.source).\n * Optional: further filter by resourceId.\n */\n readonly useFor?: (resourceId: string) => boolean\n}\n\n/**\n * Query middleware (EffectOp): external engine takeover point.\n * - Delegates ResourceSpec.load execution to Engine (cache / in-flight dedupe / invalidation, etc.)\n * - Still preserves Logix Runtime's keyHash gating and ResourceSnapshot source-of-truth semantics\n */\nexport const middleware = (config?: MiddlewareConfig): EffectOp.Middleware =>\n (() => {\n // perf: within the same Runtime instance, Engine injection is stable.\n // Cache it in the middleware closure to avoid a Context lookup on every fetch.\n let cachedEngine: EngineService | undefined\n\n return (op) => {\n if ((op.kind !== 'service' && op.kind !== 'trait-source') || !op.meta?.resourceId || !op.meta.keyHash) {\n return op.effect as any\n }\n\n const resourceId = op.meta.resourceId\n if (config?.useFor && !config.useFor(resourceId)) {\n return op.effect as any\n }\n\n const keyHash = op.meta.keyHash as string\n\n if (cachedEngine) {\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cachedEngine.fetch({ resourceId, keyHash, effect: op.effect as any })\n }\n\n return Effect.serviceOption(Engine).pipe(\n Effect.flatMap((engineOpt) => {\n if (Option.isNone(engineOpt)) {\n return Effect.fail(\n new Error(\n `[Query.Engine.middleware] Missing Query.Engine in the Runtime scope; please provide Query.Engine.layer(Query.TanStack.engine(new QueryClient())) (recommended) or Query.Engine.layer(customEngine).`,\n ),\n )\n }\n cachedEngine = engineOpt.value\n if (cachedEngine.fetchFast) {\n return cachedEngine.fetchFast(resourceId, keyHash, op.effect as any)\n }\n return cached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AM;AAAA,EACxG,YAAY,CAAC,WAAmD,WAAe,MAAM;AACvF,CAAC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/Traits.ts"],"sourcesContent":["import * as Logix from '@logixjs/core'\n\nexport type QueryTrigger = 'onMount' | 'onKeyChange' | 'manual'\n\nexport type QueryConcurrency = 'switch' | 'exhaust'\n\nexport type QueryResourceRef = { readonly id: string }\n\nexport type QueryResource = QueryResourceRef | Logix.Resource.ResourceSpec<any, any, any, any>\n\nexport type QueryResourceKey<R> = R extends Logix.Resource.ResourceSpec<infer Key, any, any, any> ? Key : unknown\n\nexport type QueryResourceData<R> = R extends Logix.Resource.ResourceSpec<any, infer Data, any, any> ? Data : unknown\n\nexport type QueryResourceError<R> = R extends Logix.Resource.ResourceSpec<any, any, infer Err, any> ? Err : unknown\n\nexport type QueryKeyState<TParams, TUI> = Readonly<{\n readonly params: TParams\n readonly ui: TUI\n}>\n\nexport type QueryDepsPath<TParams, TUI> = Logix.StateTrait.StateFieldPath<QueryKeyState<TParams, TUI>>\n\ntype DepsArgs<S extends object, Deps extends ReadonlyArray<string>> = {\n readonly [K in keyof Deps]: Deps[K] extends Logix.StateTrait.StateFieldPath<S>\n ? Logix.StateTrait.StateAtPath<S, Deps[K]>\n : any\n}\n\ntype BivariantCallback<Args extends ReadonlyArray<any>, R> = {\n bivarianceHack(...args: Args): R\n}['bivarianceHack']\n\nexport interface QuerySourceConfig<\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n> {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n /**\n * Optional static tags for invalidate(byTag), used to narrow byTag from \"refresh all\" to a matched subset.\n * - Must be serializable (recommend: string constants only)\n * - If omitted, byTag conservatively falls back to refreshing everything\n */\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: BivariantCallback<DepsArgs<QueryKeyState<TParams, TUI>, Deps>, QueryResourceKey<R> | undefined>\n}\n\nexport type QueryBuilder<TParams, TUI> = {\n readonly source: <\n R extends QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n >(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n }) => QuerySourceConfig<TParams, TUI, R, Deps>\n}\n\n/**\n * Query.source:\n * - Strongly typed helper to preserve `deps` as a tuple and infer `key(...depsValues)` argument types from it.\n * - Recommended usage inside `Query.make(..., { queries: { name: Query.source({ ... }) } })`.\n */\nexport const source = <\n TParams,\n TUI = unknown,\n R extends QueryResource = QueryResource,\n const Deps extends ReadonlyArray<string> = ReadonlyArray<QueryDepsPath<TParams, TUI>>,\n>(config: {\n readonly resource: R\n readonly deps: Deps & ReadonlyArray<QueryDepsPath<TParams, TUI>>\n readonly triggers?: ReadonlyArray<QueryTrigger>\n readonly tags?: ReadonlyArray<string>\n readonly debounceMs?: number\n readonly concurrency?: QueryConcurrency\n readonly key: (...depsValues: DepsArgs<QueryKeyState<TParams, TUI>, Deps>) => QueryResourceKey<R> | undefined\n}): QuerySourceConfig<TParams, TUI, R, Deps> => config as QuerySourceConfig<TParams, TUI, R, Deps>\n\nexport interface QueryTraitsInput<TParams, TUI> {\n readonly queries: Readonly<Record<string, QuerySourceConfig<TParams, TUI, any>>>\n}\n\n/**\n * Lowering rules (Query -> StateTrait):\n * - Each Query rule maps to a `StateTrait.source`, writing back to `queries.<name>` (isomorphic to module state).\n * - keySelector computes key from `{ params; ui }`; keyHash/race gating is guaranteed by the kernel source runtime.\n *\n * Notes:\n * - deps uses module-root paths (e.g. \"params.q\" / \"ui.query.autoEnabled\"), aligned with the constraints in 007/004.\n * - concurrency \"exhaust\" is represented as \"exhaust-trailing\" in the kernel.\n */\nexport const toStateTraitSpec = <TParams, TUI>(\n input: QueryTraitsInput<TParams, TUI>,\n): Logix.StateTrait.StateTraitSpec<any> => {\n const out: Record<string, Logix.StateTrait.StateTraitEntry<any, any>> = {}\n\n for (const [name, q] of Object.entries(input.queries)) {\n const triggers = q.triggers ?? (['onMount', 'onKeyChange'] as const)\n\n // \"manual\" must be exclusive to avoid ambiguous semantics (configuration error).\n if (triggers.includes('manual') && triggers.length > 1) {\n throw new Error(\n `[Query.traits] \"manual\" must be exclusive, but got triggers=[${triggers.join(', ')}] for query \"${name}\".`,\n )\n }\n\n out[`queries.${name}`] = Logix.StateTrait.source({\n // deps: used for graph building/diagnostics/future reverse-closure; Query also reuses deps to converge triggers.\n deps: q.deps as any,\n resource: q.resource.id,\n triggers,\n debounceMs: q.debounceMs,\n concurrency: q.concurrency === 'exhaust' ? 'exhaust-trailing' : q.concurrency,\n key: (...depsValues: ReadonlyArray<any>) => (q.key as any)(...depsValues),\n })\n }\n\n return out as Logix.StateTrait.StateTraitSpec<any>\n}\n"],"mappings":";AAAA,YAAY,WAAW;AAyEhB,IAAM,SAAS,CAKpB,WAQ8C;AAezC,IAAM,mBAAmB,CAC9B,UACyC;AACzC,QAAM,MAAkE,CAAC;AAEzE,aAAW,CAAC,MAAM,CAAC,KAAK,OAAO,QAAQ,MAAM,OAAO,GAAG;AACrD,UAAM,WAAW,EAAE,YAAa,CAAC,WAAW,aAAa;AAGzD,QAAI,SAAS,SAAS,QAAQ,KAAK,SAAS,SAAS,GAAG;AACtD,YAAM,IAAI;AAAA,QACR,gEAAgE,SAAS,KAAK,IAAI,CAAC,gBAAgB,IAAI;AAAA,MACzG;AAAA,IACF;AAEA,QAAI,WAAW,IAAI,EAAE,IAAU,iBAAW,OAAO;AAAA;AAAA,MAE/C,MAAM,EAAE;AAAA,MACR,UAAU,EAAE,SAAS;AAAA,MACrB;AAAA,MACA,YAAY,EAAE;AAAA,MACd,aAAa,EAAE,gBAAgB,YAAY,qBAAqB,EAAE;AAAA,MAClE,KAAK,IAAI,eAAoC,EAAE,IAAY,GAAG,UAAU;AAAA,IAC1E,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}