@zjazj/web 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @zjazj/web
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Browser runtime for platform apps: session, typed API client, layout shell, guards and hooks.
4
+
5
+ ```tsx
6
+ import { createApp } from '@zjazj/web'
7
+ import { routeTree } from './routeTree.gen'
8
+
9
+ createApp({ routeTree }).mount('#root')
10
+ ```
11
+
12
+ ```ts
13
+ import { createClient } from '@zjazj/web'
14
+ import type { AppType } from '../service/server'
15
+
16
+ export const api = createClient<AppType>()
17
+ ```
18
+
19
+ ## Sign-in
20
+
21
+ An app writes no sign-in code and serves no sign-in address. With `ENV=dev` the page runs
22
+ with the local dev identity. Otherwise `createApp` signs in at the platform's identity
23
+ provider, a Logto that serves two addresses on the platform's own origin:
24
+
25
+ 1. The settings come from `/auth/config`: the identity provider's address and the one
26
+ client id every app on the origin shares.
27
+ 2. A visitor who is not signed in is sent to the identity provider. The redirect address is
28
+ always `<origin>/auth/callback`.
29
+ 3. That page completes the sign-in and returns to the address the visitor came from. Tokens
30
+ are in browser storage, so every app on the origin is signed in at once.
31
+ 4. API calls carry the organization token of the current tenant, replaced before it expires.
32
+
33
+ A route with `staticData: { public: true }` opens without a user.
34
+
35
+ At an address where nothing serves `/auth/config`, the page says that sign-in is not set
36
+ up.
37
+
38
+ Part of [platform-cli](https://github.com/zjazj/platform-cli). All `@zjazj/*` packages share one version. Install them at the same version.
@@ -0,0 +1,345 @@
1
+ import * as react from 'react';
2
+ import { ComponentType, ReactNode } from 'react';
3
+ import { QueryClient } from '@tanstack/react-query';
4
+ import { AnyRoute, Router } from '@tanstack/react-router';
5
+ import { Catalog } from '@zjazj/i18n';
6
+ import { Root } from 'react-dom/client';
7
+ import { Hono } from 'hono';
8
+ import { hc } from 'hono/client';
9
+
10
+ /** Sidebar entry of a route. Declare it in the route's `staticData.menu`. */
11
+ interface MenuMeta {
12
+ /** A translation key, or plain text when no translation exists. */
13
+ label: string;
14
+ /** An icon component, for example one imported from `lucide-react`. */
15
+ icon?: ComponentType<{
16
+ className?: string;
17
+ }>;
18
+ /** Lower numbers come first. Defaults to 100. */
19
+ order?: number;
20
+ /** Heading the entry is listed under. A translation key or plain text. */
21
+ group?: string;
22
+ }
23
+ /** What the platform reads from a route's `staticData`. */
24
+ interface RouteMeta {
25
+ menu?: MenuMeta;
26
+ /** Permission needed to open the route. Several codes are all required. */
27
+ permission?: string | string[];
28
+ /** `none` renders the route without the sidebar and header. */
29
+ layout?: 'app' | 'none';
30
+ /**
31
+ * `true` opens the route with nobody signed in. Without a user it renders bare, and no
32
+ * sign-in is started. Every other route requires a signed-in user.
33
+ */
34
+ public?: boolean;
35
+ }
36
+ interface MenuItem extends MenuMeta {
37
+ to: string;
38
+ order: number;
39
+ }
40
+ interface MenuGroup {
41
+ label?: string;
42
+ items: MenuItem[];
43
+ }
44
+ interface RouteLike {
45
+ fullPath?: string;
46
+ options?: {
47
+ staticData?: RouteMeta;
48
+ };
49
+ }
50
+ /**
51
+ * Build the sidebar from the routes: every route with `staticData.menu` whose permission
52
+ * the user holds, sorted by `order` then label, grouped by `group`. Routes with path
53
+ * parameters cannot be linked to and are skipped.
54
+ */
55
+ declare function buildMenu(routes: Iterable<RouteLike>, permissions: readonly string[]): MenuGroup[];
56
+
57
+ declare module '@tanstack/react-router' {
58
+ interface StaticDataRouteOption extends RouteMeta {
59
+ }
60
+ }
61
+
62
+ /** The signed-in user as the browser sees it. Mirrors the server's `AuthUser`. */
63
+ interface CurrentUser {
64
+ id: string;
65
+ tenantId: string;
66
+ tenantSlug: string;
67
+ username: string;
68
+ roles: string[];
69
+ permissions: string[];
70
+ timeZone?: string;
71
+ isDev?: boolean;
72
+ }
73
+ /** Where the session stands. The shell picks its screen from `state`. */
74
+ interface SessionStatus {
75
+ /**
76
+ * - `loading`: the stored sign-in is being read.
77
+ * - `ready`: a user is signed in.
78
+ * - `signed-out`: nobody is signed in. A page that needs a user starts the sign-in.
79
+ * - `ended`: the user was signed in on this page and no longer is.
80
+ * - `error`: sign-in cannot work here. `code` says why.
81
+ */
82
+ state: 'loading' | 'ready' | 'signed-out' | 'ended' | 'error';
83
+ /** With `error`: `not_configured`, `no_organization`, `no_tenant` or `sign_in_failed`. */
84
+ code?: string;
85
+ message?: string;
86
+ }
87
+ interface Session {
88
+ /** `dev` for the local dev identity, `platform` for sign-in at the identity provider. */
89
+ readonly kind: string;
90
+ getUser(): CurrentUser | null;
91
+ /** The same object until the state changes, so it can back `useSyncExternalStore`. */
92
+ getStatus(): SessionStatus;
93
+ /** The bearer token for API calls, refreshed when needed. */
94
+ getAccessToken(): Promise<string | null>;
95
+ /** Send the browser to the sign-in page. It comes back to the current location. */
96
+ signIn(): Promise<void>;
97
+ signOut(): Promise<void>;
98
+ /** Called whenever the user or the status changes. Returns the unsubscribe function. */
99
+ subscribe(listener: () => void): () => void;
100
+ }
101
+ interface DevSession extends Session {
102
+ kind: 'dev';
103
+ /** Replace parts of the dev user, for example the tenant or the permissions. */
104
+ setUser(patch: Partial<CurrentUser>): void;
105
+ /** Go back to the identity the dev server provided. */
106
+ reset(): void;
107
+ }
108
+ /** The unsigned token the dev server accepts while `ENV=dev`. */
109
+ declare function encodeDevToken(user: CurrentUser): string;
110
+ /** The session used in local development. No request to the identity provider is made. */
111
+ declare function createDevSession(base: CurrentUser): DevSession;
112
+ /**
113
+ * The session of this page. Created on first use: the dev identity when the dev server
114
+ * provided one, sign-in at the platform's identity provider otherwise.
115
+ */
116
+ declare function getSession(): Session;
117
+ /** Replace the session. Meant for tests and for custom sign-in implementations. */
118
+ declare function setSession(session: Session | undefined): void;
119
+
120
+ /**
121
+ * What the app knows about itself at runtime. `@zjazj/vite-plugin` writes it into the page
122
+ * as `window.__PLATFORM__`.
123
+ */
124
+ interface PlatformConfig {
125
+ /** `name` from package.json. */
126
+ name: string;
127
+ /** `id` from package.json. */
128
+ id: string;
129
+ /** Display name. */
130
+ title: string;
131
+ version?: string;
132
+ /** Mount prefix with a trailing slash: `/apps/<name>/` when deployed, `/` in development. */
133
+ basePath: string;
134
+ /** Where the portal's Apps page lives. */
135
+ portalUrl: string;
136
+ /** Present only in local development with the dev identity enabled. */
137
+ dev?: {
138
+ user: CurrentUser;
139
+ };
140
+ }
141
+ declare global {
142
+ interface Window {
143
+ __PLATFORM__?: Partial<PlatformConfig>;
144
+ }
145
+ }
146
+ declare function getPlatformConfig(): PlatformConfig;
147
+ /** Absolute URL of the app's API root, for example `https://host/apps/demo/api`. */
148
+ declare function apiBaseUrl(config?: PlatformConfig): string;
149
+
150
+ /** What `createApp` returns. Register `router` with TanStack Router for typed links. */
151
+ interface WebApp<TRouteTree extends AnyRoute> {
152
+ config: PlatformConfig;
153
+ session: Session;
154
+ queryClient: QueryClient;
155
+ router: Router<TRouteTree, 'never', false>;
156
+ /** Render the app into an element or the first element matching a selector. */
157
+ mount(target: string | Element): Root;
158
+ }
159
+ interface CreateAppOptions<TRouteTree extends AnyRoute> {
160
+ /** The generated route tree: `import { routeTree } from './routeTree.gen'`. */
161
+ routeTree: TRouteTree;
162
+ /** The app's own messages, registered under the `app` namespace. */
163
+ messages?: Catalog;
164
+ queryClient?: QueryClient;
165
+ }
166
+ /**
167
+ * Create the browser app: translations, session, data cache and router. Call `mount` with
168
+ * the element or selector to render into.
169
+ *
170
+ * const app = createApp({ routeTree, messages })
171
+ * app.mount('#root')
172
+ */
173
+ declare function createApp<TRouteTree extends AnyRoute>(options: CreateAppOptions<TRouteTree>): WebApp<TRouteTree>;
174
+
175
+ /** The sign-in settings every app on the origin reads. */
176
+ declare const AUTH_CONFIG_PATH = "/auth/config";
177
+ /**
178
+ * The one redirect address registered with the identity provider. Its page completes the
179
+ * sign-in and returns to the address stored under `RETURN_TO_KEY`.
180
+ */
181
+ declare const AUTH_CALLBACK_PATH = "/auth/callback";
182
+ /**
183
+ * Session storage key of the address to return to after sign-in: a path on this origin. The
184
+ * callback page reads it, so the name is a contract with the identity provider's page.
185
+ */
186
+ declare const RETURN_TO_KEY = "platform.auth.returnTo";
187
+ /** What `/auth/config` answers. */
188
+ interface AuthConfig {
189
+ /** Address of the identity provider, for example `https://auth.example.com`. */
190
+ endpoint: string;
191
+ /** The one client id that every app on the origin shares. */
192
+ appId: string;
193
+ /** API resource indicator, when the platform has one. */
194
+ resource?: string;
195
+ }
196
+ /** The claims of the identity token that the session reads. */
197
+ interface IdentityClaims {
198
+ organizations?: string[] | null;
199
+ username?: string | null;
200
+ name?: string | null;
201
+ email?: string | null;
202
+ }
203
+ /** The part of the Logto browser client that the session uses. Tests pass a stand-in. */
204
+ interface IdentityClient {
205
+ isAuthenticated(): Promise<boolean>;
206
+ signIn(redirectUri: string): Promise<void>;
207
+ getIdTokenClaims(): Promise<IdentityClaims>;
208
+ getOrganizationToken(organizationId: string): Promise<string>;
209
+ clearAccessToken(): Promise<void>;
210
+ signOut(postLogoutRedirectUri?: string): Promise<void>;
211
+ }
212
+ interface PlatformSessionOptions {
213
+ /** Reads the sign-in settings. Defaults to `GET /auth/config`. */
214
+ loadConfig?: () => Promise<AuthConfig>;
215
+ /** Builds the identity client. Defaults to the Logto browser client. */
216
+ createClient?: (config: AuthConfig) => IdentityClient | Promise<IdentityClient>;
217
+ /** The clock, in milliseconds. */
218
+ now?: () => number;
219
+ }
220
+ /**
221
+ * The session of a deployed app. It reads the sign-in settings, restores a sign-in that any
222
+ * app on the origin completed, and keeps the organization token of the current tenant
223
+ * fresh. With nobody signed in, `signIn()` goes to the identity provider. Its callback page
224
+ * completes the sign-in and comes back to the page that started it.
225
+ */
226
+ declare function createPlatformSession(options?: PlatformSessionOptions): Session;
227
+
228
+ interface ErrorFields {
229
+ status: number;
230
+ code: string;
231
+ message: string;
232
+ traceId?: string;
233
+ field?: string;
234
+ }
235
+ /** A failed API call. `code` is the machine-readable reason, `traceId` identifies the request. */
236
+ declare class ApiError extends Error {
237
+ readonly status: number;
238
+ readonly code: string;
239
+ readonly traceId?: string;
240
+ readonly field?: string;
241
+ constructor(fields: ErrorFields);
242
+ /** Build the error from a response. Accepts the flat body and the body nested in `detail`. */
243
+ static fromResponse(response: Response): Promise<ApiError>;
244
+ }
245
+ /**
246
+ * `fetch` for the app's own backend. It adds the bearer token and turns every response
247
+ * that is not 2xx into a thrown `ApiError`.
248
+ */
249
+ declare function platformFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
250
+ type AnyHono = Hono<any, any, any>;
251
+ /**
252
+ * A typed client for the app's backend. Pass the type exported by `service/server.ts`:
253
+ *
254
+ * export const api = createClient<AppType>()
255
+ * const items = await (await api.items.$get()).json()
256
+ */
257
+ declare function createClient<T extends AnyHono>(baseUrl?: string): ApiClient<T>;
258
+ /** The client `createClient` returns: one property per route, typed from the backend. */
259
+ type ApiClient<T extends AnyHono> = ReturnType<typeof hc<T>>;
260
+
261
+ interface PlatformContextValue {
262
+ config: PlatformConfig;
263
+ session: Session;
264
+ }
265
+ declare function PlatformProvider(props: PlatformContextValue & {
266
+ children: ReactNode;
267
+ }): react.JSX.Element;
268
+ /** Name, id, title and base path of this app. */
269
+ declare function useAppConfig(): PlatformConfig;
270
+ declare function useSession(): Session;
271
+ /** Where the session stands: loading, ready, signed out, ended or failed. */
272
+ declare function useSessionStatus(): SessionStatus;
273
+ /** The signed-in user, or null before sign-in. Re-renders when the user changes. */
274
+ declare function useOptionalUser(): CurrentUser | null;
275
+ /** The signed-in user. Use it inside the app shell, which renders only when signed in. */
276
+ declare function useUser(): CurrentUser;
277
+ interface Tenant {
278
+ id: string;
279
+ slug: string;
280
+ timeZone?: string;
281
+ }
282
+ declare function useTenant(): Tenant;
283
+ /**
284
+ * Whether the user holds every listed permission. This only decides what to show. The
285
+ * backend enforces the same permission on every route.
286
+ */
287
+ declare function useCan(...codes: string[]): boolean;
288
+ interface CanProps {
289
+ /** One permission code, or several that are all required. */
290
+ permission: string | string[];
291
+ children: ReactNode;
292
+ /** Rendered instead when the permission is missing. Defaults to nothing. */
293
+ fallback?: ReactNode;
294
+ }
295
+ /** Render children only when the user holds the permission. */
296
+ declare function Can({ permission, children, fallback }: CanProps): ReactNode;
297
+
298
+ /** Shown for an unknown path. It names the tenant, because a link may belong to another one. */
299
+ declare function NotFound(): react.JSX.Element;
300
+ /** Shown when the user lacks the permission of the route. */
301
+ declare function Forbidden(): react.JSX.Element;
302
+ /** Shown when a route throws. An API error also shows its trace id. */
303
+ declare function ErrorScreen({ error }: {
304
+ error: unknown;
305
+ }): react.JSX.Element;
306
+ /**
307
+ * The frame every page renders in: sidebar built from the routes, header with the link back
308
+ * to the Apps page and the account menu, and the route content. Use it as the component of
309
+ * the root route. A route with `staticData.layout: 'none'` renders without the frame.
310
+ */
311
+ declare function AppShell(): react.JSX.Element;
312
+
313
+ /**
314
+ * True when `code` is covered by the granted set: an exact match, a bare `*`, or a granted
315
+ * code whose trailing segments are wildcards, for example `inventory:item:*` or
316
+ * `inventory:*:*` for `inventory:item:read`.
317
+ */
318
+ declare function permissionMatches(granted: ReadonlySet<string>, code: string): boolean;
319
+ /** True when every required code is covered. An empty requirement is always satisfied. */
320
+ declare function hasPermissions(granted: Iterable<string>, required: readonly string[]): boolean;
321
+
322
+ /**
323
+ * The current tenant of this browser. One browser profile has one current tenant, and every
324
+ * tab of every app reads the same value. Only the portal changes it.
325
+ */
326
+ declare const TENANT_STORAGE_KEY = "platform.tenant";
327
+ /** What is stored: the tenant, and the organization its tokens are issued for. */
328
+ interface StoredTenant {
329
+ /** The identity provider's organization id. Tokens are requested for it. */
330
+ organizationId: string;
331
+ /** The tenant's UUID, as the organization token carries it. */
332
+ tenantId: string;
333
+ }
334
+ /** The stored current tenant, or undefined when none is stored or storage is closed. */
335
+ declare function readStoredTenant(): StoredTenant | undefined;
336
+ /**
337
+ * Remember the tenant this tab works in. A tab keeps its tenant for its whole life, so it
338
+ * can never show one tenant's data and write to another.
339
+ */
340
+ declare function pinTenant(tenantId: string): void;
341
+ declare function getPinnedTenant(): string | undefined;
342
+ /** True once another tab switched tenant. The tab must reload before it sends anything. */
343
+ declare function isTenantChanged(): boolean;
344
+
345
+ export { AUTH_CALLBACK_PATH, AUTH_CONFIG_PATH, type ApiClient, ApiError, AppShell, type AuthConfig, Can, type CanProps, type CreateAppOptions, type CurrentUser, type DevSession, ErrorScreen, Forbidden, type IdentityClaims, type IdentityClient, type MenuGroup, type MenuItem, type MenuMeta, NotFound, type PlatformConfig, PlatformProvider, type PlatformSessionOptions, RETURN_TO_KEY, type RouteMeta, type Session, type SessionStatus, type StoredTenant, TENANT_STORAGE_KEY, type Tenant, type WebApp, apiBaseUrl, buildMenu, createApp, createClient, createDevSession, createPlatformSession, encodeDevToken, getPinnedTenant, getPlatformConfig, getSession, hasPermissions, isTenantChanged, permissionMatches, pinTenant, platformFetch, readStoredTenant, setSession, useAppConfig, useCan, useOptionalUser, useSession, useSessionStatus, useTenant, useUser };