@cloudparse/up-backoffice-sdk 0.0.0-stage → 0.1.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.
Files changed (38) hide show
  1. package/README.md +59 -2
  2. package/claude-plugin/.claude-plugin/marketplace.json +17 -0
  3. package/claude-plugin/.claude-plugin/plugin.json +21 -0
  4. package/claude-plugin/README.md +44 -0
  5. package/claude-plugin/commands/new-backoffice-plugin.md +18 -0
  6. package/claude-plugin/scripts/scaffold.mjs +186 -0
  7. package/claude-plugin/sdk-version.json +1 -0
  8. package/claude-plugin/skills/up-backoffice-plugin-builder/SKILL.md +40 -0
  9. package/claude-plugin/skills/up-backoffice-plugin-builder/references/plugin-checklist.md +14 -0
  10. package/claude-plugin/skills/up-backoffice-plugin-builder/references/recipes.md +147 -0
  11. package/claude-plugin/skills/up-backoffice-plugin-builder/references/rules-and-pitfalls.md +25 -0
  12. package/claude-plugin/skills/up-backoffice-plugin-builder/references/sdk-api.md +91 -0
  13. package/claude-plugin/templates/plugin/AGENTS.md +9 -0
  14. package/claude-plugin/templates/plugin/CLAUDE.md +1 -0
  15. package/claude-plugin/templates/plugin/biome.json +64 -0
  16. package/claude-plugin/templates/plugin/gitignore +2 -0
  17. package/claude-plugin/templates/plugin/package.json +31 -0
  18. package/claude-plugin/templates/plugin/src/features/__PLUGIN_ID__/components/AdminPage.tsx +143 -0
  19. package/claude-plugin/templates/plugin/src/features/__PLUGIN_ID__/types.ts +17 -0
  20. package/claude-plugin/templates/plugin/src/index.tsx +22 -0
  21. package/claude-plugin/templates/plugin/src/services/__PLUGIN_ID__.ts +26 -0
  22. package/claude-plugin/templates/plugin/src/styles.css +1 -0
  23. package/claude-plugin/templates/plugin/tsconfig.json +18 -0
  24. package/claude-plugin/templates/plugin/vite.config.ts +12 -0
  25. package/dist/chunk-PSBYWSHV.js +17 -0
  26. package/dist/chunk-PSBYWSHV.js.map +1 -0
  27. package/dist/contract-88aU9QZl.d.ts +122 -0
  28. package/dist/host.d.ts +33 -0
  29. package/dist/host.js +140 -0
  30. package/dist/host.js.map +1 -0
  31. package/dist/index.d.ts +564 -0
  32. package/dist/index.js +2549 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/plugin.css +9 -0
  35. package/dist/theme.css +41 -0
  36. package/dist/vite.d.ts +15 -0
  37. package/dist/vite.js +74 -0
  38. package/package.json +96 -4
@@ -0,0 +1,91 @@
1
+ # @cloudparse/up-backoffice-sdk — API
2
+
3
+ Icons: every `icon` prop takes any `ComponentType<{ className?: string }>` (lucide icons included).
4
+
5
+ Import everything a plugin uses from `@cloudparse/up-backoffice-sdk`. `/host` is for the backoffice only, `/vite` for the build config only. The typings in `node_modules/@cloudparse/up-backoffice-sdk/dist/index.d.ts` are the source of truth.
6
+
7
+ ## Plugin contract
8
+
9
+ | Export | Signature / shape |
10
+ |---|---|
11
+ | `definePlugin(def)` | `def: { id: string /* [a-z][a-z0-9-]* */, name: string, description?: string, icon?: IconComponent, pages: PluginPage[], styles?: string }` → module the host loads. Default-export it from `src/index.tsx`. |
12
+ | `PluginPage` | `{ path: string /* "" = root, no leading slash */, title: string, description?: string, icon?: IconComponent, badge?: string, component: ComponentType }` |
13
+ | `usePluginHost()` | Inside a page: `PluginHost` = `{ application: { uuid, name, httpBackendUrl, wsBackendUrl, iconUrl }, user: { uuid, fullName, admin } \| null, hubApi, miniappApi, getScopeToken(), basePath, navigate(pagePath), contractVersion }` |
14
+ | `miniappApi` | `HttpClient` on the application's `httpBackendUrl` (ends with `/api/v1`), admin scoped token attached and refreshed by the host. Usable from module-level services once a page is mounted. |
15
+ | `hubApi` | `HttpClient` on the Up hub backend with the admin session (paths start with `/api/v1/...`). |
16
+ | `getScopeToken()` | `Promise<string \| null>`: the current admin scoped token (e.g. for a GraphQL playground "token" state). |
17
+ | `HttpClient` | `get<T>(path, { params? })`, `post<T>(path, body?, opts?)`, `put`, `patch`, `delete<T>(path)`, `getBlob(path)`, `getText(path)`, `baseUrl`. JSON by default, `FormData` bodies sent as multipart. Errors throw `ApiError`. |
18
+ | `ApiService` | `new ApiService(baseUrl)` + `setToken`, `setTokenLoader`, `setUnauthorizedCallback`: the `HttpClient` implementation (hosts and tools; plugins use `miniappApi`/`hubApi`). |
19
+ | `PLUGIN_CONTRACT_VERSION` | Contract version stamped by `definePlugin`; the host refuses another one. |
20
+ | `ApiError`, `isApiError(err)` | `{ status: number, message, data }`. Always test with `isApiError`, never `instanceof`. |
21
+
22
+ ## Layout
23
+
24
+ | Component | Props |
25
+ |---|---|
26
+ | `PageHeader` | `title, icon?, description?, eyebrow?, actions?: ReactNode, bordered?` — the page `h1`. |
27
+ | `SectionHeader` | `title, icon?, description?, actions?, variant?: "section" \| "label"` — `h2` or the small uppercase label above a list. |
28
+ | `Card` | `padding?: "lg" \| "md" \| "none", interactive?, variant?: "glass" \| "solid"` + div props. |
29
+ | `StatTile` | `icon, label, value, hint?, onClick?, active?` — KPI tile; with `onClick` it is a button (tab selector). |
30
+ | `AuthStatusBadge` | `authError: boolean` — "Active token" / "Auth error" pill for `PageHeader.actions`. |
31
+ | `Badge` | `variant?: "primary" \| "accent" \| "success" \| "warning" \| "error" \| "muted" \| "outline"` + span props. |
32
+ | `Banner` | `message: string, variant: "success" \| "warning" \| "error", onClose?` — every error/success message. |
33
+ | `EmptyState` | `icon, title, description?, action?` |
34
+ | `LoadingState` | `size?: "sm" \| "md" \| "lg", padding?: "none" \| "sm" \| "md" \| "lg", label?` — the only loading indicator. |
35
+
36
+ ## Tables and lists
37
+
38
+ | Component | Props |
39
+ |---|---|
40
+ | `TableContainer` | div props — card + horizontal scroll. |
41
+ | `Table`, `TableHead`, `TableBody`, `TableRow` | native element props. Put a plain `<tr>` inside `TableHead`. |
42
+ | `TableHeaderCell`, `TableCell` | `align?: "left" \| "center" \| "right"` + th/td props. |
43
+ | `TableEmpty` | `colSpan, icon, title, description?, action?` — empty row. |
44
+ | `IconButton` | `icon, label /* aria-label + title */, variant?: "default" \| "danger" \| "success", isLoading?, spin? /* spinning icon, e.g. refresh */` + button props. |
45
+ | `RowActions` | `children` — right-aligned group of `IconButton`s. |
46
+ | `LoadMoreButton` | `onClick, loading?, label?` — cursor pagination. |
47
+ | `Pagination` | `page, totalPages, onPageChange` — page-numbered lists only. |
48
+ | `CopyableUuid` | `uuid` — mono UUID with copy button. |
49
+ | `SearchInput` | `value, onChange(value), placeholder?` + input props. |
50
+ | `Tabs` | `items: { value, label, icon?, count? }[], value, onChange(value), variant?: "underline" \| "pills", panelIdPrefix?, label?` — tab strip with Arrow/Home/End keys; render the active panel yourself (`role="tabpanel"`, id `${panelIdPrefix}-${value}`, `aria-labelledby` `${panelIdPrefix}-tab-${value}`). |
51
+
52
+ ## Forms and modals
53
+
54
+ | Component | Props |
55
+ |---|---|
56
+ | `Modal` | `title, description?, icon?, onClose, size?: "md" \| "lg" \| "xl" \| "2xl" \| "4xl" \| "5xl" \| "6xl", align?: "center" \| "top", footer?, closeOnBackdrop? /* default false */, dismissible? /* default true; pass !isSubmitting */, children` — mount only while open; Escape closes only the topmost modal (never while a `Select` menu is open or `dismissible` is false); named by its title (`aria-labelledby`); first field focused; no portal (keeps plugin styles). |
57
+ | `ModalActions` | `onCancel, submitLabel, cancelLabel?, isSubmitting?, submitDisabled?, submitType?: "submit" \| "button", onSubmit?, variant?: "primary" \| "danger"` |
58
+ | `ConfirmModal` | `title, description, confirmLabel?, cancelLabel?, isConfirming?, variant?: "danger" \| "primary", onConfirm, onCancel` — `alertdialog`; Escape cancels it (only it, even inside a `Modal`). |
59
+ | `Input` | `label?, error?, icon? /* leading icon */` + input props; id generated unless `id` is passed. |
60
+ | `Textarea` | `label?, error?` + textarea props. |
61
+ | `Select` | `value, onChange(value), options: { value, label, disabled? }[], placeholder?, disabled?, className?, id?` — searchable, always opens downward; pass a `className` for the field look. |
62
+ | `FieldLabel` | label props — for fields that are not `Input`/`Textarea`. |
63
+ | `Switch` | `checked, onChange(checked), label /* aria-label */, disabled?, tone?: "primary" \| "success" \| "error"` |
64
+ | `SettingRow` | `label, description?, control: ReactNode` — row with a `Switch`. |
65
+ | `ImageUpload` | `previewUrl?, onFile(file), onError?(message), label?, uploading?, readOnly?, readOnlyHint?, onRemove?, allowSvg?, fit?: "cover" \| "contain", aspect?: "wide" \| "square" \| "banner" \| "compact"` — WebP only (`allowSvg` adds SVG for icons). |
66
+ | `MarkdownEditor` | `label, value, onChange, placeholder?, description?, minHeight? /* Tailwind class, e.g. "min-h-36" */, maxHeight? /* e.g. "max-h-75" */, required?` |
67
+ | `Button` | `variant?: "primary" \| "secondary" \| "danger" \| "ghost", size?: "sm" \| "md" \| "lg", isLoading?` + button props. Never override its text size. |
68
+
69
+ ## Delete flow
70
+
71
+ | Export | Use |
72
+ |---|---|
73
+ | `DangerZone` | `inputValue, onInputChange, onConfirmDelete, isDeleting, entityLabel?, customDescription?, id?, inputLabel?, inputPlaceholder?` |
74
+ | `useDangerZoneDelete({ onDelete(uuid), resolveName(uuid) => string \| null, entityLabel, id? })` | Returns `{ request(uuid), dangerZoneProps, confirmModal, error, clearError }`. Row delete buttons call `request(uuid)`; render `<DangerZone {...dangerZoneProps} />`, `{confirmModal}` and a `Banner` for `error`. |
75
+
76
+ ## Dev tools and helpers
77
+
78
+ | Export | Use |
79
+ |---|---|
80
+ | `GraphQLPlayground` | `presets: { name, description, query, variables? }[], onExecute(query, variables), title?, description?, hasToken?, authError?, onConfigureToken?` |
81
+ | `RemoteImage` | `src` + img props — image with an error placeholder. |
82
+ | `useCopyToClipboard(resetMs?)` | `{ copied, copy(text) }` |
83
+ | `useModalLock({ onEscape? })` | Callback ref: scroll lock + focus trap for a custom overlay; nested locks stack (topmost handles Tab/Escape). Prefer `Modal`. |
84
+ | `cn(...classes)` | clsx + tailwind-merge. |
85
+ | `dayjs` | dayjs with `localizedFormat` and `relativeTime` (`.format("LLL")`, `.fromNow()`). |
86
+ | `assertWebp(file)`, `isWebp(file)`, `isSvg(file)`, `WEBP_ERROR_MESSAGE`, `WEBP_OR_SVG_ERROR_MESSAGE` | Image policy for custom upload code. |
87
+ | `parseMarkdown(md)`, `stripMarkdown(md)`, `insertMarkdown(...)`, `encodeBase64`, `decodeBase64` | `parseMarkdown` output is sanitized (DOMPurify). |
88
+
89
+ ## Build
90
+
91
+ `backofficePlugin()` from `@cloudparse/up-backoffice-sdk/vite`: add it after `react()` and `tailwindcss()` in `vite.config.ts`. Stylesheet: `@import "@cloudparse/up-backoffice-sdk/plugin.css";`.
@@ -0,0 +1,9 @@
1
+ # __PLUGIN_NAME__ backoffice plugin
2
+
3
+ Backoffice plugin of the __PLUGIN_NAME__ mini-app: its admin dashboards, loaded at runtime by the Up backoffice. Built with `@cloudparse/up-backoffice-sdk`.
4
+
5
+ - Entry: `src/index.tsx` default-exports `definePlugin({ id: "__PLUGIN_ID__", name, pages, styles })`.
6
+ - This is backoffice admin code: use the SDK UI kit (`PageHeader`, `Modal`, `Table`, `DangerZone` + `useDangerZoneDelete`, ...), English UI text, Tailwind theme tokens, no arbitrary values, no `any`, never `alert()`/`confirm()`.
7
+ - Backend calls go through `miniappApi` (base URL = the application's `httpBackendUrl`, already ending with `/api/v1`; admin scoped token minted by the host). Check errors with `isApiError()`, never `instanceof ApiError`.
8
+ - `npm run build` -> `dist/plugin.js` (one ES module, React provided by the backoffice). Publish it to the hub backend: `POST /api/v1/admin/applications/<applicationUuid>/backoffice-plugin/artifacts` (admin token + `X-App-Secret`), or locally with `sp task backoffice plugins`.
9
+ - Before finishing: `npm run lint && npm run build`.
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1,64 @@
1
+ {
2
+ "$schema": "https://biomejs.dev/schemas/2.5.15/schema.json",
3
+ "assist": {
4
+ "actions": {
5
+ "source": {
6
+ "organizeImports": "on",
7
+ "useSortedAttributes": "on",
8
+ "useSortedKeys": "on",
9
+ "useSortedProperties": "on"
10
+ }
11
+ },
12
+ "includes": [
13
+ "**/*.js",
14
+ "**/*.jsx",
15
+ "**/*.ts",
16
+ "**/*.tsx",
17
+ "!**/*.json",
18
+ "next.config.*.ts"
19
+ ]
20
+ },
21
+ "css": {
22
+ "parser": {
23
+ "tailwindDirectives": true
24
+ }
25
+ },
26
+ "files": {
27
+ "ignoreUnknown": true,
28
+ "includes": ["**", "!node_modules", "!dist"]
29
+ },
30
+ "formatter": {
31
+ "enabled": true,
32
+ "indentStyle": "space",
33
+ "indentWidth": 2
34
+ },
35
+ "linter": {
36
+ "domains": {
37
+ "react": "recommended"
38
+ },
39
+ "enabled": true,
40
+ "rules": {
41
+ "a11y": {
42
+ "noLabelWithoutControl": "off",
43
+ "noNoninteractiveTabindex": "off",
44
+ "noStaticElementInteractions": "off",
45
+ "noSvgWithoutTitle": "off",
46
+ "useButtonType": "off",
47
+ "useKeyWithClickEvents": "off"
48
+ },
49
+ "complexity": {
50
+ "noImportantStyles": "off"
51
+ },
52
+ "preset": "recommended",
53
+ "suspicious": {
54
+ "noArrayIndexKey": "warn",
55
+ "noUnknownAtRules": "off"
56
+ }
57
+ }
58
+ },
59
+ "vcs": {
60
+ "clientKind": "git",
61
+ "enabled": true,
62
+ "useIgnoreFile": true
63
+ }
64
+ }
@@ -0,0 +1,2 @@
1
+ node_modules
2
+ dist
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "__PACKAGE_NAME__",
3
+ "private": true,
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "description": "Backoffice plugin of the __PLUGIN_NAME__ mini-app, loaded at runtime by up/backoffice",
7
+ "scripts": {
8
+ "build": "tsc --noEmit && vite build",
9
+ "typecheck": "tsc --noEmit",
10
+ "lint": "biome check . --max-diagnostics 10000 --diagnostic-level error",
11
+ "lint.fix": "biome check --write . --max-diagnostics 10000 --diagnostic-level error"
12
+ },
13
+ "dependencies": {
14
+ "@cloudparse/up-backoffice-sdk": "^__SDK_VERSION__",
15
+ "jotai": "^2.20.3",
16
+ "lucide-react": "^1.55.0"
17
+ },
18
+ "devDependencies": {
19
+ "@biomejs/biome": "^2.5.15",
20
+ "@tailwindcss/vite": "^4.3.3",
21
+ "@types/node": "^26.6.5",
22
+ "@types/react": "^19.3.0",
23
+ "@types/react-dom": "^19.3.0",
24
+ "@vitejs/plugin-react": "^6.1.2",
25
+ "react": "^19.2.4",
26
+ "react-dom": "^19.2.4",
27
+ "tailwindcss": "^4.3.3",
28
+ "typescript": "^5.9.3",
29
+ "vite": "^8.3.4"
30
+ }
31
+ }
@@ -0,0 +1,143 @@
1
+ import {
2
+ AuthStatusBadge,
3
+ Banner,
4
+ CopyableUuid,
5
+ DangerZone,
6
+ dayjs,
7
+ IconButton,
8
+ isApiError,
9
+ LoadingState,
10
+ LoadMoreButton,
11
+ PageHeader,
12
+ RowActions,
13
+ Table,
14
+ TableBody,
15
+ TableCell,
16
+ TableContainer,
17
+ TableEmpty,
18
+ TableHead,
19
+ TableHeaderCell,
20
+ TableRow,
21
+ useDangerZoneDelete,
22
+ } from "@cloudparse/up-backoffice-sdk";
23
+ import type { Item } from "@plugin/features/__PLUGIN_ID__/types";
24
+ import { __PLUGIN_CAMEL__Service } from "@plugin/services/__PLUGIN_ID__";
25
+ import { Inbox, LayoutDashboard, Trash2 } from "lucide-react";
26
+ import { useCallback, useEffect, useState } from "react";
27
+
28
+ export function AdminPage() {
29
+ const [items, setItems] = useState<Item[]>([]);
30
+ const [nextCursor, setNextCursor] = useState<string | null>(null);
31
+ const [loading, setLoading] = useState(true);
32
+ const [loadingMore, setLoadingMore] = useState(false);
33
+ const [error, setError] = useState<string | null>(null);
34
+ const [authError, setAuthError] = useState(false);
35
+
36
+ const fetchItems = useCallback(async (cursor?: string) => {
37
+ if (cursor) setLoadingMore(true);
38
+ else setLoading(true);
39
+ setError(null);
40
+ try {
41
+ const page = await __PLUGIN_CAMEL__Service.list(cursor);
42
+ setItems((prev) => (cursor ? [...prev, ...page.items] : page.items));
43
+ setNextCursor(page.nextCursor);
44
+ setAuthError(false);
45
+ } catch (err) {
46
+ if (isApiError(err) && (err.status === 401 || err.status === 403)) {
47
+ setAuthError(true);
48
+ }
49
+ setError((err as Error).message);
50
+ } finally {
51
+ setLoading(false);
52
+ setLoadingMore(false);
53
+ }
54
+ }, []);
55
+
56
+ useEffect(() => {
57
+ fetchItems();
58
+ }, [fetchItems]);
59
+
60
+ const deletion = useDangerZoneDelete({
61
+ entityLabel: "an item",
62
+ onDelete: async (uuid) => {
63
+ await __PLUGIN_CAMEL__Service.delete(uuid);
64
+ await fetchItems();
65
+ },
66
+ resolveName: (uuid) =>
67
+ items.find((item) => item.uuid === uuid)?.name ?? null,
68
+ });
69
+
70
+ return (
71
+ <div className="space-y-8">
72
+ <PageHeader
73
+ actions={<AuthStatusBadge authError={authError} />}
74
+ bordered
75
+ description="Manage the __PLUGIN_NAME__ items."
76
+ icon={LayoutDashboard}
77
+ title="__PLUGIN_NAME__ management"
78
+ />
79
+
80
+ {error && <Banner message={error} variant="error" />}
81
+ {deletion.error && (
82
+ <Banner
83
+ message={deletion.error}
84
+ onClose={deletion.clearError}
85
+ variant="error"
86
+ />
87
+ )}
88
+
89
+ {loading ? (
90
+ <LoadingState />
91
+ ) : (
92
+ <TableContainer>
93
+ <Table>
94
+ <TableHead>
95
+ <tr>
96
+ <TableHeaderCell>Name</TableHeaderCell>
97
+ <TableHeaderCell>Created</TableHeaderCell>
98
+ <TableHeaderCell align="right">Actions</TableHeaderCell>
99
+ </tr>
100
+ </TableHead>
101
+ <TableBody>
102
+ {items.length === 0 ? (
103
+ <TableEmpty colSpan={3} icon={Inbox} title="No items yet" />
104
+ ) : (
105
+ items.map((item) => (
106
+ <TableRow key={item.uuid}>
107
+ <TableCell>
108
+ <p className="font-bold">{item.name}</p>
109
+ <CopyableUuid uuid={item.uuid} />
110
+ </TableCell>
111
+ <TableCell className="text-xs text-muted-foreground">
112
+ {dayjs(item.createdAt).format("LLL")}
113
+ </TableCell>
114
+ <TableCell align="right">
115
+ <RowActions>
116
+ <IconButton
117
+ icon={Trash2}
118
+ label="Delete"
119
+ onClick={() => deletion.request(item.uuid)}
120
+ variant="danger"
121
+ />
122
+ </RowActions>
123
+ </TableCell>
124
+ </TableRow>
125
+ ))
126
+ )}
127
+ </TableBody>
128
+ </Table>
129
+ </TableContainer>
130
+ )}
131
+
132
+ {nextCursor && (
133
+ <LoadMoreButton
134
+ loading={loadingMore}
135
+ onClick={() => fetchItems(nextCursor)}
136
+ />
137
+ )}
138
+
139
+ <DangerZone {...deletion.dangerZoneProps} />
140
+ {deletion.confirmModal}
141
+ </div>
142
+ );
143
+ }
@@ -0,0 +1,17 @@
1
+ /** Wire shape returned by the mini-app backend (camelCase). */
2
+ export interface ItemDTO {
3
+ uuid: string;
4
+ name: string;
5
+ createdAt: string;
6
+ }
7
+
8
+ /** Frontend model. */
9
+ export interface Item {
10
+ uuid: string;
11
+ name: string;
12
+ createdAt: string;
13
+ }
14
+
15
+ export function mapItemDTOToFrontend(dto: ItemDTO): Item {
16
+ return { createdAt: dto.createdAt, name: dto.name, uuid: dto.uuid };
17
+ }
@@ -0,0 +1,22 @@
1
+ import { definePlugin } from "@cloudparse/up-backoffice-sdk";
2
+ import { AdminPage } from "@plugin/features/__PLUGIN_ID__/components/AdminPage";
3
+ import { LayoutDashboard } from "lucide-react";
4
+ import styles from "./styles.css?inline";
5
+
6
+ export default definePlugin({
7
+ description: "Admin dashboards of the __PLUGIN_NAME__ mini-app.",
8
+ icon: LayoutDashboard,
9
+ id: "__PLUGIN_ID__",
10
+ name: "__PLUGIN_NAME__",
11
+ pages: [
12
+ {
13
+ badge: "Backoffice CRUD",
14
+ component: AdminPage,
15
+ description: "Manage the __PLUGIN_NAME__ data.",
16
+ icon: LayoutDashboard,
17
+ path: "",
18
+ title: "Admin Management",
19
+ },
20
+ ],
21
+ styles,
22
+ });
@@ -0,0 +1,26 @@
1
+ import { miniappApi } from "@cloudparse/up-backoffice-sdk";
2
+ import {
3
+ type Item,
4
+ type ItemDTO,
5
+ mapItemDTOToFrontend,
6
+ } from "@plugin/features/__PLUGIN_ID__/types";
7
+
8
+ interface PageDTO<T> {
9
+ data: T[];
10
+ nextCursor?: string;
11
+ }
12
+
13
+ // miniappApi targets the application's httpBackendUrl (already ending with
14
+ // /api/v1) with an admin scoped token minted by the backoffice host.
15
+ export const __PLUGIN_CAMEL__Service = {
16
+ delete: (uuid: string) => miniappApi.delete<void>(`/admin/items/${uuid}`),
17
+ list: async (cursor?: string) => {
18
+ const page = await miniappApi.get<PageDTO<ItemDTO>>("/admin/items", {
19
+ params: cursor ? { cursor } : undefined,
20
+ });
21
+ return {
22
+ items: page.data.map(mapItemDTOToFrontend) satisfies Item[],
23
+ nextCursor: page.nextCursor ?? null,
24
+ };
25
+ },
26
+ };
@@ -0,0 +1 @@
1
+ @import "@cloudparse/up-backoffice-sdk/plugin.css";
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": ["dom", "dom.iterable", "esnext"],
5
+ "module": "esnext",
6
+ "moduleResolution": "bundler",
7
+ "jsx": "react-jsx",
8
+ "strict": true,
9
+ "skipLibCheck": true,
10
+ "isolatedModules": true,
11
+ "noEmit": true,
12
+ "types": ["vite/client"],
13
+ "paths": {
14
+ "@plugin/*": ["./src/*"]
15
+ }
16
+ },
17
+ "include": ["src", "vite.config.ts"]
18
+ }
@@ -0,0 +1,12 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { backofficePlugin } from "@cloudparse/up-backoffice-sdk/vite";
3
+ import tailwindcss from "@tailwindcss/vite";
4
+ import react from "@vitejs/plugin-react";
5
+ import { defineConfig } from "vite";
6
+
7
+ export default defineConfig({
8
+ plugins: [react(), tailwindcss(), backofficePlugin()],
9
+ resolve: {
10
+ alias: { "@plugin": fileURLToPath(new URL("./src", import.meta.url)) },
11
+ },
12
+ });
@@ -0,0 +1,17 @@
1
+ "use client";
2
+
3
+ // src/plugin/contract.ts
4
+ var PLUGIN_CONTRACT_VERSION = 1;
5
+ var SHARED_MODULES_GLOBAL = "__UP_BACKOFFICE_SHARED__";
6
+ var SHARED_MODULE_IDS = [
7
+ "react",
8
+ "react-dom",
9
+ "react/jsx-runtime"
10
+ ];
11
+
12
+ export {
13
+ PLUGIN_CONTRACT_VERSION,
14
+ SHARED_MODULES_GLOBAL,
15
+ SHARED_MODULE_IDS
16
+ };
17
+ //# sourceMappingURL=chunk-PSBYWSHV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugin/contract.ts"],"sourcesContent":["import type { ComponentType, ReactElement } from \"react\";\nimport type { HttpClient } from \"../api/ApiService\";\n\n/**\n * Version of the host <-> plugin contract. The host refuses a plugin built\n * against another major contract. Bump only on a breaking change of the types\n * below (and bump the SDK major version with it).\n */\nexport const PLUGIN_CONTRACT_VERSION = 1;\n\n/** Global the backoffice host fills with the modules it shares with plugins. */\nexport const SHARED_MODULES_GLOBAL = \"__UP_BACKOFFICE_SHARED__\";\n\n/** Modules a plugin never bundles: the host provides its own instance at runtime. */\nexport const SHARED_MODULE_IDS = [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n] as const;\n\nexport type SharedModuleId = (typeof SHARED_MODULE_IDS)[number];\n\nexport type IconComponent = ComponentType<{ className?: string }>;\n\n/** Mini-app the plugin belongs to, as registered in the Up backend. */\nexport interface PluginApplication {\n uuid: string;\n name: string;\n /** Base URL of the mini-app backend, e.g. `https://api.explore.up.cloudparse.fr/api/v1`. */\n httpBackendUrl: string | null;\n wsBackendUrl: string | null;\n iconUrl: string | null;\n}\n\n/** Admin currently logged into the backoffice. */\nexport interface PluginUser {\n uuid: string;\n fullName: string;\n admin: boolean;\n}\n\n/** Everything the backoffice host gives a plugin when it renders one of its pages. */\nexport interface PluginHost {\n contractVersion: number;\n application: PluginApplication;\n user: PluginUser | null;\n /** Client for the Up hub backend, authenticated with the admin session. */\n hubApi: HttpClient;\n /**\n * Client for the mini-app backend (`application.httpBackendUrl`), authenticated\n * with an admin scoped token minted and refreshed by the host.\n */\n miniappApi: HttpClient;\n /** Returns a valid admin scoped token for the mini-app (refreshed when expired). */\n getScopeToken(): Promise<string | null>;\n /** Absolute backoffice path of the plugin root, e.g. `/dashboard/plugins/<uuid>`. */\n basePath: string;\n /** Navigates to a page of this plugin (`\"\"` is the root page). */\n navigate(pagePath: string): void;\n}\n\n/** One page of a plugin, reachable at `<basePath>/<path>`. */\nexport interface PluginPage {\n /** Path relative to the plugin root, without leading slash. `\"\"` is the root page. */\n path: string;\n title: string;\n description?: string;\n icon?: IconComponent;\n /** Short label shown on the page card (e.g. \"Backoffice CRUD\"). */\n badge?: string;\n component: ComponentType;\n}\n\n/** What a plugin author passes to `definePlugin`. */\nexport interface BackofficePluginDefinition {\n /** Stable identifier, lowercase (e.g. `explore`). */\n id: string;\n name: string;\n description?: string;\n icon?: IconComponent;\n pages: PluginPage[];\n /** Compiled CSS of the plugin, injected by the host (`import styles from \"./styles.css?inline\"`). */\n styles?: string;\n}\n\n/** Default export of a built plugin bundle, as the host receives it. */\nexport interface BackofficePluginModule\n extends Omit<BackofficePluginDefinition, \"pages\"> {\n contractVersion: number;\n sdkVersion: string;\n pages: Omit<PluginPage, \"component\">[];\n /** Renders a page wrapped in the plugin's own SDK context. */\n renderPage(pagePath: string, host: PluginHost): ReactElement | null;\n}\n"],"mappings":";;;AAQO,IAAM,0BAA0B;AAGhC,IAAM,wBAAwB;AAG9B,IAAM,oBAAoB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AACF;","names":[]}
@@ -0,0 +1,122 @@
1
+ import { ComponentType, ReactElement } from 'react';
2
+
3
+ type FetchOptions = RequestInit & {
4
+ params?: Record<string, string>;
5
+ };
6
+ /**
7
+ * HTTP client contract shared by the backoffice host and its plugins.
8
+ * Every method resolves the current token (static or through the token loader)
9
+ * before sending the request.
10
+ */
11
+ interface HttpClient {
12
+ readonly baseUrl: string;
13
+ get<T>(endpoint: string, options?: FetchOptions): Promise<T>;
14
+ post<T>(endpoint: string, body?: unknown, options?: FetchOptions): Promise<T>;
15
+ put<T>(endpoint: string, body?: unknown, options?: FetchOptions): Promise<T>;
16
+ patch<T>(endpoint: string, body?: unknown, options?: FetchOptions): Promise<T>;
17
+ delete<T>(endpoint: string, options?: FetchOptions): Promise<T>;
18
+ getBlob(endpoint: string, options?: FetchOptions): Promise<Blob>;
19
+ getText(endpoint: string, options?: FetchOptions): Promise<string>;
20
+ }
21
+ declare class ApiService implements HttpClient {
22
+ readonly baseUrl: string;
23
+ private token;
24
+ private tokenLoader;
25
+ private onUnauthorized;
26
+ constructor(baseUrl: string);
27
+ setToken(token: string | null): void;
28
+ setTokenLoader(loader: (() => Promise<string | null>) | null): void;
29
+ setUnauthorizedCallback(callback: (() => void) | null): void;
30
+ get<T>(endpoint: string, options?: FetchOptions): Promise<T>;
31
+ post<T>(endpoint: string, body?: unknown, options?: FetchOptions): Promise<T>;
32
+ put<T>(endpoint: string, body?: unknown, options?: FetchOptions): Promise<T>;
33
+ patch<T>(endpoint: string, body?: unknown, options?: FetchOptions): Promise<T>;
34
+ delete<T>(endpoint: string, options?: FetchOptions): Promise<T>;
35
+ getBlob(endpoint: string, options?: FetchOptions): Promise<Blob>;
36
+ getText(endpoint: string, options?: FetchOptions): Promise<string>;
37
+ private request;
38
+ /**
39
+ * Builds the URL, attaches the bearer token (only for URLs on this client's own
40
+ * base URL, never for absolute third-party URLs) and reports 401s.
41
+ */
42
+ private send;
43
+ }
44
+
45
+ /**
46
+ * Version of the host <-> plugin contract. The host refuses a plugin built
47
+ * against another major contract. Bump only on a breaking change of the types
48
+ * below (and bump the SDK major version with it).
49
+ */
50
+ declare const PLUGIN_CONTRACT_VERSION = 1;
51
+ /** Modules a plugin never bundles: the host provides its own instance at runtime. */
52
+ declare const SHARED_MODULE_IDS: readonly ["react", "react-dom", "react/jsx-runtime"];
53
+ type SharedModuleId = (typeof SHARED_MODULE_IDS)[number];
54
+ type IconComponent = ComponentType<{
55
+ className?: string;
56
+ }>;
57
+ /** Mini-app the plugin belongs to, as registered in the Up backend. */
58
+ interface PluginApplication {
59
+ uuid: string;
60
+ name: string;
61
+ /** Base URL of the mini-app backend, e.g. `https://api.explore.up.cloudparse.fr/api/v1`. */
62
+ httpBackendUrl: string | null;
63
+ wsBackendUrl: string | null;
64
+ iconUrl: string | null;
65
+ }
66
+ /** Admin currently logged into the backoffice. */
67
+ interface PluginUser {
68
+ uuid: string;
69
+ fullName: string;
70
+ admin: boolean;
71
+ }
72
+ /** Everything the backoffice host gives a plugin when it renders one of its pages. */
73
+ interface PluginHost {
74
+ contractVersion: number;
75
+ application: PluginApplication;
76
+ user: PluginUser | null;
77
+ /** Client for the Up hub backend, authenticated with the admin session. */
78
+ hubApi: HttpClient;
79
+ /**
80
+ * Client for the mini-app backend (`application.httpBackendUrl`), authenticated
81
+ * with an admin scoped token minted and refreshed by the host.
82
+ */
83
+ miniappApi: HttpClient;
84
+ /** Returns a valid admin scoped token for the mini-app (refreshed when expired). */
85
+ getScopeToken(): Promise<string | null>;
86
+ /** Absolute backoffice path of the plugin root, e.g. `/dashboard/plugins/<uuid>`. */
87
+ basePath: string;
88
+ /** Navigates to a page of this plugin (`""` is the root page). */
89
+ navigate(pagePath: string): void;
90
+ }
91
+ /** One page of a plugin, reachable at `<basePath>/<path>`. */
92
+ interface PluginPage {
93
+ /** Path relative to the plugin root, without leading slash. `""` is the root page. */
94
+ path: string;
95
+ title: string;
96
+ description?: string;
97
+ icon?: IconComponent;
98
+ /** Short label shown on the page card (e.g. "Backoffice CRUD"). */
99
+ badge?: string;
100
+ component: ComponentType;
101
+ }
102
+ /** What a plugin author passes to `definePlugin`. */
103
+ interface BackofficePluginDefinition {
104
+ /** Stable identifier, lowercase (e.g. `explore`). */
105
+ id: string;
106
+ name: string;
107
+ description?: string;
108
+ icon?: IconComponent;
109
+ pages: PluginPage[];
110
+ /** Compiled CSS of the plugin, injected by the host (`import styles from "./styles.css?inline"`). */
111
+ styles?: string;
112
+ }
113
+ /** Default export of a built plugin bundle, as the host receives it. */
114
+ interface BackofficePluginModule extends Omit<BackofficePluginDefinition, "pages"> {
115
+ contractVersion: number;
116
+ sdkVersion: string;
117
+ pages: Omit<PluginPage, "component">[];
118
+ /** Renders a page wrapped in the plugin's own SDK context. */
119
+ renderPage(pagePath: string, host: PluginHost): ReactElement | null;
120
+ }
121
+
122
+ export { ApiService as A, type BackofficePluginModule as B, type FetchOptions as F, type HttpClient as H, type IconComponent as I, PLUGIN_CONTRACT_VERSION as P, type SharedModuleId as S, type PluginApplication as a, type PluginHost as b, type PluginUser as c, SHARED_MODULE_IDS as d, type BackofficePluginDefinition as e, type PluginPage as f };
package/dist/host.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import { B as BackofficePluginModule, S as SharedModuleId } from './contract-88aU9QZl.js';
2
+ export { P as PLUGIN_CONTRACT_VERSION, a as PluginApplication, b as PluginHost, c as PluginUser, d as SHARED_MODULE_IDS } from './contract-88aU9QZl.js';
3
+ import 'react';
4
+
5
+ type SharedRegistry = Record<SharedModuleId, unknown>;
6
+ /**
7
+ * Exposes the host's own React instances to plugins. Must run before any plugin
8
+ * is loaded, or the plugin bundle throws on its first shared import.
9
+ */
10
+ declare function installSharedModules(modules: SharedRegistry): void;
11
+ /**
12
+ * Verifies a plugin bundle against its published checksum, then evaluates it
13
+ * as an ES module and validates its default export.
14
+ */
15
+ declare function loadPluginModule(code: string, expectedChecksum: string): Promise<BackofficePluginModule>;
16
+ /** Attribute the host puts on the element wrapping a plugin's pages. */
17
+ declare const PLUGIN_ROOT_ATTRIBUTE = "data-up-backoffice-plugin-root";
18
+ /** Props to spread on the element wrapping a plugin's pages, so its styles apply there only. */
19
+ declare function pluginRootProps(plugin: Pick<BackofficePluginModule, "id">): {
20
+ "data-up-backoffice-plugin-root": string;
21
+ };
22
+ /**
23
+ * Confines the plugin's Tailwind utilities to its own root with `@scope`. Without
24
+ * it, the plugin's copy of a utility (e.g. `.fixed`) comes later in the cascade
25
+ * than the host's responsive variants (e.g. `lg:sticky`) and breaks the host layout.
26
+ * Theme variables, `@property` and `@keyframes` stay global (same values as the host).
27
+ * Throws when the CSS has no utilities layer: unscoped plugin CSS is never injected.
28
+ */
29
+ declare function scopePluginStyles(css: string, pluginId: string): string;
30
+ /** Injects the plugin's compiled CSS once, scoped to its root; returns a cleanup removing it. */
31
+ declare function injectPluginStyles(plugin: BackofficePluginModule): () => void;
32
+
33
+ export { BackofficePluginModule, PLUGIN_ROOT_ATTRIBUTE, injectPluginStyles, installSharedModules, loadPluginModule, pluginRootProps, scopePluginStyles };