ascua-query 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +68 -0
- package/dist/index.d.ts +145 -0
- package/dist/index.js +424 -0
- package/package.json +49 -0
package/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Los autores de Ascua
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# ascua-query
|
|
2
|
+
|
|
3
|
+
Datos remotos para [Ascua](https://ascua.gitweave.run) en **2,15 kB** gzip: una
|
|
4
|
+
caché compartida por clave encima de los signals del runtime. Dos vistas que
|
|
5
|
+
piden lo mismo hacen una sola petición; una mutación invalida lo que cambió y
|
|
6
|
+
todo lo que lo muestra se recarga.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
stil add ascua-query # o npm install ascua-query
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { invalidate, mutation, remote } from "ascua-query";
|
|
14
|
+
|
|
15
|
+
const filters = signal({ status: "open", page: 1 });
|
|
16
|
+
|
|
17
|
+
const conversations = remote({
|
|
18
|
+
key: () => ["conversations", filters()], // reactiva: cambia, recarga
|
|
19
|
+
load: ([, f], { signal }) => api.conversations(f, { signal }),
|
|
20
|
+
keepPrevious: true, // sin pantalla en blanco al paginar
|
|
21
|
+
interval: 15_000, // sondeo, solo con la pestaña visible
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const create = mutation({
|
|
25
|
+
run: (data: NewUser) => api.createUser(data),
|
|
26
|
+
onSuccess: () => invalidate(["users"]), // `pending()` espera a la recarga
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
view`
|
|
30
|
+
<Show when=${() => conversations()}>${(c) => view`<Table rows=${c}/>`}</Show>
|
|
31
|
+
<button disabled=${() => create.pending()} onclick=${() => create.mutate(form())}>Create</button>`;
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Sin contexto ni proveedor que instalar, como el router: la caché es del
|
|
35
|
+
módulo. Una consulta se suscribe mientras vive el scope en que se creó; al
|
|
36
|
+
cerrar la vista la suelta, y lo que nadie mira se borra pasado `gcTime`.
|
|
37
|
+
|
|
38
|
+
## Lo que hay
|
|
39
|
+
|
|
40
|
+
| | |
|
|
41
|
+
|---|---|
|
|
42
|
+
| `remote({ key, load, … })` | Una consulta. Se lee llamándola; `state()`, `loading()`, `error()`, `placeholder()`, `updatedAt()`, `reload()`. |
|
|
43
|
+
| `mutation({ run, onMutate, onSuccess, onError, onSettled })` | Una escritura: `mutate()`, `mutateAsync()`, `state()`, `pending()`, `data()`, `error()`, `reset()`. |
|
|
44
|
+
| `invalidate(prefix?)` | Caduca lo que empieza por `prefix`; lo que se está mirando, se recarga ya. |
|
|
45
|
+
| `setData(key, value \| (old) => next)` / `getData(key)` | Leer y escribir la caché a mano: actualizaciones optimistas. |
|
|
46
|
+
| `cancel(prefix?)` | Corta las cargas en camino, para que no pisen una escritura optimista. |
|
|
47
|
+
| `prefetch(key, load)` | Cargar antes de que una vista lo pida. |
|
|
48
|
+
| `configure({ staleTime, gcTime, retry, retryDelay, refetchOnFocus })` | Valores por defecto de todas las consultas. |
|
|
49
|
+
| `clearCache()` | Vaciarla: tests y cierres de sesión. |
|
|
50
|
+
|
|
51
|
+
Los valores por defecto son los de TanStack Query, para que migrar no cambie
|
|
52
|
+
el comportamiento: `staleTime: 0`, `gcTime` de cinco minutos, tres reintentos
|
|
53
|
+
con espera creciente y recarga al volver a la pestaña o a la red.
|
|
54
|
+
|
|
55
|
+
Lo que no hay que escribir a mano:
|
|
56
|
+
|
|
57
|
+
- **Deduplicación.** Mientras una clave está cargando, quien la pida espera
|
|
58
|
+
esa misma carga.
|
|
59
|
+
- **Una respuesta vieja nunca pisa a una nueva.** Una recarga aborta la
|
|
60
|
+
anterior (el `signal` que recibe `load` se dispara) y descarta su respuesta.
|
|
61
|
+
- **Un sondeo que trae lo mismo no repinta nada.** Lo nuevo reusa cada objeto
|
|
62
|
+
de lo anterior que no cambió: con un `<For>` con clave, solo se toca la
|
|
63
|
+
fila que cambió.
|
|
64
|
+
- **La clave es reactiva.** `key: () => id() ? ["messages", id()] : null`: con
|
|
65
|
+
`null` la consulta queda en `idle`, igual que un `resource`.
|
|
66
|
+
|
|
67
|
+
`remote` se llama así, y no `query`, porque `ascua-router` ya exporta
|
|
68
|
+
`query()` —los parámetros de la URL— y una vista de lista suele usar los dos.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* # ascua-query
|
|
3
|
+
*
|
|
4
|
+
* Datos remotos para Ascua: una caché compartida por clave encima de los
|
|
5
|
+
* signals del runtime. Lo que `resource` hace para una vista —cargar, recargar,
|
|
6
|
+
* cancelar—, aquí lo comparten todas: dos vistas que piden la misma clave
|
|
7
|
+
* hacen una sola petición, una mutación invalida lo que cambió y todo lo que
|
|
8
|
+
* lo muestra se recarga.
|
|
9
|
+
*
|
|
10
|
+
* Sin contexto ni proveedor que instalar, como el router: la caché es del
|
|
11
|
+
* módulo. Los valores por defecto son los de TanStack Query, para que migrar
|
|
12
|
+
* no cambie el comportamiento: los datos caducan al momento (`staleTime: 0`),
|
|
13
|
+
* la caché de lo que nadie mira dura cinco minutos, se reintenta tres veces y
|
|
14
|
+
* se recarga al volver a la pestaña.
|
|
15
|
+
*/
|
|
16
|
+
/** La clave de una consulta: `["conversations", { page: 2 }]`. */
|
|
17
|
+
export type QueryKey = readonly unknown[];
|
|
18
|
+
/** En qué está una consulta. Como `ResourceState` del runtime. */
|
|
19
|
+
export type QueryState = "idle" | "loading" | "ready" | "error";
|
|
20
|
+
/** Lo que recibe `load`: con qué cancelar la petición. */
|
|
21
|
+
export interface LoadInfo {
|
|
22
|
+
signal: AbortSignal;
|
|
23
|
+
}
|
|
24
|
+
/** Lo que se puede configurar para todas las consultas. */
|
|
25
|
+
export interface QueryDefaults {
|
|
26
|
+
/** Milisegundos durante los que un dato se da por fresco. Por defecto, 0. */
|
|
27
|
+
staleTime: number;
|
|
28
|
+
/** Cuánto sigue en caché lo que ninguna vista mira. Por defecto, 5 minutos. */
|
|
29
|
+
gcTime: number;
|
|
30
|
+
/** Reintentos tras un fallo. Por defecto, 3. */
|
|
31
|
+
retry: number;
|
|
32
|
+
/** Espera antes del reintento `n` (desde 0). Por defecto, 1 s, 2 s, 4 s… hasta 30 s. */
|
|
33
|
+
retryDelay: (attempt: number) => number;
|
|
34
|
+
/** Recargar lo caducado al volver a la pestaña o a la red. Por defecto, sí. */
|
|
35
|
+
refetchOnFocus: boolean;
|
|
36
|
+
}
|
|
37
|
+
export interface RemoteOptions<K extends QueryKey, T, R = T> extends Partial<QueryDefaults> {
|
|
38
|
+
/**
|
|
39
|
+
* La clave. Es reactiva: si lee un signal, la consulta sigue a ese signal.
|
|
40
|
+
* `null`, `undefined` o `false` la desactivan (queda en `idle`).
|
|
41
|
+
*/
|
|
42
|
+
key: () => K | null | undefined | false;
|
|
43
|
+
/** Carga los datos de una clave. */
|
|
44
|
+
load: (key: K, info: LoadInfo) => Promise<T>;
|
|
45
|
+
/**
|
|
46
|
+
* Recargar cada tantos milisegundos mientras la vista esté montada y la
|
|
47
|
+
* pestaña visible. Puede ser reactivo: `() => polling() ? 5000 : false`.
|
|
48
|
+
*/
|
|
49
|
+
interval?: number | false | (() => number | false);
|
|
50
|
+
/** Al cambiar de clave, seguir mostrando los datos anteriores hasta que lleguen los nuevos. */
|
|
51
|
+
keepPrevious?: boolean;
|
|
52
|
+
/** Transforma lo cargado antes de entregarlo. */
|
|
53
|
+
select?: (data: T) => R;
|
|
54
|
+
}
|
|
55
|
+
/** Una consulta: se lee llamándola, como un signal. */
|
|
56
|
+
export interface Remote<R> {
|
|
57
|
+
/** Los datos, o `undefined` hasta que lleguen. Mientras se recarga siguen ahí. */
|
|
58
|
+
(): R | undefined;
|
|
59
|
+
state(): QueryState;
|
|
60
|
+
/** Hay una carga en camino: la primera o una recarga. */
|
|
61
|
+
loading(): boolean;
|
|
62
|
+
/** El error de la última carga, o `undefined` si fue bien. */
|
|
63
|
+
error(): unknown;
|
|
64
|
+
/** Lo que se ve es de la clave anterior (`keepPrevious`) mientras carga la nueva. */
|
|
65
|
+
placeholder(): boolean;
|
|
66
|
+
/** Cuándo llegaron los datos (`Date.now()`), o 0 si aún no. */
|
|
67
|
+
updatedAt(): number;
|
|
68
|
+
/** Vuelve a cargar ahora, aunque los datos estén frescos. */
|
|
69
|
+
reload(): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
/** Cambia los valores por defecto de todas las consultas. */
|
|
72
|
+
export declare function configure(opciones: Partial<QueryDefaults>): void;
|
|
73
|
+
/**
|
|
74
|
+
* Datos remotos con caché: `const users = remote({ key: () => ["users"], load: api.users })`.
|
|
75
|
+
*
|
|
76
|
+
* Carga al crearse si no hay datos frescos para la clave, y cada vez que la
|
|
77
|
+
* clave cambia. Se suscribe a la entrada de la caché mientras viva el scope
|
|
78
|
+
* en que se creó: al cerrar la vista la suelta, y lo que nadie mira se borra
|
|
79
|
+
* pasado `gcTime`. En el servidor no carga: se queda en `idle`.
|
|
80
|
+
*/
|
|
81
|
+
export declare function remote<K extends QueryKey, T, R = T>(opciones: RemoteOptions<K, T, R>): Remote<R>;
|
|
82
|
+
/**
|
|
83
|
+
* Da por caducado todo lo que empieza por `prefix` (`["users"]` cubre
|
|
84
|
+
* `["users", 4]`; sin prefijo, todo). Lo que alguna vista está mirando se
|
|
85
|
+
* recarga ya, cortando la carga en camino si la hay; el resto, la próxima vez
|
|
86
|
+
* que se monte. La promesa se cumple cuando terminan las recargas.
|
|
87
|
+
*/
|
|
88
|
+
export declare function invalidate(prefix?: QueryKey, options?: {
|
|
89
|
+
refetch?: boolean;
|
|
90
|
+
}): Promise<void>;
|
|
91
|
+
/** Los datos en caché de una clave exacta, sin cargar nada. */
|
|
92
|
+
export declare function getData<T>(key: QueryKey): T | undefined;
|
|
93
|
+
/**
|
|
94
|
+
* Escribe los datos de una clave como si acabaran de llegar: lo que ya se
|
|
95
|
+
* sabe tras guardar algo, o una actualización optimista.
|
|
96
|
+
*/
|
|
97
|
+
export declare function setData<T>(key: QueryKey, value: T | ((old: T | undefined) => T)): T;
|
|
98
|
+
/**
|
|
99
|
+
* Corta las cargas en camino de lo que empieza por `prefix`. Antes de una
|
|
100
|
+
* actualización optimista, para que una respuesta vieja no pise lo escrito.
|
|
101
|
+
*/
|
|
102
|
+
export declare function cancel(prefix?: QueryKey): Promise<void>;
|
|
103
|
+
/** Carga una clave antes de que una vista la pida (si no hay datos frescos). */
|
|
104
|
+
export declare function prefetch<K extends QueryKey, T>(key: K, load: (key: K, info: LoadInfo) => Promise<T>, options?: Partial<QueryDefaults>): Promise<void>;
|
|
105
|
+
/** Vacía la caché entera, cortando lo que esté en camino. Para tests y cierres de sesión. */
|
|
106
|
+
export declare function clearCache(): void;
|
|
107
|
+
/** En qué está una mutación. */
|
|
108
|
+
export type MutationState = "idle" | "pending" | "success" | "error";
|
|
109
|
+
export interface MutationOptions<V, R, C = unknown> {
|
|
110
|
+
/** Lo que guarda: una petición al servidor. */
|
|
111
|
+
run: (variables: V) => Promise<R>;
|
|
112
|
+
/**
|
|
113
|
+
* Antes de `run`. Lo que devuelva llega como contexto a los demás: el
|
|
114
|
+
* estado anterior para deshacer una actualización optimista.
|
|
115
|
+
*/
|
|
116
|
+
onMutate?: (variables: V) => C | Promise<C>;
|
|
117
|
+
onSuccess?: (data: R, variables: V, context: C | undefined) => unknown;
|
|
118
|
+
onError?: (error: unknown, variables: V, context: C | undefined) => unknown;
|
|
119
|
+
/** Al terminar, haya ido bien o mal. */
|
|
120
|
+
onSettled?: (data: R | undefined, error: unknown, variables: V, context: C | undefined) => unknown;
|
|
121
|
+
}
|
|
122
|
+
/** Sin variables, `mutate()` se llama sin argumentos. */
|
|
123
|
+
type Variables<V> = undefined extends V ? [variables?: V] : [variables: V];
|
|
124
|
+
export interface Mutation<V, R> {
|
|
125
|
+
/** Lanza la mutación. Un fallo queda en `error()`: no hace falta capturarlo. */
|
|
126
|
+
mutate(...variables: Variables<V>): void;
|
|
127
|
+
/** Igual, pero devuelve el resultado y rechaza si falla. */
|
|
128
|
+
mutateAsync(...variables: Variables<V>): Promise<R>;
|
|
129
|
+
state(): MutationState;
|
|
130
|
+
pending(): boolean;
|
|
131
|
+
/** El resultado de la última que fue bien. */
|
|
132
|
+
data(): R | undefined;
|
|
133
|
+
error(): unknown;
|
|
134
|
+
/** Vuelve a `idle`, olvidando resultado y error. */
|
|
135
|
+
reset(): void;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Una escritura con su estado: `const save = mutation({ run: api.save, onSuccess: () => invalidate(["users"]) })`.
|
|
139
|
+
*
|
|
140
|
+
* Los `on…` se esperan si devuelven una promesa: `pending()` sigue siendo
|
|
141
|
+
* `true` mientras `onSuccess` recarga lo que invalidó, así que el botón no se
|
|
142
|
+
* libera antes de que la lista esté al día.
|
|
143
|
+
*/
|
|
144
|
+
export declare function mutation<V = void, R = unknown, C = unknown>(opciones: MutationOptions<V, R, C>): Mutation<V, R>;
|
|
145
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* # ascua-query
|
|
3
|
+
*
|
|
4
|
+
* Datos remotos para Ascua: una caché compartida por clave encima de los
|
|
5
|
+
* signals del runtime. Lo que `resource` hace para una vista —cargar, recargar,
|
|
6
|
+
* cancelar—, aquí lo comparten todas: dos vistas que piden la misma clave
|
|
7
|
+
* hacen una sola petición, una mutación invalida lo que cambió y todo lo que
|
|
8
|
+
* lo muestra se recarga.
|
|
9
|
+
*
|
|
10
|
+
* Sin contexto ni proveedor que instalar, como el router: la caché es del
|
|
11
|
+
* módulo. Los valores por defecto son los de TanStack Query, para que migrar
|
|
12
|
+
* no cambie el comportamiento: los datos caducan al momento (`staleTime: 0`),
|
|
13
|
+
* la caché de lo que nadie mira dura cinco minutos, se reintenta tres veces y
|
|
14
|
+
* se recarga al volver a la pestaña.
|
|
15
|
+
*/
|
|
16
|
+
import { batch, effect, memo, onCleanup, signal, untrack } from "ascua";
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// La caché
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
const porDefecto = {
|
|
21
|
+
staleTime: 0,
|
|
22
|
+
gcTime: 5 * 60_000,
|
|
23
|
+
retry: 3,
|
|
24
|
+
retryDelay: (n) => Math.min(1000 * 2 ** n, 30_000),
|
|
25
|
+
refetchOnFocus: true,
|
|
26
|
+
};
|
|
27
|
+
/** Cambia los valores por defecto de todas las consultas. */
|
|
28
|
+
export function configure(opciones) {
|
|
29
|
+
Object.assign(porDefecto, opciones);
|
|
30
|
+
}
|
|
31
|
+
const cache = new Map();
|
|
32
|
+
/** Un texto estable para una clave: los objetos, con las propiedades ordenadas. */
|
|
33
|
+
function hashDe(clave) {
|
|
34
|
+
return JSON.stringify(clave, (_, valor) => valor && typeof valor === "object" && !Array.isArray(valor)
|
|
35
|
+
? Object.fromEntries(Object.keys(valor)
|
|
36
|
+
.sort()
|
|
37
|
+
.map((k) => [k, valor[k]]))
|
|
38
|
+
: valor);
|
|
39
|
+
}
|
|
40
|
+
/** ¿Empieza `clave` por `prefijo`? `["users"]` cubre `["users", 4]`. */
|
|
41
|
+
function coincide(prefijo, clave) {
|
|
42
|
+
return prefijo.length <= clave.length && prefijo.every((p, i) => hashDe([p]) === hashDe([clave[i]]));
|
|
43
|
+
}
|
|
44
|
+
function obtener(clave) {
|
|
45
|
+
const hash = hashDe(clave);
|
|
46
|
+
let e = cache.get(hash);
|
|
47
|
+
if (!e) {
|
|
48
|
+
e = {
|
|
49
|
+
clave,
|
|
50
|
+
hash,
|
|
51
|
+
datos: signal(undefined),
|
|
52
|
+
estado: signal("idle"),
|
|
53
|
+
fallo: signal(undefined),
|
|
54
|
+
actualizado: signal(0),
|
|
55
|
+
invalidada: false,
|
|
56
|
+
opciones: { ...porDefecto },
|
|
57
|
+
oyentes: 0,
|
|
58
|
+
};
|
|
59
|
+
cache.set(hash, e);
|
|
60
|
+
programarRecogida(e);
|
|
61
|
+
}
|
|
62
|
+
return e;
|
|
63
|
+
}
|
|
64
|
+
function caducada(e) {
|
|
65
|
+
const cuando = e.actualizado.peek();
|
|
66
|
+
return e.invalidada || cuando === 0 || Date.now() - cuando >= e.opciones.staleTime;
|
|
67
|
+
}
|
|
68
|
+
function esperar(ms, señal) {
|
|
69
|
+
return new Promise((resolver, rechazar) => {
|
|
70
|
+
const t = setTimeout(resolver, ms);
|
|
71
|
+
señal.addEventListener("abort", () => {
|
|
72
|
+
clearTimeout(t);
|
|
73
|
+
rechazar(señal.reason);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
/** Carga una entrada. Si ya hay una carga en camino, es esa: no se duplica. */
|
|
78
|
+
function cargar(e) {
|
|
79
|
+
if (e.vuelo)
|
|
80
|
+
return e.vuelo;
|
|
81
|
+
const fn = e.cargar;
|
|
82
|
+
if (!fn)
|
|
83
|
+
return Promise.resolve();
|
|
84
|
+
const control = new AbortController();
|
|
85
|
+
const { retry, retryDelay } = e.opciones;
|
|
86
|
+
e.control = control;
|
|
87
|
+
e.estado.set("loading");
|
|
88
|
+
const vuelo = (async () => {
|
|
89
|
+
for (let intento = 0;; intento++) {
|
|
90
|
+
try {
|
|
91
|
+
return await fn(e.clave, { signal: control.signal });
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (control.signal.aborted || intento >= retry)
|
|
95
|
+
throw error;
|
|
96
|
+
await esperar(retryDelay(intento), control.signal);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
})()
|
|
100
|
+
.then((dato) => {
|
|
101
|
+
if (control.signal.aborted)
|
|
102
|
+
return;
|
|
103
|
+
e.invalidada = false;
|
|
104
|
+
batch(() => {
|
|
105
|
+
e.datos.set(compartir(e.datos.peek(), dato));
|
|
106
|
+
e.fallo.set(undefined);
|
|
107
|
+
e.actualizado.set(Date.now());
|
|
108
|
+
e.estado.set("ready");
|
|
109
|
+
});
|
|
110
|
+
}, (error) => {
|
|
111
|
+
if (control.signal.aborted)
|
|
112
|
+
return;
|
|
113
|
+
batch(() => {
|
|
114
|
+
e.fallo.set(error);
|
|
115
|
+
e.estado.set("error");
|
|
116
|
+
});
|
|
117
|
+
})
|
|
118
|
+
.finally(() => {
|
|
119
|
+
if (e.control === control) {
|
|
120
|
+
e.control = undefined;
|
|
121
|
+
e.vuelo = undefined;
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
e.vuelo = vuelo;
|
|
125
|
+
return vuelo;
|
|
126
|
+
}
|
|
127
|
+
/** Corta la carga en camino y deja el estado como estaba antes de empezarla. */
|
|
128
|
+
function abortar(e) {
|
|
129
|
+
if (!e.control)
|
|
130
|
+
return;
|
|
131
|
+
e.control.abort();
|
|
132
|
+
e.control = undefined;
|
|
133
|
+
e.vuelo = undefined;
|
|
134
|
+
e.estado.set(e.fallo.peek() !== undefined ? "error" : e.datos.peek() !== undefined ? "ready" : "idle");
|
|
135
|
+
}
|
|
136
|
+
function programarRecogida(e) {
|
|
137
|
+
if (e.gc)
|
|
138
|
+
clearTimeout(e.gc);
|
|
139
|
+
const t = setTimeout(() => {
|
|
140
|
+
if (e.oyentes > 0 || cache.get(e.hash) !== e)
|
|
141
|
+
return;
|
|
142
|
+
abortar(e);
|
|
143
|
+
cache.delete(e.hash);
|
|
144
|
+
}, e.opciones.gcTime);
|
|
145
|
+
// En Node, un temporizador de la caché no debe mantener vivo el proceso.
|
|
146
|
+
t.unref?.();
|
|
147
|
+
e.gc = t;
|
|
148
|
+
}
|
|
149
|
+
function suscribir(e) {
|
|
150
|
+
e.oyentes++;
|
|
151
|
+
if (e.gc) {
|
|
152
|
+
clearTimeout(e.gc);
|
|
153
|
+
e.gc = undefined;
|
|
154
|
+
}
|
|
155
|
+
escucharFoco();
|
|
156
|
+
}
|
|
157
|
+
function soltar(e) {
|
|
158
|
+
e.oyentes--;
|
|
159
|
+
if (e.oyentes === 0)
|
|
160
|
+
programarRecogida(e);
|
|
161
|
+
}
|
|
162
|
+
const enNavegador = typeof window !== "undefined" && typeof document !== "undefined";
|
|
163
|
+
let escuchando = false;
|
|
164
|
+
function escucharFoco() {
|
|
165
|
+
if (escuchando || !enNavegador)
|
|
166
|
+
return;
|
|
167
|
+
escuchando = true;
|
|
168
|
+
const alVolver = () => {
|
|
169
|
+
for (const e of cache.values()) {
|
|
170
|
+
if (e.oyentes > 0 && e.opciones.refetchOnFocus && caducada(e))
|
|
171
|
+
void cargar(e);
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
document.addEventListener("visibilitychange", () => {
|
|
175
|
+
if (document.visibilityState === "visible")
|
|
176
|
+
alVolver();
|
|
177
|
+
});
|
|
178
|
+
window.addEventListener("online", alVolver);
|
|
179
|
+
}
|
|
180
|
+
function esPlano(v) {
|
|
181
|
+
if (!v || typeof v !== "object")
|
|
182
|
+
return false;
|
|
183
|
+
const proto = Object.getPrototypeOf(v);
|
|
184
|
+
return proto === Object.prototype || proto === null;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Lo nuevo, pero reusando de lo viejo cada objeto que no cambió. Un sondeo que
|
|
188
|
+
* trae lo mismo devuelve el mismo objeto, y nada se vuelve a pintar; si cambió
|
|
189
|
+
* una fila, las demás conservan su identidad.
|
|
190
|
+
*/
|
|
191
|
+
function compartir(viejo, nuevo) {
|
|
192
|
+
if (viejo === nuevo)
|
|
193
|
+
return viejo;
|
|
194
|
+
const arreglos = Array.isArray(viejo) && Array.isArray(nuevo);
|
|
195
|
+
if (!arreglos && !(esPlano(viejo) && esPlano(nuevo)))
|
|
196
|
+
return nuevo;
|
|
197
|
+
const a = viejo;
|
|
198
|
+
const b = nuevo;
|
|
199
|
+
const claves = Object.keys(b);
|
|
200
|
+
const resultado = arreglos ? [] : {};
|
|
201
|
+
let iguales = claves.length === Object.keys(a).length;
|
|
202
|
+
for (const k of claves) {
|
|
203
|
+
const v = compartir(a[k], b[k]);
|
|
204
|
+
resultado[k] = v;
|
|
205
|
+
if (v !== a[k] || !(k in a))
|
|
206
|
+
iguales = false;
|
|
207
|
+
}
|
|
208
|
+
return iguales ? viejo : resultado;
|
|
209
|
+
}
|
|
210
|
+
// ---------------------------------------------------------------------------
|
|
211
|
+
// Consultas
|
|
212
|
+
// ---------------------------------------------------------------------------
|
|
213
|
+
/**
|
|
214
|
+
* Datos remotos con caché: `const users = remote({ key: () => ["users"], load: api.users })`.
|
|
215
|
+
*
|
|
216
|
+
* Carga al crearse si no hay datos frescos para la clave, y cada vez que la
|
|
217
|
+
* clave cambia. Se suscribe a la entrada de la caché mientras viva el scope
|
|
218
|
+
* en que se creó: al cerrar la vista la suelta, y lo que nadie mira se borra
|
|
219
|
+
* pasado `gcTime`. En el servidor no carga: se queda en `idle`.
|
|
220
|
+
*/
|
|
221
|
+
export function remote(opciones) {
|
|
222
|
+
const actual = signal(null);
|
|
223
|
+
/** La última entrada que tenía datos: lo que `keepPrevious` sigue mostrando. */
|
|
224
|
+
let anterior = null;
|
|
225
|
+
effect(() => {
|
|
226
|
+
const clave = opciones.key();
|
|
227
|
+
if (clave === null || clave === undefined || clave === false) {
|
|
228
|
+
actual.set(null);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
untrack(() => {
|
|
232
|
+
const e = obtener(clave);
|
|
233
|
+
e.cargar = opciones.load;
|
|
234
|
+
e.opciones = {
|
|
235
|
+
staleTime: opciones.staleTime ?? porDefecto.staleTime,
|
|
236
|
+
gcTime: opciones.gcTime ?? porDefecto.gcTime,
|
|
237
|
+
retry: opciones.retry ?? porDefecto.retry,
|
|
238
|
+
retryDelay: opciones.retryDelay ?? porDefecto.retryDelay,
|
|
239
|
+
refetchOnFocus: opciones.refetchOnFocus ?? porDefecto.refetchOnFocus,
|
|
240
|
+
};
|
|
241
|
+
suscribir(e);
|
|
242
|
+
onCleanup(() => soltar(e));
|
|
243
|
+
const previa = actual.peek();
|
|
244
|
+
if (previa && previa !== e && previa.datos.peek() !== undefined)
|
|
245
|
+
anterior = previa;
|
|
246
|
+
actual.set(e);
|
|
247
|
+
if (enNavegador && !e.vuelo && caducada(e))
|
|
248
|
+
void cargar(e);
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
if (opciones.interval) {
|
|
252
|
+
effect(() => {
|
|
253
|
+
const e = actual();
|
|
254
|
+
const intervalo = opciones.interval;
|
|
255
|
+
const ms = typeof intervalo === "function" ? intervalo() : intervalo;
|
|
256
|
+
if (!e || !ms || !enNavegador)
|
|
257
|
+
return;
|
|
258
|
+
const t = setInterval(() => {
|
|
259
|
+
if (document.visibilityState !== "hidden")
|
|
260
|
+
void cargar(e);
|
|
261
|
+
}, ms);
|
|
262
|
+
onCleanup(() => clearInterval(t));
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
const propia = memo(() => actual()?.datos());
|
|
266
|
+
const placeholder = memo(() => {
|
|
267
|
+
if (!opciones.keepPrevious || !actual() || propia() !== undefined)
|
|
268
|
+
return false;
|
|
269
|
+
return anterior?.datos() !== undefined;
|
|
270
|
+
});
|
|
271
|
+
const crudo = memo(() => (placeholder() ? anterior?.datos() : propia()));
|
|
272
|
+
const seleccion = memo(() => {
|
|
273
|
+
const dato = crudo();
|
|
274
|
+
return dato === undefined || !opciones.select ? dato : opciones.select(dato);
|
|
275
|
+
});
|
|
276
|
+
const consulta = (() => seleccion());
|
|
277
|
+
consulta.state = () => actual()?.estado() ?? "idle";
|
|
278
|
+
consulta.loading = () => consulta.state() === "loading";
|
|
279
|
+
consulta.error = () => actual()?.fallo();
|
|
280
|
+
consulta.placeholder = placeholder;
|
|
281
|
+
consulta.updatedAt = () => actual()?.actualizado() ?? 0;
|
|
282
|
+
consulta.reload = () => {
|
|
283
|
+
const e = actual.peek();
|
|
284
|
+
if (!e)
|
|
285
|
+
return Promise.resolve();
|
|
286
|
+
abortar(e);
|
|
287
|
+
return cargar(e);
|
|
288
|
+
};
|
|
289
|
+
return consulta;
|
|
290
|
+
}
|
|
291
|
+
// ---------------------------------------------------------------------------
|
|
292
|
+
// La caché a mano
|
|
293
|
+
// ---------------------------------------------------------------------------
|
|
294
|
+
function entradas(prefijo) {
|
|
295
|
+
return [...cache.values()].filter((e) => coincide(prefijo, e.clave));
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Da por caducado todo lo que empieza por `prefix` (`["users"]` cubre
|
|
299
|
+
* `["users", 4]`; sin prefijo, todo). Lo que alguna vista está mirando se
|
|
300
|
+
* recarga ya, cortando la carga en camino si la hay; el resto, la próxima vez
|
|
301
|
+
* que se monte. La promesa se cumple cuando terminan las recargas.
|
|
302
|
+
*/
|
|
303
|
+
export function invalidate(prefix = [], options = {}) {
|
|
304
|
+
const recargas = [];
|
|
305
|
+
for (const e of entradas(prefix)) {
|
|
306
|
+
e.invalidada = true;
|
|
307
|
+
if (e.oyentes > 0 && options.refetch !== false && enNavegador) {
|
|
308
|
+
abortar(e);
|
|
309
|
+
recargas.push(cargar(e));
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return Promise.all(recargas).then(() => undefined);
|
|
313
|
+
}
|
|
314
|
+
/** Los datos en caché de una clave exacta, sin cargar nada. */
|
|
315
|
+
export function getData(key) {
|
|
316
|
+
return cache.get(hashDe(key))?.datos.peek();
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Escribe los datos de una clave como si acabaran de llegar: lo que ya se
|
|
320
|
+
* sabe tras guardar algo, o una actualización optimista.
|
|
321
|
+
*/
|
|
322
|
+
export function setData(key, value) {
|
|
323
|
+
const e = obtener(key);
|
|
324
|
+
const nuevo = typeof value === "function" ? value(e.datos.peek()) : value;
|
|
325
|
+
e.invalidada = false;
|
|
326
|
+
batch(() => {
|
|
327
|
+
e.datos.set(nuevo);
|
|
328
|
+
e.fallo.set(undefined);
|
|
329
|
+
e.actualizado.set(Date.now());
|
|
330
|
+
if (!e.vuelo)
|
|
331
|
+
e.estado.set("ready");
|
|
332
|
+
});
|
|
333
|
+
return nuevo;
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Corta las cargas en camino de lo que empieza por `prefix`. Antes de una
|
|
337
|
+
* actualización optimista, para que una respuesta vieja no pise lo escrito.
|
|
338
|
+
*/
|
|
339
|
+
export function cancel(prefix = []) {
|
|
340
|
+
for (const e of entradas(prefix))
|
|
341
|
+
abortar(e);
|
|
342
|
+
return Promise.resolve();
|
|
343
|
+
}
|
|
344
|
+
/** Carga una clave antes de que una vista la pida (si no hay datos frescos). */
|
|
345
|
+
export function prefetch(key, load, options = {}) {
|
|
346
|
+
const e = obtener(key);
|
|
347
|
+
e.cargar = load;
|
|
348
|
+
e.opciones = { ...porDefecto, ...options };
|
|
349
|
+
return caducada(e) ? cargar(e) : Promise.resolve();
|
|
350
|
+
}
|
|
351
|
+
/** Vacía la caché entera, cortando lo que esté en camino. Para tests y cierres de sesión. */
|
|
352
|
+
export function clearCache() {
|
|
353
|
+
for (const e of cache.values()) {
|
|
354
|
+
abortar(e);
|
|
355
|
+
if (e.gc)
|
|
356
|
+
clearTimeout(e.gc);
|
|
357
|
+
}
|
|
358
|
+
cache.clear();
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Una escritura con su estado: `const save = mutation({ run: api.save, onSuccess: () => invalidate(["users"]) })`.
|
|
362
|
+
*
|
|
363
|
+
* Los `on…` se esperan si devuelven una promesa: `pending()` sigue siendo
|
|
364
|
+
* `true` mientras `onSuccess` recarga lo que invalidó, así que el botón no se
|
|
365
|
+
* libera antes de que la lista esté al día.
|
|
366
|
+
*/
|
|
367
|
+
export function mutation(opciones) {
|
|
368
|
+
const estado = signal("idle");
|
|
369
|
+
const datos = signal(undefined);
|
|
370
|
+
const fallo = signal(undefined);
|
|
371
|
+
/** Si se lanza otra antes de que termine, el estado es de la última. */
|
|
372
|
+
let vuelta = 0;
|
|
373
|
+
const mutateAsync = async (...args) => {
|
|
374
|
+
const variables = args[0];
|
|
375
|
+
const esta = ++vuelta;
|
|
376
|
+
batch(() => {
|
|
377
|
+
estado.set("pending");
|
|
378
|
+
fallo.set(undefined);
|
|
379
|
+
});
|
|
380
|
+
let contexto;
|
|
381
|
+
try {
|
|
382
|
+
contexto = await opciones.onMutate?.(variables);
|
|
383
|
+
const resultado = await opciones.run(variables);
|
|
384
|
+
await opciones.onSuccess?.(resultado, variables, contexto);
|
|
385
|
+
await opciones.onSettled?.(resultado, undefined, variables, contexto);
|
|
386
|
+
if (esta === vuelta) {
|
|
387
|
+
batch(() => {
|
|
388
|
+
datos.set(resultado);
|
|
389
|
+
estado.set("success");
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
return resultado;
|
|
393
|
+
}
|
|
394
|
+
catch (error) {
|
|
395
|
+
if (esta === vuelta) {
|
|
396
|
+
batch(() => {
|
|
397
|
+
fallo.set(error);
|
|
398
|
+
estado.set("error");
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
await opciones.onError?.(error, variables, contexto);
|
|
402
|
+
await opciones.onSettled?.(undefined, error, variables, contexto);
|
|
403
|
+
throw error;
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
return {
|
|
407
|
+
mutate: (...variables) => {
|
|
408
|
+
mutateAsync(...variables).catch(() => { });
|
|
409
|
+
},
|
|
410
|
+
mutateAsync,
|
|
411
|
+
state: () => estado(),
|
|
412
|
+
pending: () => estado() === "pending",
|
|
413
|
+
data: () => datos(),
|
|
414
|
+
error: () => fallo(),
|
|
415
|
+
reset: () => {
|
|
416
|
+
vuelta++;
|
|
417
|
+
batch(() => {
|
|
418
|
+
estado.set("idle");
|
|
419
|
+
datos.set(undefined);
|
|
420
|
+
fallo.set(undefined);
|
|
421
|
+
});
|
|
422
|
+
},
|
|
423
|
+
};
|
|
424
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "ascua-query",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Datos remotos para Ascua: caché por clave, recarga, sondeo, invalidación y mutaciones optimistas. Sin contexto ni proveedor.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"query",
|
|
7
|
+
"cache",
|
|
8
|
+
"fetch",
|
|
9
|
+
"signals",
|
|
10
|
+
"ascua"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://ascua.gitweave.run",
|
|
13
|
+
"license": "MIT OR Apache-2.0",
|
|
14
|
+
"type": "module",
|
|
15
|
+
"main": "./dist/index.js",
|
|
16
|
+
"module": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"LICENSE-MIT",
|
|
27
|
+
"LICENSE-APACHE"
|
|
28
|
+
],
|
|
29
|
+
"sideEffects": false,
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsc -p tsconfig.build.json",
|
|
35
|
+
"test": "vitest run",
|
|
36
|
+
"size": "node ../../scripts/measure-query.mjs",
|
|
37
|
+
"prepublishOnly": "tsc -p tsconfig.build.json"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"ascua": "^0.5.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"vite": "^8.3.0",
|
|
44
|
+
"vitest": "^5.0.1",
|
|
45
|
+
"happy-dom": "^20.14.5",
|
|
46
|
+
"typescript": "^7.0.2",
|
|
47
|
+
"terser": "^5.51.2"
|
|
48
|
+
}
|
|
49
|
+
}
|