wcz-layout 10.2.0 → 10.2.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/dist/{ChatLayout-Tpuwo8-b.mjs → ChatLayout-CkS9oyPp.mjs} +597 -293
- package/dist/ChatLayout-CkS9oyPp.mjs.map +1 -0
- package/dist/{Employee-C8xIlBxY.d.mts → ExtractFile-ClTc-e1H.d.mts} +20 -3
- package/dist/RouterListItemButton-CF-8w-08.mjs.map +1 -1
- package/dist/Translate-Ad784Dps.d.mts +24 -0
- package/dist/{Approval-D1TfISUL.mjs → Translate-BiCjnlyx.mjs} +22 -2
- package/dist/Translate-BiCjnlyx.mjs.map +1 -0
- package/dist/ai.d.mts +36 -0
- package/dist/ai.mjs +168 -0
- package/dist/ai.mjs.map +1 -0
- package/dist/auth.d.mts +4 -3
- package/dist/auth.mjs +5 -4
- package/dist/auth.mjs.map +1 -1
- package/dist/authMiddleware-D4GSt7m9.mjs +50 -0
- package/dist/authMiddleware-D4GSt7m9.mjs.map +1 -0
- package/dist/components.mjs +55 -45
- package/dist/components.mjs.map +1 -1
- package/dist/{createApi-CKgFi53y.mjs → createApi-CF4ZL82B.mjs} +3 -4
- package/dist/createApi-CF4ZL82B.mjs.map +1 -0
- package/dist/data/client.d.mts +17 -1
- package/dist/data/client.mjs +11 -5
- package/dist/data/client.mjs.map +1 -1
- package/dist/data/server.d.mts +18 -3
- package/dist/data/server.mjs +5 -5
- package/dist/{env-BwFl7nWc.mjs → env-Cddts_dn.mjs} +2 -1
- package/dist/env-Cddts_dn.mjs.map +1 -0
- package/dist/{file-X1sK4ok6.mjs → file-D4kSR_lC.mjs} +5 -6
- package/dist/file-D4kSR_lC.mjs.map +1 -0
- package/dist/{file-tkfsnk5F.mjs → file-DcwYjofa.mjs} +6 -7
- package/dist/file-DcwYjofa.mjs.map +1 -0
- package/dist/generatedChart-k7NEdi5Z.mjs.map +1 -1
- package/dist/hooks.d.mts +2 -2
- package/dist/hooks.mjs +296 -194
- package/dist/hooks.mjs.map +1 -1
- package/dist/index.mjs +224 -173
- package/dist/index.mjs.map +1 -1
- package/dist/{approval-HB2w5jzc.mjs → layout-6We_KFgN.mjs} +28 -4
- package/dist/layout-6We_KFgN.mjs.map +1 -0
- package/dist/middleware.mjs +1 -45
- package/dist/middleware.mjs.map +1 -1
- package/dist/models.d.mts +3 -3
- package/dist/models.mjs +2 -2
- package/dist/{peoplesoft-RnvfLbWH.mjs → peoplesoft-DH31FCMC.mjs} +3 -3
- package/dist/{peoplesoft-RnvfLbWH.mjs.map → peoplesoft-DH31FCMC.mjs.map} +1 -1
- package/dist/{peoplesoft-C-zPdRVj.d.mts → peoplesoft-DXukeeFr.d.mts} +2 -2
- package/dist/{providers-BfFg_3eo.mjs → providers-DOFje2P6.mjs} +7 -7
- package/dist/providers-DOFje2P6.mjs.map +1 -0
- package/dist/{tokens-C4SErO-K.mjs → tokens-DNe_Qifk.mjs} +63 -9
- package/dist/tokens-DNe_Qifk.mjs.map +1 -0
- package/dist/user-Bc2nLjAG.mjs +136 -0
- package/dist/user-Bc2nLjAG.mjs.map +1 -0
- package/dist/utils-CgabUlDD.mjs +131 -0
- package/dist/utils-CgabUlDD.mjs.map +1 -0
- package/dist/utils.d.mts +1 -10
- package/dist/utils.mjs +5 -3
- package/package.json +45 -14
- package/skills/ai/SKILL.md +108 -75
- package/skills/general/references/auth.md +7 -3
- package/skills/migrations/versions/migrate-v10-to-v11.md +4 -0
- package/skills/services/SKILL.md +41 -7
- package/skills/services/docs/approval.md +5 -0
- package/skills/services/docs/layout.md +130 -0
- package/skills/start/steps/03-apm-setup.md +8 -1
- package/dist/Approval-D1TfISUL.mjs.map +0 -1
- package/dist/ChatLayout-Tpuwo8-b.mjs.map +0 -1
- package/dist/Email-Dz5k0UWE.d.mts +0 -15
- package/dist/approval-HB2w5jzc.mjs.map +0 -1
- package/dist/createApi-CKgFi53y.mjs.map +0 -1
- package/dist/env-BwFl7nWc.mjs.map +0 -1
- package/dist/file-X1sK4ok6.mjs.map +0 -1
- package/dist/file-tkfsnk5F.mjs.map +0 -1
- package/dist/providers-BfFg_3eo.mjs.map +0 -1
- package/dist/tokens-C4SErO-K.mjs.map +0 -1
- package/dist/utils-C2MZoH9U.mjs +0 -263
- package/dist/utils-C2MZoH9U.mjs.map +0 -1
- package/dist/utils-DnMFybj3.mjs +0 -27
- package/dist/utils-DnMFybj3.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"user-Bc2nLjAG.mjs","names":[],"sources":["../src/lib/auth/offline.ts","../src/lib/auth/session.ts","../src/lib/auth/user.ts"],"sourcesContent":["/**\n * Offline fallback for identity. The refresh token never leaves the sealed\n * httpOnly cookie — what is cached here is only the display snapshot (user\n * claims and avatar) so the UI and offline route permissions can still work\n * while the server is unreachable. Server requests remain independently\n * authorized. At-rest protection is the device's OS login and disk encryption.\n */\n\nexport const OFFLINE_USER_KEY = \"auth-user\";\nexport const OFFLINE_PHOTO_KEY = \"auth-photo\";\n\n/** One shift — matches Intune's default offline grace period. */\nconst GRACE_PERIOD = 12 * 60 * 60 * 1000;\n\ntype Cached<T> = { value: T; savedAt: number };\n\nconst recall = <T>(key: string): T | null => {\n if (typeof localStorage === \"undefined\") return null;\n try {\n const raw = localStorage.getItem(key);\n if (!raw) return null;\n const { value, savedAt } = JSON.parse(raw) as Cached<T>;\n if (Date.now() - savedAt > GRACE_PERIOD) {\n localStorage.removeItem(key);\n return null;\n }\n return value;\n } catch {\n localStorage.removeItem(key);\n return null;\n }\n};\n\nconst remember = (key: string, value: unknown): void => {\n if (typeof localStorage === \"undefined\") return;\n try {\n if (value === null || value === undefined) localStorage.removeItem(key);\n else localStorage.setItem(key, JSON.stringify({ value, savedAt: Date.now() }));\n } catch {\n // Storage full or blocked — the offline fallback is best-effort.\n }\n};\n\nconst isOfflineFailure = (error: unknown): boolean =>\n (typeof navigator !== \"undefined\" && !navigator.onLine) || error instanceof TypeError;\n\n/**\n * Answers from the server when reachable, remembering the result; when the call\n * has a transport failure, replays the last result instead, for up to\n * {@link GRACE_PERIOD} since it was last confirmed.\n *\n * Cached values are untrusted client state. Server authorization must never\n * depend on them.\n */\nexport const withOfflineFallback = async <T>(\n key: string,\n fetchFresh: () => Promise<T>,\n): Promise<T | null> => {\n try {\n const fresh = await fetchFresh();\n remember(key, fresh);\n return fresh;\n } catch (error) {\n if (!isOfflineFailure(error)) throw error;\n return recall<T>(key);\n }\n};\n\n/** Drops the cached identity. Call on logout, before leaving the page. */\nexport const clearSessionSnapshot = (): void => {\n if (typeof localStorage === \"undefined\") return;\n localStorage.removeItem(OFFLINE_USER_KEY);\n localStorage.removeItem(OFFLINE_PHOTO_KEY);\n localStorage.setItem(\"auth-logout\", String(Date.now()));\n};\n\nif (typeof window !== \"undefined\")\n window.addEventListener(\"storage\", (event) => {\n if (event.key === \"auth-logout\") location.href = \"/auth/logout\";\n });\n","import type { IronSession } from \"iron-session\";\nimport { serverEnv } from \"~/env\";\nimport type { ProviderId, User } from \"~/models/User\";\n\nexport interface AppSessionData {\n /** Which identity provider signed this user in. */\n provider?: ProviderId;\n /** The only token persisted; delegated access tokens are minted from it. */\n refreshToken?: string;\n user?: User;\n /** Transient, only between /auth/login and /auth/callback. */\n pkceVerifier?: string;\n state?: string;\n returnTo?: string;\n}\n\nexport type AppSession = IronSession<AppSessionData>;\n\nexport const getAppSession = async (): Promise<AppSession> => {\n // Dynamic import: `@tanstack/react-start/server` is the server entry and drags\n // in the SSR renderer (`react-dom/server`). Keep it out of the client graph —\n // this helper is only ever called server-side, and all callers already await it.\n const [{ getIronSession }, { getCookie, setCookie }] = await Promise.all([\n import(\"iron-session\"),\n import(\"@tanstack/react-start/server\"),\n ]);\n\n return getIronSession<AppSessionData>(\n { read: getCookie, write: setCookie },\n {\n // Not `session`: that name holds the pre-stable `useSession` seal, which\n // iron-session can't read. Users sign in once more after the upgrade.\n cookieName: \"app-session\",\n password: serverEnv.SESSION_SECRET,\n chunk: true,\n cookieOptions: {\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"lax\",\n httpOnly: true,\n path: \"/\",\n // Explicit `undefined`: browser-session cookie and a seal that never\n // expires — what `useSession` did. Omit it to fall back to iron's 14-day `ttl`.\n maxAge: undefined,\n },\n },\n );\n};\n","import { queryOptions } from \"@tanstack/react-query\";\nimport { createServerFn } from \"@tanstack/react-start\";\nimport type { QueryClientParam } from \"~/models/QueryClientParam\";\nimport type { ProviderId, User } from \"~/models/User\";\nimport { OFFLINE_USER_KEY, withOfflineFallback } from \"./offline\";\nimport { getAppSession } from \"./session\";\n\n/**\n * Reads the signed-in user from the session cookie, or null. As a server function\n * it runs in-process when called on the server (SSR, middleware) and as an RPC\n * when called from the client — so it doubles as the client `queryFn`.\n */\nexport const getSessionUser = createServerFn({ method: \"GET\" }).handler(\n async (): Promise<User | null> => {\n const session = await getAppSession();\n return session.user ?? null;\n },\n);\n\n/** The identity providers the server offers, for the login page. */\nexport const getLoginProviders = createServerFn({ method: \"GET\" }).handler(\n async (): Promise<Array<{ id: ProviderId; label: string }>> => {\n // Dynamic import: `providers` reads `serverEnv` and must not reach the client.\n const { providers } = await import(\"./providers\");\n return providers.map(({ id, label }) => ({ id, label }));\n },\n);\n\n/**\n * Feeds `LoginForm`. Server config, not per-user, so it is safe to prime on the\n * server — the `/login` route's loader does that to avoid a flash of empty card.\n */\nexport const loginProvidersQueryOptions = queryOptions({\n queryKey: [\"auth\", \"providers\"],\n queryFn: () => getLoginProviders(),\n staleTime: \"static\",\n});\n\n/**\n * Client-side query for the signed-in user. Shared between `getUser` (route\n * `beforeLoad`) and the always-mounted observer in `LayoutProvider` — the\n * observer is what seeds the offline snapshot on the very first page load\n * (`beforeLoad` does not re-run after SSR hydration) and what makes\n * `refetchOnReconnect` fire once connectivity returns.\n */\nexport const userQueryOptions = queryOptions({\n queryKey: [\"auth\", \"user\"],\n queryFn: () => withOfflineFallback(OFFLINE_USER_KEY, () => getSessionUser()),\n staleTime: Infinity,\n // Default \"online\" pauses the query (never calling queryFn) once the browser\n // reports no connection — which is exactly when the fallback is needed.\n networkMode: \"offlineFirst\",\n // Back online: re-confirm the session and re-stamp the snapshot's grace period.\n refetchOnReconnect: \"always\",\n});\n\nexport const getUser = ({ queryClient }: QueryClientParam): Promise<User | null> => {\n if (import.meta.env.SSR) return getSessionUser();\n\n return queryClient.ensureQueryData(userQueryOptions);\n};\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,mBAAmB;AAChC,MAAa,oBAAoB;;AAGjC,MAAM,eAAe;AAIrB,MAAM,UAAa,QAA0B;CAC3C,IAAI,OAAO,iBAAiB,aAAa,OAAO;CAChD,IAAI;EACF,MAAM,MAAM,aAAa,QAAQ,GAAG;EACpC,IAAI,CAAC,KAAK,OAAO;EACjB,MAAM,EAAE,OAAO,YAAY,KAAK,MAAM,GAAG;EACzC,IAAI,KAAK,IAAI,IAAI,UAAU,cAAc;GACvC,aAAa,WAAW,GAAG;GAC3B,OAAO;EACT;EACA,OAAO;CACT,QAAQ;EACN,aAAa,WAAW,GAAG;EAC3B,OAAO;CACT;AACF;AAEA,MAAM,YAAY,KAAa,UAAyB;CACtD,IAAI,OAAO,iBAAiB,aAAa;CACzC,IAAI;EACF,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,aAAa,WAAW,GAAG;OACjE,aAAa,QAAQ,KAAK,KAAK,UAAU;GAAE;GAAO,SAAS,KAAK,IAAI;EAAE,CAAC,CAAC;CAC/E,QAAQ,CAER;AACF;AAEA,MAAM,oBAAoB,UACvB,OAAO,cAAc,eAAe,CAAC,UAAU,UAAW,iBAAiB;;;;;;;;;AAU9E,MAAa,sBAAsB,OACjC,KACA,eACsB;CACtB,IAAI;EACF,MAAM,QAAQ,MAAM,WAAW;EAC/B,SAAS,KAAK,KAAK;EACnB,OAAO;CACT,SAAS,OAAO;EACd,IAAI,CAAC,iBAAiB,KAAK,GAAG,MAAM;EACpC,OAAO,OAAU,GAAG;CACtB;AACF;;AAGA,MAAa,6B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oB;AACtB,CAAC;AAED,MAAa,WAAW,EAAE,kBAA0D;CAClF,IAAI,YAAY,IAAI,KAAK,OAAO,eAAe;CAE/C,OAAO,YAAY,gBAAgB,gBAAgB;AACrD"}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { n as getUser } from "./user-Bc2nLjAG.mjs";
|
|
2
|
+
import { manifest, permissions } from "virtual:wcz-layout";
|
|
3
|
+
import { redirect } from "@tanstack/react-router";
|
|
4
|
+
// src/lib/utils.ts
|
|
5
|
+
const WISTRON_PRIMARY_COLOR = "#00506E";
|
|
6
|
+
const WISTRON_SECONDARY_COLOR = "#64DC00";
|
|
7
|
+
var Platform = class {
|
|
8
|
+
static get isAndroid() {
|
|
9
|
+
return /android/i.test(this.userAgent);
|
|
10
|
+
}
|
|
11
|
+
static get isIOS() {
|
|
12
|
+
return /iPad|iPhone|iPod/.test(this.userAgent);
|
|
13
|
+
}
|
|
14
|
+
static get isWindows() {
|
|
15
|
+
return /windows/i.test(this.userAgent);
|
|
16
|
+
}
|
|
17
|
+
static get isMacOS() {
|
|
18
|
+
return /Macintosh|MacIntel|MacPPC|Mac68K/.test(this.userAgent);
|
|
19
|
+
}
|
|
20
|
+
static get userAgent() {
|
|
21
|
+
return typeof navigator === "undefined" ? "" : navigator.userAgent;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
const rootRouteHead = (options) => ({
|
|
25
|
+
meta: [
|
|
26
|
+
{ charSet: "utf-8" },
|
|
27
|
+
{
|
|
28
|
+
name: "viewport",
|
|
29
|
+
content: "width=device-width, initial-scale=1"
|
|
30
|
+
},
|
|
31
|
+
{ title: manifest.name },
|
|
32
|
+
{
|
|
33
|
+
name: "og:type",
|
|
34
|
+
content: "website"
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: "og:title",
|
|
38
|
+
content: manifest.name
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
name: "og:image",
|
|
42
|
+
content: "/favicon-32x32.png"
|
|
43
|
+
}
|
|
44
|
+
],
|
|
45
|
+
links: [
|
|
46
|
+
{
|
|
47
|
+
rel: "apple-touch-icon",
|
|
48
|
+
sizes: "180x180",
|
|
49
|
+
href: "/apple-touch-icon.png"
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
rel: "icon",
|
|
53
|
+
type: "image/png",
|
|
54
|
+
sizes: "32x32",
|
|
55
|
+
href: "/favicon-32x32.png"
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
rel: "icon",
|
|
59
|
+
type: "image/png",
|
|
60
|
+
sizes: "16x16",
|
|
61
|
+
href: "/favicon-16x16.png"
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
rel: "manifest",
|
|
65
|
+
href: options?.manifest || "/manifest.json"
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
rel: "icon",
|
|
69
|
+
href: "/favicon.ico"
|
|
70
|
+
}
|
|
71
|
+
]
|
|
72
|
+
});
|
|
73
|
+
/**
|
|
74
|
+
* Route guard for `beforeLoad`. Routes are public by default; add this to close one.
|
|
75
|
+
*
|
|
76
|
+
* - `requireAuth()` — signed in with any provider. The only gate a population
|
|
77
|
+
* without permission groups (e.g. AWS users) can pass.
|
|
78
|
+
* - `requireAuth("admin")` — signed in *and* in a group listed under that key.
|
|
79
|
+
*
|
|
80
|
+
* `reloadDocument` is required: `/auth/login` is a component-less server route and
|
|
81
|
+
* must be reached with a full-document navigation. It starts the login directly when
|
|
82
|
+
* only one provider is registered, otherwise it forwards to the `/login` chooser.
|
|
83
|
+
*/
|
|
84
|
+
const requireAuth = (permissionKey) => {
|
|
85
|
+
return async ({ location, context }) => {
|
|
86
|
+
const user = await getUser({ queryClient: context.queryClient });
|
|
87
|
+
if (!user) throw redirect({
|
|
88
|
+
href: `/auth/login?returnTo=${encodeURIComponent(location.href)}`,
|
|
89
|
+
reloadDocument: true
|
|
90
|
+
});
|
|
91
|
+
if (permissionKey && !hasPermission(user, permissionKey)) throw new Error("You do not have permission to access this page.");
|
|
92
|
+
return { user };
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
const NON_PRODUCTION = /(?:^|[.-])(?:dev|qas|uat|test)(?:[.-]|$)/i;
|
|
96
|
+
/** True only for a dev/qas/uat/test domain — localhost and production are not. */
|
|
97
|
+
const isTestEnv = (origin) => NON_PRODUCTION.test((origin ?? "").split(".").slice(1).join("."));
|
|
98
|
+
const getFieldStatus = (field) => {
|
|
99
|
+
const { meta } = field.state;
|
|
100
|
+
return {
|
|
101
|
+
isTouched: meta.isTouched,
|
|
102
|
+
hasError: !!meta.errors.length,
|
|
103
|
+
helperText: meta.errors[0]?.message
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* Only same-origin paths are allowed, so `returnTo` cannot become an open
|
|
108
|
+
* redirect. Backslash counts as a separator too: browsers normalize `/\evil`
|
|
109
|
+
* to the protocol-relative `//evil`.
|
|
110
|
+
*/
|
|
111
|
+
const sanitizeReturnTo = (value) => value && /^\/(?![/\\])/.test(value) ? value : "/";
|
|
112
|
+
const foldForSearch = (value) => String(value ?? "").toLowerCase().normalize("NFD").replaceAll(/[\u{300}-\u{36F}]/gu, "").normalize("NFC");
|
|
113
|
+
const permissionGroups = new Set(Object.values(permissions).flat());
|
|
114
|
+
/**
|
|
115
|
+
* Maps id/access-token claims to the serializable `User`. Groups are trimmed to
|
|
116
|
+
* those named in `permissions.ts` — an unfiltered group list would blow the
|
|
117
|
+
* cookie. Cognito's claim names differ, so both are read.
|
|
118
|
+
*/
|
|
119
|
+
const buildUser = (payload, provider) => ({
|
|
120
|
+
provider,
|
|
121
|
+
name: (payload.name ?? payload["cognito:username"] ?? "").split("/")[0],
|
|
122
|
+
email: (payload.preferred_username ?? payload.email ?? "").toLowerCase(),
|
|
123
|
+
department: payload.department?.toUpperCase() || "",
|
|
124
|
+
employeeId: (payload.employeeId ?? payload["cognito:username"] ?? "").toUpperCase(),
|
|
125
|
+
companyName: payload.companyName || "",
|
|
126
|
+
groups: (payload.groups ?? payload["cognito:groups"])?.filter((group) => permissionGroups.has(group)) ?? []
|
|
127
|
+
});
|
|
128
|
+
const hasPermission = (user, key) => user ? permissions[key].some((group) => user.groups.includes(group)) : false;
|
|
129
|
+
export { foldForSearch as a, isTestEnv as c, sanitizeReturnTo as d, buildUser as i, requireAuth as l, WISTRON_PRIMARY_COLOR as n, getFieldStatus as o, WISTRON_SECONDARY_COLOR as r, hasPermission as s, Platform as t, rootRouteHead as u };
|
|
130
|
+
|
|
131
|
+
//# sourceMappingURL=utils-CgabUlDD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils-CgabUlDD.mjs","names":[],"sources":["../src/lib/utils.ts"],"sourcesContent":["import type { AnyFieldApi } from \"@tanstack/react-form\";\nimport { redirect } from \"@tanstack/react-router\";\nimport type { ParsedLocation } from \"@tanstack/react-router\";\nimport { manifest, permissions } from \"virtual:wcz-layout\";\nimport type { QueryClientParam } from \"~/models/QueryClientParam\";\nimport type { TokenPayload } from \"~/models/TokenPayload\";\nimport type { ProviderId, User } from \"~/models/User\";\nimport { getUser } from \"./auth/user\";\n\nexport const WISTRON_PRIMARY_COLOR = \"#00506E\";\nexport const WISTRON_SECONDARY_COLOR = \"#64DC00\";\n\nexport class Platform {\n static get isAndroid() {\n return /android/i.test(this.userAgent);\n }\n static get isIOS() {\n return /iPad|iPhone|iPod/.test(this.userAgent);\n }\n static get isWindows() {\n return /windows/i.test(this.userAgent);\n }\n static get isMacOS() {\n return /Macintosh|MacIntel|MacPPC|Mac68K/.test(this.userAgent);\n }\n\n private static get userAgent() {\n return typeof navigator === \"undefined\" ? \"\" : navigator.userAgent;\n }\n}\n\ninterface RootRouteHeadOptions {\n manifest?: string;\n}\n\nexport const rootRouteHead = (options?: RootRouteHeadOptions) => ({\n meta: [\n { charSet: \"utf-8\" },\n { name: \"viewport\", content: \"width=device-width, initial-scale=1\" },\n { title: manifest.name },\n { name: \"og:type\", content: \"website\" },\n { name: \"og:title\", content: manifest.name },\n { name: \"og:image\", content: \"/favicon-32x32.png\" },\n ],\n links: [\n { rel: \"apple-touch-icon\", sizes: \"180x180\", href: \"/apple-touch-icon.png\" },\n { rel: \"icon\", type: \"image/png\", sizes: \"32x32\", href: \"/favicon-32x32.png\" },\n { rel: \"icon\", type: \"image/png\", sizes: \"16x16\", href: \"/favicon-16x16.png\" },\n { rel: \"manifest\", href: options?.manifest || \"/manifest.json\" },\n { rel: \"icon\", href: \"/favicon.ico\" },\n ],\n});\n\ntype GuardArgs = { location: ParsedLocation; context: QueryClientParam };\n\n/**\n * Route guard for `beforeLoad`. Routes are public by default; add this to close one.\n *\n * - `requireAuth()` — signed in with any provider. The only gate a population\n * without permission groups (e.g. AWS users) can pass.\n * - `requireAuth(\"admin\")` — signed in *and* in a group listed under that key.\n *\n * `reloadDocument` is required: `/auth/login` is a component-less server route and\n * must be reached with a full-document navigation. It starts the login directly when\n * only one provider is registered, otherwise it forwards to the `/login` chooser.\n */\nexport const requireAuth = (permissionKey?: keyof typeof permissions) => {\n return async ({ location, context }: GuardArgs) => {\n const user = await getUser({ queryClient: context.queryClient });\n\n if (!user)\n throw redirect({\n href: `/auth/login?returnTo=${encodeURIComponent(location.href)}`,\n reloadDocument: true,\n });\n\n if (permissionKey && !hasPermission(user, permissionKey))\n throw new Error(\"You do not have permission to access this page.\");\n\n return { user };\n };\n};\n\n/* Internal Utils */\nconst NON_PRODUCTION = /(?:^|[.-])(?:dev|qas|uat|test)(?:[.-]|$)/i;\n\n/** True only for a dev/qas/uat/test domain — localhost and production are not. */\nexport const isTestEnv = (origin: string | undefined) =>\n NON_PRODUCTION.test((origin ?? \"\").split(\".\").slice(1).join(\".\"));\n\nexport type FormOmittedProps =\n | \"name\"\n | \"value\"\n | \"onChange\"\n | \"onBlur\"\n | \"error\"\n | \"helperText\"\n | \"renderInput\"\n | \"type\"\n | \"aria-label\";\n\nexport const getFieldStatus = (field: AnyFieldApi) => {\n const { meta } = field.state;\n\n const isTouched = meta.isTouched;\n const hasError = !!meta.errors.length;\n const helperText = meta.errors[0]?.message;\n\n return { isTouched, hasError, helperText };\n};\n\n/**\n * Only same-origin paths are allowed, so `returnTo` cannot become an open\n * redirect. Backslash counts as a separator too: browsers normalize `/\\evil`\n * to the protocol-relative `//evil`.\n */\nexport const sanitizeReturnTo = (value: string | null | undefined): string =>\n value && /^\\/(?![/\\\\])/.test(value) ? value : \"/\";\n\nexport const toKebabCase = (str: string): string => {\n return str\n .replaceAll(/([a-z])([A-Z])/g, \"$1-$2\")\n .replaceAll(/[\\s_]+/g, \"-\")\n .replaceAll(/[^a-zA-Z0-9-]/g, \"\")\n .toLowerCase()\n .replaceAll(/-+/g, \"-\")\n .replaceAll(/(^-|-$)/g, \"\");\n};\n\nexport const foldForSearch = (value: unknown): string =>\n String(value ?? \"\")\n .toLowerCase()\n .normalize(\"NFD\")\n .replaceAll(/[\\u{300}-\\u{36F}]/gu, \"\")\n .normalize(\"NFC\");\n\nconst permissionGroups = new Set<string>(Object.values(permissions).flat());\n\n/**\n * Maps id/access-token claims to the serializable `User`. Groups are trimmed to\n * those named in `permissions.ts` — an unfiltered group list would blow the\n * cookie. Cognito's claim names differ, so both are read.\n */\nexport const buildUser = (payload: TokenPayload, provider: ProviderId): User => ({\n provider,\n name: (payload.name ?? payload[\"cognito:username\"] ?? \"\").split(\"/\")[0],\n email: (payload.preferred_username ?? payload.email ?? \"\").toLowerCase(),\n department: payload.department?.toUpperCase() || \"\",\n employeeId: (payload.employeeId ?? payload[\"cognito:username\"] ?? \"\").toUpperCase(),\n companyName: payload.companyName || \"\",\n groups:\n (payload.groups ?? payload[\"cognito:groups\"])?.filter((group) => permissionGroups.has(group)) ??\n [],\n});\n\nexport const hasPermission = (user: User | null, key: keyof typeof permissions): boolean =>\n user ? permissions[key].some((group) => user.groups.includes(group)) : false;\n"],"mappings":";;;;AASA,MAAa,wBAAwB;AACrC,MAAa,0BAA0B;AAEvC,IAAa,WAAb,MAAsB;C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
|
|
3
3
|
import { createEnv } from "@t3-oss/env-core";
|
|
4
4
|
import { uuidv7 } from "uuidv7";
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Text adapter for the Wistron AI gateway; create it per request in a server function
|
|
8
|
-
* (`getAppToken` caches the token). Chat Completions, not Responses: the gateway load-balances
|
|
9
|
-
* Azure deployments, and Responses replays encrypted reasoning that other deployments cannot read
|
|
10
|
-
* (400 invalid_encrypted_content).
|
|
11
|
-
*/
|
|
12
|
-
export declare const chatAdapter: <TModel extends OpenAIChatModel>(model: TModel) => Promise<OpenAIChatCompletionsTextAdapter<TModel>>;
|
|
13
|
-
export { Platform, createEnv, hasPermission, i18next, requireAuth, t, uuidv7 };
|
|
14
|
-
//# sourceMappingURL=utils.d.mts.map
|
|
5
|
+
export { Platform, createEnv, hasPermission, i18next, requireAuth, t, uuidv7 };
|
package/dist/utils.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
import { l as requireAuth, s as hasPermission, t as Platform } from "./utils-
|
|
2
|
-
import
|
|
3
|
-
|
|
1
|
+
import { l as requireAuth, s as hasPermission, t as Platform } from "./utils-CgabUlDD.mjs";
|
|
2
|
+
import i18next, { t } from "i18next";
|
|
3
|
+
import { createEnv } from "@t3-oss/env-core";
|
|
4
|
+
import { uuidv7 } from "uuidv7";
|
|
5
|
+
export { Platform, createEnv, hasPermission, i18next, requireAuth, t, uuidv7 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wcz-layout",
|
|
3
|
-
"version": "10.2.
|
|
3
|
+
"version": "10.2.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"keywords": [
|
|
6
6
|
"tanstack-intent"
|
|
@@ -52,6 +52,10 @@
|
|
|
52
52
|
"types": "./dist/utils.d.mts",
|
|
53
53
|
"import": "./dist/utils.mjs"
|
|
54
54
|
},
|
|
55
|
+
"./ai": {
|
|
56
|
+
"types": "./dist/ai.d.mts",
|
|
57
|
+
"import": "./dist/ai.mjs"
|
|
58
|
+
},
|
|
55
59
|
"./auth": {
|
|
56
60
|
"types": "./dist/auth.d.mts",
|
|
57
61
|
"import": "./dist/auth.mjs"
|
|
@@ -71,12 +75,12 @@
|
|
|
71
75
|
"@t3-oss/env-core": "^0.13.11",
|
|
72
76
|
"@tanstack/ai-react": "^1.0.2",
|
|
73
77
|
"@tanstack/markdown": "^1.2.0",
|
|
74
|
-
"i18next": "^
|
|
78
|
+
"i18next": "^27.1.3",
|
|
75
79
|
"i18next-browser-languagedetector": "^8.3.0",
|
|
76
|
-
"iron-session": "^9.0
|
|
77
|
-
"jose": "^6.2.
|
|
78
|
-
"react-dropzone": "^20.
|
|
79
|
-
"react-i18next": "^
|
|
80
|
+
"iron-session": "^9.1.0",
|
|
81
|
+
"jose": "^6.2.17",
|
|
82
|
+
"react-dropzone": "^20.2.0",
|
|
83
|
+
"react-i18next": "^18.0.1",
|
|
80
84
|
"react-intersection-observer": "^11.0.1",
|
|
81
85
|
"react-number-format": "^5.4.5",
|
|
82
86
|
"tus-js-client": "^4.3.1",
|
|
@@ -84,22 +88,24 @@
|
|
|
84
88
|
},
|
|
85
89
|
"devDependencies": {
|
|
86
90
|
"@arethetypeswrong/core": "^0.18.5",
|
|
87
|
-
"@tanstack/ai": "^1.1.
|
|
88
|
-
"@tanstack/ai-
|
|
89
|
-
"@tanstack/
|
|
91
|
+
"@tanstack/ai-code-mode": "^1.1.1",
|
|
92
|
+
"@tanstack/ai-compaction": "^1.0.1",
|
|
93
|
+
"@tanstack/ai-isolate-quickjs": "^1.1.0",
|
|
94
|
+
"@tanstack/ai-openai": "^1.1.1",
|
|
95
|
+
"@tanstack/highlight": "^1.2.12",
|
|
90
96
|
"@tanstack/intent": "^0.5.6",
|
|
91
97
|
"@tanstack/react-pacer": "^0.24.1",
|
|
92
98
|
"@types/node": "^26.6.6",
|
|
93
99
|
"@types/react": "^19.3.0",
|
|
94
100
|
"@types/react-dom": "^19.3.0",
|
|
95
|
-
"@vitejs/plugin-react": "^6.
|
|
96
|
-
"jsdom": "^
|
|
101
|
+
"@vitejs/plugin-react": "^6.3.0",
|
|
102
|
+
"jsdom": "^31.0.1",
|
|
97
103
|
"nitro": "3.0.261103-rc",
|
|
98
|
-
"oxc-transform-react": "^0.
|
|
104
|
+
"oxc-transform-react": "^0.156.0",
|
|
99
105
|
"publint": "^0.3.25",
|
|
100
106
|
"typescript": "^7.0.2",
|
|
101
|
-
"vite": "npm:@voidzero-dev/vite-plus-core@1.
|
|
102
|
-
"vite-plus": "1.
|
|
107
|
+
"vite": "npm:@voidzero-dev/vite-plus-core@1.6.0",
|
|
108
|
+
"vite-plus": "1.6.0"
|
|
103
109
|
},
|
|
104
110
|
"peerDependencies": {
|
|
105
111
|
"@emotion/cache": "11.x",
|
|
@@ -108,6 +114,11 @@
|
|
|
108
114
|
"@mui/icons-material": "9.x",
|
|
109
115
|
"@mui/material": "9.x",
|
|
110
116
|
"@mui/x-date-pickers": "9.x",
|
|
117
|
+
"@tanstack/ai": "1.x",
|
|
118
|
+
"@tanstack/ai-code-mode": "1.x",
|
|
119
|
+
"@tanstack/ai-compaction": "1.x",
|
|
120
|
+
"@tanstack/ai-isolate-quickjs": "1.x",
|
|
121
|
+
"@tanstack/ai-openai": "1.x",
|
|
111
122
|
"@tanstack/charts": "1.x",
|
|
112
123
|
"@tanstack/react-form": "1.x",
|
|
113
124
|
"@tanstack/react-hotkeys": "0.x",
|
|
@@ -124,7 +135,27 @@
|
|
|
124
135
|
"react-dom": "19.x",
|
|
125
136
|
"zod": "4.x"
|
|
126
137
|
},
|
|
138
|
+
"peerDependenciesMeta": {
|
|
139
|
+
"@tanstack/ai": {
|
|
140
|
+
"optional": true
|
|
141
|
+
},
|
|
142
|
+
"@tanstack/ai-code-mode": {
|
|
143
|
+
"optional": true
|
|
144
|
+
},
|
|
145
|
+
"@tanstack/ai-compaction": {
|
|
146
|
+
"optional": true
|
|
147
|
+
},
|
|
148
|
+
"@tanstack/ai-isolate-quickjs": {
|
|
149
|
+
"optional": true
|
|
150
|
+
},
|
|
151
|
+
"@tanstack/ai-openai": {
|
|
152
|
+
"optional": true
|
|
153
|
+
}
|
|
154
|
+
},
|
|
127
155
|
"overrides": {
|
|
156
|
+
"@tanstack/ai-persistence": {
|
|
157
|
+
"vitest": "5.1.0"
|
|
158
|
+
},
|
|
128
159
|
"vite": "$vite"
|
|
129
160
|
},
|
|
130
161
|
"packageManager": "npm@12.2.2"
|
package/skills/ai/SKILL.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: ai
|
|
3
|
-
description: "Use when adding LLM features (chat, streamed text, structured output, tools, media generation)"
|
|
3
|
+
description: "Use when adding LLM features (the assistant, chat, streamed text, structured output, tools, media generation)"
|
|
4
4
|
metadata:
|
|
5
5
|
type: convention
|
|
6
6
|
library: wcz-layout
|
|
@@ -11,18 +11,50 @@ metadata:
|
|
|
11
11
|
|
|
12
12
|
## Rules
|
|
13
13
|
|
|
14
|
-
- Install `@tanstack/ai` in the app (if missing)
|
|
15
|
-
`@tanstack/
|
|
16
|
-
|
|
14
|
+
- Install `@tanstack/ai` and `@tanstack/ai-openai` in the app (if missing). An app with the
|
|
15
|
+
assistant also installs `@tanstack/ai-code-mode`, `@tanstack/ai-isolate-quickjs` and
|
|
16
|
+
`@tanstack/ai-compaction`: `layoutChat` loads them on its first call. Code mode's optional
|
|
17
|
+
peers ask for an older vitest than vite-plus brings, so npm refuses to install it until the
|
|
18
|
+
app's `package.json` has `"overrides": { "@tanstack/ai-persistence": { "vitest": "<version>" } }`,
|
|
19
|
+
with the version `npm ls vitest` shows. `@tanstack/charts` is a peer of wcz-layout, which npm
|
|
20
|
+
installs with it; the chat loads it with the first chart the model draws.
|
|
21
|
+
- Code mode runs the model's programs in QuickJS, whose WebAssembly a production bundle leaves
|
|
22
|
+
behind: give the app's `nitro()` plugin `traceDeps: ["quickjs-emscripten"]` in `vite.config.ts`.
|
|
17
23
|
- Require the gateway env in the app's `src/env.ts` `server` block, so a missing value fails at
|
|
18
24
|
startup: `AI_BASE_URL: z.url()` and `AI_SUBSCRIPTION_KEY: z.string()`. The gateway token also
|
|
19
25
|
uses the Entra app registration: `ENTRA_TENANT_ID`, `ENTRA_CLIENT_ID`, `ENTRA_CLIENT_SECRET`.
|
|
20
26
|
Values come from `.env.local` or Vault.
|
|
21
|
-
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
27
|
+
- The assistant is one server function that returns `layoutChat({ data, user, systemPrompts,
|
|
28
|
+
tools, guides })` from `wcz-layout/ai`, and nothing else. `layoutChat` brings what every app's
|
|
29
|
+
assistant shares: the model, code mode, the guides, the shared rules (how to read and change
|
|
30
|
+
data, deletes, charts, attached files, the page, the reply's language), who the user is, a
|
|
31
|
+
conversation bounded at 100k tokens and a `[chat]` line in the server log with the tokens of
|
|
32
|
+
each model call. Never call `chat()` for the assistant yourself, and never repeat those rules
|
|
33
|
+
in the app's prompt.
|
|
34
|
+
- `systemPrompts` say only what the app is: what its records are called and mean, what the
|
|
35
|
+
assistant cannot do there, and the paths of its pages (`[name](/orders/<id>)`), so the model
|
|
36
|
+
links the records it mentions. Keep it the same for every user and every request: no user,
|
|
37
|
+
date or page in it, or the provider's prompt cache misses. `layoutChat` adds the user; the
|
|
38
|
+
model reads the time with `get_time` and the page with `read_page` when a request needs them.
|
|
39
|
+
- `tools` are server tools (`toolDefinition(...).server(...)`) that call the app's own server
|
|
40
|
+
functions, `deleteOrder({ data: id })`: called on the server they run in the same request, with
|
|
41
|
+
the screens' middleware, validation and permission checks. Never reimplement a server function
|
|
42
|
+
for a tool. After a write, `context?.emitCustomEvent("invalidate", { queryKey })` makes the
|
|
43
|
+
chat invalidate that query, so open screens refetch.
|
|
44
|
+
- A tool without `needsApproval` becomes a function of the programs the model runs
|
|
45
|
+
(`execute_typescript`): it reads, filters, joins and counts on the server, and creates or
|
|
46
|
+
changes many records in one program, e.g. a device per row of an attached spreadsheet. Only
|
|
47
|
+
the program's answer enters the conversation. So a reading tool takes no filters: it returns
|
|
48
|
+
every record the user may see, with an `outputSchema` that gives the model the rows' shape.
|
|
49
|
+
- Only tools that delete get `needsApproval: true`. They stay tool calls of their own, and the
|
|
50
|
+
chat asks "Are you sure?" (Cancel / Confirm) before one runs.
|
|
51
|
+
- Give feature tools `lazy: true`: the model sees names and first sentences, and loads a
|
|
52
|
+
feature's types only when a request needs them. Write each description's first sentence to
|
|
53
|
+
stand alone.
|
|
54
|
+
- `guides` is how the app works, as markdown by topic, each starting with a `# Title` line:
|
|
55
|
+
`import orders from "./guides/orders.md?raw"`. Only the titles ride on every request; the
|
|
56
|
+
model reads a guide when a question touches it. Write them from the user's view: the rules,
|
|
57
|
+
who may do what, what happens next. This is what lets a new user ask anything about the app.
|
|
26
58
|
- Build every chat with `createLayoutChatHook(chatFn)` from `wcz-layout/hooks`. Its labels are
|
|
27
59
|
`Layout.Chat.*` keys: copy the `Layout.Chat` object from wcz-layout's `src/lib/locales/*.json`
|
|
28
60
|
into each of the app's locale files, or the chat shows raw keys.
|
|
@@ -31,48 +63,45 @@ metadata:
|
|
|
31
63
|
`options.chat`. It shows for a signed-in user, opens from the app bar and mounts on the first
|
|
32
64
|
open. From `lg` up it docks beside the page and remembers its width and whether it is open;
|
|
33
65
|
below `lg` it covers the page right of the navigation rail, opens only from the button and
|
|
34
|
-
closes when a page opens, so a link, `navigate` or the rail shows the page. A chat page of its
|
|
35
|
-
parent with a height (e.g. `Fullscreen`). `LayoutChat` takes `sx` for its root,
|
|
36
|
-
it has none of its own.
|
|
66
|
+
closes when a page opens, so a link, `navigate` or the rail shows the page. A chat page of its
|
|
67
|
+
own sits in a parent with a height (e.g. `Fullscreen`). `LayoutChat` takes `sx` for its root,
|
|
68
|
+
e.g. a background; it has none of its own.
|
|
69
|
+
- The chat brings these without any app code. Never build them again:
|
|
70
|
+
- Files: the user drops them anywhere on the chat, pastes them or picks them. They travel in
|
|
71
|
+
the message, never to the file service, and the model reads them as they are: images, PDF,
|
|
72
|
+
Word, Excel, PowerPoint, CSV and text, up to 10 MB each. Nothing is parsed in the app. Of a
|
|
73
|
+
spreadsheet the model sees the first 1000 rows of each sheet.
|
|
74
|
+
- A message sent while a reply streams waits in a queue above the input, where it can be
|
|
75
|
+
cancelled.
|
|
76
|
+
- The conversation survives a reload and ends with the tab (`sessionStorage`, per user).
|
|
77
|
+
- Each tool shows as one line with its name, and a program with the functions it calls.
|
|
37
78
|
- Every chat has these client tools built in: `show_ui` (the model renders MUI components, and
|
|
38
79
|
charts: a `Chart` node with TanStack Charts marks as children, their official options as
|
|
39
|
-
props), `ask_user` (asks with an MUI form), `get_user` (the signed-in user), `set_app_theme`
|
|
40
|
-
dark or system), `navigate` (opens one of the app's pages, listed from its route tree,
|
|
41
|
-
leaves a page whose record was just deleted), `get_time` (the user's current time and
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
types and presses keys, and never answers a `useDialogs` confirmation). Never
|
|
45
|
-
again.
|
|
46
|
-
server function only merges them: `tools: mergeAgentTools(serverTools, tools)`. It must also
|
|
47
|
-
forward `parentRunId` and `resume`, or tool results and approvals never continue the run.
|
|
48
|
-
- The chat sends the page the user is on as AG-UI context. Put it in the prompt: each
|
|
49
|
-
`aguiContext` item becomes a `"<description>: <value>"` line in `systemPrompts` (see the example).
|
|
50
|
-
- Data and writes are server tools (`toolDefinition(...).server(...)`) in `serverTools` that
|
|
51
|
-
call the app's own server functions, `deleteOrder({ data: id })`: called on the server they run
|
|
52
|
-
in the same request, with the screens' middleware, validation and permission checks. Never
|
|
53
|
-
reimplement a server function for a tool. After a write,
|
|
54
|
-
`context?.emitCustomEvent("invalidate", { queryKey })` makes the chat invalidate that query, so
|
|
55
|
-
open screens refetch.
|
|
56
|
-
- Only tools that delete get `needsApproval: true`: the chat asks "Are you sure?" (Cancel /
|
|
57
|
-
Confirm) before they run, so the prompt tells the model to say first what it will delete.
|
|
58
|
-
Creating and changing run straight away, and the model says what it did.
|
|
59
|
-
- Give feature tools `lazy: true` and pass `lazyToolsConfig: { includeDescription:
|
|
60
|
-
"first-sentence" }` to `chat()`: the model sees names and first sentences, and loads a feature's
|
|
61
|
-
schemas only when a request needs them. Write each description's first sentence to stand alone.
|
|
62
|
-
Pass `agentLoopStrategy: maxIterations(20)` too: the default 5 turns end a run without a reply
|
|
63
|
-
once discovering, looking up and saving add up.
|
|
80
|
+
props), `ask_user` (asks with an MUI form), `get_user` (the signed-in user), `set_app_theme`
|
|
81
|
+
(light, dark or system), `navigate` (opens one of the app's pages, listed from its route tree,
|
|
82
|
+
and leaves a page whose record was just deleted), `get_time` (the user's current time and
|
|
83
|
+
zone), and `read_page`, `click`, `fill` and `press_key` (the model uses the page the user is on
|
|
84
|
+
as they would: it reads the address, the text, the numbered controls and the one the user was
|
|
85
|
+
last in, clicks, types and presses keys, and never answers a `useDialogs` confirmation). Never
|
|
86
|
+
define them again.
|
|
64
87
|
- The page tools read what a screen reader would, so a page the model can use has a name on
|
|
65
88
|
every control: a `Tooltip` title or `aria-label` on each icon button, a label on each field,
|
|
66
89
|
and a button, link or `CardActionArea` for anything clickable. Deletes confirm through
|
|
67
90
|
`useDialogs`, which the model never clicks.
|
|
68
91
|
- Other browser actions are client tools:
|
|
69
92
|
`useLayoutChat({ threadId, tools: [def.client(run)] })`, with `run` using the screen's hooks.
|
|
70
|
-
-
|
|
71
|
-
|
|
93
|
+
- One-off calls (a translation, a typed answer, reading a document) are `chat()` with
|
|
94
|
+
`adapter: await chatAdapter("gpt-5.5")` from `wcz-layout/ai`, created per request in a server
|
|
95
|
+
function (`src/server/...`): it reads server env and tokens, and sends the app token and the
|
|
96
|
+
subscription key itself. It is the one adapter for everything, files included: a `document`
|
|
97
|
+
part with `source: { type: "data", value: base64, mimeType }` and `metadata: { filename }`
|
|
98
|
+
reaches the model as the file itself (PDF, Word, Excel, PowerPoint, CSV, text). Never build
|
|
99
|
+
an OpenAI adapter in the app: `createOpenaiChat` (Responses API) fails on follow-ups with
|
|
100
|
+
`400 invalid_encrypted_content`, because the gateway load-balances Azure deployments, and
|
|
101
|
+
TanStack's own Chat Completions adapter refuses documents.
|
|
72
102
|
- Structured output (one typed object, e.g. a generated document) stays raw `useChat` with
|
|
73
|
-
`outputSchema` and `partial`, not the chat.
|
|
74
|
-
|
|
75
|
-
`<Markdown>` from `@tanstack/markdown/react`.
|
|
103
|
+
`outputSchema` and `partial`, not the chat. Render streamed text outside the chat with
|
|
104
|
+
`@tanstack/markdown` (install if missing): `<Markdown>` from `@tanstack/markdown/react`.
|
|
76
105
|
|
|
77
106
|
## Example
|
|
78
107
|
|
|
@@ -82,22 +111,39 @@ AI_BASE_URL: z.url(),
|
|
|
82
111
|
AI_SUBSCRIPTION_KEY: z.string(),
|
|
83
112
|
|
|
84
113
|
// src/server/actions/assistant.ts
|
|
85
|
-
import {
|
|
86
|
-
chat,
|
|
87
|
-
chatParamsFromRequestBody,
|
|
88
|
-
maxIterations,
|
|
89
|
-
mergeAgentTools,
|
|
90
|
-
toServerSentEventsResponse,
|
|
91
|
-
toolDefinition,
|
|
92
|
-
} from "@tanstack/ai";
|
|
114
|
+
import { toolDefinition } from "@tanstack/ai";
|
|
93
115
|
import type { RunAgentInput } from "@tanstack/ai/client";
|
|
94
116
|
import { createServerFn } from "@tanstack/react-start";
|
|
117
|
+
import { layoutChat } from "wcz-layout/ai";
|
|
95
118
|
import { authMiddleware } from "wcz-layout/middleware";
|
|
96
|
-
import { chatAdapter } from "wcz-layout/utils";
|
|
97
119
|
import z from "zod";
|
|
98
|
-
import {
|
|
120
|
+
import { OrderSchema } from "~/lib/schemas/order";
|
|
121
|
+
import orders from "../guides/orders.md?raw";
|
|
122
|
+
import { deleteOrder, insertOrder, selectOrders } from "./order"; // the screens' server functions
|
|
99
123
|
|
|
100
|
-
const
|
|
124
|
+
const SYSTEM_PROMPT =
|
|
125
|
+
"You are the assistant in Orders, the application in which departments order material. " +
|
|
126
|
+
"Link an order to its page with a markdown link: [number](/orders/<id>).";
|
|
127
|
+
|
|
128
|
+
const orderTools = [
|
|
129
|
+
toolDefinition({
|
|
130
|
+
name: "list_orders",
|
|
131
|
+
description: "Every order the user can see, with its lines and state.",
|
|
132
|
+
inputSchema: z.object({}),
|
|
133
|
+
outputSchema: OrderSchema.array(),
|
|
134
|
+
lazy: true,
|
|
135
|
+
}).server(() => selectOrders()),
|
|
136
|
+
toolDefinition({
|
|
137
|
+
name: "create_order",
|
|
138
|
+
description: "Create an order. It needs a supplier and at least one line.",
|
|
139
|
+
inputSchema: OrderSchema.omit({ id: true }),
|
|
140
|
+
lazy: true,
|
|
141
|
+
}).server(async (order, context) => {
|
|
142
|
+
const id = crypto.randomUUID();
|
|
143
|
+
await insertOrder({ data: { ...order, id } });
|
|
144
|
+
context?.emitCustomEvent("invalidate", { queryKey: ["orders"] });
|
|
145
|
+
return { id, page: `/orders/${id}` };
|
|
146
|
+
}),
|
|
101
147
|
toolDefinition({
|
|
102
148
|
name: "delete_order",
|
|
103
149
|
description: "Delete one of the user's orders.",
|
|
@@ -114,28 +160,15 @@ const orderTools = () => [
|
|
|
114
160
|
export const assistant = createServerFn({ method: "POST" })
|
|
115
161
|
.validator(z.custom<RunAgentInput>())
|
|
116
162
|
.middleware([authMiddleware()])
|
|
117
|
-
.handler(
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
resume,
|
|
127
|
-
systemPrompts: [
|
|
128
|
-
SYSTEM_PROMPT,
|
|
129
|
-
...aguiContext.map(({ description, value }) => `${description}: ${value}`),
|
|
130
|
-
],
|
|
131
|
-
messages,
|
|
132
|
-
tools: mergeAgentTools(orderTools(), tools),
|
|
133
|
-
lazyToolsConfig: { includeDescription: "first-sentence" },
|
|
134
|
-
agentLoopStrategy: maxIterations(20),
|
|
135
|
-
abortController,
|
|
136
|
-
});
|
|
137
|
-
return toServerSentEventsResponse(stream, { abortController });
|
|
138
|
-
});
|
|
163
|
+
.handler(({ data, context: { user } }) =>
|
|
164
|
+
layoutChat({
|
|
165
|
+
data,
|
|
166
|
+
user,
|
|
167
|
+
systemPrompts: [SYSTEM_PROMPT],
|
|
168
|
+
tools: orderTools,
|
|
169
|
+
guides: { orders },
|
|
170
|
+
}),
|
|
171
|
+
);
|
|
139
172
|
```
|
|
140
173
|
|
|
141
174
|
```tsx
|
|
@@ -50,9 +50,13 @@ export const scopes = {
|
|
|
50
50
|
|
|
51
51
|
From `wcz-layout/auth`, server-only (call inside a server function or server route):
|
|
52
52
|
|
|
53
|
-
- `getAccessToken(scopeKey)` — delegated token for the
|
|
54
|
-
|
|
55
|
-
|
|
53
|
+
- `getAccessToken(scopeKey)` — delegated token for the user behind the request: minted from
|
|
54
|
+
their session, or, when a sibling service calls with an Entra user token as Bearer, exchanged
|
|
55
|
+
for it on behalf of that user (OBO). OBO needs this app's registration to hold the delegated
|
|
56
|
+
permission for the downstream API, with admin consent; Cognito has no OBO, so an AWS Bearer
|
|
57
|
+
caller or an app token counts as no user and throws. An expired session clears the cookie and
|
|
58
|
+
throws a 401 `Response`. `createApi` services use it whenever there is a user, and fall back
|
|
59
|
+
to `getAppToken` otherwise.
|
|
56
60
|
- `getAppToken(scopeKey)` — app-only Entra token (client credentials, `<resource>/.default`),
|
|
57
61
|
cached in memory. For background jobs and calls with no user.
|
|
58
62
|
- Downstream APIs must trust both issuers to accept AWS users; Cognito tokens have no `aud`
|
|
@@ -28,3 +28,7 @@ Note that there is one catch that in that. This project is public npm library an
|
|
|
28
28
|
# Material UI 10
|
|
29
29
|
|
|
30
30
|
One of the changes (instead of "react-number-format"): https://mui.com/material-ui/react-number-field/
|
|
31
|
+
|
|
32
|
+
# Export
|
|
33
|
+
|
|
34
|
+
Remove "src/exports/ai.ts" and put it into utils
|
package/skills/services/SKILL.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: services
|
|
3
|
-
description: "Use when a feature needs a built-in wcz-layout backend service: file upload, download, thumbnails; approval requests, approvers and flows; PeopleSoft employee, manager, department lookups; or
|
|
3
|
+
description: "Use when a feature needs a built-in wcz-layout backend service: file upload, download, thumbnails; approval requests, approvers and flows; PeopleSoft employee, manager, department lookups; sending email; or AI features: translating text into several languages with language detection, and extracting fields from an uploaded PDF or image. Also when an app calls another downstream REST API that wcz-layout has no service for."
|
|
4
4
|
metadata:
|
|
5
5
|
type: integration
|
|
6
6
|
library: wcz-layout
|
|
@@ -26,9 +26,43 @@ You can read about each service in the links below. Services are categorized as
|
|
|
26
26
|
|
|
27
27
|
## Services
|
|
28
28
|
|
|
29
|
-
| Service | File | Summary
|
|
30
|
-
| ---------- | ----------------------------------- |
|
|
31
|
-
| file | [file.md](docs/file.md) | File metadata, thumbnails, binary download/open, upload, update, delete
|
|
32
|
-
| approval | [approval.md](docs/approval.md) | Approval request lifecycle, approvers, flows, statuses, step results
|
|
33
|
-
| peoplesoft | [peoplesoft.md](docs/peoplesoft.md) | Employee, manager, department, and company general manager lookups
|
|
34
|
-
| email | [email.md](docs/email.md) | Server-only email sending with optional file attachment references
|
|
29
|
+
| Service | File | Summary |
|
|
30
|
+
| ---------- | ----------------------------------- | ------------------------------------------------------------------------ |
|
|
31
|
+
| file | [file.md](docs/file.md) | File metadata, thumbnails, binary download/open, upload, update, delete |
|
|
32
|
+
| approval | [approval.md](docs/approval.md) | Approval request lifecycle, approvers, flows, statuses, step results |
|
|
33
|
+
| peoplesoft | [peoplesoft.md](docs/peoplesoft.md) | Employee, manager, department, and company general manager lookups |
|
|
34
|
+
| email | [email.md](docs/email.md) | Server-only email sending with optional file attachment references |
|
|
35
|
+
| layout | [layout.md](docs/layout.md) | Layout app AI: translation with language detection, file data extraction |
|
|
36
|
+
|
|
37
|
+
## Custom API
|
|
38
|
+
|
|
39
|
+
When the app needs a downstream REST API that no service above covers, build the client with
|
|
40
|
+
`createApi` from `wcz-layout/data/server`. It resolves the base URL from env, attaches the
|
|
41
|
+
signed-in user's token for the scope and turns error responses into `Error(message)`. It is
|
|
42
|
+
server-only: call it inside a server function handler, never at module scope.
|
|
43
|
+
|
|
44
|
+
1. `src/env.ts`: add `MY_API_BASE_URL: z.url()` to `serverEnv` (the key must contain `BASE_URL`).
|
|
45
|
+
2. `src/lib/auth/scopes.ts`: add `myApi: "api://wistron.com/my-api/access_as_user"`.
|
|
46
|
+
3. `src/lib/schemas/<name>.ts`: Zod input schemas and response models.
|
|
47
|
+
4. `src/server/actions/<name>.ts`: one server function per endpoint, gated with `authMiddleware`
|
|
48
|
+
(the token belongs to the signed-in user); see **server-functions**.
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import { createServerFn } from "@tanstack/react-start";
|
|
52
|
+
import { createApi } from "wcz-layout/data/server";
|
|
53
|
+
import { authMiddleware } from "wcz-layout/middleware";
|
|
54
|
+
import { MyModelSchema, type MyModel } from "~/lib/schemas/inventory";
|
|
55
|
+
|
|
56
|
+
const myApi = () => createApi({ baseURL: "MY_API_BASE_URL", scopeKey: "myApi" });
|
|
57
|
+
|
|
58
|
+
export const getItem = createServerFn({ method: "GET" })
|
|
59
|
+
.validator(MyModelSchema)
|
|
60
|
+
.middleware([authMiddleware()])
|
|
61
|
+
.handler(async ({ data }) => {
|
|
62
|
+
const api = await myApi();
|
|
63
|
+
const { data: item } = await api.get<MyModel>(`/items/${encodeURIComponent(data.id)}`);
|
|
64
|
+
return item;
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Wrap reads in `queryOptions` and writes in `mutationOptions`, the same shape as the built-in client exports.
|