@rojaebl/supa-store 0.0.0-stage → 0.7.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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +707 -3
  3. package/dist/derived.d.ts +9 -0
  4. package/dist/derived.js +103 -0
  5. package/dist/index.d.ts +123 -0
  6. package/dist/index.js +271 -0
  7. package/dist/label.d.ts +5 -0
  8. package/dist/label.js +38 -0
  9. package/dist/mutation.d.ts +46 -0
  10. package/dist/mutation.js +131 -0
  11. package/dist/query.d.ts +184 -0
  12. package/dist/query.js +301 -0
  13. package/dist/react.d.ts +29 -0
  14. package/dist/react.js +36 -0
  15. package/dist/refetch.d.ts +25 -0
  16. package/dist/refetch.js +117 -0
  17. package/dist/resourceHook.d.ts +57 -0
  18. package/dist/resourceHook.js +292 -0
  19. package/dist/rpc/client.d.ts +65 -0
  20. package/dist/rpc/client.js +226 -0
  21. package/dist/rpc/error.d.ts +7 -0
  22. package/dist/rpc/error.js +13 -0
  23. package/dist/rpc/framing.d.ts +4 -0
  24. package/dist/rpc/framing.js +64 -0
  25. package/dist/rpc/index.d.ts +4 -0
  26. package/dist/rpc/index.js +4 -0
  27. package/dist/rpc/session.d.ts +18 -0
  28. package/dist/rpc/session.js +120 -0
  29. package/dist/rpc/transport.d.ts +26 -0
  30. package/dist/rpc/transport.js +122 -0
  31. package/dist/server/core.d.ts +72 -0
  32. package/dist/server/core.js +367 -0
  33. package/dist/server/index.d.ts +2 -0
  34. package/dist/server/index.js +2 -0
  35. package/dist/server/node.d.ts +12 -0
  36. package/dist/server/node.js +240 -0
  37. package/dist/server/sse.d.ts +10 -0
  38. package/dist/server/sse.js +25 -0
  39. package/dist/server/web.d.ts +8 -0
  40. package/dist/server/web.js +147 -0
  41. package/dist/stream/client.d.ts +43 -0
  42. package/dist/stream/client.js +397 -0
  43. package/dist/stream/hook.d.ts +9 -0
  44. package/dist/stream/hook.js +70 -0
  45. package/dist/stream/index.d.ts +53 -0
  46. package/dist/stream/index.js +43 -0
  47. package/dist/stream/protocol.d.ts +105 -0
  48. package/dist/stream/protocol.js +32 -0
  49. package/dist/track.d.ts +19 -0
  50. package/dist/track.js +25 -0
  51. package/package.json +104 -3
  52. package/tools/decline-loader.cjs +8 -0
  53. package/tools/definition.cjs +14 -0
  54. package/tools/next.d.mts +2 -0
  55. package/tools/next.mjs +30 -0
  56. package/tools/vite.d.mts +3 -0
  57. package/tools/vite.mjs +43 -0
@@ -0,0 +1,131 @@
1
+ // 바꾸기 하나의 상태 — 자원이 쥐고, 어디서 부르든 같은 칸을 거친다. React 를 가져오지 않는다
2
+ import { noteRead } from "./track.js";
3
+ export const message = (e) => (e instanceof Error ? e.message : String(e));
4
+ /** scope.id → 그 줄 마지막 호출이 끝나면 풀리는 약속 — 던지지 않는다 */
5
+ const scopes = new Map();
6
+ /** 시험 사이에 줄이 남지 않도록 비운다 */
7
+ export function resetScopes() {
8
+ scopes.clear();
9
+ }
10
+ const FIELDS = ["inflight", "optimistic", "pending", "error", "data"];
11
+ /** 콜백이 던져도 호출의 결과와 inflight 를 붙잡지 않는다 — 콘솔에 남기고 삼킨다 */
12
+ function safely(cb, ...args) {
13
+ try {
14
+ cb?.(...args);
15
+ }
16
+ catch (e) {
17
+ console.error(e);
18
+ }
19
+ }
20
+ /**
21
+ * 바꾸기 함수를 감싸 상태 칸을 쥔다. 호출마다 안쪽 번호를 매긴다 — 같은 인자로 두 번 불러도 끝난 쪽만 inflight 에서 뺀다.
22
+ * 나중에 보낸 호출이 성공하면 앞 호출은 모두 밀려난다: 그 순간 optimistic 에서 빠지고, 응답은 칸과 콜백을 건드리지 않는다.
23
+ * 나중 호출의 실패는 아무것도 밀어내지 않는다. reset 앞에 보낸 호출은 칸에만 적지 않는다
24
+ */
25
+ export function createMutation(fn, hooks = {}) {
26
+ const listeners = new Set();
27
+ let state = { inflight: [], optimistic: [], pending: false, error: null, data: undefined };
28
+ /** 응답을 기다리는 호출 — inflight */
29
+ let calls = [];
30
+ /** 겹에 얹을 호출 — optimistic */
31
+ let shown = [];
32
+ let sent = 0;
33
+ /** 성공한 가장 큰 번호 — 이보다 작은 호출은 밀려나 칸도 콜백도 건드리지 않는다 */
34
+ let won = 0;
35
+ /** 시작한 확인의 수 — 가장 나중 확인이 끝날 때만 겹을 비운다 */
36
+ let confirms = 0;
37
+ /** reset 할 때 보낸 가장 큰 번호 — 이보다 작거나 같은 호출은 칸에 적지 않지만 콜백은 부른다 */
38
+ let floor = 0;
39
+ const write = (patch) => {
40
+ state = { ...state, ...patch };
41
+ listeners.forEach((l) => l());
42
+ };
43
+ const publish = (patch = {}) => write({ ...patch, inflight: calls.map((c) => c.args), optimistic: shown.map((c) => c.args), pending: calls.length > 0 });
44
+ const channel = {
45
+ subscribe(listener) {
46
+ listeners.add(listener);
47
+ return () => void listeners.delete(listener);
48
+ },
49
+ snapshot: () => state,
50
+ };
51
+ // 확인이 던지거나 거부되어도 끝난 것으로 본다 — 앞 확인이 뒤 확인의 겹을 비우지 않게 번호로 가린다
52
+ const confirm = async () => {
53
+ const mine = ++confirms;
54
+ try {
55
+ await hooks.onAllSettled();
56
+ }
57
+ catch (e) {
58
+ console.error(e);
59
+ }
60
+ if (mine === confirms && calls.length === 0) {
61
+ shown = [];
62
+ publish();
63
+ }
64
+ };
65
+ const call = async (...args) => {
66
+ const n = ++sent;
67
+ const mine = { n, args };
68
+ calls = [...calls, mine];
69
+ shown = [...shown, mine];
70
+ // 다시 부르면 앞 실패의 문구를 지운다 — 0.2 의 화면별 바꾸기와 같다
71
+ publish({ error: null });
72
+ // 같은 scope 의 앞 호출이 끝나기를 기다린다 — 앞이 실패해도 줄은 풀린다
73
+ const id = hooks.scope?.id;
74
+ const prev = id === undefined ? undefined : scopes.get(id);
75
+ let release = () => { };
76
+ let ok = false;
77
+ if (id !== undefined) {
78
+ const mine = new Promise((r) => (release = () => (scopes.get(id) === mine && scopes.delete(id), r())));
79
+ scopes.set(id, mine);
80
+ }
81
+ try {
82
+ if (prev)
83
+ await prev;
84
+ const result = await fn(...args);
85
+ ok = true;
86
+ if (n > won) {
87
+ won = n;
88
+ shown = shown.filter((c) => c.n >= n);
89
+ publish(n > floor ? { data: result, error: null } : {});
90
+ safely(hooks.onSuccess, result, ...args);
91
+ safely(hooks.onSettled, result, null, ...args);
92
+ }
93
+ return result;
94
+ }
95
+ catch (e) {
96
+ if (n > won) {
97
+ if (n > floor)
98
+ write({ error: message(e) });
99
+ safely(hooks.onError, e, ...args);
100
+ safely(hooks.onSettled, undefined, e, ...args);
101
+ }
102
+ throw e;
103
+ }
104
+ finally {
105
+ // 칸과 콜백이 먼저 — 그 뒤에 빠져야 캐시가 서버 값이 된 다음 겹이 빠진다
106
+ calls = calls.filter((c) => c !== mine);
107
+ // 확인을 켰으면 성공한 호출은 확인이 끝날 때까지 겹에 남는다 — 실패한 호출은 바로 빠지고, 밀려났으면 위에서 이미 빠졌다
108
+ if (!hooks.onAllSettled || !ok)
109
+ shown = shown.filter((c) => c !== mine);
110
+ publish();
111
+ release();
112
+ // 호출의 Promise 사슬 밖에서 돈다 — mutateAsync 는 확인을 기다리지 않는다
113
+ if (hooks.onAllSettled && calls.length === 0)
114
+ void confirm();
115
+ }
116
+ };
117
+ for (const field of FIELDS) {
118
+ Object.defineProperty(call, field, {
119
+ get() {
120
+ noteRead(channel);
121
+ return state[field];
122
+ },
123
+ });
124
+ }
125
+ // 앞서 떠난 호출이 칸에 적지 못하게 한다 — 그 콜백은 돈다. inflight 는 그 호출이 끝날 때 빠진다
126
+ const reset = () => {
127
+ floor = sent;
128
+ write({ error: null, data: undefined });
129
+ };
130
+ return { call: Object.assign(call, { reset }), channel };
131
+ }
@@ -0,0 +1,184 @@
1
+ import { USE } from "./index.js";
2
+ import { type RefetchInterval } from "./refetch.js";
3
+ import { type MutationFn, type MutationHooks } from "./mutation.js";
4
+ export type { MutationFn, MutationHooks, MutationSnapshot } from "./mutation.js";
5
+ export type { RefetchInterval };
6
+ export { createDerived } from "./derived.js";
7
+ type Fn = (...args: any[]) => any;
8
+ export interface Event<P> {
9
+ /** 반응하는 store 들을 부른다 */
10
+ emit(payload: P): void;
11
+ /** 반응한다. 짓는 동안 걸면 지금 짓는 store 가 누구이고 그 store 를 버릴 때 떨어진다. 풀기 함수를 돌려준다 */
12
+ on(fn: (payload: P) => void): () => void;
13
+ /** 지금 짓는 store 는 일부러 반응하지 않는다 — 실행에는 영향이 없고 결정이라는 기록만 남긴다. 짓는 동안에만 부른다 */
14
+ exempt(why: string): void;
15
+ /** 출력 스냅숏이 읽는다. 둘 다 who(부른 자리의 이름)로 정렬한다. 이름이 같아도 store 가 다르면 따로 선다 */
16
+ record(): {
17
+ on: string[];
18
+ exempt: Array<{
19
+ who: string;
20
+ why: string;
21
+ }>;
22
+ };
23
+ }
24
+ /** 자원 사이를 잇는 event. const x = createStore(() => createEvent<P>()) 로 둔다 */
25
+ export declare function createEvent<P>(): Event<P>;
26
+ export interface Cache<A, D> {
27
+ /** args 하나면 값 하나, 배열이면 같은 순서의 값 배열 */
28
+ getData(args?: A): D | undefined;
29
+ getData(args: readonly A[]): (D | undefined)[];
30
+ /** 응답이 실어 온 값으로 바로 고친다 — 다시 받지 않는다. 배열이면 args 마다 updater 를 부른다. undefined 면 그 칸을 비워 idle 로. 낡음은 끄지 않는다 */
31
+ setData(updater: D | undefined | ((prev: D | undefined, args: A) => D | undefined), args?: A | readonly A[]): void;
32
+ /**
33
+ * 무효화한다 — args 를 주면 그 칸만(배열이면 그 칸들만, 빈 배열은 아무것도 안 함), 함수면 참인 칸, 없으면 받아 둔 칸 모두.
34
+ * 화면이 보는 칸은 곧바로 다시 받고(이것만 기다린다), 보지 않는 칸은 값을 두고 낡음만 표시해 다시 볼 때 · fetch 할 때 받는다.
35
+ * 실패는 칸의 error 에 둔다
36
+ */
37
+ invalidate(args?: A | readonly A[] | ((args: A) => boolean)): Promise<void>;
38
+ /** 받아서 칸에 넣고 값을 돌려준다 — 받는 중이면 끝을 기다려 칸의 값을, 아니고 이미 받은 칸이면 그 값을 바로 준다(체인에서 쓴다). 실패하면 던진다. 배열이면 하나라도 실패할 때 그 오류로 거절한다 */
39
+ fetch(args?: A): Promise<D>;
40
+ fetch(args: readonly A[]): Promise<D[]>;
41
+ }
42
+ export type Status = "idle" | "loading" | "ready" | "error";
43
+ export interface QueryView<D> {
44
+ data: D | undefined;
45
+ status: Status;
46
+ error: string | null;
47
+ /** 보이는 data 가 받은 값이 아니라 자리를 채운 값이면 true */
48
+ isPlaceholderData: boolean;
49
+ /** 그 args 의 요청이 진행 중이면 true — 처음 받을 때도. 값이 있는 동안 다시 받아도 status 는 그대로다 */
50
+ isFetching: boolean;
51
+ refetch(): Promise<void>;
52
+ }
53
+ export type QueryField = "data" | "status" | "error" | "isPlaceholderData" | "isFetching" | "refetch";
54
+ export interface MutationView<F extends Fn> {
55
+ /** 아무것도 돌려주지 않는다 — 실패는 error 에만 둔다. 결과가 필요하면 mutateAsync */
56
+ mutate(...args: Parameters<F>): void;
57
+ /** 결과를 돌려주고 실패하면 원래 오류를 던진다. error·data 칸도 mutate 와 같이 채운다 */
58
+ mutateAsync(...args: Parameters<F>): Promise<Awaited<ReturnType<F>>>;
59
+ /** 보냈지만 아직 끝나지 않은 호출들의 인자 — 보낸 차례대로 선다 */
60
+ readonly inflight: readonly Parameters<F>[];
61
+ /** 겹에 얹을 호출들의 인자 — inflight 에서 밀려난 호출을 뺀 것 */
62
+ readonly optimistic: readonly Parameters<F>[];
63
+ pending: boolean;
64
+ error: string | null;
65
+ data: Awaited<ReturnType<F>> | undefined;
66
+ reset(): void;
67
+ }
68
+ /** 정의한 객체에서 query 를 뺀 함수 칸 — 정의한 그대로의 바꾸기 함수 */
69
+ type Defined<R> = {
70
+ [K in keyof R as K extends "query" ? never : R[K] extends Fn ? K : never]: R[K];
71
+ };
72
+ /** 바꾸기 — 자원이 상태 칸을 달아 감싼 함수 */
73
+ export type Mutations<R> = {
74
+ [K in keyof Defined<R>]: MutationFn<Extract<Defined<R>[K], Fn>>;
75
+ };
76
+ export type ResourceView<D, R> = QueryView<D> & {
77
+ [K in keyof Defined<R>]: MutationView<Extract<Defined<R>[K], Fn>>;
78
+ };
79
+ /** 바꾸기 이름을 열쇠로 그 바꾸기의 콜백(또는 scope)을 적는다 — 없는 이름은 타입 오류다 */
80
+ type ByName<R, H extends keyof MutationHooks<Fn>> = {
81
+ [K in keyof Defined<R>]?: MutationHooks<Extract<Defined<R>[K], Fn>>[H];
82
+ };
83
+ type ViewName<D, R> = keyof ResourceView<D, R> & string;
84
+ /** 이 화면이 바로 전 렌더에 보이던 args 와 그 값(select 전 D) */
85
+ export type Prev<A, D> = {
86
+ args: A;
87
+ data: D;
88
+ };
89
+ /** 받은 값이 없을 때 보일 값 — 지어낸 값 그대로, 또는 함수(undefined 면 정하지 않았다) */
90
+ export type PlaceholderData<A, D> = D | ((args: A, prev: Prev<A, D>[]) => D | undefined);
91
+ /** 화면의 select 는 자원 select 의 결과(S)를 이어 받고, 자리 채우기는 select 전 모양 D 를 짓는다 */
92
+ type ScreenOptions<A, S, D> = {
93
+ select?: (data: S, args: A) => unknown;
94
+ placeholderData?: PlaceholderData<A, D>;
95
+ /** 자원이 간격을 정하지 않은 args 를 채운다 — 보는 화면들 가운데 가장 짧은 간격 */
96
+ refetchInterval?: RefetchInterval<A>;
97
+ };
98
+ /** 하나 꼴 — 조회 칸과 바꾸기 칸을 고른다 */
99
+ export type ResourceOptions<A, N extends string, S = unknown, D = unknown> = ScreenOptions<A, S, D> & ({
100
+ args?: A;
101
+ pick?: readonly N[];
102
+ omit?: never;
103
+ } | {
104
+ args?: A;
105
+ omit?: readonly N[];
106
+ pick?: never;
107
+ });
108
+ /** 목록 꼴 — 조회 칸만 고른다. 바꾸기는 자원 전체에 하나라 항목에 넣지 않는다 */
109
+ export type ResourceListOptions<A, S = unknown, D = unknown> = ScreenOptions<A, S, D> & ({
110
+ args: readonly A[];
111
+ pick?: readonly QueryField[];
112
+ omit?: never;
113
+ } | {
114
+ args: readonly A[];
115
+ omit?: readonly QueryField[];
116
+ pick?: never;
117
+ });
118
+ type Chosen<V, O> = [O] extends [{
119
+ pick: readonly (infer N)[];
120
+ }] ? Pick<V, N & keyof V> : [O] extends [{
121
+ omit: readonly (infer N)[];
122
+ }] ? Omit<V, N & keyof V> : V;
123
+ export type PickedView<D, R, O> = Chosen<ResourceView<D, R>, O>;
124
+ export type PickedQuery<D, O> = Chosen<QueryView<D>, O>;
125
+ export type ResourceUseOptions<A, S, R, D = S> = ResourceOptions<A, ViewName<S, R>, S, D> | ResourceListOptions<A, S, D> | undefined;
126
+ /** 화면 select 가 있으면 그 결과가 data 다 */
127
+ type Selected<S, O> = [O] extends [{
128
+ select: (...a: any[]) => infer S2;
129
+ }] ? S2 : S;
130
+ export type ResourceUseResult<S, R, O> = [O] extends [{
131
+ args: readonly unknown[];
132
+ }] ? PickedQuery<Selected<S, O>, O>[] : PickedView<Selected<S, O>, R, O>;
133
+ /** 자원의 꺼내기 — 서명 하나다. 입력이 목록이면 배열을 돌려준다 */
134
+ export interface ResourceUse<A, S, R, D = S> {
135
+ <O extends ResourceUseOptions<A, S, R, D>>(options?: O): ResourceUseResult<S, R, O>;
136
+ }
137
+ /** store 끼리·시험이 보는 자원의 모양. 캐시는 서버 모양 D, 화면은 useStore 로 꺼내 select 를 거친 S 를 받는다 */
138
+ export type Resource<A, D, R, S = D> = Cache<A, D> & Mutations<R> & {
139
+ [USE]: ResourceUse<A, S, R, D>;
140
+ };
141
+ type KeepPrevious = (<A, D>(args: A, prev: Prev<A, D>[]) => D | undefined) & (<A>(match: (args: A, prev: {
142
+ args: A;
143
+ }) => boolean) => <D>(args: A, prev: Prev<A, D>[]) => D | undefined);
144
+ /**
145
+ * 자리 채우기 도우미. `placeholderData: keepPreviousData` 는 하나 꼴에서 바로 전 값을, 목록 꼴에서 같은 args 의 앞 값만 잇는다.
146
+ * `keepPreviousData(match)` 는 prev 가운데 match 가 참인 첫 항목의 값을 잇는다.
147
+ */
148
+ export declare const keepPreviousData: KeepPrevious;
149
+ /**
150
+ * 내용이 같으면 앞 값을, 아니면 새 값을 준다 — 다시 받은 응답이 그대로면 앞 객체를 두어 그것을 읽는 쪽이 깨지 않게 한다.
151
+ * 둘 다 배열이거나 둘 다 보통 객체일 때만 칸마다 깊이 견준다. Date · Map · 클래스 인스턴스는 Object.is 로만 본다
152
+ */
153
+ export declare function keepEqual<T>(prev: T | undefined, next: T): T;
154
+ /**
155
+ * 자원 하나를 정의한다. `query` 가 조회 하나이고, 나머지 함수가 모두 바꾸기다.
156
+ *
157
+ * `cache` 를 쓰면 인자에 타입을 적는다 — 한 호출 안에서는 TypeScript 가 `query` 에서 `cache` 의 타입을 추론하지 못한다.
158
+ * ```ts
159
+ * createResource((cache: Cache<void, Pick[]>) => ({
160
+ * query: async () => …, // Pick[] 을 돌려준다
161
+ * async save(numbers: number[]) { cache.setData((prev) => …) },
162
+ * }))
163
+ * createResource(() => ({ query: async (id: string) => … })) // cache 를 쓰지 않으면 적지 않는다
164
+ * ```
165
+ * 함수는 늘 정의한 객체를 this 로 부른다 — 메서드 꼴은 this.다른함수() 를 쓸 수 있다.
166
+ *
167
+ * `select` 는 화면에 줄 때만 바꾼다 — 캐시(getData · setData · fetch)는 서버 모양 그대로다.
168
+ */
169
+ export declare function createResource<A = void, D = never, R extends object = object, S = D>(define: (cache: Cache<A, D>) => R & {
170
+ query?: (args: A) => Promise<D>;
171
+ }, options?: {
172
+ auto?: boolean;
173
+ select?: (data: D, args: A) => S;
174
+ placeholderData?: PlaceholderData<A, D>;
175
+ refetchInterval?: RefetchInterval<A>;
176
+ /** 그 args 를 보던 마지막 화면이 빠지고(화면 없이 받았으면 받기가 끝나고) 이만큼(ms) 지나면 칸을 놓는다. 생략 · false 면 쥔다 */
177
+ release?: number | false;
178
+ /** 바꾸기가 늦지 않게 성공했을 때 — 결과를 다른 곳에 넘기는 일(setData · emit)은 여기에 적는다 */
179
+ onSuccess?: ByName<R, "onSuccess">;
180
+ onError?: ByName<R, "onError">;
181
+ onSettled?: ByName<R, "onSettled">;
182
+ onAllSettled?: ByName<R, "onAllSettled">;
183
+ scope?: ByName<R, "scope">;
184
+ }): Resource<A, D, R, S>;
package/dist/query.js ADDED
@@ -0,0 +1,301 @@
1
+ // 정의 도우미 — 정의 파일은 서버 쪽에서도 평가되므로 "use client" 를 두지 않는다. 훅은 [USE] 안에서만 부른다
2
+ // 훅은 resourceHook.ts 에 살고, 이 파일은 React 를 가져오지 않는다
3
+ import { currentBuild, USE } from "./index.js";
4
+ import { createRefetcher } from "./refetch.js";
5
+ import { createMutation, message } from "./mutation.js";
6
+ import { IDLE, makeResourceHook, noop, plain, QUERY_FIELDS } from "./resourceHook.js";
7
+ import { isTracking, noteRead } from "./track.js";
8
+ export { createDerived } from "./derived.js";
9
+ /** 자원 사이를 잇는 event. const x = createStore(() => createEvent<P>()) 로 둔다 */
10
+ export function createEvent() {
11
+ // store 는 handle 로 가린다 — 이름(부른 자리)은 한 도우미 함수 안에서 지은 store 끼리 겹친다
12
+ const handlers = [];
13
+ const exempts = new Map();
14
+ const hasOn = (owner) => handlers.some((h) => h.owner === owner);
15
+ return {
16
+ emit: (payload) => [...handlers].forEach((h) => h.fn(payload)),
17
+ on(fn) {
18
+ const build = currentBuild();
19
+ if (build && exempts.has(build.handle))
20
+ throw new Error(`${build.label} 는 이미 exempt 했다 — on 과 함께 적을 수 없다`);
21
+ const handler = { owner: build?.handle ?? null, who: build?.label ?? null, fn };
22
+ handlers.push(handler);
23
+ const off = () => {
24
+ const at = handlers.indexOf(handler);
25
+ if (at >= 0)
26
+ handlers.splice(at, 1);
27
+ };
28
+ build?.adopt(off);
29
+ return off;
30
+ },
31
+ exempt(why) {
32
+ const build = currentBuild();
33
+ if (!build)
34
+ throw new Error("exempt 는 store 를 짓는 동안에만 부른다");
35
+ if (hasOn(build.handle))
36
+ throw new Error(`${build.label} 는 이미 on 했다 — exempt 와 함께 적을 수 없다`);
37
+ exempts.set(build.handle, { who: build.label, why });
38
+ build.adopt(() => void exempts.delete(build.handle));
39
+ },
40
+ record: () => ({
41
+ // 같은 store 가 둘 건 on 은 하나로 센다
42
+ on: [...new Map(handlers.flatMap((h) => (h.owner === null ? [] : [[h.owner, h.who]]))).values()].sort(),
43
+ exempt: [...exempts.values()].sort((a, b) => (a.who < b.who ? -1 : a.who > b.who ? 1 : 0)),
44
+ }),
45
+ };
46
+ }
47
+ /**
48
+ * 자리 채우기 도우미. `placeholderData: keepPreviousData` 는 하나 꼴에서 바로 전 값을, 목록 꼴에서 같은 args 의 앞 값만 잇는다.
49
+ * `keepPreviousData(match)` 는 prev 가운데 match 가 참인 첫 항목의 값을 잇는다.
50
+ */
51
+ export const keepPreviousData = ((...a) => {
52
+ if (a.length === 1 && typeof a[0] === "function") {
53
+ const match = a[0];
54
+ return (args, prev) => prev.find((p) => match(args, p))?.data;
55
+ }
56
+ // 목록 꼴인지는 훅이 셋째 인자로 알린다 — 목록이면 자리를 밀지 않고 같은 args 만 본다
57
+ const [args, prev, list] = a;
58
+ const id = JSON.stringify(args ?? null);
59
+ return list ? prev.find((p) => JSON.stringify(p.args ?? null) === id)?.data : prev[0]?.data;
60
+ });
61
+ /**
62
+ * 내용이 같으면 앞 값을, 아니면 새 값을 준다 — 다시 받은 응답이 그대로면 앞 객체를 두어 그것을 읽는 쪽이 깨지 않게 한다.
63
+ * 둘 다 배열이거나 둘 다 보통 객체일 때만 칸마다 깊이 견준다. Date · Map · 클래스 인스턴스는 Object.is 로만 본다
64
+ */
65
+ export function keepEqual(prev, next) {
66
+ return equal(prev, next) ? prev : next;
67
+ }
68
+ function equal(a, b) {
69
+ if (Object.is(a, b))
70
+ return true;
71
+ if (Array.isArray(a) && Array.isArray(b))
72
+ return a.length === b.length && a.every((v, i) => equal(v, b[i]));
73
+ if (!plain(a) || !plain(b) || Array.isArray(a) || Array.isArray(b))
74
+ return false;
75
+ const keys = Object.keys(a);
76
+ return keys.length === Object.keys(b).length && keys.every((k) => k in b && equal(a[k], b[k]));
77
+ }
78
+ const RESERVED = [...QUERY_FIELDS, "fetch", "getData", "setData", "invalidate"];
79
+ /**
80
+ * 자원 하나를 정의한다. `query` 가 조회 하나이고, 나머지 함수가 모두 바꾸기다.
81
+ *
82
+ * `cache` 를 쓰면 인자에 타입을 적는다 — 한 호출 안에서는 TypeScript 가 `query` 에서 `cache` 의 타입을 추론하지 못한다.
83
+ * ```ts
84
+ * createResource((cache: Cache<void, Pick[]>) => ({
85
+ * query: async () => …, // Pick[] 을 돌려준다
86
+ * async save(numbers: number[]) { cache.setData((prev) => …) },
87
+ * }))
88
+ * createResource(() => ({ query: async (id: string) => … })) // cache 를 쓰지 않으면 적지 않는다
89
+ * ```
90
+ * 함수는 늘 정의한 객체를 this 로 부른다 — 메서드 꼴은 this.다른함수() 를 쓸 수 있다.
91
+ *
92
+ * `select` 는 화면에 줄 때만 바꾼다 — 캐시(getData · setData · fetch)는 서버 모양 그대로다.
93
+ */
94
+ export function createResource(define, options = {}) {
95
+ const auto = options.auto ?? true;
96
+ const cells = new Map();
97
+ const listeners = new Set();
98
+ const idOf = (args) => JSON.stringify(args ?? null);
99
+ const { release } = options;
100
+ // 놓기 타이머는 이 자원의 cells 만 본다 — 다시 지은 자원의 칸을 건드리지 않는다
101
+ const timers = new Map();
102
+ const letGo = (id) => {
103
+ if (typeof release !== "number")
104
+ return;
105
+ clearTimeout(timers.get(id));
106
+ const timer = setTimeout(() => {
107
+ timers.delete(id);
108
+ const cell = cells.get(id);
109
+ if (!cell || refetcher.watching(cell.args))
110
+ return;
111
+ cells.delete(id);
112
+ // 진행 중 응답은 떨어진 칸에 닿으므로 버려진다 — 주기에도 알리지 않는다. 다시 보면 처음 간격부터
113
+ cell.seq += 1;
114
+ cell.request = undefined;
115
+ refetcher.forget(cell.args);
116
+ }, release);
117
+ // 서버에서 fetch 로 받은 칸의 타이머가 프로세스를 붙잡지 않게
118
+ timer.unref?.();
119
+ timers.set(id, timer);
120
+ };
121
+ /** 화면도 타이머도 없는 살아 있는 칸이면 지금부터 센다 — 받기가 끝났을 때 · setData 했을 때 */
122
+ const countIfLoose = (cell) => {
123
+ const id = idOf(cell.args);
124
+ if (cells.get(id) === cell && !timers.has(id) && !refetcher.watching(cell.args))
125
+ letGo(id);
126
+ };
127
+ const refetcher = createRefetcher({
128
+ resource: options.refetchInterval,
129
+ load: (args) => load(args),
130
+ idOf,
131
+ inflight: (args) => cells.get(idOf(args))?.request,
132
+ // 낡은 칸을 다시 보면 받는다 — 그사이 fetch 가 받는 중이면 그것을 나눠 쓴다
133
+ onWatch(args) {
134
+ const id = idOf(args);
135
+ clearTimeout(timers.get(id));
136
+ timers.delete(id);
137
+ const cell = cells.get(id);
138
+ if (!cell?.stale)
139
+ return;
140
+ cell.stale = false;
141
+ if (cell.view.status !== "idle")
142
+ load(args).catch(noop);
143
+ },
144
+ onUnwatch: (args) => letGo(idOf(args)),
145
+ });
146
+ const cellOf = (args) => {
147
+ const id = idOf(args);
148
+ let cell = cells.get(id);
149
+ if (!cell)
150
+ cells.set(id, (cell = { args, view: IDLE, seq: 0 }));
151
+ return cell;
152
+ };
153
+ const write = (cell, view) => {
154
+ cell.view = { ...cell.view, ...view };
155
+ listeners.forEach((l) => l());
156
+ };
157
+ const subscribe = (listener) => {
158
+ listeners.add(listener);
159
+ return () => void listeners.delete(listener);
160
+ };
161
+ /** 받는다. 진행 중인 요청이 있으면 그것을 나눠 쓰고, force 면 새로 보내 앞 요청의 응답을 버린다 */
162
+ const load = (args, force = false) => {
163
+ const cell = cellOf(args);
164
+ if (cell.request && !force)
165
+ return cell.request;
166
+ const seq = ++cell.seq;
167
+ cell.stale = false;
168
+ // 받은 값이 있으면 status · error 는 그대로 두고 isFetching 만 켠다
169
+ write(cell, cell.view.data === undefined ? { status: "loading", error: null, isFetching: true } : { isFetching: true });
170
+ // 실행자는 곧바로 돈다 — query 가 동기로 던져도 거절로 바뀐다
171
+ // 이 칸의 마지막 요청이 끝날 때만 주기에 알린다 — setData 로 응답을 버려도 끝은 알린다
172
+ const end = (ok, view) => {
173
+ const last = cell.request === request;
174
+ if (last)
175
+ cell.request = undefined;
176
+ const next = { ...(cell.seq === seq ? view : {}), ...(last ? { isFetching: false } : {}) };
177
+ if (Object.keys(next).length)
178
+ write(cell, next);
179
+ if (last)
180
+ refetcher.settled(args, ok);
181
+ // 화면 없이 받은 칸은 받기가 끝난 때부터 센다 — 이미 세는 중이면 그대로
182
+ if (last)
183
+ countIfLoose(cell);
184
+ };
185
+ const request = new Promise((resolve) => resolve(query.call(defined, args))).then((fresh) => {
186
+ // 내용이 같으면 앞 객체를 둔다 — 같은 응답을 다시 받아도 읽는 쪽(화면 · 파생)이 깨지 않는다
187
+ const data = keepEqual(cell.view.data, fresh);
188
+ end(true, { data, status: "ready", error: null });
189
+ return data;
190
+ }, (e) => {
191
+ end(false, { status: "error", error: message(e) });
192
+ throw e;
193
+ });
194
+ cell.request = request;
195
+ return request;
196
+ };
197
+ /**
198
+ * 칸마다 하나인 채널 — 계산 공간(파생 · select)이 getData 로 읽으면 적힌다. 파생이 이것을 구독하는 동안은 화면이 칸을 볼 때와 같다:
199
+ * 비어 있으면 받고(auto), 주기 받기를 걸고, 놓기 타이머를 멈춘다. 칸이 놓여도 채널은 남는다 — 다시 보면 칸이 새로 선다
200
+ */
201
+ const channels = new Map();
202
+ const channelOf = (args) => {
203
+ const id = idOf(args);
204
+ let channel = channels.get(id);
205
+ if (!channel)
206
+ channels.set(id, (channel = {
207
+ subscribe,
208
+ snapshot: () => cells.get(id)?.view.data,
209
+ watch() {
210
+ const stop = refetcher.watch(args, undefined);
211
+ const cell = cellOf(args);
212
+ if (auto && cell.view.status !== "ready" && !cell.request)
213
+ load(args).catch(noop);
214
+ return stop;
215
+ },
216
+ }));
217
+ return channel;
218
+ };
219
+ // 목록은 Array.isArray 로 가른다 — 생성기가 args 자체가 배열인 자원을 막는다
220
+ const getOne = (args) => {
221
+ // 계산 공간 밖(바꾸기 · 콜백)에서 읽으면 채널을 짓지 않는다 — args 마다 쌓이지 않게
222
+ if (isTracking())
223
+ noteRead(channelOf(args));
224
+ return cells.get(idOf(args))?.view.data;
225
+ };
226
+ const setOne = (updater, args) => {
227
+ const cell = cellOf(args);
228
+ const data = typeof updater === "function" ? updater(cell.view.data, args) : updater;
229
+ // 차례를 올려 이 앞에 떠난 조회의 늦은 응답이 고친 값을 덮지 못하게 한다
230
+ cell.seq += 1;
231
+ // 값을 비우면(받은 적 없는 목록으로 되돌리기) 처음으로 돌린다 — 버린 응답 탓에 loading 에 갇히지 않고 다음에 다시 받는다
232
+ write(cell, { data, status: data === undefined ? "idle" : "ready", error: null });
233
+ // setData 로만 만든 칸도 놓인다
234
+ countIfLoose(cell);
235
+ };
236
+ // 보는 칸만 곧바로 다시 받고, 보지 않는 칸은 낡음만 표시한다. 받는 중인 칸은 보지 않아도 다시 받는다 —
237
+ // 무효화 앞에 떠난 응답을 뒤 fetch · 다시 보는 화면이 받지 않게. 그래서 낡은 칸에는 앞서 떠난 요청이 없다
238
+ const reload = (cell) => {
239
+ if (cell.view.status === "idle")
240
+ return;
241
+ if (cell.request || refetcher.watching(cell.args))
242
+ return load(cell.args, true).catch(noop);
243
+ cell.stale = true;
244
+ };
245
+ const fetchOne = (args) => {
246
+ const cell = cellOf(args);
247
+ // 받는 중이면 끝을 기다려 칸의 값을 준다 — invalidate 뒤 체인이 앞 값을 받지 않게. 그사이 setData 한 값이면 그것이다.
248
+ // 기다리던 요청을 다른 요청이 밀어냈으면 그것을 다시 기다리고, 그사이 칸을 비웠거나 놓았으면 받은 응답을 준다
249
+ const gone = () => cells.get(idOf(args)) !== cell;
250
+ const wait = (p) => p.then((d) => (gone() ? d : cell.request ? wait(cell.request) : cell.view.data === undefined ? d : cell.view.data), (e) => (!gone() && cell.request ? wait(cell.request) : Promise.reject(e)));
251
+ if (cell.request)
252
+ return wait(cell.request);
253
+ return cell.view.status === "ready" && !cell.stale ? Promise.resolve(cell.view.data) : wait(load(args));
254
+ };
255
+ const cache = {
256
+ getData: (args) => (Array.isArray(args) ? args.map(getOne) : getOne(args)),
257
+ setData(updater, args) {
258
+ if (Array.isArray(args))
259
+ args.forEach((a) => setOne(updater, a));
260
+ else
261
+ setOne(updater, args);
262
+ },
263
+ async invalidate(args) {
264
+ // 함수 args 는 생성기가 막으므로 함수면 조건이다. idle 칸은 reload 가 건너뛰므로 조건도 부르지 않는다
265
+ const targets = args === undefined
266
+ ? [...cells.values()]
267
+ : typeof args === "function"
268
+ ? [...cells.values()].filter((c) => c.view.status !== "idle" && args(c.args))
269
+ : // 받은 적 없는 args 의 칸은 만들지 않는다
270
+ (Array.isArray(args) ? args : [args]).flatMap((a) => cells.get(idOf(a)) ?? []);
271
+ await Promise.all(targets.map(reload));
272
+ },
273
+ fetch: (args) => (Array.isArray(args) ? Promise.all(args.map(fetchOne)) : fetchOne(args)),
274
+ };
275
+ const defined = define(cache);
276
+ const query = defined.query;
277
+ const mutations = {};
278
+ const hooksOf = (name) => {
279
+ const { onSuccess, onError, onSettled, onAllSettled, scope } = options;
280
+ return {
281
+ onSuccess: onSuccess?.[name],
282
+ onError: onError?.[name],
283
+ onSettled: onSettled?.[name],
284
+ onAllSettled: onAllSettled?.[name],
285
+ scope: scope?.[name],
286
+ };
287
+ };
288
+ for (const [name, value] of Object.entries(defined)) {
289
+ if (name === "query" || typeof value !== "function")
290
+ continue;
291
+ if (RESERVED.includes(name))
292
+ throw new Error(`바꾸기 이름으로 쓸 수 없다: ${name}`);
293
+ mutations[name] = createMutation(value.bind(defined), hooksOf(name));
294
+ }
295
+ const names = Object.keys(mutations);
296
+ const calls = Object.fromEntries(names.map((name) => [name, mutations[name].call]));
297
+ const { select, placeholderData } = options;
298
+ const { watch, rearm } = refetcher;
299
+ const useResource = makeResourceHook({ cellOf, load, subscribe, idOf, query, auto, select, placeholderData, mutations, names, watch, rearm });
300
+ return Object.assign(cache, calls, { [USE]: useResource });
301
+ }
@@ -0,0 +1,29 @@
1
+ import { DISPOSE, USE, type Names, type Picked, type PickOptions, type Store } from "./index.js";
2
+ import type { ResourceUse, ResourceUseOptions, ResourceUseResult } from "./query.js";
3
+ import type { StreamUse, StreamUseOptions, StreamUseResult } from "./stream/index.js";
4
+ type UseState = {
5
+ [USE]: (...a: any[]) => any;
6
+ };
7
+ type UseFn<S> = Extract<S[typeof USE & keyof S], (...a: any[]) => any>;
8
+ type UseOf<S> = S[typeof USE & keyof S];
9
+ type ResourceTypes<S> = UseOf<S> extends ResourceUse<infer A, infer V, infer R, infer D> ? [A, V, R, D] : never;
10
+ type StreamState = {
11
+ [USE]: StreamUse<any, any>;
12
+ [DISPOSE](): void;
13
+ };
14
+ type StreamTypes<S> = UseOf<S> extends StreamUse<infer V, infer Cmd> ? [V, Cmd] : never;
15
+ /**
16
+ * 핸들이 가리키는 store 의 상태를 꺼낸다.
17
+ * - 상태에 [USE] 가 있으면 꺼내기를 그 함수에 맡긴다: useStore(store, ...args) = state[USE](...args)
18
+ * - 없으면 전부, 또는 { pick } / { omit } 으로 고른 칸만. 고른 칸이 (묶기 전 값으로) 그대로면 같은 객체를 돌려준다
19
+ */
20
+ export declare function useStore<S extends StreamState, O extends StreamUseOptions<StreamTypes<S>[0], StreamTypes<S>[1]>>(store: Store<S>, options?: O): StreamUseResult<StreamTypes<S>[0], StreamTypes<S>[1], O>;
21
+ export declare function useStore<S extends {
22
+ [USE]: ResourceUse<any, any, any, any>;
23
+ }, O extends ResourceUseOptions<ResourceTypes<S>[0], ResourceTypes<S>[1], ResourceTypes<S>[2], ResourceTypes<S>[3]>>(store: Store<S>, options?: O): ResourceUseResult<ResourceTypes<S>[1], ResourceTypes<S>[2], O>;
24
+ export declare function useStore<S extends UseState>(store: Store<S>, ...args: Parameters<UseFn<S>>): ReturnType<UseFn<S>>;
25
+ export declare function useStore<S>(store: Store<S>): S;
26
+ export declare function useStore<S extends object & {
27
+ [USE]?: never;
28
+ }, N extends Names<S>, O extends PickOptions<S, N>>(store: Store<S>, options: O): Picked<S, O>;
29
+ export {};