@zjazj/web 0.0.0-stage → 0.0.1
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 +20 -2
- package/dist/index.d.ts +256 -0
- package/dist/index.js +663 -0
- package/dist/styles.css +12 -0
- package/package.json +55 -3
package/README.md
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zjazj/web
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
In this version the browser runs with the local dev identity only. Sign-in through the portal arrives in a later version.
|
|
20
|
+
|
|
21
|
+
Part of [platform-cli](https://github.com/zjazj/platform-cli). All `@zjazj/*` packages share one version. Install them at the same version.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
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
|
+
interface MenuItem extends MenuMeta {
|
|
32
|
+
to: string;
|
|
33
|
+
order: number;
|
|
34
|
+
}
|
|
35
|
+
interface MenuGroup {
|
|
36
|
+
label?: string;
|
|
37
|
+
items: MenuItem[];
|
|
38
|
+
}
|
|
39
|
+
interface RouteLike {
|
|
40
|
+
fullPath?: string;
|
|
41
|
+
options?: {
|
|
42
|
+
staticData?: RouteMeta;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Build the sidebar from the routes: every route with `staticData.menu` whose permission
|
|
47
|
+
* the user holds, sorted by `order` then label, grouped by `group`. Routes with path
|
|
48
|
+
* parameters cannot be linked to and are skipped.
|
|
49
|
+
*/
|
|
50
|
+
declare function buildMenu(routes: Iterable<RouteLike>, permissions: readonly string[]): MenuGroup[];
|
|
51
|
+
|
|
52
|
+
declare module '@tanstack/react-router' {
|
|
53
|
+
interface StaticDataRouteOption extends RouteMeta {
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The signed-in user as the browser sees it. Mirrors the server's `AuthUser`. */
|
|
58
|
+
interface CurrentUser {
|
|
59
|
+
id: string;
|
|
60
|
+
tenantId: string;
|
|
61
|
+
tenantSlug: string;
|
|
62
|
+
username: string;
|
|
63
|
+
roles: string[];
|
|
64
|
+
permissions: string[];
|
|
65
|
+
timeZone?: string;
|
|
66
|
+
isDev?: boolean;
|
|
67
|
+
}
|
|
68
|
+
interface Session {
|
|
69
|
+
/** `dev` for the local dev identity, `none` when no sign-in is available. */
|
|
70
|
+
readonly kind: string;
|
|
71
|
+
getUser(): CurrentUser | null;
|
|
72
|
+
/** The bearer token for API calls, refreshed when needed. */
|
|
73
|
+
getAccessToken(): Promise<string | null>;
|
|
74
|
+
signIn(): Promise<void>;
|
|
75
|
+
signOut(): Promise<void>;
|
|
76
|
+
/** Called whenever the user changes. Returns the unsubscribe function. */
|
|
77
|
+
subscribe(listener: () => void): () => void;
|
|
78
|
+
}
|
|
79
|
+
interface DevSession extends Session {
|
|
80
|
+
kind: 'dev';
|
|
81
|
+
/** Replace parts of the dev user, for example the tenant or the permissions. */
|
|
82
|
+
setUser(patch: Partial<CurrentUser>): void;
|
|
83
|
+
/** Go back to the identity the dev server provided. */
|
|
84
|
+
reset(): void;
|
|
85
|
+
}
|
|
86
|
+
/** The unsigned token the dev server accepts while `ENV=dev`. */
|
|
87
|
+
declare function encodeDevToken(user: CurrentUser): string;
|
|
88
|
+
/** The session used in local development. No request to the identity provider is made. */
|
|
89
|
+
declare function createDevSession(base: CurrentUser): DevSession;
|
|
90
|
+
/** The session of this page. Created on first use from the injected configuration. */
|
|
91
|
+
declare function getSession(): Session;
|
|
92
|
+
/** Replace the session. Meant for tests and for custom sign-in implementations. */
|
|
93
|
+
declare function setSession(session: Session | undefined): void;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* What the app knows about itself at runtime. `@zjazj/vite-plugin` writes it into the page
|
|
97
|
+
* as `window.__PLATFORM__`.
|
|
98
|
+
*/
|
|
99
|
+
interface PlatformConfig {
|
|
100
|
+
/** `name` from package.json. */
|
|
101
|
+
name: string;
|
|
102
|
+
/** `id` from package.json. */
|
|
103
|
+
id: string;
|
|
104
|
+
/** Display name. */
|
|
105
|
+
title: string;
|
|
106
|
+
version?: string;
|
|
107
|
+
/** Mount prefix with a trailing slash: `/apps/<name>/` when deployed, `/` in development. */
|
|
108
|
+
basePath: string;
|
|
109
|
+
/** Where the portal's Apps page lives. */
|
|
110
|
+
portalUrl: string;
|
|
111
|
+
/** Present only in local development with the dev identity enabled. */
|
|
112
|
+
dev?: {
|
|
113
|
+
user: CurrentUser;
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
declare global {
|
|
117
|
+
interface Window {
|
|
118
|
+
__PLATFORM__?: Partial<PlatformConfig>;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
declare function getPlatformConfig(): PlatformConfig;
|
|
122
|
+
/** Absolute URL of the app's API root, for example `https://host/apps/demo/api`. */
|
|
123
|
+
declare function apiBaseUrl(config?: PlatformConfig): string;
|
|
124
|
+
|
|
125
|
+
/** What `createApp` returns. Register `router` with TanStack Router for typed links. */
|
|
126
|
+
interface WebApp<TRouteTree extends AnyRoute> {
|
|
127
|
+
config: PlatformConfig;
|
|
128
|
+
session: Session;
|
|
129
|
+
queryClient: QueryClient;
|
|
130
|
+
router: Router<TRouteTree, 'never', false>;
|
|
131
|
+
/** Render the app into an element or the first element matching a selector. */
|
|
132
|
+
mount(target: string | Element): Root;
|
|
133
|
+
}
|
|
134
|
+
interface CreateAppOptions<TRouteTree extends AnyRoute> {
|
|
135
|
+
/** The generated route tree: `import { routeTree } from './routeTree.gen'`. */
|
|
136
|
+
routeTree: TRouteTree;
|
|
137
|
+
/** The app's own messages, registered under the `app` namespace. */
|
|
138
|
+
messages?: Catalog;
|
|
139
|
+
queryClient?: QueryClient;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Create the browser app: translations, session, data cache and router. Call `mount` with
|
|
143
|
+
* the element or selector to render into.
|
|
144
|
+
*
|
|
145
|
+
* const app = createApp({ routeTree, messages })
|
|
146
|
+
* app.mount('#root')
|
|
147
|
+
*/
|
|
148
|
+
declare function createApp<TRouteTree extends AnyRoute>(options: CreateAppOptions<TRouteTree>): WebApp<TRouteTree>;
|
|
149
|
+
|
|
150
|
+
interface ErrorFields {
|
|
151
|
+
status: number;
|
|
152
|
+
code: string;
|
|
153
|
+
message: string;
|
|
154
|
+
traceId?: string;
|
|
155
|
+
field?: string;
|
|
156
|
+
}
|
|
157
|
+
/** A failed API call. `code` is the machine-readable reason, `traceId` identifies the request. */
|
|
158
|
+
declare class ApiError extends Error {
|
|
159
|
+
readonly status: number;
|
|
160
|
+
readonly code: string;
|
|
161
|
+
readonly traceId?: string;
|
|
162
|
+
readonly field?: string;
|
|
163
|
+
constructor(fields: ErrorFields);
|
|
164
|
+
/** Build the error from a response. Accepts the flat body and the body nested in `detail`. */
|
|
165
|
+
static fromResponse(response: Response): Promise<ApiError>;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* `fetch` for the app's own backend. It adds the bearer token and turns every response
|
|
169
|
+
* that is not 2xx into a thrown `ApiError`.
|
|
170
|
+
*/
|
|
171
|
+
declare function platformFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
|
|
172
|
+
type AnyHono = Hono<any, any, any>;
|
|
173
|
+
/**
|
|
174
|
+
* A typed client for the app's backend. Pass the type exported by `service/server.ts`:
|
|
175
|
+
*
|
|
176
|
+
* export const api = createClient<AppType>()
|
|
177
|
+
* const items = await (await api.items.$get()).json()
|
|
178
|
+
*/
|
|
179
|
+
declare function createClient<T extends AnyHono>(baseUrl?: string): ApiClient<T>;
|
|
180
|
+
/** The client `createClient` returns: one property per route, typed from the backend. */
|
|
181
|
+
type ApiClient<T extends AnyHono> = ReturnType<typeof hc<T>>;
|
|
182
|
+
|
|
183
|
+
interface PlatformContextValue {
|
|
184
|
+
config: PlatformConfig;
|
|
185
|
+
session: Session;
|
|
186
|
+
}
|
|
187
|
+
declare function PlatformProvider(props: PlatformContextValue & {
|
|
188
|
+
children: ReactNode;
|
|
189
|
+
}): react.JSX.Element;
|
|
190
|
+
/** Name, id, title and base path of this app. */
|
|
191
|
+
declare function useAppConfig(): PlatformConfig;
|
|
192
|
+
declare function useSession(): Session;
|
|
193
|
+
/** The signed-in user, or null before sign-in. Re-renders when the user changes. */
|
|
194
|
+
declare function useOptionalUser(): CurrentUser | null;
|
|
195
|
+
/** The signed-in user. Use it inside the app shell, which renders only when signed in. */
|
|
196
|
+
declare function useUser(): CurrentUser;
|
|
197
|
+
interface Tenant {
|
|
198
|
+
id: string;
|
|
199
|
+
slug: string;
|
|
200
|
+
timeZone?: string;
|
|
201
|
+
}
|
|
202
|
+
declare function useTenant(): Tenant;
|
|
203
|
+
/**
|
|
204
|
+
* Whether the user holds every listed permission. This only decides what to show. The
|
|
205
|
+
* backend enforces the same permission on every route.
|
|
206
|
+
*/
|
|
207
|
+
declare function useCan(...codes: string[]): boolean;
|
|
208
|
+
interface CanProps {
|
|
209
|
+
/** One permission code, or several that are all required. */
|
|
210
|
+
permission: string | string[];
|
|
211
|
+
children: ReactNode;
|
|
212
|
+
/** Rendered instead when the permission is missing. Defaults to nothing. */
|
|
213
|
+
fallback?: ReactNode;
|
|
214
|
+
}
|
|
215
|
+
/** Render children only when the user holds the permission. */
|
|
216
|
+
declare function Can({ permission, children, fallback }: CanProps): ReactNode;
|
|
217
|
+
|
|
218
|
+
/** Shown for an unknown path. It names the tenant, because a link may belong to another one. */
|
|
219
|
+
declare function NotFound(): react.JSX.Element;
|
|
220
|
+
/** Shown when the user lacks the permission of the route. */
|
|
221
|
+
declare function Forbidden(): react.JSX.Element;
|
|
222
|
+
/** Shown when a route throws. An API error also shows its trace id. */
|
|
223
|
+
declare function ErrorScreen({ error }: {
|
|
224
|
+
error: unknown;
|
|
225
|
+
}): react.JSX.Element;
|
|
226
|
+
/**
|
|
227
|
+
* The frame every page renders in: sidebar built from the routes, header with the link back
|
|
228
|
+
* to the Apps page and the account menu, and the route content. Use it as the component of
|
|
229
|
+
* the root route. A route with `staticData.layout: 'none'` renders without the frame.
|
|
230
|
+
*/
|
|
231
|
+
declare function AppShell(): react.JSX.Element;
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* True when `code` is covered by the granted set: an exact match, a bare `*`, or a granted
|
|
235
|
+
* code whose trailing segments are wildcards, for example `inventory:item:*` or
|
|
236
|
+
* `inventory:*:*` for `inventory:item:read`.
|
|
237
|
+
*/
|
|
238
|
+
declare function permissionMatches(granted: ReadonlySet<string>, code: string): boolean;
|
|
239
|
+
/** True when every required code is covered. An empty requirement is always satisfied. */
|
|
240
|
+
declare function hasPermissions(granted: Iterable<string>, required: readonly string[]): boolean;
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The current tenant of this browser, written by the portal. One browser profile has one
|
|
244
|
+
* current tenant, and every tab of every app reads the same value.
|
|
245
|
+
*/
|
|
246
|
+
declare const TENANT_STORAGE_KEY = "platform.tenant";
|
|
247
|
+
/**
|
|
248
|
+
* Remember the tenant this tab works in. A tab keeps its tenant for its whole life, so it
|
|
249
|
+
* can never show one tenant's data and write to another.
|
|
250
|
+
*/
|
|
251
|
+
declare function pinTenant(tenantId: string): void;
|
|
252
|
+
declare function getPinnedTenant(): string | undefined;
|
|
253
|
+
/** True once another tab switched tenant. The tab must reload before it sends anything. */
|
|
254
|
+
declare function isTenantChanged(): boolean;
|
|
255
|
+
|
|
256
|
+
export { type ApiClient, ApiError, AppShell, Can, type CanProps, type CreateAppOptions, type CurrentUser, type DevSession, ErrorScreen, Forbidden, type MenuGroup, type MenuItem, type MenuMeta, NotFound, type PlatformConfig, PlatformProvider, type RouteMeta, type Session, TENANT_STORAGE_KEY, type Tenant, type WebApp, apiBaseUrl, buildMenu, createApp, createClient, createDevSession, encodeDevToken, getPinnedTenant, getPlatformConfig, getSession, hasPermissions, isTenantChanged, permissionMatches, pinTenant, platformFetch, setSession, useAppConfig, useCan, useOptionalUser, useSession, useTenant, useUser };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { registerMessages as registerMessages2 } from "@zjazj/i18n";
|
|
3
|
+
|
|
4
|
+
// src/locales/en-US.json
|
|
5
|
+
var en_US_default = {
|
|
6
|
+
apps: "Apps",
|
|
7
|
+
account: "Account",
|
|
8
|
+
signOut: "Sign out",
|
|
9
|
+
theme: "Theme",
|
|
10
|
+
themeLight: "Light",
|
|
11
|
+
themeDark: "Dark",
|
|
12
|
+
themeSystem: "System",
|
|
13
|
+
language: "Language",
|
|
14
|
+
localeEnUS: "English",
|
|
15
|
+
localeZhCN: "\u7B80\u4F53\u4E2D\u6587",
|
|
16
|
+
tenant: "Tenant",
|
|
17
|
+
devIdentity: "Dev identity",
|
|
18
|
+
notFoundTitle: "Page not found",
|
|
19
|
+
notFoundBody: "This page does not exist in tenant {{tenant}}.",
|
|
20
|
+
forbiddenTitle: "No access",
|
|
21
|
+
forbiddenBody: "You do not have permission to open this page.",
|
|
22
|
+
tenantChangedTitle: "Tenant changed",
|
|
23
|
+
tenantChangedBody: "You switched tenant in another tab. Reload this page to continue.",
|
|
24
|
+
reload: "Reload",
|
|
25
|
+
backToApps: "Back to Apps",
|
|
26
|
+
signInRequiredTitle: "Sign-in is not available",
|
|
27
|
+
signInRequiredBody: "This version runs with the dev identity only. Start the app with ENV=dev.",
|
|
28
|
+
errorTitle: "Something went wrong",
|
|
29
|
+
traceId: "Trace id: {{id}}"
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// src/locales/zh-CN.json
|
|
33
|
+
var zh_CN_default = {
|
|
34
|
+
apps: "\u5E94\u7528",
|
|
35
|
+
account: "\u8D26\u53F7",
|
|
36
|
+
signOut: "\u9000\u51FA\u767B\u5F55",
|
|
37
|
+
theme: "\u4E3B\u9898",
|
|
38
|
+
themeLight: "\u6D45\u8272",
|
|
39
|
+
themeDark: "\u6DF1\u8272",
|
|
40
|
+
themeSystem: "\u8DDF\u968F\u7CFB\u7EDF",
|
|
41
|
+
language: "\u8BED\u8A00",
|
|
42
|
+
localeEnUS: "English",
|
|
43
|
+
localeZhCN: "\u7B80\u4F53\u4E2D\u6587",
|
|
44
|
+
tenant: "\u79DF\u6237",
|
|
45
|
+
devIdentity: "\u5F00\u53D1\u8EAB\u4EFD",
|
|
46
|
+
notFoundTitle: "\u9875\u9762\u4E0D\u5B58\u5728",
|
|
47
|
+
notFoundBody: "\u79DF\u6237 {{tenant}} \u4E0B\u6CA1\u6709\u8FD9\u4E2A\u9875\u9762\u3002",
|
|
48
|
+
forbiddenTitle: "\u65E0\u6743\u8BBF\u95EE",
|
|
49
|
+
forbiddenBody: "\u4F60\u6CA1\u6709\u6253\u5F00\u8FD9\u4E2A\u9875\u9762\u7684\u6743\u9650\u3002",
|
|
50
|
+
tenantChangedTitle: "\u79DF\u6237\u5DF2\u5207\u6362",
|
|
51
|
+
tenantChangedBody: "\u4F60\u5728\u53E6\u4E00\u4E2A\u6807\u7B7E\u9875\u5207\u6362\u4E86\u79DF\u6237\u3002\u8BF7\u5237\u65B0\u672C\u9875\u540E\u7EE7\u7EED\u3002",
|
|
52
|
+
reload: "\u5237\u65B0",
|
|
53
|
+
backToApps: "\u8FD4\u56DE\u5E94\u7528\u5217\u8868",
|
|
54
|
+
signInRequiredTitle: "\u6682\u4E0D\u652F\u6301\u767B\u5F55",
|
|
55
|
+
signInRequiredBody: "\u5F53\u524D\u7248\u672C\u53EA\u652F\u6301\u5F00\u53D1\u8EAB\u4EFD\u3002\u8BF7\u4EE5 ENV=dev \u542F\u52A8\u5E94\u7528\u3002",
|
|
56
|
+
errorTitle: "\u51FA\u9519\u4E86",
|
|
57
|
+
traceId: "\u8FFD\u8E2A\u53F7\uFF1A{{id}}"
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// src/app.tsx
|
|
61
|
+
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
62
|
+
import { createRouter, RouterProvider } from "@tanstack/react-router";
|
|
63
|
+
import { registerMessages, setTimeZone } from "@zjazj/i18n";
|
|
64
|
+
import { Toaster } from "@zjazj/ui";
|
|
65
|
+
import { StrictMode } from "react";
|
|
66
|
+
import { createRoot } from "react-dom/client";
|
|
67
|
+
|
|
68
|
+
// src/client.ts
|
|
69
|
+
import { hc } from "hono/client";
|
|
70
|
+
|
|
71
|
+
// src/config.ts
|
|
72
|
+
function withSlashes(path) {
|
|
73
|
+
const trimmed = (path ?? "/").replace(/^\/+|\/+$/g, "");
|
|
74
|
+
return trimmed ? `/${trimmed}/` : "/";
|
|
75
|
+
}
|
|
76
|
+
function getPlatformConfig() {
|
|
77
|
+
const raw = typeof window !== "undefined" && window.__PLATFORM__ || {};
|
|
78
|
+
const name = raw.name ?? "app";
|
|
79
|
+
return {
|
|
80
|
+
name,
|
|
81
|
+
id: raw.id ?? "",
|
|
82
|
+
title: raw.title ?? name,
|
|
83
|
+
version: raw.version,
|
|
84
|
+
basePath: withSlashes(raw.basePath),
|
|
85
|
+
portalUrl: raw.portalUrl ?? "/",
|
|
86
|
+
dev: raw.dev
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function apiBaseUrl(config = getPlatformConfig()) {
|
|
90
|
+
const origin = typeof window !== "undefined" ? window.location.origin : "http://localhost";
|
|
91
|
+
return `${origin}${config.basePath}api`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/session.ts
|
|
95
|
+
var DEV_USER_STORAGE_KEY = "platform.dev.user";
|
|
96
|
+
var DEV_TOKEN_PREFIX = "dev.";
|
|
97
|
+
function base64Url(value) {
|
|
98
|
+
const bytes = new TextEncoder().encode(value);
|
|
99
|
+
let binary = "";
|
|
100
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
101
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
102
|
+
}
|
|
103
|
+
function encodeDevToken(user) {
|
|
104
|
+
const { isDev: _isDev, ...payload } = user;
|
|
105
|
+
return DEV_TOKEN_PREFIX + base64Url(JSON.stringify(payload));
|
|
106
|
+
}
|
|
107
|
+
function readStoredPatch() {
|
|
108
|
+
try {
|
|
109
|
+
const stored = globalThis.localStorage?.getItem(DEV_USER_STORAGE_KEY);
|
|
110
|
+
const parsed = stored ? JSON.parse(stored) : null;
|
|
111
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
112
|
+
} catch {
|
|
113
|
+
return {};
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function createDevSession(base) {
|
|
117
|
+
const listeners2 = /* @__PURE__ */ new Set();
|
|
118
|
+
let patch = readStoredPatch();
|
|
119
|
+
let current = { ...base, ...patch, isDev: true };
|
|
120
|
+
const update = (next) => {
|
|
121
|
+
patch = next;
|
|
122
|
+
current = { ...base, ...patch, isDev: true };
|
|
123
|
+
try {
|
|
124
|
+
if (Object.keys(patch).length === 0) globalThis.localStorage?.removeItem(DEV_USER_STORAGE_KEY);
|
|
125
|
+
else globalThis.localStorage?.setItem(DEV_USER_STORAGE_KEY, JSON.stringify(patch));
|
|
126
|
+
} catch {
|
|
127
|
+
}
|
|
128
|
+
for (const listener of listeners2) listener();
|
|
129
|
+
};
|
|
130
|
+
return {
|
|
131
|
+
kind: "dev",
|
|
132
|
+
getUser: () => current,
|
|
133
|
+
getAccessToken: async () => encodeDevToken(current),
|
|
134
|
+
signIn: async () => {
|
|
135
|
+
},
|
|
136
|
+
signOut: async () => update({}),
|
|
137
|
+
subscribe(listener) {
|
|
138
|
+
listeners2.add(listener);
|
|
139
|
+
return () => {
|
|
140
|
+
listeners2.delete(listener);
|
|
141
|
+
};
|
|
142
|
+
},
|
|
143
|
+
setUser: (next) => update({ ...patch, ...next }),
|
|
144
|
+
reset: () => update({})
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function createUnavailableSession() {
|
|
148
|
+
return {
|
|
149
|
+
kind: "none",
|
|
150
|
+
getUser: () => null,
|
|
151
|
+
getAccessToken: async () => null,
|
|
152
|
+
signIn: async () => {
|
|
153
|
+
throw new Error(
|
|
154
|
+
"Sign-in is not available in this version of @zjazj/web. Run the app with ENV=dev."
|
|
155
|
+
);
|
|
156
|
+
},
|
|
157
|
+
signOut: async () => {
|
|
158
|
+
},
|
|
159
|
+
subscribe: () => () => {
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
var active;
|
|
164
|
+
function getSession() {
|
|
165
|
+
if (!active) {
|
|
166
|
+
const dev = getPlatformConfig().dev;
|
|
167
|
+
active = dev ? createDevSession(dev.user) : createUnavailableSession();
|
|
168
|
+
}
|
|
169
|
+
return active;
|
|
170
|
+
}
|
|
171
|
+
function setSession(session) {
|
|
172
|
+
active = session;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// src/tenant.ts
|
|
176
|
+
var TENANT_STORAGE_KEY = "platform.tenant";
|
|
177
|
+
var listeners = /* @__PURE__ */ new Set();
|
|
178
|
+
var pinned;
|
|
179
|
+
var changed = false;
|
|
180
|
+
function notify() {
|
|
181
|
+
for (const listener of listeners) listener();
|
|
182
|
+
}
|
|
183
|
+
function pinTenant(tenantId) {
|
|
184
|
+
pinned = tenantId;
|
|
185
|
+
if (changed) {
|
|
186
|
+
changed = false;
|
|
187
|
+
notify();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
function getPinnedTenant() {
|
|
191
|
+
return pinned;
|
|
192
|
+
}
|
|
193
|
+
function isTenantChanged() {
|
|
194
|
+
return changed;
|
|
195
|
+
}
|
|
196
|
+
function subscribeTenant(listener) {
|
|
197
|
+
listeners.add(listener);
|
|
198
|
+
return () => {
|
|
199
|
+
listeners.delete(listener);
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function handleTenantStorage(newValue) {
|
|
203
|
+
if (!pinned || !newValue || newValue === pinned || changed) return;
|
|
204
|
+
changed = true;
|
|
205
|
+
notify();
|
|
206
|
+
}
|
|
207
|
+
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
|
|
208
|
+
window.addEventListener("storage", (event) => {
|
|
209
|
+
if (event.key === TENANT_STORAGE_KEY) handleTenantStorage(event.newValue);
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// src/client.ts
|
|
214
|
+
var ApiError = class _ApiError extends Error {
|
|
215
|
+
status;
|
|
216
|
+
code;
|
|
217
|
+
traceId;
|
|
218
|
+
field;
|
|
219
|
+
constructor(fields) {
|
|
220
|
+
super(fields.message);
|
|
221
|
+
this.name = "ApiError";
|
|
222
|
+
this.status = fields.status;
|
|
223
|
+
this.code = fields.code;
|
|
224
|
+
this.traceId = fields.traceId;
|
|
225
|
+
this.field = fields.field;
|
|
226
|
+
}
|
|
227
|
+
/** Build the error from a response. Accepts the flat body and the body nested in `detail`. */
|
|
228
|
+
static async fromResponse(response) {
|
|
229
|
+
let body = {};
|
|
230
|
+
try {
|
|
231
|
+
const parsed = await response.clone().json();
|
|
232
|
+
if (parsed && typeof parsed === "object") {
|
|
233
|
+
const detail = parsed.detail;
|
|
234
|
+
body = detail && typeof detail === "object" ? detail : parsed;
|
|
235
|
+
}
|
|
236
|
+
} catch {
|
|
237
|
+
}
|
|
238
|
+
const text = (value) => typeof value === "string" && value ? value : void 0;
|
|
239
|
+
return new _ApiError({
|
|
240
|
+
status: response.status,
|
|
241
|
+
code: text(body.code) ?? `http_${response.status}`,
|
|
242
|
+
message: text(body.message) ?? (response.statusText || `Request failed (${response.status})`),
|
|
243
|
+
traceId: text(body.trace_id) ?? response.headers.get("X-Request-Id") ?? void 0,
|
|
244
|
+
field: text(body.field)
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
async function platformFetch(input, init) {
|
|
249
|
+
if (isTenantChanged()) {
|
|
250
|
+
throw new ApiError({
|
|
251
|
+
status: 409,
|
|
252
|
+
code: "tenant_changed",
|
|
253
|
+
message: "The tenant changed in another tab. Reload the page."
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
const session = getSession();
|
|
257
|
+
const headers = new Headers(
|
|
258
|
+
init?.headers ?? (input instanceof Request ? input.headers : void 0)
|
|
259
|
+
);
|
|
260
|
+
if (!headers.has("Authorization")) {
|
|
261
|
+
const token = await session.getAccessToken();
|
|
262
|
+
if (token) headers.set("Authorization", `Bearer ${token}`);
|
|
263
|
+
}
|
|
264
|
+
const response = await fetch(input, { ...init, headers });
|
|
265
|
+
if (response.ok) return response;
|
|
266
|
+
const error = await ApiError.fromResponse(response);
|
|
267
|
+
if (response.status === 401 && session.kind !== "dev") {
|
|
268
|
+
void session.signIn().catch(() => {
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
throw error;
|
|
272
|
+
}
|
|
273
|
+
function createClient(baseUrl = apiBaseUrl()) {
|
|
274
|
+
return hc(baseUrl, { fetch: platformFetch });
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// src/context.tsx
|
|
278
|
+
import { createContext, useContext, useSyncExternalStore } from "react";
|
|
279
|
+
|
|
280
|
+
// src/permissions.ts
|
|
281
|
+
function permissionMatches(granted, code) {
|
|
282
|
+
if (granted.has(code) || granted.has("*")) return true;
|
|
283
|
+
const parts = code.split(":");
|
|
284
|
+
for (let keep = parts.length - 1; keep > 0; keep -= 1) {
|
|
285
|
+
const candidate = [...parts.slice(0, keep), ...Array(parts.length - keep).fill("*")].join(":");
|
|
286
|
+
if (granted.has(candidate)) return true;
|
|
287
|
+
}
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
function hasPermissions(granted, required) {
|
|
291
|
+
const set = granted instanceof Set ? granted : new Set(granted);
|
|
292
|
+
return required.every((code) => permissionMatches(set, code));
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// src/context.tsx
|
|
296
|
+
import { jsx } from "react/jsx-runtime";
|
|
297
|
+
var PlatformContext = createContext(null);
|
|
298
|
+
function PlatformProvider(props) {
|
|
299
|
+
const { children, ...value } = props;
|
|
300
|
+
return /* @__PURE__ */ jsx(PlatformContext.Provider, { value, children });
|
|
301
|
+
}
|
|
302
|
+
function usePlatform() {
|
|
303
|
+
const value = useContext(PlatformContext);
|
|
304
|
+
if (!value) throw new Error("Platform hooks must be used inside an app created by createApp()");
|
|
305
|
+
return value;
|
|
306
|
+
}
|
|
307
|
+
function useAppConfig() {
|
|
308
|
+
return usePlatform().config;
|
|
309
|
+
}
|
|
310
|
+
function useSession() {
|
|
311
|
+
return usePlatform().session;
|
|
312
|
+
}
|
|
313
|
+
function useOptionalUser() {
|
|
314
|
+
const { session } = usePlatform();
|
|
315
|
+
return useSyncExternalStore(session.subscribe, session.getUser, session.getUser);
|
|
316
|
+
}
|
|
317
|
+
function useUser() {
|
|
318
|
+
const user = useOptionalUser();
|
|
319
|
+
if (!user) throw new Error("useUser() was called without a signed-in user");
|
|
320
|
+
return user;
|
|
321
|
+
}
|
|
322
|
+
function useTenant() {
|
|
323
|
+
const user = useUser();
|
|
324
|
+
return { id: user.tenantId, slug: user.tenantSlug, timeZone: user.timeZone };
|
|
325
|
+
}
|
|
326
|
+
function useCan(...codes) {
|
|
327
|
+
const user = useOptionalUser();
|
|
328
|
+
return user ? hasPermissions(user.permissions, codes) : false;
|
|
329
|
+
}
|
|
330
|
+
function Can({ permission, children, fallback = null }) {
|
|
331
|
+
const codes = Array.isArray(permission) ? permission : [permission];
|
|
332
|
+
return useCan(...codes) ? children : fallback;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// src/layout.tsx
|
|
336
|
+
import { Link, Outlet, useMatches, useRouter, useRouterState } from "@tanstack/react-router";
|
|
337
|
+
import { LOCALES } from "@zjazj/i18n";
|
|
338
|
+
import { useLocale, useT } from "@zjazj/i18n/react";
|
|
339
|
+
import {
|
|
340
|
+
Avatar,
|
|
341
|
+
AvatarFallback,
|
|
342
|
+
Badge,
|
|
343
|
+
Button,
|
|
344
|
+
DropdownMenu,
|
|
345
|
+
DropdownMenuContent,
|
|
346
|
+
DropdownMenuItem,
|
|
347
|
+
DropdownMenuLabel,
|
|
348
|
+
DropdownMenuRadioGroup,
|
|
349
|
+
DropdownMenuRadioItem,
|
|
350
|
+
DropdownMenuSeparator,
|
|
351
|
+
DropdownMenuSub,
|
|
352
|
+
DropdownMenuSubContent,
|
|
353
|
+
DropdownMenuSubTrigger,
|
|
354
|
+
DropdownMenuTrigger,
|
|
355
|
+
Separator,
|
|
356
|
+
Sidebar,
|
|
357
|
+
SidebarContent,
|
|
358
|
+
SidebarGroup,
|
|
359
|
+
SidebarGroupContent,
|
|
360
|
+
SidebarGroupLabel,
|
|
361
|
+
SidebarHeader,
|
|
362
|
+
SidebarInset,
|
|
363
|
+
SidebarMenu,
|
|
364
|
+
SidebarMenuButton,
|
|
365
|
+
SidebarMenuItem,
|
|
366
|
+
SidebarProvider,
|
|
367
|
+
SidebarRail,
|
|
368
|
+
SidebarTrigger,
|
|
369
|
+
useTheme
|
|
370
|
+
} from "@zjazj/ui";
|
|
371
|
+
import { LayoutGrid, LogOut } from "lucide-react";
|
|
372
|
+
import { useEffect, useMemo, useSyncExternalStore as useSyncExternalStore2 } from "react";
|
|
373
|
+
|
|
374
|
+
// src/menu.ts
|
|
375
|
+
function requiredPermissions(meta) {
|
|
376
|
+
if (!meta?.permission) return [];
|
|
377
|
+
return Array.isArray(meta.permission) ? meta.permission : [meta.permission];
|
|
378
|
+
}
|
|
379
|
+
function buildMenu(routes, permissions) {
|
|
380
|
+
const items = [];
|
|
381
|
+
const seen = /* @__PURE__ */ new Set();
|
|
382
|
+
for (const route of routes) {
|
|
383
|
+
const meta = route.options?.staticData;
|
|
384
|
+
const to = route.fullPath;
|
|
385
|
+
if (!meta?.menu || !to || to.includes("$") || seen.has(to)) continue;
|
|
386
|
+
if (!hasPermissions(permissions, requiredPermissions(meta))) continue;
|
|
387
|
+
seen.add(to);
|
|
388
|
+
items.push({ ...meta.menu, to, order: meta.menu.order ?? 100 });
|
|
389
|
+
}
|
|
390
|
+
items.sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));
|
|
391
|
+
const groups = [];
|
|
392
|
+
for (const item of items) {
|
|
393
|
+
let group = groups.find((candidate) => candidate.label === item.group);
|
|
394
|
+
if (!group) {
|
|
395
|
+
group = { label: item.group, items: [] };
|
|
396
|
+
groups.push(group);
|
|
397
|
+
}
|
|
398
|
+
group.items.push(item);
|
|
399
|
+
}
|
|
400
|
+
return groups;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// src/layout.tsx
|
|
404
|
+
import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
|
|
405
|
+
function Message(props) {
|
|
406
|
+
return /* @__PURE__ */ jsxs("div", { className: "flex min-h-[60vh] flex-col items-center justify-center gap-3 p-8 text-center", children: [
|
|
407
|
+
/* @__PURE__ */ jsx2("h1", { className: "text-2xl font-semibold", children: props.title }),
|
|
408
|
+
/* @__PURE__ */ jsx2("p", { className: "text-muted-foreground max-w-md", children: props.body }),
|
|
409
|
+
props.children
|
|
410
|
+
] });
|
|
411
|
+
}
|
|
412
|
+
function AppsLink() {
|
|
413
|
+
const t = useT("web");
|
|
414
|
+
const { portalUrl } = useAppConfig();
|
|
415
|
+
return /* @__PURE__ */ jsx2(Button, { asChild: true, variant: "outline", size: "sm", children: /* @__PURE__ */ jsxs("a", { href: portalUrl, target: "platform-portal", children: [
|
|
416
|
+
/* @__PURE__ */ jsx2(LayoutGrid, {}),
|
|
417
|
+
t("backToApps")
|
|
418
|
+
] }) });
|
|
419
|
+
}
|
|
420
|
+
function NotFound() {
|
|
421
|
+
const t = useT("web");
|
|
422
|
+
const user = useOptionalUser();
|
|
423
|
+
return /* @__PURE__ */ jsx2(
|
|
424
|
+
Message,
|
|
425
|
+
{
|
|
426
|
+
title: t("notFoundTitle"),
|
|
427
|
+
body: t("notFoundBody", { tenant: user?.tenantSlug || user?.tenantId || "-" }),
|
|
428
|
+
children: /* @__PURE__ */ jsx2(AppsLink, {})
|
|
429
|
+
}
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
function Forbidden() {
|
|
433
|
+
const t = useT("web");
|
|
434
|
+
return /* @__PURE__ */ jsx2(Message, { title: t("forbiddenTitle"), body: t("forbiddenBody") });
|
|
435
|
+
}
|
|
436
|
+
function ErrorScreen({ error }) {
|
|
437
|
+
const t = useT("web");
|
|
438
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
439
|
+
return /* @__PURE__ */ jsx2(Message, { title: t("errorTitle"), body: message, children: error instanceof ApiError && error.traceId ? /* @__PURE__ */ jsx2("code", { className: "text-muted-foreground text-xs", children: t("traceId", { id: error.traceId }) }) : null });
|
|
440
|
+
}
|
|
441
|
+
function TenantChanged() {
|
|
442
|
+
const t = useT("web");
|
|
443
|
+
return /* @__PURE__ */ jsx2("div", { className: "bg-background/95 fixed inset-0 z-[100] flex items-center justify-center", children: /* @__PURE__ */ jsx2(Message, { title: t("tenantChangedTitle"), body: t("tenantChangedBody"), children: /* @__PURE__ */ jsx2(Button, { onClick: () => window.location.reload(), children: t("reload") }) }) });
|
|
444
|
+
}
|
|
445
|
+
var THEME_MODES = [
|
|
446
|
+
{ mode: "light", label: "themeLight" },
|
|
447
|
+
{ mode: "dark", label: "themeDark" },
|
|
448
|
+
{ mode: "system", label: "themeSystem" }
|
|
449
|
+
];
|
|
450
|
+
var LOCALE_LABELS = { "en-US": "localeEnUS", "zh-CN": "localeZhCN" };
|
|
451
|
+
function AccountMenu() {
|
|
452
|
+
const t = useT("web");
|
|
453
|
+
const user = useUser();
|
|
454
|
+
const session = useSession();
|
|
455
|
+
const { theme, setTheme } = useTheme();
|
|
456
|
+
const [locale, setLocale] = useLocale();
|
|
457
|
+
const initials = user.username.trim().slice(0, 2).toUpperCase() || "?";
|
|
458
|
+
return /* @__PURE__ */ jsxs(DropdownMenu, { children: [
|
|
459
|
+
/* @__PURE__ */ jsx2(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx2(Button, { variant: "ghost", size: "icon", className: "rounded-full", "aria-label": t("account"), children: /* @__PURE__ */ jsx2(Avatar, { className: "size-8", children: /* @__PURE__ */ jsx2(AvatarFallback, { children: initials }) }) }) }),
|
|
460
|
+
/* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", className: "w-56", children: [
|
|
461
|
+
/* @__PURE__ */ jsxs(DropdownMenuLabel, { className: "flex flex-col gap-1", children: [
|
|
462
|
+
/* @__PURE__ */ jsx2("span", { className: "truncate", children: user.username }),
|
|
463
|
+
/* @__PURE__ */ jsxs("span", { className: "text-muted-foreground truncate text-xs font-normal", children: [
|
|
464
|
+
t("tenant"),
|
|
465
|
+
": ",
|
|
466
|
+
user.tenantSlug || user.tenantId
|
|
467
|
+
] })
|
|
468
|
+
] }),
|
|
469
|
+
/* @__PURE__ */ jsx2(DropdownMenuSeparator, {}),
|
|
470
|
+
/* @__PURE__ */ jsxs(DropdownMenuSub, { children: [
|
|
471
|
+
/* @__PURE__ */ jsx2(DropdownMenuSubTrigger, { children: t("theme") }),
|
|
472
|
+
/* @__PURE__ */ jsx2(DropdownMenuSubContent, { children: /* @__PURE__ */ jsx2(
|
|
473
|
+
DropdownMenuRadioGroup,
|
|
474
|
+
{
|
|
475
|
+
value: theme,
|
|
476
|
+
onValueChange: (value) => setTheme(value),
|
|
477
|
+
children: THEME_MODES.map((option) => /* @__PURE__ */ jsx2(DropdownMenuRadioItem, { value: option.mode, children: t(option.label) }, option.mode))
|
|
478
|
+
}
|
|
479
|
+
) })
|
|
480
|
+
] }),
|
|
481
|
+
/* @__PURE__ */ jsxs(DropdownMenuSub, { children: [
|
|
482
|
+
/* @__PURE__ */ jsx2(DropdownMenuSubTrigger, { children: t("language") }),
|
|
483
|
+
/* @__PURE__ */ jsx2(DropdownMenuSubContent, { children: /* @__PURE__ */ jsx2(
|
|
484
|
+
DropdownMenuRadioGroup,
|
|
485
|
+
{
|
|
486
|
+
value: locale,
|
|
487
|
+
onValueChange: (value) => setLocale(value),
|
|
488
|
+
children: LOCALES.map((option) => /* @__PURE__ */ jsx2(DropdownMenuRadioItem, { value: option, children: t(LOCALE_LABELS[option]) }, option))
|
|
489
|
+
}
|
|
490
|
+
) })
|
|
491
|
+
] }),
|
|
492
|
+
/* @__PURE__ */ jsx2(DropdownMenuSeparator, {}),
|
|
493
|
+
/* @__PURE__ */ jsxs(DropdownMenuItem, { onSelect: () => void session.signOut(), children: [
|
|
494
|
+
/* @__PURE__ */ jsx2(LogOut, {}),
|
|
495
|
+
t("signOut")
|
|
496
|
+
] })
|
|
497
|
+
] })
|
|
498
|
+
] });
|
|
499
|
+
}
|
|
500
|
+
function Navigation({ groups, pathname }) {
|
|
501
|
+
const t = useT("app");
|
|
502
|
+
return /* @__PURE__ */ jsx2(Fragment, { children: groups.map((group) => /* @__PURE__ */ jsxs(SidebarGroup, { children: [
|
|
503
|
+
group.label ? /* @__PURE__ */ jsx2(SidebarGroupLabel, { children: t(group.label) }) : null,
|
|
504
|
+
/* @__PURE__ */ jsx2(SidebarGroupContent, { children: /* @__PURE__ */ jsx2(SidebarMenu, { children: group.items.map((item) => {
|
|
505
|
+
const active2 = item.to === "/" ? pathname === "/" : pathname === item.to || pathname.startsWith(`${item.to}/`);
|
|
506
|
+
return /* @__PURE__ */ jsx2(SidebarMenuItem, { children: /* @__PURE__ */ jsx2(SidebarMenuButton, { asChild: true, isActive: active2, tooltip: t(item.label), children: /* @__PURE__ */ jsxs(Link, { to: item.to, children: [
|
|
507
|
+
item.icon ? /* @__PURE__ */ jsx2(item.icon, {}) : null,
|
|
508
|
+
/* @__PURE__ */ jsx2("span", { children: t(item.label) })
|
|
509
|
+
] }) }) }, item.to);
|
|
510
|
+
}) }) })
|
|
511
|
+
] }, group.label ?? "")) });
|
|
512
|
+
}
|
|
513
|
+
function AppShell() {
|
|
514
|
+
const t = useT("web");
|
|
515
|
+
const config = useAppConfig();
|
|
516
|
+
const user = useOptionalUser();
|
|
517
|
+
const router = useRouter();
|
|
518
|
+
const matches = useMatches();
|
|
519
|
+
const pathname = useRouterState({ select: (state) => state.location.pathname });
|
|
520
|
+
const tenantChanged = useSyncExternalStore2(subscribeTenant, isTenantChanged, () => false);
|
|
521
|
+
const permissions = user?.permissions;
|
|
522
|
+
const groups = useMemo(
|
|
523
|
+
() => buildMenu(Object.values(router.routesById), permissions ?? []),
|
|
524
|
+
[router, permissions]
|
|
525
|
+
);
|
|
526
|
+
const metas = matches.map((match) => match.staticData);
|
|
527
|
+
const leaf = metas.at(-1);
|
|
528
|
+
const required = metas.flatMap(requiredPermissions);
|
|
529
|
+
const allowed = hasPermissions(permissions ?? [], required);
|
|
530
|
+
const label = [...metas].reverse().find((meta) => meta?.menu)?.menu?.label;
|
|
531
|
+
const tApp = useT("app");
|
|
532
|
+
const pageTitle = label ? tApp(label) : void 0;
|
|
533
|
+
useEffect(() => {
|
|
534
|
+
document.title = pageTitle ? `${pageTitle} \xB7 ${config.title}` : config.title;
|
|
535
|
+
}, [pageTitle, config.title]);
|
|
536
|
+
if (!user) {
|
|
537
|
+
return /* @__PURE__ */ jsx2(Message, { title: t("signInRequiredTitle"), body: t("signInRequiredBody") });
|
|
538
|
+
}
|
|
539
|
+
if (leaf?.layout === "none") {
|
|
540
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
541
|
+
allowed ? /* @__PURE__ */ jsx2(Outlet, {}) : /* @__PURE__ */ jsx2(Forbidden, {}),
|
|
542
|
+
tenantChanged ? /* @__PURE__ */ jsx2(TenantChanged, {}) : null
|
|
543
|
+
] });
|
|
544
|
+
}
|
|
545
|
+
return /* @__PURE__ */ jsxs(SidebarProvider, { children: [
|
|
546
|
+
/* @__PURE__ */ jsxs(Sidebar, { collapsible: "icon", children: [
|
|
547
|
+
/* @__PURE__ */ jsx2(SidebarHeader, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 px-2 py-1.5", children: [
|
|
548
|
+
/* @__PURE__ */ jsx2("span", { className: "bg-primary text-primary-foreground flex size-7 shrink-0 items-center justify-center rounded-md text-xs font-semibold", children: config.title.slice(0, 1).toUpperCase() }),
|
|
549
|
+
/* @__PURE__ */ jsx2("span", { className: "truncate font-semibold group-data-[collapsible=icon]:hidden", children: config.title })
|
|
550
|
+
] }) }),
|
|
551
|
+
/* @__PURE__ */ jsx2(SidebarContent, { children: /* @__PURE__ */ jsx2(Navigation, { groups, pathname }) }),
|
|
552
|
+
/* @__PURE__ */ jsx2(SidebarRail, {})
|
|
553
|
+
] }),
|
|
554
|
+
/* @__PURE__ */ jsxs(SidebarInset, { children: [
|
|
555
|
+
/* @__PURE__ */ jsxs("header", { className: "bg-background sticky top-0 z-10 flex h-14 shrink-0 items-center gap-2 border-b px-4", children: [
|
|
556
|
+
/* @__PURE__ */ jsx2(SidebarTrigger, {}),
|
|
557
|
+
/* @__PURE__ */ jsx2(Separator, { orientation: "vertical", className: "mx-1 h-5" }),
|
|
558
|
+
/* @__PURE__ */ jsx2("span", { className: "truncate font-medium", children: pageTitle ?? config.title }),
|
|
559
|
+
/* @__PURE__ */ jsxs("div", { className: "ml-auto flex items-center gap-2", children: [
|
|
560
|
+
user.isDev ? /* @__PURE__ */ jsx2(Badge, { variant: "outline", children: t("devIdentity") }) : null,
|
|
561
|
+
/* @__PURE__ */ jsx2(Button, { asChild: true, variant: "ghost", size: "sm", children: /* @__PURE__ */ jsxs("a", { href: config.portalUrl, target: "platform-portal", children: [
|
|
562
|
+
/* @__PURE__ */ jsx2(LayoutGrid, {}),
|
|
563
|
+
t("apps")
|
|
564
|
+
] }) }),
|
|
565
|
+
/* @__PURE__ */ jsx2(AccountMenu, {})
|
|
566
|
+
] })
|
|
567
|
+
] }),
|
|
568
|
+
/* @__PURE__ */ jsx2("main", { className: "flex-1 p-4 md:p-6", children: allowed ? /* @__PURE__ */ jsx2(Outlet, {}) : /* @__PURE__ */ jsx2(Forbidden, {}) })
|
|
569
|
+
] }),
|
|
570
|
+
tenantChanged ? /* @__PURE__ */ jsx2(TenantChanged, {}) : null
|
|
571
|
+
] });
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// src/app.tsx
|
|
575
|
+
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
576
|
+
function defaultQueryClient() {
|
|
577
|
+
return new QueryClient({
|
|
578
|
+
defaultOptions: {
|
|
579
|
+
queries: {
|
|
580
|
+
// A 4xx will not succeed on a retry.
|
|
581
|
+
retry: (failureCount, error) => !(error instanceof ApiError && error.status < 500) && failureCount < 2,
|
|
582
|
+
staleTime: 1e4
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
function createApp(options) {
|
|
588
|
+
const config = getPlatformConfig();
|
|
589
|
+
const session = getSession();
|
|
590
|
+
const queryClient = options.queryClient ?? defaultQueryClient();
|
|
591
|
+
if (options.messages) registerMessages("app", options.messages);
|
|
592
|
+
const syncUser = () => {
|
|
593
|
+
const user = session.getUser();
|
|
594
|
+
setTimeZone(user?.timeZone);
|
|
595
|
+
if (user) pinTenant(user.tenantId);
|
|
596
|
+
};
|
|
597
|
+
syncUser();
|
|
598
|
+
session.subscribe(() => {
|
|
599
|
+
syncUser();
|
|
600
|
+
queryClient.clear();
|
|
601
|
+
void router.invalidate();
|
|
602
|
+
});
|
|
603
|
+
const router = createRouter({
|
|
604
|
+
routeTree: options.routeTree,
|
|
605
|
+
basepath: config.basePath,
|
|
606
|
+
context: { queryClient },
|
|
607
|
+
defaultPreload: "intent",
|
|
608
|
+
defaultNotFoundComponent: NotFound,
|
|
609
|
+
defaultErrorComponent: ErrorScreen
|
|
610
|
+
});
|
|
611
|
+
return {
|
|
612
|
+
config,
|
|
613
|
+
session,
|
|
614
|
+
queryClient,
|
|
615
|
+
router,
|
|
616
|
+
mount(target) {
|
|
617
|
+
const element = typeof target === "string" ? document.querySelector(target) : target;
|
|
618
|
+
if (!element) throw new Error(`createApp().mount: no element matches ${String(target)}`);
|
|
619
|
+
const root = createRoot(element);
|
|
620
|
+
root.render(
|
|
621
|
+
/* @__PURE__ */ jsx3(StrictMode, { children: /* @__PURE__ */ jsx3(PlatformProvider, { config, session, children: /* @__PURE__ */ jsxs2(QueryClientProvider, { client: queryClient, children: [
|
|
622
|
+
/* @__PURE__ */ jsx3(RouterProvider, { router }),
|
|
623
|
+
/* @__PURE__ */ jsx3(Toaster, {})
|
|
624
|
+
] }) }) })
|
|
625
|
+
);
|
|
626
|
+
return root;
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// src/index.ts
|
|
632
|
+
registerMessages2("web", { "en-US": en_US_default, "zh-CN": zh_CN_default });
|
|
633
|
+
export {
|
|
634
|
+
ApiError,
|
|
635
|
+
AppShell,
|
|
636
|
+
Can,
|
|
637
|
+
ErrorScreen,
|
|
638
|
+
Forbidden,
|
|
639
|
+
NotFound,
|
|
640
|
+
PlatformProvider,
|
|
641
|
+
TENANT_STORAGE_KEY,
|
|
642
|
+
apiBaseUrl,
|
|
643
|
+
buildMenu,
|
|
644
|
+
createApp,
|
|
645
|
+
createClient,
|
|
646
|
+
createDevSession,
|
|
647
|
+
encodeDevToken,
|
|
648
|
+
getPinnedTenant,
|
|
649
|
+
getPlatformConfig,
|
|
650
|
+
getSession,
|
|
651
|
+
hasPermissions,
|
|
652
|
+
isTenantChanged,
|
|
653
|
+
permissionMatches,
|
|
654
|
+
pinTenant,
|
|
655
|
+
platformFetch,
|
|
656
|
+
setSession,
|
|
657
|
+
useAppConfig,
|
|
658
|
+
useCan,
|
|
659
|
+
useOptionalUser,
|
|
660
|
+
useSession,
|
|
661
|
+
useTenant,
|
|
662
|
+
useUser
|
|
663
|
+
};
|
package/dist/styles.css
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Styles for a platform app. Import it once, after Tailwind, in the app's stylesheet:
|
|
3
|
+
*
|
|
4
|
+
* @import 'tailwindcss';
|
|
5
|
+
* @import '@zjazj/web/styles.css';
|
|
6
|
+
*
|
|
7
|
+
* It brings the theme and component styles of @zjazj/ui with it.
|
|
8
|
+
*/
|
|
9
|
+
@import '@zjazj/ui/styles.css';
|
|
10
|
+
|
|
11
|
+
/* Let Tailwind see the class names used inside the compiled layout shell. */
|
|
12
|
+
@source './';
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zjazj/web",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Browser runtime for platform apps: session, typed API client, layout shell, guards and hooks.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "UNLICENSED",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/zjazj/platform-cli.git",
|
|
10
|
+
"directory": "packages/web"
|
|
11
|
+
},
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./styles.css": "./dist/styles.css"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"sideEffects": [
|
|
23
|
+
"*.css",
|
|
24
|
+
"./dist/index.js"
|
|
25
|
+
],
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"hono": "^4.13.17",
|
|
28
|
+
"lucide-react": "^0.545.0",
|
|
29
|
+
"@zjazj/i18n": "^0.0.1",
|
|
30
|
+
"@zjazj/ui": "^0.0.1"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@tanstack/react-query": "^5.90.0",
|
|
34
|
+
"@tanstack/react-router": "^1.132.0",
|
|
35
|
+
"react": "^19.0.0",
|
|
36
|
+
"react-dom": "^19.0.0"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@tanstack/react-query": "^5.107.1",
|
|
40
|
+
"@tanstack/react-router": "^1.170.46",
|
|
41
|
+
"@testing-library/react": "^16.3.3",
|
|
42
|
+
"@types/react": "^19.2.0",
|
|
43
|
+
"@types/react-dom": "^19.2.0",
|
|
44
|
+
"jsdom": "^26.1.0",
|
|
45
|
+
"react": "^19.2.0",
|
|
46
|
+
"react-dom": "^19.2.0",
|
|
47
|
+
"@zjazj/server": "^0.0.1"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public",
|
|
51
|
+
"registry": "https://registry.npmjs.org/"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"build": "tsup",
|
|
55
|
+
"test": "vitest run",
|
|
56
|
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
57
|
+
}
|
|
6
58
|
}
|