@checkstack/frontend-api 0.0.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,138 @@
1
1
  # @checkstack/frontend-api
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 7a23261: ## TanStack Query Integration
8
+
9
+ Migrated all frontend components to use `usePluginClient` hook with TanStack Query integration, replacing the legacy `forPlugin()` pattern.
10
+
11
+ ### New Features
12
+
13
+ - **`usePluginClient` hook**: Provides type-safe access to plugin APIs with `.useQuery()` and `.useMutation()` methods
14
+ - **Automatic request deduplication**: Multiple components requesting the same data share a single network request
15
+ - **Built-in caching**: Configurable stale time and cache duration per query
16
+ - **Loading/error states**: TanStack Query provides `isLoading`, `error`, `isRefetching` states automatically
17
+ - **Background refetching**: Stale data is automatically refreshed when components mount
18
+
19
+ ### Contract Changes
20
+
21
+ All RPC contracts now require `operationType: "query"` or `operationType: "mutation"` metadata:
22
+
23
+ ```typescript
24
+ const getItems = proc()
25
+ .meta({ operationType: "query", access: [access.read] })
26
+ .output(z.array(itemSchema))
27
+ .query();
28
+
29
+ const createItem = proc()
30
+ .meta({ operationType: "mutation", access: [access.manage] })
31
+ .input(createItemSchema)
32
+ .output(itemSchema)
33
+ .mutation();
34
+ ```
35
+
36
+ ### Migration
37
+
38
+ ```typescript
39
+ // Before (forPlugin pattern)
40
+ const api = useApi(myPluginApiRef);
41
+ const [items, setItems] = useState<Item[]>([]);
42
+ useEffect(() => {
43
+ api.getItems().then(setItems);
44
+ }, [api]);
45
+
46
+ // After (usePluginClient pattern)
47
+ const client = usePluginClient(MyPluginApi);
48
+ const { data: items, isLoading } = client.getItems.useQuery({});
49
+ ```
50
+
51
+ ### Bug Fixes
52
+
53
+ - Fixed `rpc.test.ts` test setup for middleware type inference
54
+ - Fixed `SearchDialog` to use `setQuery` instead of deprecated `search` method
55
+ - Fixed null→undefined warnings in notification and queue frontends
56
+
57
+ ### Patch Changes
58
+
59
+ - Updated dependencies [7a23261]
60
+ - @checkstack/common@0.3.0
61
+
62
+ ## 0.1.0
63
+
64
+ ### Minor Changes
65
+
66
+ - 9faec1f: # Unified AccessRule Terminology Refactoring
67
+
68
+ This release completes a comprehensive terminology refactoring from "permission" to "accessRule" across the entire codebase, establishing a consistent and modern access control vocabulary.
69
+
70
+ ## Changes
71
+
72
+ ### Core Infrastructure (`@checkstack/common`)
73
+
74
+ - Introduced `AccessRule` interface as the primary access control type
75
+ - Added `accessPair()` helper for creating read/manage access rule pairs
76
+ - Added `access()` builder for individual access rules
77
+ - Replaced `Permission` type with `AccessRule` throughout
78
+
79
+ ### API Changes
80
+
81
+ - `env.registerPermissions()` → `env.registerAccessRules()`
82
+ - `meta.permissions` → `meta.access` in RPC contracts
83
+ - `usePermission()` → `useAccess()` in frontend hooks
84
+ - Route `permission:` field → `accessRule:` field
85
+
86
+ ### UI Changes
87
+
88
+ - "Roles & Permissions" tab → "Roles & Access Rules"
89
+ - "You don't have permission..." → "You don't have access..."
90
+ - All permission-related UI text updated
91
+
92
+ ### Documentation & Templates
93
+
94
+ - Updated 18 documentation files with AccessRule terminology
95
+ - Updated 7 scaffolding templates with `accessPair()` pattern
96
+ - All code examples use new AccessRule API
97
+
98
+ ## Migration Guide
99
+
100
+ ### Backend Plugins
101
+
102
+ ```diff
103
+ - import { permissionList } from "./permissions";
104
+ - env.registerPermissions(permissionList);
105
+ + import { accessRules } from "./access";
106
+ + env.registerAccessRules(accessRules);
107
+ ```
108
+
109
+ ### RPC Contracts
110
+
111
+ ```diff
112
+ - .meta({ userType: "user", permissions: [permissions.read.id] })
113
+ + .meta({ userType: "user", access: [access.read] })
114
+ ```
115
+
116
+ ### Frontend Hooks
117
+
118
+ ```diff
119
+ - const canRead = accessApi.usePermission(permissions.read.id);
120
+ + const canRead = accessApi.useAccess(access.read);
121
+ ```
122
+
123
+ ### Routes
124
+
125
+ ```diff
126
+ - permission: permissions.entityRead.id,
127
+ + accessRule: access.read,
128
+ ```
129
+
130
+ ### Patch Changes
131
+
132
+ - Updated dependencies [9faec1f]
133
+ - Updated dependencies [f533141]
134
+ - @checkstack/common@0.2.0
135
+
3
136
  ## 0.0.4
4
137
 
5
138
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checkstack/frontend-api",
3
- "version": "0.0.4",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "main": "./src/index.ts",
6
6
  "scripts": {
@@ -13,7 +13,10 @@
13
13
  },
14
14
  "dependencies": {
15
15
  "@checkstack/common": "workspace:*",
16
- "@orpc/client": "^1.13.2"
16
+ "@orpc/client": "^1.13.2",
17
+ "@orpc/react-query": "1.13.4",
18
+ "@orpc/tanstack-query": "^1.13.2",
19
+ "@tanstack/react-query": "^5.64.0"
17
20
  },
18
21
  "devDependencies": {
19
22
  "@types/bun": "^1.3.5",
package/src/core-apis.ts CHANGED
@@ -1,8 +1,4 @@
1
- import {
2
- PermissionAction,
3
- ClientDefinition,
4
- InferClient,
5
- } from "@checkstack/common";
1
+ import { AccessRule, ClientDefinition, InferClient } from "@checkstack/common";
6
2
  import { createApiRef } from "./api-ref";
7
3
 
8
4
  export interface LoggerApi {
@@ -22,16 +18,30 @@ export interface FetchApi {
22
18
  export const loggerApiRef = createApiRef<LoggerApi>("core.logger");
23
19
  export const fetchApiRef = createApiRef<FetchApi>("core.fetch");
24
20
 
25
- export interface PermissionApi {
26
- usePermission(permission: string): { loading: boolean; allowed: boolean };
27
- useResourcePermission(
28
- resource: string,
29
- action: PermissionAction
30
- ): { loading: boolean; allowed: boolean };
31
- useManagePermission(resource: string): { loading: boolean; allowed: boolean };
21
+ /**
22
+ * Unified access API for checking user access via AccessRules.
23
+ *
24
+ * Uses the same AccessRule objects from plugin common packages
25
+ * that are used in backend contracts.
26
+ */
27
+ export interface AccessApi {
28
+ /**
29
+ * Check if the current user has access based on an AccessRule.
30
+ *
31
+ * @example
32
+ * ```tsx
33
+ * import { catalogAccess } from "@checkstack/catalog-common";
34
+ *
35
+ * const { allowed, loading } = accessApi.useAccess(catalogAccess.system.manage);
36
+ * if (allowed) {
37
+ * // User can manage systems
38
+ * }
39
+ * ```
40
+ */
41
+ useAccess(accessRule: AccessRule): { loading: boolean; allowed: boolean };
32
42
  }
33
43
 
34
- export const permissionApiRef = createApiRef<PermissionApi>("core.permission");
44
+ export const accessApiRef = createApiRef<AccessApi>("core.access");
35
45
 
36
46
  export interface RpcApi {
37
47
  client: unknown;
package/src/index.ts CHANGED
@@ -8,3 +8,4 @@ export * from "./utils";
8
8
  export * from "./slots";
9
9
  export * from "./use-plugin-route";
10
10
  export * from "./runtime-config";
11
+ export * from "./orpc-query";
@@ -0,0 +1,341 @@
1
+ import { createContext, useContext, useMemo, type ReactNode } from "react";
2
+ import {
3
+ createRouterUtils,
4
+ type RouterUtils,
5
+ type ProcedureUtils,
6
+ } from "@orpc/react-query";
7
+ import type { NestedClient, ClientContext } from "@orpc/client";
8
+ import {
9
+ useQuery,
10
+ useMutation,
11
+ type UseQueryResult,
12
+ type UseMutationResult,
13
+ type UseQueryOptions,
14
+ type UseMutationOptions,
15
+ } from "@tanstack/react-query";
16
+ import { useApi } from "./api-context";
17
+ import { rpcApiRef } from "./core-apis";
18
+ import type { ClientDefinition, InferClient } from "@checkstack/common";
19
+ import type { ContractProcedure, AnyContractRouter } from "@orpc/contract";
20
+
21
+ // =============================================================================
22
+ // TYPES
23
+ // =============================================================================
24
+
25
+ type OrpcUtils = RouterUtils<NestedClient<ClientContext>>;
26
+
27
+ // =============================================================================
28
+ // CONTEXT
29
+ // =============================================================================
30
+
31
+ const OrpcQueryContext = createContext<OrpcUtils | undefined>(undefined);
32
+
33
+ // =============================================================================
34
+ // PROVIDER
35
+ // =============================================================================
36
+
37
+ interface OrpcQueryProviderProps {
38
+ children: ReactNode;
39
+ }
40
+
41
+ /**
42
+ * Provides oRPC React Query utilities to the application.
43
+ * Must be inside ApiProvider and QueryClientProvider.
44
+ */
45
+ export const OrpcQueryProvider: React.FC<OrpcQueryProviderProps> = ({
46
+ children,
47
+ }) => {
48
+ const rpcApi = useApi(rpcApiRef);
49
+
50
+ const orpcUtils = useMemo(() => {
51
+ return createRouterUtils(rpcApi.client as NestedClient<ClientContext>);
52
+ }, [rpcApi.client]);
53
+
54
+ return (
55
+ <OrpcQueryContext.Provider value={orpcUtils}>
56
+ {children}
57
+ </OrpcQueryContext.Provider>
58
+ );
59
+ };
60
+
61
+ // =============================================================================
62
+ // INTERNAL
63
+ // =============================================================================
64
+
65
+ function useOrpcUtils(): OrpcUtils {
66
+ const context = useContext(OrpcQueryContext);
67
+ if (!context) {
68
+ throw new Error(
69
+ "usePluginClient must be used within OrpcQueryProvider. " +
70
+ "Wrap your app with <OrpcQueryProvider>."
71
+ );
72
+ }
73
+ return context;
74
+ }
75
+
76
+ // =============================================================================
77
+ // TYPE HELPERS FOR STRICT operationType INFERENCE
78
+ // =============================================================================
79
+
80
+ /**
81
+ * Query procedure hook interface - only exposes useQuery.
82
+ * Input is optional when the procedure has no input schema.
83
+ */
84
+ interface QueryProcedure<TInput, TOutput> {
85
+ useQuery: (
86
+ input?: TInput,
87
+ options?: Omit<UseQueryOptions<TOutput, Error>, "queryKey" | "queryFn">
88
+ ) => UseQueryResult<TOutput, Error>;
89
+ }
90
+
91
+ /**
92
+ * Mutation procedure hook interface - only exposes useMutation.
93
+ * Mutations don't take input directly - it's passed to mutate/mutateAsync.
94
+ */
95
+ interface MutationProcedure<TInput, TOutput> {
96
+ useMutation: (
97
+ options?: Omit<
98
+ UseMutationOptions<TOutput, Error, TInput>,
99
+ "mutationFn" | "mutationKey"
100
+ >
101
+ ) => UseMutationResult<TOutput, Error, TInput>;
102
+ }
103
+
104
+ /**
105
+ * Maps a contract procedure to the appropriate hook type based on operationType.
106
+ * Extracts input/output types from ContractProcedure's schema types.
107
+ */
108
+ type WrappedProcedure<TContractProcedure, _TClientProcedure> =
109
+ TContractProcedure extends ContractProcedure<
110
+ infer TInputSchema,
111
+ infer TOutputSchema,
112
+ infer _TErrors,
113
+ infer TMeta
114
+ >
115
+ ? TMeta extends { operationType: "mutation" }
116
+ ? MutationProcedure<
117
+ InferSchemaInputType<TInputSchema>,
118
+ InferSchemaOutputType<TOutputSchema>
119
+ >
120
+ : QueryProcedure<
121
+ InferSchemaInputType<TInputSchema>,
122
+ InferSchemaOutputType<TOutputSchema>
123
+ >
124
+ : never;
125
+
126
+ /**
127
+ * Extract input type from Zod schema.
128
+ * Zod schemas have { _input: T } for input inference.
129
+ * Returns empty object when no input schema is defined (unknown input),
130
+ * allowing useQuery({}) calls for parameterless procedures.
131
+ */
132
+ type InferSchemaInputType<T> = T extends { _input: infer I }
133
+ ? unknown extends I
134
+ ? Record<string, never>
135
+ : I
136
+ : Record<string, never>;
137
+
138
+ /**
139
+ * Extract output type from Zod schema.
140
+ * Zod schemas have { _output: T } for output inference.
141
+ */
142
+ type InferSchemaOutputType<T> = T extends { _output: infer O } ? O : unknown;
143
+
144
+ /**
145
+ * Check if a contract type is a procedure (not a nested router).
146
+ */
147
+ type IsContractProcedure<T> = T extends ContractProcedure<
148
+ infer _TInput,
149
+ infer _TOutput,
150
+ infer _TErrors,
151
+ infer _TMeta
152
+ >
153
+ ? true
154
+ : false;
155
+
156
+ /**
157
+ * Maps a contract router to wrapped procedures based on operationType.
158
+ * Recursively handles nested routers.
159
+ */
160
+ type WrappedClient<TContract extends AnyContractRouter, TClient> = {
161
+ [K in keyof TClient & keyof TContract]: IsContractProcedure<
162
+ TContract[K]
163
+ > extends true
164
+ ? WrappedProcedure<TContract[K], TClient[K]>
165
+ : TClient[K] extends object
166
+ ? TContract[K] extends AnyContractRouter
167
+ ? WrappedClient<TContract[K], TClient[K]>
168
+ : never
169
+ : never;
170
+ };
171
+
172
+ // =============================================================================
173
+ // HOOK: usePluginClient
174
+ // =============================================================================
175
+
176
+ /**
177
+ * Access a plugin's RPC client with TanStack Query integration.
178
+ *
179
+ * Each procedure exposes only the appropriate hook based on its operationType:
180
+ * - `operationType: "query"` → `.useQuery(input, options)`
181
+ * - `operationType: "mutation"` → `.useMutation(options)`
182
+ *
183
+ * @example
184
+ * ```tsx
185
+ * const catalog = usePluginClient(CatalogApi);
186
+ *
187
+ * // Queries (only useQuery available)
188
+ * const { data, isLoading } = catalog.getEntities.useQuery({});
189
+ *
190
+ * // Mutations (only useMutation available)
191
+ * const deleteMutation = catalog.deleteSystem.useMutation({
192
+ * onSuccess: () => toast.success("Deleted!"),
193
+ * });
194
+ *
195
+ * const handleDelete = () => {
196
+ * deleteMutation.mutate({ systemId });
197
+ * };
198
+ * ```
199
+ */
200
+ export function usePluginClient<T extends ClientDefinition>(
201
+ definition: T
202
+ ): WrappedClient<NonNullable<T["__contractType"]>, InferClient<T>> {
203
+ const orpcUtils = useOrpcUtils();
204
+
205
+ const pluginUtils = (orpcUtils as Record<string, unknown>)[
206
+ definition.pluginId
207
+ ] as Record<string, unknown> | undefined;
208
+
209
+ if (!pluginUtils) {
210
+ throw new Error(
211
+ `Plugin "${definition.pluginId}" not found. ` +
212
+ `Ensure the plugin is registered and the backend is running.`
213
+ );
214
+ }
215
+
216
+ // Get contract for operationType checking
217
+ const contract = definition.contract as Record<string, unknown>;
218
+
219
+ return useMemo(() => {
220
+ return wrapPluginUtils(pluginUtils, contract);
221
+ }, [pluginUtils, contract]) as WrappedClient<
222
+ NonNullable<T["__contractType"]>,
223
+ InferClient<T>
224
+ >;
225
+ }
226
+
227
+ // =============================================================================
228
+ // WRAPPER IMPLEMENTATION
229
+ // =============================================================================
230
+
231
+ function wrapPluginUtils(
232
+ utils: Record<string, unknown>,
233
+ contract: Record<string, unknown>
234
+ ): Record<string, unknown> {
235
+ const wrapped: Record<string, unknown> = {};
236
+
237
+ // Iterate over CONTRACT keys (procedure names like "getTheme", "getSystems")
238
+ // not the internal oRPC utility methods ("key", "call", "queryOptions" etc.)
239
+ for (const key of Object.keys(contract)) {
240
+ // Skip oRPC internal metadata keys
241
+ if (key.startsWith("~")) continue;
242
+
243
+ const procedureUtils = utils[key] as
244
+ | ProcedureUtils<ClientContext, unknown, unknown, Error>
245
+ | Record<string, unknown>
246
+ | undefined;
247
+
248
+ const contractProcedure = contract[key] as
249
+ | Record<string, unknown>
250
+ | undefined;
251
+
252
+ if (!procedureUtils || typeof procedureUtils !== "object") {
253
+ // Procedure might not be available in utils
254
+ continue;
255
+ }
256
+
257
+ // Check if this is a procedure (has queryOptions or mutationOptions method)
258
+ if (
259
+ typeof (
260
+ procedureUtils as ProcedureUtils<ClientContext, unknown, unknown, Error>
261
+ ).queryOptions === "function" ||
262
+ typeof (
263
+ procedureUtils as ProcedureUtils<ClientContext, unknown, unknown, Error>
264
+ ).mutationOptions === "function"
265
+ ) {
266
+ // Get operationType from contract metadata
267
+ const operationType = getOperationType(contractProcedure, key);
268
+ wrapped[key] = createProcedureHook(
269
+ procedureUtils as ProcedureUtils<
270
+ ClientContext,
271
+ unknown,
272
+ unknown,
273
+ Error
274
+ >,
275
+ operationType
276
+ );
277
+ } else {
278
+ // Nested namespace - recurse
279
+ wrapped[key] = wrapPluginUtils(
280
+ procedureUtils as Record<string, unknown>,
281
+ (contractProcedure || {}) as Record<string, unknown>
282
+ );
283
+ }
284
+ }
285
+
286
+ return wrapped;
287
+ }
288
+
289
+ /**
290
+ * Extract operationType from contract procedure metadata.
291
+ * Throws if operationType is not defined (required in all contracts).
292
+ */
293
+ function getOperationType(
294
+ contractProcedure: Record<string, unknown> | undefined,
295
+ procedureName?: string
296
+ ): "query" | "mutation" {
297
+ const orpcMeta = contractProcedure?.["~orpc"] as
298
+ | { meta?: { operationType?: "query" | "mutation" } }
299
+ | undefined;
300
+
301
+ const operationType = orpcMeta?.meta?.operationType;
302
+
303
+ if (!operationType) {
304
+ throw new Error(
305
+ `Procedure ${
306
+ procedureName ? `"${procedureName}" ` : ""
307
+ }is missing required "operationType" in contract metadata. ` +
308
+ `Add operationType: "query" or operationType: "mutation" to the procedure's .meta() call.`
309
+ );
310
+ }
311
+
312
+ return operationType;
313
+ }
314
+
315
+ /**
316
+ * Creates the appropriate hook wrapper based on operationType.
317
+ */
318
+ function createProcedureHook<TInput, TOutput>(
319
+ proc: ProcedureUtils<ClientContext, TInput, TOutput, Error>,
320
+ operationType: "query" | "mutation"
321
+ ): QueryProcedure<TInput, TOutput> | MutationProcedure<TInput, TOutput> {
322
+ if (operationType === "mutation") {
323
+ return {
324
+ useMutation: (options) => {
325
+ const mutationOpts = proc.mutationOptions(options);
326
+ return useMutation(mutationOpts);
327
+ },
328
+ };
329
+ }
330
+
331
+ return {
332
+ useQuery: (input, options) => {
333
+ // Get base query options from oRPC
334
+ const queryOpts = proc.queryOptions({
335
+ input: input as TInput,
336
+ });
337
+ // Spread caller options AFTER to ensure they take precedence (e.g., enabled: false)
338
+ return useQuery({ ...queryOpts, ...options });
339
+ },
340
+ };
341
+ }
@@ -14,7 +14,7 @@ interface ResolvedRoute {
14
14
  pluginId: string;
15
15
  element?: React.ReactNode;
16
16
  title?: string;
17
- permission?: string;
17
+ accessRule?: string;
18
18
  }
19
19
 
20
20
  class PluginRegistry {
@@ -61,7 +61,7 @@ class PluginRegistry {
61
61
  pluginId: route.route.pluginId,
62
62
  element: route.element,
63
63
  title: route.title,
64
- permission: route.permission?.id,
64
+ accessRule: route.accessRule?.id,
65
65
  };
66
66
 
67
67
  // Add to route map for resolution
@@ -175,7 +175,7 @@ class PluginRegistry {
175
175
  path: fullPath,
176
176
  element: route.element,
177
177
  title: route.title,
178
- permission: route.permission?.id,
178
+ accessRule: route.accessRule?.id,
179
179
  };
180
180
  });
181
181
  });
package/src/plugin.ts CHANGED
@@ -4,7 +4,7 @@ import type { SlotDefinition } from "./slots";
4
4
  import type {
5
5
  RouteDefinition,
6
6
  PluginMetadata,
7
- Permission,
7
+ AccessRule,
8
8
  } from "@checkstack/common";
9
9
 
10
10
  /**
@@ -51,8 +51,8 @@ export interface PluginRoute {
51
51
  /** Page title */
52
52
  title?: string;
53
53
 
54
- /** Permission required to access this route (use permission object from common package) */
55
- permission?: Permission;
54
+ /** Access rule required to access this route (use access object from common package) */
55
+ accessRule?: AccessRule;
56
56
  }
57
57
 
58
58
  /**
@@ -15,6 +15,18 @@ interface RuntimeConfigContextValue {
15
15
  error: Error | undefined;
16
16
  }
17
17
 
18
+ // Module-level cache for synchronous access from non-React code
19
+ let cachedConfig: RuntimeConfig | undefined;
20
+
21
+ /**
22
+ * Get the cached runtime config synchronously.
23
+ * Returns undefined if config hasn't been loaded yet.
24
+ * Use this for class-based APIs that can't use hooks.
25
+ */
26
+ export function getCachedRuntimeConfig(): RuntimeConfig | undefined {
27
+ return cachedConfig;
28
+ }
29
+
18
30
  const RuntimeConfigContext = createContext<RuntimeConfigContextValue>({
19
31
  config: undefined,
20
32
  isLoading: true,
@@ -50,11 +62,14 @@ export const RuntimeConfigProvider: React.FC<RuntimeConfigProviderProps> = ({
50
62
  throw new Error(`Failed to fetch config: ${response.status}`);
51
63
  }
52
64
  const data = (await response.json()) as RuntimeConfig;
65
+ cachedConfig = data; // Populate module-level cache
53
66
  setConfig(data);
54
67
  } catch (error_) {
55
68
  console.error("RuntimeConfigProvider: Failed to load config", error_);
56
69
  // Fallback to localhost for development
57
- setConfig({ baseUrl: "http://localhost:3000" });
70
+ const fallback = { baseUrl: "http://localhost:3000" };
71
+ cachedConfig = fallback; // Populate cache even on error
72
+ setConfig(fallback);
58
73
  setError(error_ instanceof Error ? error_ : new Error(String(error_)));
59
74
  } finally {
60
75
  setIsLoading(false);
package/src/slots.ts CHANGED
@@ -44,10 +44,10 @@ export const NavbarRightSlot = createSlot("core.layout.navbar.right");
44
44
 
45
45
  /**
46
46
  * Context for user menu item slots.
47
- * Provides the user's permissions array and authentication info for synchronous checks.
47
+ * Provides the user's access rules array and authentication info for synchronous checks.
48
48
  */
49
49
  export interface UserMenuItemsContext {
50
- permissions: string[];
50
+ accessRules: string[];
51
51
  hasCredentialAccount: boolean;
52
52
  }
53
53