capable-kit 0.0.1-alpha.5 → 0.0.1-alpha.7

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.
@@ -0,0 +1,14 @@
1
+ //#region packages/next/src/index.d.ts
2
+ type NextRouteHandler = (request: Request) => Promise<Response> | Response;
3
+ declare function createNextRouteHandlers(fetch: NextRouteHandler): {
4
+ GET: NextRouteHandler;
5
+ POST: NextRouteHandler;
6
+ PUT: NextRouteHandler;
7
+ PATCH: NextRouteHandler;
8
+ DELETE: NextRouteHandler;
9
+ HEAD: NextRouteHandler;
10
+ OPTIONS: NextRouteHandler;
11
+ };
12
+ //#endregion
13
+ export { NextRouteHandler, createNextRouteHandlers };
14
+ //# sourceMappingURL=next.d.mts.map
package/dist/next.mjs ADDED
@@ -0,0 +1,16 @@
1
+ //#region packages/next/src/index.ts
2
+ function createNextRouteHandlers(fetch) {
3
+ return {
4
+ GET: fetch,
5
+ POST: fetch,
6
+ PUT: fetch,
7
+ PATCH: fetch,
8
+ DELETE: fetch,
9
+ HEAD: fetch,
10
+ OPTIONS: fetch
11
+ };
12
+ }
13
+ //#endregion
14
+ export { createNextRouteHandlers };
15
+
16
+ //# sourceMappingURL=next.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next.mjs","names":[],"sources":["../../next/src/index.ts"],"sourcesContent":["export type NextRouteHandler = (request: Request) => Promise<Response> | Response;\n\nexport function createNextRouteHandlers(fetch: NextRouteHandler): {\n GET: NextRouteHandler;\n POST: NextRouteHandler;\n PUT: NextRouteHandler;\n PATCH: NextRouteHandler;\n DELETE: NextRouteHandler;\n HEAD: NextRouteHandler;\n OPTIONS: NextRouteHandler;\n} {\n return {\n GET: fetch,\n POST: fetch,\n PUT: fetch,\n PATCH: fetch,\n DELETE: fetch,\n HEAD: fetch,\n OPTIONS: fetch,\n };\n}\n"],"mappings":";AAEA,SAAgB,wBAAwB,OAQtC;CACA,OAAO;EACL,KAAK;EACL,MAAM;EACN,KAAK;EACL,OAAO;EACP,QAAQ;EACR,MAAM;EACN,SAAS;CACX;AACF"}
@@ -0,0 +1,34 @@
1
+ import { u as AppCapabilityIsSubscribable } from "./index-Dbc4g9WM.mjs";
2
+ import { QueryFunction, QueryKey, UseMutationOptions, UseQueryOptions } from "@tanstack/react-query";
3
+ //#region packages/react-query/src/index.d.ts
4
+ type CapabilityCall = (...args: any[]) => Promise<any>;
5
+ type CapabilityInput<TCall extends CapabilityCall> = Exclude<Parameters<TCall>[0], undefined>;
6
+ type CapabilityVariables<TCall extends CapabilityCall> = undefined extends Parameters<TCall>[0] ? void : Parameters<TCall>[0];
7
+ type CapabilityOutput<TCall extends CapabilityCall> = Awaited<ReturnType<TCall>>;
8
+ type CapabilityQueryOptions<TCall extends CapabilityCall, TData = CapabilityOutput<TCall>> = Omit<UseQueryOptions<CapabilityOutput<TCall>, Error, TData, QueryKey>, "queryKey" | "queryFn">;
9
+ type CapabilityMutationOptions<TCall extends CapabilityCall, TOnMutateResult = unknown> = Omit<UseMutationOptions<CapabilityOutput<TCall>, Error, CapabilityVariables<TCall>, TOnMutateResult>, "mutationKey" | "mutationFn">;
10
+ type ReactQueryCapability<TCall extends CapabilityCall> = {
11
+ queryKey(input?: CapabilityInput<TCall>): QueryKey;
12
+ queryOptions<TData = CapabilityOutput<TCall>>(input: CapabilityInput<TCall>, options?: CapabilityQueryOptions<TCall, TData>): UseQueryOptions<CapabilityOutput<TCall>, Error, TData, QueryKey> & {
13
+ readonly queryKey: QueryKey;
14
+ readonly queryFn: QueryFunction<CapabilityOutput<TCall>, QueryKey>;
15
+ };
16
+ mutationOptions<TOnMutateResult = unknown>(options?: CapabilityMutationOptions<TCall, TOnMutateResult>): UseMutationOptions<CapabilityOutput<TCall>, Error, CapabilityVariables<TCall>, TOnMutateResult> & {
17
+ readonly mutationKey: QueryKey;
18
+ readonly mutationFn: (variables: CapabilityVariables<TCall>) => Promise<CapabilityOutput<TCall>>;
19
+ };
20
+ };
21
+ type ReactQueryLiveCapability<TCall extends CapabilityCall> = ReactQueryCapability<TCall> & {
22
+ liveQueryOptions<TData = CapabilityOutput<TCall>>(input: CapabilityInput<TCall>, options?: CapabilityQueryOptions<TCall, TData>): UseQueryOptions<CapabilityOutput<TCall>, Error, TData, QueryKey> & {
23
+ readonly queryKey: QueryKey;
24
+ readonly queryFn: QueryFunction<CapabilityOutput<TCall>, QueryKey>;
25
+ };
26
+ };
27
+ type ReactQueryNode<TValue> = TValue extends CapabilityCall ? AppCapabilityIsSubscribable<TValue> extends true ? ReactQueryLiveCapability<TValue> : ReactQueryCapability<TValue> : TValue extends object ? { readonly [TKey in Extract<keyof TValue, string>]: ReactQueryNode<TValue[TKey]>; } : never;
28
+ type ReactQueryApp<TApp extends object> = ReactQueryNode<TApp>;
29
+ declare function createReactQuery<const TApp extends object>(app: TApp, options?: {
30
+ readonly keyPrefix?: QueryKey;
31
+ }): ReactQueryApp<TApp>;
32
+ //#endregion
33
+ export { CapabilityMutationOptions, CapabilityQueryOptions, ReactQueryApp, ReactQueryCapability, ReactQueryLiveCapability, createReactQuery };
34
+ //# sourceMappingURL=react-query.d.mts.map
@@ -0,0 +1,47 @@
1
+ import { u as subscribe } from "./src-C2MGIlT0.mjs";
2
+ import { experimental_streamedQuery } from "@tanstack/react-query";
3
+ //#region packages/react-query/src/index.ts
4
+ const subscribeCall = subscribe;
5
+ function createReactQuery(app, options = {}) {
6
+ const keyPrefix = Object.freeze([...options.keyPrefix ?? ["capable"]]);
7
+ const callableAt = (path) => {
8
+ let current = app;
9
+ for (const segment of path) current = current[segment];
10
+ return current;
11
+ };
12
+ const capabilityKey = (path, input) => Object.freeze([
13
+ ...keyPrefix,
14
+ ...path,
15
+ ...input === void 0 ? [] : [input]
16
+ ]);
17
+ const proxy = (path) => new Proxy({}, { get(_target, key) {
18
+ if (key === "then") return void 0;
19
+ if (key === "queryKey") return (input) => capabilityKey(path, input);
20
+ if (key === "queryOptions") return (input, queryOptions = {}) => ({
21
+ ...queryOptions,
22
+ queryKey: capabilityKey(path, input),
23
+ queryFn: ({ signal }) => callableAt(path)(input, { signal })
24
+ });
25
+ if (key === "liveQueryOptions") return (input, queryOptions = {}) => ({
26
+ ...queryOptions,
27
+ queryKey: capabilityKey(path, input),
28
+ queryFn: experimental_streamedQuery({
29
+ streamFn: ({ signal }) => subscribeCall(callableAt(path), input, { signal }),
30
+ reducer: (_current, output) => output,
31
+ initialValue: void 0
32
+ })
33
+ });
34
+ if (key === "mutationOptions") return (mutationOptions = {}) => ({
35
+ ...mutationOptions,
36
+ mutationKey: capabilityKey(path),
37
+ mutationFn: (input) => callableAt(path)(input ?? {})
38
+ });
39
+ if (typeof key !== "string") return void 0;
40
+ return proxy([...path, key]);
41
+ } });
42
+ return proxy([]);
43
+ }
44
+ //#endregion
45
+ export { createReactQuery };
46
+
47
+ //# sourceMappingURL=react-query.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react-query.mjs","names":[],"sources":["../../react-query/src/index.ts"],"sourcesContent":["import {\n subscribe,\n type AppCapabilityIsSubscribable,\n} from \"@capable/app\";\nimport {\n experimental_streamedQuery,\n type QueryFunction,\n type QueryKey,\n type UseMutationOptions,\n type UseQueryOptions,\n} from \"@tanstack/react-query\";\n\ntype CapabilityCall = (...args: any[]) => Promise<any>;\n\nconst subscribeCall = subscribe as unknown as (\n capabilityCall: CapabilityCall,\n input: unknown,\n options: { readonly signal: AbortSignal },\n) => AsyncIterableIterator<unknown>;\n\ntype CapabilityInput<TCall extends CapabilityCall> =\n Exclude<Parameters<TCall>[0], undefined>;\n\ntype CapabilityVariables<TCall extends CapabilityCall> =\n undefined extends Parameters<TCall>[0]\n ? void\n : Parameters<TCall>[0];\n\ntype CapabilityOutput<TCall extends CapabilityCall> =\n Awaited<ReturnType<TCall>>;\n\nexport type CapabilityQueryOptions<\n TCall extends CapabilityCall,\n TData = CapabilityOutput<TCall>,\n> = Omit<\n UseQueryOptions<\n CapabilityOutput<TCall>,\n Error,\n TData,\n QueryKey\n >,\n \"queryKey\" | \"queryFn\"\n>;\n\nexport type CapabilityMutationOptions<\n TCall extends CapabilityCall,\n TOnMutateResult = unknown,\n> = Omit<\n UseMutationOptions<\n CapabilityOutput<TCall>,\n Error,\n CapabilityVariables<TCall>,\n TOnMutateResult\n >,\n \"mutationKey\" | \"mutationFn\"\n>;\n\nexport type ReactQueryCapability<TCall extends CapabilityCall> = {\n queryKey(input?: CapabilityInput<TCall>): QueryKey;\n queryOptions<TData = CapabilityOutput<TCall>>(\n input: CapabilityInput<TCall>,\n options?: CapabilityQueryOptions<TCall, TData>,\n ): UseQueryOptions<\n CapabilityOutput<TCall>,\n Error,\n TData,\n QueryKey\n > & {\n readonly queryKey: QueryKey;\n readonly queryFn: QueryFunction<CapabilityOutput<TCall>, QueryKey>;\n };\n mutationOptions<TOnMutateResult = unknown>(\n options?: CapabilityMutationOptions<TCall, TOnMutateResult>,\n ): UseMutationOptions<\n CapabilityOutput<TCall>,\n Error,\n CapabilityVariables<TCall>,\n TOnMutateResult\n > & {\n readonly mutationKey: QueryKey;\n readonly mutationFn: (\n variables: CapabilityVariables<TCall>,\n ) => Promise<CapabilityOutput<TCall>>;\n };\n};\n\nexport type ReactQueryLiveCapability<TCall extends CapabilityCall> =\n ReactQueryCapability<TCall> & {\n liveQueryOptions<TData = CapabilityOutput<TCall>>(\n input: CapabilityInput<TCall>,\n options?: CapabilityQueryOptions<TCall, TData>,\n ): UseQueryOptions<\n CapabilityOutput<TCall>,\n Error,\n TData,\n QueryKey\n > & {\n readonly queryKey: QueryKey;\n readonly queryFn: QueryFunction<CapabilityOutput<TCall>, QueryKey>;\n };\n };\n\ntype ReactQueryNode<TValue> =\n TValue extends CapabilityCall\n ? AppCapabilityIsSubscribable<TValue> extends true\n ? ReactQueryLiveCapability<TValue>\n : ReactQueryCapability<TValue>\n : TValue extends object\n ? {\n readonly [TKey in Extract<keyof TValue, string>]:\n ReactQueryNode<TValue[TKey]>;\n }\n : never;\n\nexport type ReactQueryApp<TApp extends object> = ReactQueryNode<TApp>;\n\nexport function createReactQuery<const TApp extends object>(\n app: TApp,\n options: {\n readonly keyPrefix?: QueryKey;\n } = {},\n): ReactQueryApp<TApp> {\n const keyPrefix = Object.freeze([...(options.keyPrefix ?? [\"capable\"])]);\n\n const callableAt = (path: readonly string[]): CapabilityCall => {\n let current: unknown = app;\n for (const segment of path) {\n current = (current as Record<string, unknown>)[segment];\n }\n return current as CapabilityCall;\n };\n\n const capabilityKey = (\n path: readonly string[],\n input?: unknown,\n ): QueryKey => Object.freeze([\n ...keyPrefix,\n ...path,\n ...(input === undefined ? [] : [input]),\n ]);\n\n const proxy = (path: readonly string[]): unknown =>\n new Proxy({}, {\n get(_target, key) {\n if (key === \"then\") return undefined;\n if (key === \"queryKey\") {\n return (input?: unknown) => capabilityKey(path, input);\n }\n if (key === \"queryOptions\") {\n return (\n input: unknown,\n queryOptions: Record<string, unknown> = {},\n ) => ({\n ...queryOptions,\n queryKey: capabilityKey(path, input),\n queryFn: ({ signal }: { readonly signal: AbortSignal }) =>\n callableAt(path)(input, { signal }),\n });\n }\n if (key === \"liveQueryOptions\") {\n return (\n input: unknown,\n queryOptions: Record<string, unknown> = {},\n ) => ({\n ...queryOptions,\n queryKey: capabilityKey(path, input),\n queryFn: experimental_streamedQuery<unknown, unknown>({\n streamFn: ({ signal }) =>\n subscribeCall(callableAt(path), input, { signal }),\n reducer: (_current, output) => output,\n initialValue: undefined,\n }) as QueryFunction<unknown, QueryKey>,\n });\n }\n if (key === \"mutationOptions\") {\n return (\n mutationOptions: Record<string, unknown> = {},\n ) => ({\n ...mutationOptions,\n mutationKey: capabilityKey(path),\n mutationFn: (input?: unknown) =>\n callableAt(path)(input ?? {}),\n });\n }\n if (typeof key !== \"string\") return undefined;\n return proxy([...path, key]);\n },\n });\n\n return proxy([]) as ReactQueryApp<TApp>;\n}\n"],"mappings":";;;AAcA,MAAM,gBAAgB;AAsGtB,SAAgB,iBACd,KACA,UAEI,CAAC,GACgB;CACrB,MAAM,YAAY,OAAO,OAAO,CAAC,GAAI,QAAQ,aAAa,CAAC,SAAS,CAAE,CAAC;CAEvE,MAAM,cAAc,SAA4C;EAC9D,IAAI,UAAmB;EACvB,KAAK,MAAM,WAAW,MACpB,UAAW,QAAoC;EAEjD,OAAO;CACT;CAEA,MAAM,iBACJ,MACA,UACa,OAAO,OAAO;EAC3B,GAAG;EACH,GAAG;EACH,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,CAAC,KAAK;CACvC,CAAC;CAED,MAAM,SAAS,SACb,IAAI,MAAM,CAAC,GAAG,EACZ,IAAI,SAAS,KAAK;EAChB,IAAI,QAAQ,QAAQ,OAAO,KAAA;EAC3B,IAAI,QAAQ,YACV,QAAQ,UAAoB,cAAc,MAAM,KAAK;EAEvD,IAAI,QAAQ,gBACV,QACE,OACA,eAAwC,CAAC,OACrC;GACJ,GAAG;GACH,UAAU,cAAc,MAAM,KAAK;GACnC,UAAU,EAAE,aACV,WAAW,IAAI,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC;EACtC;EAEF,IAAI,QAAQ,oBACV,QACE,OACA,eAAwC,CAAC,OACrC;GACJ,GAAG;GACH,UAAU,cAAc,MAAM,KAAK;GACnC,SAAS,2BAA6C;IACpD,WAAW,EAAE,aACX,cAAc,WAAW,IAAI,GAAG,OAAO,EAAE,OAAO,CAAC;IACnD,UAAU,UAAU,WAAW;IAC/B,cAAc,KAAA;GAChB,CAAC;EACH;EAEF,IAAI,QAAQ,mBACV,QACE,kBAA2C,CAAC,OACxC;GACJ,GAAG;GACH,aAAa,cAAc,IAAI;GAC/B,aAAa,UACX,WAAW,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC;EAChC;EAEF,IAAI,OAAO,QAAQ,UAAU,OAAO,KAAA;EACpC,OAAO,MAAM,CAAC,GAAG,MAAM,GAAG,CAAC;CAC7B,EACF,CAAC;CAEH,OAAO,MAAM,CAAC,CAAC;AACjB"}
package/dist/swr.d.mts ADDED
@@ -0,0 +1,36 @@
1
+ import { u as AppCapabilityIsSubscribable } from "./index-Dbc4g9WM.mjs";
2
+ import { Fetcher, SWRConfiguration } from "swr";
3
+ import { MutationFetcher, SWRMutationConfiguration } from "swr/mutation";
4
+ import { SWRSubscription } from "swr/subscription";
5
+ //#region packages/swr/src/index.d.ts
6
+ type CapabilityCall = (...args: any[]) => Promise<any>;
7
+ type CapabilityInput<TCall extends CapabilityCall> = Exclude<Parameters<TCall>[0], undefined>;
8
+ type CapabilityVariables<TCall extends CapabilityCall> = undefined extends Parameters<TCall>[0] ? Exclude<Parameters<TCall>[0], undefined> | void : Parameters<TCall>[0];
9
+ type CapabilityOutput<TCall extends CapabilityCall> = Awaited<ReturnType<TCall>>;
10
+ type CapabilitySWRKey = readonly [unknown, ...unknown[]];
11
+ type CapabilityFetcher<TCall extends CapabilityCall> = Fetcher<CapabilityOutput<TCall>, CapabilitySWRKey>;
12
+ type CapabilityMutationFetcher<TCall extends CapabilityCall> = MutationFetcher<CapabilityOutput<TCall>, CapabilitySWRKey, CapabilityVariables<TCall>>;
13
+ type CapabilitySWRConfiguration<TCall extends CapabilityCall> = Omit<SWRConfiguration<CapabilityOutput<TCall>, Error, CapabilityFetcher<TCall>>, "fetcher">;
14
+ type CapabilitySWRMutationConfiguration<TCall extends CapabilityCall, TSWRData = CapabilityOutput<TCall>> = SWRMutationConfiguration<CapabilityOutput<TCall>, Error, CapabilitySWRKey, CapabilityVariables<TCall>, TSWRData> & {
15
+ readonly throwOnError?: boolean;
16
+ };
17
+ type CapabilitySWRSubscriptionConfiguration<TCall extends CapabilityCall> = SWRConfiguration<CapabilityOutput<TCall>, Error>;
18
+ type SWRCapability<TCall extends CapabilityCall> = {
19
+ key(input?: CapabilityInput<TCall>): CapabilitySWRKey;
20
+ swr(input: CapabilityInput<TCall>): readonly [key: CapabilitySWRKey, fetcher: CapabilityFetcher<TCall>];
21
+ swr<const TOptions extends CapabilitySWRConfiguration<TCall>>(input: CapabilityInput<TCall>, options: TOptions): readonly [key: CapabilitySWRKey, fetcher: CapabilityFetcher<TCall>, options: TOptions];
22
+ mutation(): readonly [key: CapabilitySWRKey, fetcher: CapabilityMutationFetcher<TCall>];
23
+ mutation<TSWRData = CapabilityOutput<TCall>>(options: CapabilitySWRMutationConfiguration<TCall, TSWRData>): readonly [key: CapabilitySWRKey, fetcher: CapabilityMutationFetcher<TCall>, options: CapabilitySWRMutationConfiguration<TCall, TSWRData>];
24
+ };
25
+ type SWRLiveCapability<TCall extends CapabilityCall> = SWRCapability<TCall> & {
26
+ subscription(input: CapabilityInput<TCall>): readonly [key: CapabilitySWRKey, subscriber: SWRSubscription<CapabilitySWRKey, CapabilityOutput<TCall>, Error>];
27
+ subscription<const TOptions extends CapabilitySWRSubscriptionConfiguration<TCall>>(input: CapabilityInput<TCall>, options: TOptions): readonly [key: CapabilitySWRKey, subscriber: SWRSubscription<CapabilitySWRKey, CapabilityOutput<TCall>, Error>, options: TOptions];
28
+ };
29
+ type SWRNode<TValue> = TValue extends CapabilityCall ? AppCapabilityIsSubscribable<TValue> extends true ? SWRLiveCapability<TValue> : SWRCapability<TValue> : TValue extends object ? { readonly [TKey in Extract<keyof TValue, string>]: SWRNode<TValue[TKey]>; } : never;
30
+ type SWRApp<TApp extends object> = SWRNode<TApp>;
31
+ declare function createSWR<const TApp extends object>(app: TApp, options?: {
32
+ readonly keyPrefix?: readonly unknown[];
33
+ }): SWRApp<TApp>;
34
+ //#endregion
35
+ export { CapabilitySWRConfiguration, CapabilitySWRKey, CapabilitySWRMutationConfiguration, CapabilitySWRSubscriptionConfiguration, SWRApp, SWRCapability, SWRLiveCapability, createSWR };
36
+ //# sourceMappingURL=swr.d.mts.map
package/dist/swr.mjs ADDED
@@ -0,0 +1,48 @@
1
+ import { u as subscribe } from "./src-C2MGIlT0.mjs";
2
+ //#region packages/swr/src/index.ts
3
+ const subscribeCall = subscribe;
4
+ function createSWR(app, options = {}) {
5
+ const keyPrefix = Object.freeze([...options.keyPrefix ?? ["capable"]]);
6
+ const callableAt = (path) => {
7
+ let current = app;
8
+ for (const segment of path) current = current[segment];
9
+ return current;
10
+ };
11
+ const capabilityKey = (path, input) => Object.freeze([
12
+ ...keyPrefix,
13
+ ...path,
14
+ ...input === void 0 ? [] : [input]
15
+ ]);
16
+ const withOptions = (key, operation, hookOptions) => hookOptions === void 0 ? [key, operation] : [
17
+ key,
18
+ operation,
19
+ hookOptions
20
+ ];
21
+ const proxy = (path) => new Proxy({}, { get(_target, key) {
22
+ if (key === "then") return void 0;
23
+ if (key === "key") return (input) => capabilityKey(path, input);
24
+ if (key === "swr") return (input, swrOptions) => withOptions(capabilityKey(path, input), () => callableAt(path)(input), swrOptions);
25
+ if (key === "mutation") return (mutationOptions) => withOptions(capabilityKey(path), (_key, { arg }) => callableAt(path)(arg), mutationOptions);
26
+ if (key === "subscription") return (input, subscriptionOptions) => withOptions(capabilityKey(path, input), (_key, { next }) => {
27
+ const controller = new AbortController();
28
+ (async () => {
29
+ try {
30
+ for await (const output of subscribeCall(callableAt(path), input, { signal: controller.signal })) next(null, output);
31
+ } catch (error) {
32
+ if (!controller.signal.aborted) next(toError(error));
33
+ }
34
+ })();
35
+ return () => controller.abort();
36
+ }, subscriptionOptions);
37
+ if (typeof key !== "string") return void 0;
38
+ return proxy([...path, key]);
39
+ } });
40
+ return proxy([]);
41
+ }
42
+ function toError(error) {
43
+ return error instanceof Error ? error : new Error(String(error));
44
+ }
45
+ //#endregion
46
+ export { createSWR };
47
+
48
+ //# sourceMappingURL=swr.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"swr.mjs","names":[],"sources":["../../swr/src/index.ts"],"sourcesContent":["import {\n subscribe,\n type AppCapabilityIsSubscribable,\n} from \"@capable/app\";\nimport type {\n Fetcher,\n SWRConfiguration,\n} from \"swr\";\nimport type {\n MutationFetcher,\n SWRMutationConfiguration,\n} from \"swr/mutation\";\nimport type { SWRSubscription } from \"swr/subscription\";\n\ntype CapabilityCall = (...args: any[]) => Promise<any>;\n\nconst subscribeCall = subscribe as unknown as (\n capabilityCall: CapabilityCall,\n input: unknown,\n options: { readonly signal: AbortSignal },\n) => AsyncIterableIterator<unknown>;\n\ntype CapabilityInput<TCall extends CapabilityCall> =\n Exclude<Parameters<TCall>[0], undefined>;\n\ntype CapabilityVariables<TCall extends CapabilityCall> =\n undefined extends Parameters<TCall>[0]\n ? Exclude<Parameters<TCall>[0], undefined> | void\n : Parameters<TCall>[0];\n\ntype CapabilityOutput<TCall extends CapabilityCall> =\n Awaited<ReturnType<TCall>>;\n\nexport type CapabilitySWRKey = readonly [unknown, ...unknown[]];\n\ntype CapabilityFetcher<TCall extends CapabilityCall> = Fetcher<\n CapabilityOutput<TCall>,\n CapabilitySWRKey\n>;\n\ntype CapabilityMutationFetcher<TCall extends CapabilityCall> = MutationFetcher<\n CapabilityOutput<TCall>,\n CapabilitySWRKey,\n CapabilityVariables<TCall>\n>;\n\nexport type CapabilitySWRConfiguration<\n TCall extends CapabilityCall,\n> = Omit<\n SWRConfiguration<\n CapabilityOutput<TCall>,\n Error,\n CapabilityFetcher<TCall>\n >,\n \"fetcher\"\n>;\n\nexport type CapabilitySWRMutationConfiguration<\n TCall extends CapabilityCall,\n TSWRData = CapabilityOutput<TCall>,\n> = SWRMutationConfiguration<\n CapabilityOutput<TCall>,\n Error,\n CapabilitySWRKey,\n CapabilityVariables<TCall>,\n TSWRData\n> & {\n readonly throwOnError?: boolean;\n};\n\nexport type CapabilitySWRSubscriptionConfiguration<\n TCall extends CapabilityCall,\n> = SWRConfiguration<CapabilityOutput<TCall>, Error>;\n\nexport type SWRCapability<TCall extends CapabilityCall> = {\n key(input?: CapabilityInput<TCall>): CapabilitySWRKey;\n swr(input: CapabilityInput<TCall>): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityFetcher<TCall>,\n ];\n swr<const TOptions extends CapabilitySWRConfiguration<TCall>>(\n input: CapabilityInput<TCall>,\n options: TOptions,\n ): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityFetcher<TCall>,\n options: TOptions,\n ];\n mutation(): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityMutationFetcher<TCall>,\n ];\n mutation<TSWRData = CapabilityOutput<TCall>>(\n options: CapabilitySWRMutationConfiguration<TCall, TSWRData>,\n ): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityMutationFetcher<TCall>,\n options: CapabilitySWRMutationConfiguration<TCall, TSWRData>,\n ];\n};\n\nexport type SWRLiveCapability<TCall extends CapabilityCall> =\n SWRCapability<TCall> & {\n subscription(input: CapabilityInput<TCall>): readonly [\n key: CapabilitySWRKey,\n subscriber: SWRSubscription<\n CapabilitySWRKey,\n CapabilityOutput<TCall>,\n Error\n >,\n ];\n subscription<\n const TOptions extends CapabilitySWRSubscriptionConfiguration<TCall>,\n >(\n input: CapabilityInput<TCall>,\n options: TOptions,\n ): readonly [\n key: CapabilitySWRKey,\n subscriber: SWRSubscription<\n CapabilitySWRKey,\n CapabilityOutput<TCall>,\n Error\n >,\n options: TOptions,\n ];\n };\n\ntype SWRNode<TValue> =\n TValue extends CapabilityCall\n ? AppCapabilityIsSubscribable<TValue> extends true\n ? SWRLiveCapability<TValue>\n : SWRCapability<TValue>\n : TValue extends object\n ? {\n readonly [TKey in Extract<keyof TValue, string>]:\n SWRNode<TValue[TKey]>;\n }\n : never;\n\nexport type SWRApp<TApp extends object> = SWRNode<TApp>;\n\nexport function createSWR<const TApp extends object>(\n app: TApp,\n options: {\n readonly keyPrefix?: readonly unknown[];\n } = {},\n): SWRApp<TApp> {\n const keyPrefix = Object.freeze([...(options.keyPrefix ?? [\"capable\"])]);\n\n const callableAt = (path: readonly string[]): CapabilityCall => {\n let current: unknown = app;\n for (const segment of path) {\n current = (current as Record<string, unknown>)[segment];\n }\n return current as CapabilityCall;\n };\n\n const capabilityKey = (\n path: readonly string[],\n input?: unknown,\n ): CapabilitySWRKey => Object.freeze([\n ...keyPrefix,\n ...path,\n ...(input === undefined ? [] : [input]),\n ]) as CapabilitySWRKey;\n\n const withOptions = (\n key: CapabilitySWRKey,\n operation: (...args: any[]) => unknown,\n hookOptions: unknown,\n ): readonly unknown[] => hookOptions === undefined\n ? [key, operation]\n : [key, operation, hookOptions];\n\n const proxy = (path: readonly string[]): unknown =>\n new Proxy({}, {\n get(_target, key) {\n if (key === \"then\") return undefined;\n if (key === \"key\") {\n return (input?: unknown) => capabilityKey(path, input);\n }\n if (key === \"swr\") {\n return (input: unknown, swrOptions?: unknown) => withOptions(\n capabilityKey(path, input),\n () => callableAt(path)(input),\n swrOptions,\n );\n }\n if (key === \"mutation\") {\n return (mutationOptions?: unknown) => withOptions(\n capabilityKey(path),\n (_key: CapabilitySWRKey, { arg }: { readonly arg?: unknown }) =>\n callableAt(path)(arg),\n mutationOptions,\n );\n }\n if (key === \"subscription\") {\n return (input: unknown, subscriptionOptions?: unknown) => withOptions(\n capabilityKey(path, input),\n (\n _key: CapabilitySWRKey,\n { next }: {\n readonly next: (error?: Error | null, data?: unknown) => void;\n },\n ) => {\n const controller = new AbortController();\n\n void (async () => {\n try {\n for await (const output of subscribeCall(\n callableAt(path),\n input,\n { signal: controller.signal },\n )) {\n next(null, output);\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n next(toError(error));\n }\n }\n })();\n\n return () => controller.abort();\n },\n subscriptionOptions,\n );\n }\n if (typeof key !== \"string\") return undefined;\n return proxy([...path, key]);\n },\n });\n\n return proxy([]) as SWRApp<TApp>;\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n"],"mappings":";;AAgBA,MAAM,gBAAgB;AA6HtB,SAAgB,UACd,KACA,UAEI,CAAC,GACS;CACd,MAAM,YAAY,OAAO,OAAO,CAAC,GAAI,QAAQ,aAAa,CAAC,SAAS,CAAE,CAAC;CAEvE,MAAM,cAAc,SAA4C;EAC9D,IAAI,UAAmB;EACvB,KAAK,MAAM,WAAW,MACpB,UAAW,QAAoC;EAEjD,OAAO;CACT;CAEA,MAAM,iBACJ,MACA,UACqB,OAAO,OAAO;EACnC,GAAG;EACH,GAAG;EACH,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,CAAC,KAAK;CACvC,CAAC;CAED,MAAM,eACJ,KACA,WACA,gBACuB,gBAAgB,KAAA,IACrC,CAAC,KAAK,SAAS,IACf;EAAC;EAAK;EAAW;CAAW;CAEhC,MAAM,SAAS,SACb,IAAI,MAAM,CAAC,GAAG,EACZ,IAAI,SAAS,KAAK;EAChB,IAAI,QAAQ,QAAQ,OAAO,KAAA;EAC3B,IAAI,QAAQ,OACV,QAAQ,UAAoB,cAAc,MAAM,KAAK;EAEvD,IAAI,QAAQ,OACV,QAAQ,OAAgB,eAAyB,YAC/C,cAAc,MAAM,KAAK,SACnB,WAAW,IAAI,CAAC,CAAC,KAAK,GAC5B,UACF;EAEF,IAAI,QAAQ,YACV,QAAQ,oBAA8B,YACpC,cAAc,IAAI,IACjB,MAAwB,EAAE,UACzB,WAAW,IAAI,CAAC,CAAC,GAAG,GACtB,eACF;EAEF,IAAI,QAAQ,gBACV,QAAQ,OAAgB,wBAAkC,YACxD,cAAc,MAAM,KAAK,IAEvB,MACA,EAAE,WAGC;GACH,MAAM,aAAa,IAAI,gBAAgB;GAEvC,CAAM,YAAY;IAChB,IAAI;KACF,WAAW,MAAM,UAAU,cACzB,WAAW,IAAI,GACf,OACA,EAAE,QAAQ,WAAW,OAAO,CAC9B,GACE,KAAK,MAAM,MAAM;IAErB,SAAS,OAAO;KACd,IAAI,CAAC,WAAW,OAAO,SACrB,KAAK,QAAQ,KAAK,CAAC;IAEvB;GACF,EAAA,CAAG;GAEH,aAAa,WAAW,MAAM;EAChC,GACA,mBACF;EAEF,IAAI,OAAO,QAAQ,UAAU,OAAO,KAAA;EACpC,OAAO,MAAM,CAAC,GAAG,MAAM,GAAG,CAAC;CAC7B,EACF,CAAC;CAEH,OAAO,MAAM,CAAC,CAAC;AACjB;AAEA,SAAS,QAAQ,OAAuB;CACtC,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE"}
@@ -27,13 +27,18 @@ App Definition ──────────────► createServer(defini
27
27
  direct calls createCli await createMcp await createAiSdkTools
28
28
  createEveTools
29
29
  createReactQuery
30
+ createSWR
30
31
  ```
31
32
 
32
33
  ## Package responsibilities
33
34
 
35
+ The scoped `@capable/*` packages below are private workspace boundaries. The
36
+ public `capable-kit` package bundles user-facing APIs behind subpath exports such
37
+ as `capable-kit/server`, `capable-kit/next`, and `capable-kit/swr`.
38
+
34
39
  | Package | Owns |
35
40
  | ------------------- | -------------------------------------------------------------------- |
36
- | `capable` | Public facade and the user-installed `cap` command |
41
+ | `capable-kit` | Public facade and the user-installed `cap` command |
37
42
  | `@capable/core` | Authoring, tree composition, validation, middleware, errors, execution |
38
43
  | `@capable/app` | Callable local and remote Apps, merge, selection, manifests |
39
44
  | `@capable/fetch` | Capable transport encoding and the HTTP/OpenAPI projection |
@@ -43,6 +48,7 @@ App Definition ──────────────► createServer(defini
43
48
  | `@capable/ai-sdk` | Typed AI SDK v7 tool projection |
44
49
  | `@capable/eve` | Native in-process Eve tool projection |
45
50
  | `@capable/react-query` | Query keys, query options, mutations, live queries |
51
+ | `@capable/swr` | SWR keys, fetchers, mutations, and subscriptions |
46
52
  | `@capable/next` | Method-export translation for the App Router |
47
53
  | `@capable/nitro-host` | Development server, build, and preview for standalone projects |
48
54
  | `@capable/toolchain` | Internal command implementation and project discovery |
@@ -3,6 +3,19 @@
3
3
  This is a live engineering log. Record awkward, unexpectedly heavy,
4
4
  duplicated, or leaky implementation work as it appears.
5
5
 
6
+ ## 2026-08-05 — Markdown negotiation must run before static page matching
7
+
8
+ - **Observed:** The `dom-md` Next.js example returns a flat rewrite list, which
9
+ Next.js 16.2.6 places in `afterFiles`. Those rewrites never see this site's
10
+ statically prerendered MDX routes because filesystem routes win first.
11
+ - **Why it matters:** The Markdown Route Handler worked directly, but
12
+ `Accept: text/markdown` silently returned cached HTML at the public docs URL.
13
+ - **Current choice:** Register the same header-matched rewrite in
14
+ `beforeFiles`, ahead of static route matching. The route's internal request
15
+ explicitly accepts HTML, so it does not negotiate back into itself.
16
+ - **Follow-up:** Recheck whether a flat rewrite becomes safe if Next.js or the
17
+ `dom-md` guide changes its ordering guidance.
18
+
6
19
  ## 2026-07-31 — Rich presentation must be requested explicitly
7
20
 
8
21
  - **Observed:** The App runtime previously derived Markdown after every call,
@@ -50,13 +63,13 @@ duplicated, or leaky implementation work as it appears.
50
63
  required cross-file inference. The complete build now takes about 0.5–0.7
51
64
  seconds and its declarations are equivalent to the TypeScript-generated
52
65
  output. TypeScript 7 RC handles workspace typechecking separately.
53
- - **Follow-up:** Decide whether scoped surface packages and their
54
- `capable-kit/*` facades should both remain public. Treat that as a package API
55
- decision rather than a build-performance shortcut.
66
+ - **Resolution (2026-08-05):** Scoped `@capable/*` packages are private
67
+ workspace boundaries. `capable-kit` is the only published package and exposes
68
+ user-facing surfaces through subpaths.
56
69
 
57
70
  ## 2026-07-29 — Bundling duplicated nominal App type identities
58
71
 
59
- - **Observed:** The standalone `capable` facade bundles `@capable/app`, while
72
+ - **Observed:** The standalone `capable-kit` facade bundles `@capable/app`, while
60
73
  surface packages such as `@capable/react-query` reference their own external
61
74
  copy. A private `unique symbol` used only to carry Capability type information
62
75
  therefore had two incompatible identities in a consuming application.
@@ -67,9 +80,10 @@ duplicated, or leaky implementation work as it appears.
67
80
  Capability-call phantom metadata structural. React Query accepts the typed
68
81
  callable object it actually projects instead of depending on runtime
69
82
  ownership it never reads.
70
- - **Follow-up:** Add an installed-package consumer fixture so declaration
71
- identity is checked across the bundled facade and separately published
72
- surfaces before release.
83
+ - **Resolution (2026-08-05):** React Query and the other user-facing surfaces
84
+ now ship through bundled `capable-kit/*` subpaths. Keep an installed-package
85
+ consumer fixture so their declarations and optional peers are checked before
86
+ release.
73
87
 
74
88
  ## 2026-07-29 — Manifest discovery cannot be globally eager
75
89
 
@@ -383,6 +397,37 @@ duplicated, or leaky implementation work as it appears.
383
397
  this only if a real App uses one of those names or callable Apps gain
384
398
  synchronous leaf metadata.
385
399
 
400
+ ## 2026-08-05 — SWR fetchers do not receive a cancellation signal
401
+
402
+ - **Observed:** SWR passes the cache key to a unary fetcher, but does not expose
403
+ an `AbortSignal` in that fetcher's contract. Capability subscriptions do have
404
+ an explicit cleanup boundary.
405
+ - **Why it matters:** `@capable/swr` cannot forward hook disposal to an in-flight
406
+ unary Capability call the way `@capable/react-query` can. Pretending to own a
407
+ controller would abort at the wrong time because SWR owns request deduplication
408
+ and revalidation.
409
+ - **Current choice:** Unary `swr()` fetchers call the Capability without a
410
+ signal. `subscription()` creates a controller and aborts it from SWR's
411
+ unsubscribe callback.
412
+ - **Follow-up:** Forward cancellation if SWR adds a fetcher lifecycle signal.
413
+ The projection's `key`, `swr`, `mutation`, and `subscription` member names are
414
+ reserved until App leaves have synchronous metadata.
415
+
416
+ ## 2026-08-05 — npm pack silently accepted missing export targets
417
+
418
+ - **Observed:** `capable-kit@0.0.1-alpha.6` advertised the new `next`,
419
+ `react-query`, and `swr` subpaths, but the publishing worktree's ignored
420
+ `dist/` directory did not contain their built files. npm included the export
421
+ map without warning and published a tarball with phantom entry points.
422
+ - **Why it matters:** Type-aware tooling could see the intended API while every
423
+ runtime import failed. A successful source build in another worktree did not
424
+ prove the contents of the worktree used for publishing.
425
+ - **Current choice:** `prepack` builds from source, verifies every export and bin
426
+ target, and only then assembles documentation. The package test independently
427
+ checks that every manifest target appears in the produced tarball.
428
+ - **Follow-up:** Keep release validation tarball-based; do not treat an ignored
429
+ local `dist/` directory or a source-level test as publication evidence.
430
+
386
431
  ## 2026-07-28 — A fresh Next.js build can race SQLite initialization
387
432
 
388
433
  - **Observed:** Next.js page-data collection imports the authenticated Todo
@@ -40,7 +40,7 @@ You do not give up the normal full-stack experience by choosing Capable. A brows
40
40
  ```ts title="query.ts"
41
41
  import { createRemoteApp } from "capable-kit";
42
42
  import { createHttpTransport } from "capable-kit/http";
43
- import { createReactQuery } from "@capable/react-query";
43
+ import { createReactQuery } from "capable-kit/react-query";
44
44
  import type definition from "../capable.app";
45
45
 
46
46
  const app = createRemoteApp<typeof definition>(
@@ -17,7 +17,7 @@ Compose the server once in a shared module. The adapter only maps methods; execu
17
17
 
18
18
  ```ts title="capable/server.ts"
19
19
  // capable/server.ts
20
- import { createNextRouteHandlers } from "@capable/next";
20
+ import { createNextRouteHandlers } from "capable-kit/next";
21
21
  import { protocol, createServer, http } from "capable-kit/server";
22
22
  import definition from "../capable.app";
23
23
 
@@ -88,7 +88,7 @@ MCP /mcp
88
88
  Keep your existing Next.js application, authentication, and deployment. Mount a Capable server in App Router handlers.
89
89
 
90
90
  ```ts title="capable/server.ts"
91
- import { createNextRouteHandlers } from "@capable/next";
91
+ import { createNextRouteHandlers } from "capable-kit/next";
92
92
  import { mcp } from "capable-kit/mcp";
93
93
  import { createServer, http, protocol } from "capable-kit/server";
94
94
  import definition from "../capable.app";
@@ -210,7 +210,7 @@ export default createEveTools(app);
210
210
  ```tsx title="add-todo.tsx"
211
211
  "use client";
212
212
 
213
- import { createReactQuery } from "@capable/react-query";
213
+ import { createReactQuery } from "capable-kit/react-query";
214
214
  import { useMutation } from "@tanstack/react-query";
215
215
  import { createRemoteApp } from "capable-kit";
216
216
  import { createHttpTransport } from "capable-kit/http";
@@ -230,7 +230,7 @@ Capable works two ways: as its own service, or embedded in an app you already ha
230
230
 
231
231
  ```sh title="terminal"
232
232
  # inside your existing Next.js app
233
- pnpm add capable-kit zod @capable/next
233
+ pnpm add capable-kit zod
234
234
  ```
235
235
 
236
236
  2. ### Define capabilities
@@ -292,7 +292,7 @@ Capable works two ways: as its own service, or embedded in an app you already ha
292
292
 
293
293
  ```ts title="capable/server.ts"
294
294
  // capable/server.ts
295
- import { createNextRouteHandlers } from "@capable/next";
295
+ import { createNextRouteHandlers } from "capable-kit/next";
296
296
  import { protocol, createServer, http } from "capable-kit/server";
297
297
  import definition from "./app";
298
298
 
@@ -347,12 +347,12 @@ Capable works two ways: as its own service, or embedded in an app you already ha
347
347
 
348
348
  6. ### Call from React Query
349
349
 
350
- `@capable/react-query` mirrors the app tree into query keys and options. The browser talks to the Capable transport at `/_capable`.
350
+ `capable-kit/react-query` mirrors the app tree into query keys and options. The browser talks to the Capable transport at `/_capable`.
351
351
 
352
352
  ```ts title="app/query.ts"
353
353
  import { createRemoteApp } from "capable-kit";
354
354
  import { createHttpTransport } from "capable-kit/http";
355
- import { createReactQuery } from "@capable/react-query";
355
+ import { createReactQuery } from "capable-kit/react-query";
356
356
  import type definition from "../capable/app";
357
357
 
358
358
  const app = createRemoteApp<typeof definition>(
@@ -13,7 +13,7 @@ Entry points are explicit so that a server mount, a UI projection, or an agent i
13
13
 
14
14
  ## The root entry point [#root]
15
15
 
16
- `capable` is deliberately limited to authoring and composing apps. Everything you need to define capabilities lives here.
16
+ `capable-kit` is deliberately limited to authoring and composing apps. Everything you need to define capabilities lives here.
17
17
 
18
18
  ```ts title="import"
19
19
  import {
@@ -37,17 +37,18 @@ import {
37
37
 
38
38
  | Import | Contains |
39
39
  | --- | --- |
40
- | `capable` | Capability authoring, app definitions, executable and remote apps, composition, and the capable command |
41
- | `capable/server` | `createServer()` plus the `protocol()` and `http()` mounts |
42
- | `capable/http` | Capable transport client and server encoding: `createHttpTransport()`, `createHttpHandler()` |
43
- | `capable/cli` | `createCli()` |
44
- | `capable/mcp` | `createMcp()` and the `mcp()` server mount |
45
- | `capable/eve` | `createEveTools()` |
46
- | `capable/ai-sdk` | `createAiSdkTools()` |
47
- | `capable/app` | App runtime internals: manifests, transport types, selection |
48
- | `capable/core` | Execution and schema primitives for building your own surface |
49
- | `@capable/react-query` | `createReactQuery()` |
50
- | `@capable/next` | `createNextRouteHandlers()` |
40
+ | `capable-kit` | Capability authoring, app definitions, executable and remote apps, composition, and the capable command |
41
+ | `capable-kit/server` | `createServer()` plus the `protocol()` and `http()` mounts |
42
+ | `capable-kit/http` | Capable transport client and server encoding: `createHttpTransport()`, `createHttpHandler()` |
43
+ | `capable-kit/cli` | `createCli()` |
44
+ | `capable-kit/mcp` | `createMcp()` and the `mcp()` server mount |
45
+ | `capable-kit/eve` | `createEveTools()` |
46
+ | `capable-kit/ai-sdk` | `createAiSdkTools()` |
47
+ | `capable-kit/app` | App runtime internals: manifests, transport types, selection |
48
+ | `capable-kit/core` | Execution and schema primitives for building your own surface |
49
+ | `capable-kit/react-query` | `createReactQuery()` |
50
+ | `capable-kit/swr` | `createSWR()` |
51
+ | `capable-kit/next` | `createNextRouteHandlers()` |
51
52
 
52
53
  > **Dependency direction**
53
54
  >
@@ -9,16 +9,20 @@ export const metadata = docMetadata("/surfaces/react-query", frontmatter);
9
9
 
10
10
  <DocsPage href="/surfaces/react-query" frontmatter={frontmatter}>
11
11
 
12
- `@capable/react-query` mirrors the app tree into TanStack Query primitives. Keys, query functions, and mutation functions are derived, so components stop repeating endpoint names and cache keys.
12
+ `capable-kit/react-query` mirrors the app tree into TanStack Query primitives. Keys, query functions, and mutation functions are derived, so components stop repeating endpoint names and cache keys.
13
13
 
14
14
  ## Create the client [#create]
15
15
 
16
16
  Point it at any app. In the browser this is usually a remote app over the Capable transport; on the server it can be a local app. Both App creation and the React Query projection are synchronous. Manifest discovery is deferred until a query actually executes.
17
17
 
18
+ ```sh title="terminal"
19
+ pnpm add capable-kit @tanstack/react-query
20
+ ```
21
+
18
22
  ```ts title="query.ts"
19
23
  import { createRemoteApp } from "capable-kit";
20
24
  import { createHttpTransport } from "capable-kit/http";
21
- import { createReactQuery } from "@capable/react-query";
25
+ import { createReactQuery } from "capable-kit/react-query";
22
26
  import type definition from "../capable.app";
23
27
 
24
28
  const app = createRemoteApp<typeof definition>(
@@ -0,0 +1,97 @@
1
+ ---
2
+ title: "SWR"
3
+ description: "Derive typed keys and hook arguments for SWR."
4
+ ---
5
+
6
+ import { DocsPage, docMetadata } from "../../_components/docs-page";
7
+
8
+ export const metadata = docMetadata("/surfaces/swr", frontmatter);
9
+
10
+ <DocsPage href="/surfaces/swr" frontmatter={frontmatter}>
11
+
12
+ `capable-kit/swr` mirrors the app tree into SWR keys, fetchers, mutation fetchers,
13
+ and subscribers. Components keep using SWR's hooks and configuration directly,
14
+ without repeating Capability paths or input types.
15
+
16
+ ## Create the projection [#create]
17
+
18
+ Point it at a local or remote App. Manifest discovery remains lazy and starts
19
+ only when SWR calls a generated fetcher.
20
+
21
+ ```sh title="terminal"
22
+ pnpm add capable-kit swr
23
+ ```
24
+
25
+ ```ts title="swr.ts"
26
+ import { createRemoteApp } from "capable-kit";
27
+ import { createHttpTransport } from "capable-kit/http";
28
+ import { createSWR } from "capable-kit/swr";
29
+ import type definition from "../capable.app";
30
+
31
+ const app = createRemoteApp<typeof definition>(
32
+ createHttpTransport({ url: "/_capable/" }),
33
+ );
34
+
35
+ export const capableSWR = createSWR(app);
36
+ ```
37
+
38
+ ## Use it in components [#use]
39
+
40
+ Each operation returns the arguments for its corresponding SWR hook, so the
41
+ generated types flow through a normal spread call.
42
+
43
+ ```tsx title="todo-list.tsx"
44
+ import useSWR, { useSWRConfig } from "swr";
45
+ import useSWRMutation from "swr/mutation";
46
+ import { capableSWR } from "./swr";
47
+
48
+ export function TodoList() {
49
+ const { mutate } = useSWRConfig();
50
+ const todos = useSWR(...capableSWR.todos.list.swr({}));
51
+ const createTodo = useSWRMutation(
52
+ ...capableSWR.todos.create.mutation({
53
+ onSuccess: () => mutate(capableSWR.todos.list.key()),
54
+ }),
55
+ );
56
+
57
+ if (todos.isLoading) return <Spinner />;
58
+ if (todos.error) return <Error error={todos.error} />;
59
+
60
+ return (
61
+ <>
62
+ <ul>{todos.data?.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
63
+ <button onClick={() => createTodo.trigger({ title: "New" })}>Add</button>
64
+ </>
65
+ );
66
+ }
67
+ ```
68
+
69
+ | Method | Returns |
70
+ | --- | --- |
71
+ | `key(input?)` | `["capable", ...path, input?]`, for cache access and revalidation |
72
+ | `swr(input, options?)` | Typed arguments for `useSWR` |
73
+ | `mutation(options?)` | Typed arguments for `useSWRMutation`; `trigger` takes the Capability input |
74
+ | `subscription(input, options?)` | Typed arguments for `useSWRSubscription`, only on subscribable Capabilities |
75
+
76
+ Pass `keyPrefix` to `createSWR()` if the `capable` prefix collides with existing
77
+ keys.
78
+
79
+ ## Subscriptions [#subscriptions]
80
+
81
+ When a Capability defines [subscribe](/patterns/subscriptions), the projection
82
+ adds `subscription()`. Unmounting aborts the Capability subscription.
83
+
84
+ ```tsx title="live-todos.tsx"
85
+ import useSWRSubscription from "swr/subscription";
86
+ import { capableSWR } from "./swr";
87
+
88
+ const todos = useSWRSubscription(
89
+ ...capableSWR.todos.list.subscription({}),
90
+ );
91
+ ```
92
+
93
+ > SWR does not provide an `AbortSignal` to unary fetchers, so unary Capability
94
+ > calls cannot be cancelled by hook disposal. Subscription cleanup is wired to
95
+ > an `AbortController`.
96
+
97
+ </DocsPage>
@@ -36,12 +36,14 @@ A projection needs no server at all. It takes an executable app and returns comm
36
36
  import { createCli } from "capable-kit/cli";
37
37
  import { createAiSdkTools } from "capable-kit/ai-sdk";
38
38
  import { createEveTools } from "capable-kit/eve";
39
- import { createReactQuery } from "@capable/react-query";
39
+ import { createReactQuery } from "capable-kit/react-query";
40
+ import { createSWR } from "capable-kit/swr";
40
41
 
41
42
  createCli(app); // process-level command tree
42
43
  await createAiSdkTools(app); // typed AI SDK tools
43
44
  createEveTools(app); // durable in-process agent tools
44
45
  createReactQuery(app); // query keys and options for a UI
46
+ createSWR(app); // SWR keys and hook arguments for a UI
45
47
  ```
46
48
 
47
49
  ## Choosing surfaces [#choose]
@@ -55,7 +57,8 @@ createReactQuery(app); // query keys and options for a UI
55
57
  | [MCP](/surfaces/mcp) | External agents connect over the network | `capable/mcp` |
56
58
  | [Eve](/surfaces/eve) | An agent runs in your process | `capable/eve` |
57
59
  | [AI SDK](/surfaces/ai-sdk) | An AI SDK model or agent calls your app | `capable/ai-sdk` |
58
- | [React Query](/surfaces/react-query) | A React UI reads and mutates the app | `@capable/react-query` |
60
+ | [React Query](/surfaces/react-query) | A React UI reads and mutates the app | `capable-kit/react-query` |
61
+ | [SWR](/surfaces/swr) | A React UI reads, mutates, and subscribes with SWR | `capable-kit/swr` |
59
62
 
60
63
  > **Nothing is implicit**
61
64
  >
@@ -74,5 +77,6 @@ createReactQuery(app); // query keys and options for a UI
74
77
  - [**AI SDK**](/surfaces/ai-sdk) — Typed tools for generateText, streamText, and agents.
75
78
  - [**Eve**](/surfaces/eve) — Native in-process tools with approvals.
76
79
  - [**React Query**](/surfaces/react-query) — Query keys, mutations, and live queries.
80
+ - [**SWR**](/surfaces/swr) — Keys and arguments for queries, mutations, and subscriptions.
77
81
 
78
82
  </DocsPage>
@@ -0,0 +1,137 @@
1
+ import { existsSync } from "node:fs";
2
+ import {
3
+ cp,
4
+ mkdir,
5
+ readdir,
6
+ readFile,
7
+ rm,
8
+ writeFile,
9
+ } from "node:fs/promises";
10
+ import { dirname, join, relative } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+
13
+ const repositoryDirectory = new URL("../../", import.meta.url);
14
+ const outputDirectory = new URL("./docs/", import.meta.url);
15
+ const canonicalSiteDirectory = new URL("./website/app/", repositoryDirectory);
16
+ const packagedSiteDirectory = new URL("./site/", outputDirectory);
17
+ const canonicalDocumentationAvailable = [
18
+ new URL("./CONTEXT.md", repositoryDirectory),
19
+ new URL("./docs/", repositoryDirectory),
20
+ canonicalSiteDirectory,
21
+ ].every(existsSync);
22
+
23
+ async function findPages(directory) {
24
+ const entries = await readdir(directory, { withFileTypes: true });
25
+ const nested = await Promise.all(
26
+ entries.map((entry) => {
27
+ const path = join(directory, entry.name);
28
+ if (entry.isDirectory()) return findPages(path);
29
+ return entry.name === "page.mdx" ? [path] : [];
30
+ }),
31
+ );
32
+ return nested.flat();
33
+ }
34
+
35
+ function titleSlug(source, file) {
36
+ const title = source.match(/^title:\s*"([^"]+)"$/m)?.[1];
37
+ if (!title) throw new Error(`Missing title frontmatter in ${file}`);
38
+
39
+ return title
40
+ .normalize("NFKD")
41
+ .replace(/[\u0300-\u036f]/g, "")
42
+ .replace(/[^a-zA-Z0-9]+/g, "-")
43
+ .replace(/^-|-$/g, "")
44
+ .toLowerCase();
45
+ }
46
+
47
+ async function copyPublicGuides() {
48
+ const sourceRoot = fileURLToPath(canonicalSiteDirectory);
49
+ const outputRoot = fileURLToPath(packagedSiteDirectory);
50
+
51
+ for (const page of await findPages(sourceRoot)) {
52
+ const source = await readFile(page, "utf8");
53
+ const routeDirectory = relative(sourceRoot, dirname(page));
54
+ const section =
55
+ routeDirectory === "" ? "" : dirname(routeDirectory);
56
+ const destinationDirectory = join(
57
+ outputRoot,
58
+ section === "." ? "" : section,
59
+ );
60
+
61
+ await mkdir(destinationDirectory, { recursive: true });
62
+ await writeFile(
63
+ join(destinationDirectory, `${titleSlug(source, page)}.mdx`),
64
+ source,
65
+ );
66
+ }
67
+ }
68
+
69
+ async function copyDocumentation() {
70
+ // A tarball can be packed again after installation. In that case the
71
+ // canonical repository sources are absent and the included docs are already
72
+ // the correct input.
73
+ if (!canonicalDocumentationAvailable) {
74
+ if (existsSync(outputDirectory)) return;
75
+ throw new Error("Could not find Capable's canonical documentation sources.");
76
+ }
77
+
78
+ await rm(outputDirectory, { force: true, recursive: true });
79
+ await mkdir(outputDirectory, { recursive: true });
80
+
81
+ await Promise.all([
82
+ cp(
83
+ new URL("./docs/", repositoryDirectory),
84
+ new URL("./internal/", outputDirectory),
85
+ { recursive: true },
86
+ ),
87
+ cp(
88
+ new URL("./CONTEXT.md", repositoryDirectory),
89
+ new URL("./CONTEXT.md", outputDirectory),
90
+ ),
91
+ copyPublicGuides(),
92
+ ]);
93
+
94
+ await writeFile(
95
+ new URL("./README.md", outputDirectory),
96
+ `# Capable documentation
97
+
98
+ This directory is assembled from Capable's canonical documentation sources when
99
+ the npm package is packed. It matches the installed package version.
100
+
101
+ ## For coding agents
102
+
103
+ Do not rely on remembered Capable APIs. Read the relevant bundled guide and
104
+ inspect \`../src/\` when you need a detail the guides do not cover.
105
+
106
+ Start here:
107
+
108
+ 1. [Introduction](./site/introduction.mdx)
109
+ 2. [Quickstart](./site/quickstart.mdx)
110
+ 3. [Capabilities](./site/concepts/capabilities.mdx)
111
+ 4. [Apps](./site/concepts/apps.mdx)
112
+ 5. [Surfaces](./site/surfaces.mdx)
113
+ 6. [Packages and entry points](./site/reference/packages-and-entry-points.mdx)
114
+
115
+ Public guides are grouped by section and named from their frontmatter titles.
116
+ To find a topic, search the files under \`site/\` or list its \`.mdx\` files.
117
+
118
+ - \`site/\` contains the canonical, human- and agent-readable MDX guides.
119
+ - \`internal/\` contains design notes for contributors.
120
+ - \`CONTEXT.md\` defines the framework's domain language and invariants.
121
+
122
+ The canonical sources live in \`website/\`, \`docs/\`, and \`CONTEXT.md\` in the
123
+ Capable repository. Edit those sources rather than the generated package copy.
124
+ `,
125
+ );
126
+ }
127
+
128
+ async function cleanDocumentation() {
129
+ if (!canonicalDocumentationAvailable) return;
130
+ await rm(outputDirectory, { force: true, recursive: true });
131
+ }
132
+
133
+ if (process.argv.includes("--clean")) {
134
+ await cleanDocumentation();
135
+ } else {
136
+ await copyDocumentation();
137
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "capable-kit",
3
- "version": "0.0.1-alpha.5",
3
+ "version": "0.0.1-alpha.7",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "cap": "dist/bin.mjs",
@@ -39,9 +39,21 @@
39
39
  "types": "./dist/mcp.d.mts",
40
40
  "import": "./dist/mcp.mjs"
41
41
  },
42
+ "./next": {
43
+ "types": "./dist/next.d.mts",
44
+ "import": "./dist/next.mjs"
45
+ },
46
+ "./react-query": {
47
+ "types": "./dist/react-query.d.mts",
48
+ "import": "./dist/react-query.mjs"
49
+ },
42
50
  "./server": {
43
51
  "types": "./dist/server.d.mts",
44
52
  "import": "./dist/server.mjs"
53
+ },
54
+ "./swr": {
55
+ "types": "./dist/swr.d.mts",
56
+ "import": "./dist/swr.mjs"
45
57
  }
46
58
  },
47
59
  "files": [
@@ -49,14 +61,17 @@
49
61
  "dist/*.mjs",
50
62
  "dist/*.mjs.map",
51
63
  "docs",
64
+ "package-docs.mjs",
65
+ "prepare-package.mjs",
52
66
  "src",
67
+ "verify-package-exports.mjs",
53
68
  "README.md"
54
69
  ],
55
70
  "directories": {
56
71
  "doc": "./docs"
57
72
  },
58
73
  "scripts": {
59
- "prepack": "node package-docs.mjs",
74
+ "prepack": "node prepare-package.mjs",
60
75
  "postpack": "node package-docs.mjs --clean"
61
76
  },
62
77
  "engines": {
@@ -73,15 +88,23 @@
73
88
  "nitro": "3.0.260610-beta"
74
89
  },
75
90
  "peerDependencies": {
91
+ "@tanstack/react-query": ">=5.80.2 <6",
76
92
  "ai": "^7.0.0",
77
- "eve": ">=0.27.1"
93
+ "eve": ">=0.27.1",
94
+ "swr": ">=2.3.0 <3"
78
95
  },
79
96
  "peerDependenciesMeta": {
97
+ "@tanstack/react-query": {
98
+ "optional": true
99
+ },
80
100
  "ai": {
81
101
  "optional": true
82
102
  },
83
103
  "eve": {
84
104
  "optional": true
105
+ },
106
+ "swr": {
107
+ "optional": true
85
108
  }
86
109
  }
87
110
  }
@@ -0,0 +1,21 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const repositorySource = new URL("../../packages/capable/src/index.ts", import.meta.url);
6
+ if (existsSync(repositorySource)) {
7
+ const pnpm = process.platform === "win32" ? "pnpm.cmd" : "pnpm";
8
+ const build = spawnSync(pnpm, ["--dir", "../..", "build"], {
9
+ cwd: fileURLToPath(new URL("./", import.meta.url)),
10
+ encoding: "utf8",
11
+ });
12
+
13
+ if (build.status !== 0) {
14
+ process.stderr.write(build.stdout ?? "");
15
+ process.stderr.write(build.stderr ?? "");
16
+ process.exit(build.status ?? 1);
17
+ }
18
+ }
19
+
20
+ await import("./verify-package-exports.mjs");
21
+ await import("./package-docs.mjs");
package/src/index.test.ts CHANGED
@@ -7,7 +7,10 @@ import { executeCapability } from "./core.ts";
7
7
  import { createEveTools } from "./eve.ts";
8
8
  import { createHttpHandler, createHttpTransport } from "./http.ts";
9
9
  import { createMcp, mcp } from "./mcp.ts";
10
+ import { createNextRouteHandlers } from "./next.ts";
11
+ import { createReactQuery } from "./react-query.ts";
10
12
  import { createServer } from "./server.ts";
13
+ import { createSWR } from "./swr.ts";
11
14
 
12
15
  describe("capable public entry points", () => {
13
16
  test("ships cap as the primary command with the capable alias", async () => {
@@ -49,8 +52,11 @@ describe("capable public entry points", () => {
49
52
  createEveTools,
50
53
  createHttpHandler,
51
54
  createMcp,
55
+ createNextRouteHandlers,
56
+ createReactQuery,
52
57
  mcp,
53
58
  createServer,
59
+ createSWR,
54
60
  createHttpTransport,
55
61
  ].every((value) => typeof value === "function")).toBe(true);
56
62
  });
package/src/next.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "@capable/next";
@@ -1,5 +1,11 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { existsSync, mkdtempSync, rmSync } from "node:fs";
2
+ import {
3
+ existsSync,
4
+ mkdtempSync,
5
+ readdirSync,
6
+ readFileSync,
7
+ rmSync,
8
+ } from "node:fs";
3
9
  import { tmpdir } from "node:os";
4
10
  import { join } from "node:path";
5
11
  import { fileURLToPath } from "node:url";
@@ -22,30 +28,40 @@ describe("published package", () => {
22
28
 
23
29
  try {
24
30
  const output = execFileSync(
25
- "pnpm",
31
+ "npm",
26
32
  ["pack", "--json", "--pack-destination", destination],
27
33
  {
28
34
  cwd: packageDirectory,
29
35
  encoding: "utf8",
30
36
  },
31
37
  );
32
- const result = JSON.parse(output) as PackResult;
38
+ const result = findPackResult(JSON.parse(output));
33
39
  const paths = new Set(result.files.map((file) => file.path));
40
+ const archive = join(destination, result.filename);
34
41
  const manifest = JSON.parse(
35
42
  execFileSync(
36
43
  "tar",
37
- ["-xOzf", result.filename, "package/package.json"],
44
+ ["-xOzf", archive, "package/package.json"],
38
45
  { encoding: "utf8" },
39
46
  ),
40
47
  ) as {
48
+ readonly bin?: Readonly<Record<string, string>>;
41
49
  readonly directories?: { readonly doc?: string };
50
+ readonly exports?: Readonly<Record<
51
+ string,
52
+ string | Readonly<Record<string, string>>
53
+ >>;
54
+ readonly peerDependenciesMeta?: Readonly<Record<
55
+ string,
56
+ { readonly optional?: boolean }
57
+ >>;
42
58
  readonly scripts?: Record<string, string>;
43
59
  };
44
60
  const quickstart = execFileSync(
45
61
  "tar",
46
62
  [
47
63
  "-xOzf",
48
- result.filename,
64
+ archive,
49
65
  "package/docs/site/quickstart.mdx",
50
66
  ],
51
67
  { encoding: "utf8" },
@@ -66,9 +82,10 @@ describe("published package", () => {
66
82
  (path) =>
67
83
  path.startsWith("docs/site/") && path.endsWith(".mdx"),
68
84
  ),
69
- ).toHaveLength(26);
85
+ ).toHaveLength(27);
70
86
  expect(paths).toContain("docs/site/introduction.mdx");
71
87
  expect(paths).toContain("docs/site/concepts/presentations.mdx");
88
+ expect(paths).toContain("docs/site/surfaces/swr.mdx");
72
89
  expect(
73
90
  [...paths].some(
74
91
  (path) =>
@@ -82,10 +99,47 @@ describe("published package", () => {
82
99
  (path) => path.startsWith("dist/package/") || path.endsWith(".tgz"),
83
100
  ),
84
101
  ).toBe(false);
85
- expect(paths).not.toContain("package-docs.mjs");
102
+ expect(paths).toContain("package-docs.mjs");
103
+ expect(paths).toContain("prepare-package.mjs");
104
+ expect(paths).toContain("verify-package-exports.mjs");
86
105
  expect(manifest.directories?.doc).toBe("./docs");
87
- expect(manifest.scripts?.prepack).toBeUndefined();
88
- expect(manifest.scripts?.postpack).toBeUndefined();
106
+ expect(manifest.scripts).toMatchObject({
107
+ prepack: "node prepare-package.mjs",
108
+ postpack: "node package-docs.mjs --clean",
109
+ });
110
+ expect(Object.keys(manifest.exports ?? {})).toEqual([
111
+ ".",
112
+ "./ai-sdk",
113
+ "./app",
114
+ "./cli",
115
+ "./core",
116
+ "./eve",
117
+ "./http",
118
+ "./mcp",
119
+ "./next",
120
+ "./react-query",
121
+ "./server",
122
+ "./swr",
123
+ ]);
124
+ expect(manifest.peerDependenciesMeta).toMatchObject({
125
+ "@tanstack/react-query": { optional: true },
126
+ swr: { optional: true },
127
+ });
128
+ for (const [entryPoint, conditions] of Object.entries(
129
+ manifest.exports ?? {},
130
+ )) {
131
+ const targets = typeof conditions === "string"
132
+ ? [conditions]
133
+ : Object.values(conditions);
134
+ for (const target of targets) {
135
+ expect(paths, `${entryPoint} -> ${target}`).toContain(
136
+ target.replace(/^\.\//, ""),
137
+ );
138
+ }
139
+ }
140
+ for (const [command, target] of Object.entries(manifest.bin ?? {})) {
141
+ expect(paths, `bin:${command} -> ${target}`).toContain(target);
142
+ }
89
143
  expect(quickstart).toMatch(
90
144
  /^---\ntitle: "Quickstart"\ndescription: ".+"\n---/,
91
145
  );
@@ -99,4 +153,41 @@ describe("published package", () => {
99
153
  });
100
154
  }
101
155
  });
156
+
157
+ test("keeps scoped workspace packages private", () => {
158
+ const packagesDirectory = new URL("../../", import.meta.url);
159
+
160
+ for (const entry of readdirSync(packagesDirectory, {
161
+ withFileTypes: true,
162
+ })) {
163
+ if (!entry.isDirectory()) continue;
164
+ const manifestPath = new URL(
165
+ `./${entry.name}/package.json`,
166
+ packagesDirectory,
167
+ );
168
+ if (!existsSync(manifestPath)) continue;
169
+
170
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as {
171
+ readonly name?: string;
172
+ readonly private?: boolean;
173
+ readonly publishConfig?: unknown;
174
+ };
175
+ if (!manifest.name?.startsWith("@capable/")) continue;
176
+
177
+ expect(manifest.private, manifest.name).toBe(true);
178
+ expect(manifest.publishConfig, manifest.name).toBeUndefined();
179
+ }
180
+ });
102
181
  });
182
+
183
+ function findPackResult(value: unknown): PackResult {
184
+ if (Array.isArray(value)) return findPackResult(value[0]);
185
+ if (typeof value !== "object" || value === null) {
186
+ throw new Error("npm pack did not return a package");
187
+ }
188
+ if ("filename" in value && "files" in value) return value as PackResult;
189
+
190
+ const nested = Object.values(value);
191
+ if (nested.length === 1) return findPackResult(nested[0]);
192
+ throw new Error("npm pack returned an unknown result shape");
193
+ }
@@ -0,0 +1 @@
1
+ export * from "@capable/react-query";
package/src/swr.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "@capable/swr";
@@ -0,0 +1,37 @@
1
+ import { access, readFile } from "node:fs/promises";
2
+
3
+ const packageDirectory = new URL("./", import.meta.url);
4
+ const manifest = JSON.parse(
5
+ await readFile(new URL("./package.json", packageDirectory), "utf8"),
6
+ );
7
+
8
+ const targets = [
9
+ ...Object.entries(manifest.exports ?? {}).flatMap(([entryPoint, conditions]) =>
10
+ typeof conditions === "string"
11
+ ? [[entryPoint, conditions]]
12
+ : Object.entries(conditions).map(([condition, target]) => [
13
+ `${entryPoint} (${condition})`,
14
+ target,
15
+ ]),
16
+ ),
17
+ ...Object.entries(manifest.bin ?? {}).map(([command, target]) => [
18
+ `bin:${command}`,
19
+ target,
20
+ ]),
21
+ ];
22
+
23
+ const missing = [];
24
+ for (const [label, target] of targets) {
25
+ if (typeof target !== "string") continue;
26
+ try {
27
+ await access(new URL(target, packageDirectory));
28
+ } catch {
29
+ missing.push(`${label} -> ${target}`);
30
+ }
31
+ }
32
+
33
+ if (missing.length > 0) {
34
+ throw new Error(
35
+ `Package manifest points to missing files:\n${missing.join("\n")}`,
36
+ );
37
+ }