@cloudparse/up-backoffice-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # @cloudparse/up-backoffice-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build plugins for the Up backoffice.
4
+
5
+ ```bash
6
+ npm install @cloudparse/up-backoffice-sdk react react-dom
7
+ npm install -D vite @vitejs/plugin-react @tailwindcss/vite tailwindcss
8
+ ```
9
+
10
+ `vite.config.ts`:
11
+
12
+ ```ts
13
+ import tailwindcss from "@tailwindcss/vite";
14
+ import react from "@vitejs/plugin-react";
15
+ import { backofficePlugin } from "@cloudparse/up-backoffice-sdk/vite";
16
+ import { defineConfig } from "vite";
17
+
18
+ export default defineConfig({ plugins: [react(), tailwindcss(), backofficePlugin()] });
19
+ ```
20
+
21
+ `src/styles.css`:
22
+
23
+ ```css
24
+ @import "@cloudparse/up-backoffice-sdk/plugin.css";
25
+ ```
26
+
27
+ `src/index.tsx`:
28
+
29
+ ```tsx
30
+ import { definePlugin, miniappApi } from "@cloudparse/up-backoffice-sdk";
31
+ import { Compass } from "lucide-react";
32
+ import styles from "./styles.css?inline";
33
+
34
+ function AdminPage() {
35
+ // miniappApi targets the mini-app backend with an admin scoped token.
36
+ return <div className="p-8 text-sm text-muted-foreground">Hello</div>;
37
+ }
38
+
39
+ export default definePlugin({
40
+ id: "my-app",
41
+ name: "My app",
42
+ icon: Compass,
43
+ pages: [{ path: "", title: "Admin", component: AdminPage }],
44
+ styles,
45
+ });
46
+ ```
47
+
48
+ `vite build` produces `dist/plugin.js`, the artifact to publish to the Up backend. See `AGENTS.md` for the full flow.
49
+
50
+ ## UI kit
51
+
52
+ Admin pages are built from the SDK components: `PageHeader`, `SectionHeader`, `Card`, `StatTile`, `Table*`, `IconButton`/`RowActions`, `Modal`/`ModalActions`, `ConfirmModal`, `DangerZone` + `useDangerZoneDelete`, `ImageUpload`, `Switch`/`SettingRow`, `Input`, `Textarea`, `Select`, `SearchInput`, `Tabs`, `LoadMoreButton`, `LoadingState`, `Banner`, `Badge`, `EmptyState`, `GraphQLPlayground`... Full list with props: `claude-plugin/skills/up-backoffice-plugin-builder/references/sdk-api.md`.
53
+
54
+ ## Storybook
55
+
56
+ `npm run storybook` (http://localhost:6007) shows every component with the backoffice theme; `npm run build-storybook` builds the static site (also built in CI).
57
+
58
+ ## Claude Code
59
+
60
+ `claude-plugin/` is a Claude Code plugin: `/new-backoffice-plugin <id>` scaffolds a plugin, and the `up-backoffice-plugin-builder` skill carries the API reference, recipes and rules. See `claude-plugin/README.md`.
@@ -0,0 +1,17 @@
1
+ {
2
+ "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
3
+ "name": "up-backoffice",
4
+ "description": "Claude Code plugin for building Up backoffice plugins with the @cloudparse/up-backoffice-sdk.",
5
+ "owner": {
6
+ "name": "CloudParse",
7
+ "url": "https://github.com/CloudParse"
8
+ },
9
+ "plugins": [
10
+ {
11
+ "name": "up-backoffice-sdk",
12
+ "description": "Scaffold and build Up backoffice plugins (mini-app admin dashboards).",
13
+ "source": "./",
14
+ "category": "development"
15
+ }
16
+ ]
17
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "up-backoffice-sdk",
3
+ "description": "Build Up backoffice plugins with @cloudparse/up-backoffice-sdk: scaffold a mini-app's backoffice-plugin/ folder, the plugin contract, the shared UI kit, and how to build, publish and test a plugin locally.",
4
+ "version": "0.1.0",
5
+ "author": {
6
+ "name": "CloudParse",
7
+ "url": "https://github.com/CloudParse"
8
+ },
9
+ "license": "MIT",
10
+ "keywords": [
11
+ "up",
12
+ "backoffice",
13
+ "plugin",
14
+ "sdk",
15
+ "react",
16
+ "vite",
17
+ "tailwind",
18
+ "admin",
19
+ "dashboard"
20
+ ]
21
+ }
@@ -0,0 +1,44 @@
1
+ # up-backoffice-sdk — Claude Code plugin
2
+
3
+ Build Up backoffice plugins (a mini-app's admin dashboards) with Claude Code. The plugin scaffolds a ready-to-build `backoffice-plugin/` folder on top of `@cloudparse/up-backoffice-sdk`, and gives Claude the SDK reference, tested recipes and the mandatory rules.
4
+
5
+ ## What is inside
6
+
7
+ | Path | Purpose |
8
+ |---|---|
9
+ | `.claude-plugin/plugin.json` | Plugin manifest |
10
+ | `.claude-plugin/marketplace.json` | Single-plugin marketplace, so the plugin installs from this folder |
11
+ | `skills/up-backoffice-plugin-builder/` | Skill loaded for plugin work: workflow, rules, references (`sdk-api.md`, `recipes.md`, `rules-and-pitfalls.md`, `plugin-checklist.md`) |
12
+ | `commands/new-backoffice-plugin.md` | `/new-backoffice-plugin <plugin-id> [--name <Name>]` |
13
+ | `scripts/scaffold.mjs` | Zero-dependency scaffold: copies `templates/plugin/`, replaces the id/name/package/SDK version |
14
+ | `templates/plugin/` | Plugin skeleton: Vite + React + Tailwind 4 config, `definePlugin` entry, an example service and a list page using the UI kit (table, row actions, delete flow, load more) |
15
+ | `sdk-version.json` | SDK version the scaffolded plugins depend on |
16
+ | `test/scaffold.test.mjs` | Black-box tests of the scaffold (`npm test` at the SDK root) |
17
+
18
+ ## Install
19
+
20
+ From a local checkout of `up/backoffice-sdk`:
21
+
22
+ ```sh
23
+ # Session only:
24
+ claude --plugin-dir /path/to/backoffice-sdk/claude-plugin
25
+
26
+ # Persistent:
27
+ claude plugin marketplace add /path/to/backoffice-sdk/claude-plugin
28
+ claude plugin install up-backoffice-sdk@up-backoffice
29
+ ```
30
+
31
+ Check: `/new-backoffice-plugin` appears in Claude Code. The plugin is also shipped inside the npm package (`node_modules/@cloudparse/up-backoffice-sdk/claude-plugin`).
32
+
33
+ ## Use
34
+
35
+ ```text
36
+ /new-backoffice-plugin explore --name Explore # inside up-miniapps-explore
37
+ ```
38
+
39
+ Then ask Claude for the pages you need ("add a page to manage the collections"); the skill loads automatically for `backoffice-plugin/` work.
40
+
41
+ ## Maintenance
42
+
43
+ - Bump `sdk-version.json` with the SDK `package.json` version on each release.
44
+ - When the SDK gains or changes a component, update `references/sdk-api.md` and the template if it uses it, then run `npm test`.
@@ -0,0 +1,18 @@
1
+ ---
2
+ description: Scaffold the backoffice plugin (admin dashboards) of an Up mini-app and walk through publishing it
3
+ argument-hint: "<plugin-id> [--name <Display Name>]"
4
+ ---
5
+
6
+ Create the backoffice plugin of a mini-app from `$ARGUMENTS`.
7
+
8
+ 1. Parse `$ARGUMENTS`: the first token is the plugin id (lowercase letters, digits, dashes, e.g. `explore`); `--name` is the display name (default: the id capitalized). If no id is given, ask for one and stop.
9
+ 2. Find the target: the plugin lives in `<mini-app repo>/backoffice-plugin/`. If the current directory is a mini-app repo (`up-miniapps-*` with a `package.json`), use `./backoffice-plugin`; otherwise ask where the mini-app repo is. Stop if `backoffice-plugin/` already exists and is not empty.
10
+ 3. Locate the scaffold script: `${CLAUDE_PLUGIN_ROOT}/scripts/scaffold.mjs` when that variable is set; otherwise `find ~/.claude/plugins "$PWD" -path "*/claude-plugin/scripts/scaffold.mjs" -not -path "*/node_modules/*" 2>/dev/null` and keep the match whose sibling `.claude-plugin/plugin.json` has `"name": "up-backoffice-sdk"`.
11
+ 4. Run `node <scaffold-path> <target> --id <id> [--name "<Name>"]`. Stop and report if it fails.
12
+ 5. If the mini-app repo has a root `biome.json`, add `"!backoffice-plugin"` to its `files.includes` so the mini-app lint does not apply to the plugin.
13
+ 6. Read `up-backoffice-plugin-builder`'s `SKILL.md` and its references before editing code.
14
+ 7. In the target, run `npm install` then `npm run build`. If the SDK version is not published yet, tell the user and use a local `file:` link to the SDK checkout with `install-links=true` in `.npmrc`.
15
+ 8. Ask, one question at a time, what the first admin page must manage (which backend routes). Replace the example `Item` service and page with the real ones, following `references/recipes.md`.
16
+ 9. Explain how to publish: `POST /api/v1/admin/applications/<applicationUuid>/backoffice-plugin/artifacts` with an admin token and `X-App-Secret`, or locally with `sp task backoffice plugins` (add the plugin to that task in `starter-pack/orgs/up/services.yaml`).
17
+
18
+ Finish with: the folder, the plugin id, the SDK version, and what is left (real pages, publish job).
@@ -0,0 +1,186 @@
1
+ #!/usr/bin/env node
2
+ // Scaffolds a backoffice plugin (the `backoffice-plugin/` folder of an Up mini-app repo).
3
+ // Zero dependencies: Node built-ins only (runs on Node >= 18; the SDK itself needs Node >= 22).
4
+
5
+ import {
6
+ existsSync,
7
+ mkdirSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ statSync,
11
+ writeFileSync,
12
+ } from "node:fs";
13
+ import path from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+
16
+ const pluginRoot = path.resolve(
17
+ path.dirname(fileURLToPath(import.meta.url)),
18
+ "..",
19
+ );
20
+ const templateDir = path.join(pluginRoot, "templates", "plugin");
21
+ const PLUGIN_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
22
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
23
+ const DISPLAY_NAME = /^[A-Za-z0-9][A-Za-z0-9 ._-]{0,63}$/;
24
+ const NPM_PACKAGE = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
25
+
26
+ class ScaffoldError extends Error {}
27
+
28
+ function fail(message) {
29
+ throw new ScaffoldError(message);
30
+ }
31
+
32
+ function usage() {
33
+ return [
34
+ "Usage: node scaffold.mjs <target-dir> --id <plugin-id> [options]",
35
+ "",
36
+ "<target-dir> is usually <mini-app repo>/backoffice-plugin.",
37
+ "",
38
+ "Options:",
39
+ " --id <id> Plugin id: lowercase letters, digits, dashes (e.g. explore). Required.",
40
+ " --name <Name> Display name (default: the id, capitalized)",
41
+ " --package <name> npm package name (default: @cloudparse/up-miniapps-<id>-backoffice-plugin)",
42
+ " --sdk-version <v> SDK version to depend on (default: claude-plugin/sdk-version.json)",
43
+ " --force Write into a non-empty directory (only the template's files are overwritten)",
44
+ " -h, --help Show this help",
45
+ ].join("\n");
46
+ }
47
+
48
+ function parseArgs(argv) {
49
+ const options = { force: false };
50
+ const valued = {
51
+ "--id": "id",
52
+ "--name": "name",
53
+ "--package": "packageName",
54
+ "--sdk-version": "sdkVersion",
55
+ };
56
+ for (let index = 0; index < argv.length; index += 1) {
57
+ const arg = argv[index];
58
+ if (arg === "-h" || arg === "--help") {
59
+ console.log(usage());
60
+ process.exit(0);
61
+ } else if (arg === "--force") {
62
+ options.force = true;
63
+ } else if (arg in valued) {
64
+ const value = argv[index + 1];
65
+ if (!value || value.startsWith("--")) fail(`${arg} needs a value`);
66
+ options[valued[arg]] = value;
67
+ index += 1;
68
+ } else if (arg.startsWith("--")) {
69
+ fail(`unknown option ${arg}\n\n${usage()}`);
70
+ } else if (options.target === undefined) {
71
+ options.target = arg;
72
+ } else {
73
+ fail(`unexpected argument ${arg}`);
74
+ }
75
+ }
76
+ if (!options.target) fail(`missing <target-dir>\n\n${usage()}`);
77
+ if (!options.id) fail(`missing --id\n\n${usage()}`);
78
+ if (!PLUGIN_ID.test(options.id)) {
79
+ fail(
80
+ `invalid --id "${options.id}": lowercase words of letters and digits separated by single dashes (e.g. night-life)`,
81
+ );
82
+ }
83
+ if (options.name !== undefined && !DISPLAY_NAME.test(options.name)) {
84
+ fail(
85
+ `invalid --name "${options.name}": letters, digits, spaces, dots, dashes and underscores only`,
86
+ );
87
+ }
88
+ if (
89
+ options.packageName !== undefined &&
90
+ !NPM_PACKAGE.test(options.packageName)
91
+ ) {
92
+ fail(
93
+ `invalid --package "${options.packageName}": not a valid npm package name`,
94
+ );
95
+ }
96
+ return options;
97
+ }
98
+
99
+ function resolveSdkVersion(explicit) {
100
+ const version =
101
+ explicit ??
102
+ JSON.parse(readFileSync(path.join(pluginRoot, "sdk-version.json"), "utf8"))
103
+ .version;
104
+ if (!SEMVER.test(version)) fail(`invalid SDK version "${version}"`);
105
+ return version;
106
+ }
107
+
108
+ /** Template-relative file paths (directories excluded). */
109
+ function listTemplateFiles(dir, prefix = "") {
110
+ const files = [];
111
+ for (const entry of readdirSync(dir)) {
112
+ const relative = path.join(prefix, entry);
113
+ if (statSync(path.join(dir, entry)).isDirectory()) {
114
+ files.push(...listTemplateFiles(path.join(dir, entry), relative));
115
+ } else {
116
+ files.push(relative);
117
+ }
118
+ }
119
+ return files;
120
+ }
121
+
122
+ /** Where a template file lands: placeholders replaced in every path segment. */
123
+ function targetPath(relative, id) {
124
+ return relative
125
+ .split(path.sep)
126
+ .map((segment) =>
127
+ // npm drops .gitignore from published packages: the template ships it as `gitignore`.
128
+ segment === "gitignore"
129
+ ? ".gitignore"
130
+ : segment.split("__PLUGIN_ID__").join(id),
131
+ )
132
+ .join(path.sep);
133
+ }
134
+
135
+ function main() {
136
+ const options = parseArgs(process.argv.slice(2));
137
+ const target = path.resolve(options.target);
138
+ if (existsSync(target) && readdirSync(target).length > 0 && !options.force) {
139
+ fail(`${target} is not empty (use --force to write into it)`);
140
+ }
141
+
142
+ const name =
143
+ options.name ?? options.id.charAt(0).toUpperCase() + options.id.slice(1);
144
+ const replacements = [
145
+ [
146
+ "__PLUGIN_CAMEL__",
147
+ options.id.replace(/-([a-z0-9])/g, (_, char) => char.toUpperCase()),
148
+ ],
149
+ ["__PLUGIN_ID__", options.id],
150
+ ["__PLUGIN_NAME__", name],
151
+ [
152
+ "__PACKAGE_NAME__",
153
+ options.packageName ??
154
+ `@cloudparse/up-miniapps-${options.id}-backoffice-plugin`,
155
+ ],
156
+ ["__SDK_VERSION__", resolveSdkVersion(options.sdkVersion)],
157
+ ];
158
+
159
+ // Each template file is written straight to its final path: re-running with
160
+ // --force overwrites the template's own files and never touches anything else
161
+ // in the target (user code, node_modules, binaries).
162
+ for (const relative of listTemplateFiles(templateDir)) {
163
+ const destination = path.join(target, targetPath(relative, options.id));
164
+ mkdirSync(path.dirname(destination), { recursive: true });
165
+ let content = readFileSync(path.join(templateDir, relative), "utf8");
166
+ for (const [token, value] of replacements) {
167
+ content = content.split(token).join(value);
168
+ }
169
+ writeFileSync(destination, content);
170
+ }
171
+
172
+ console.log(
173
+ `Backoffice plugin "${name}" (${options.id}) scaffolded in ${target}`,
174
+ );
175
+ console.log("Next: npm install && npm run build (output: dist/plugin.js)");
176
+ }
177
+
178
+ try {
179
+ main();
180
+ } catch (error) {
181
+ if (error instanceof ScaffoldError) {
182
+ console.error(`scaffold: ${error.message}`);
183
+ process.exit(1);
184
+ }
185
+ throw error;
186
+ }
@@ -0,0 +1 @@
1
+ { "version": "0.1.0" }
@@ -0,0 +1,40 @@
1
+ ---
2
+ name: up-backoffice-plugin-builder
3
+ description: Build an Up backoffice plugin (a mini-app's admin dashboards) with @cloudparse/up-backoffice-sdk. Use when creating or editing a `backoffice-plugin/` folder, adding an admin page for a mini-app, using the backoffice UI kit (PageHeader, Modal, Table, DangerZone, useDangerZoneDelete, ImageUpload, StatTile...), calling a mini-app backend from the backoffice (miniappApi), or publishing/loading a plugin. Triggers include "backoffice plugin", "backoffice-plugin", "@cloudparse/up-backoffice-sdk", "definePlugin", "miniappApi", "admin dashboard for <mini-app>", "plugin bundle".
4
+ ---
5
+
6
+ # Building an Up backoffice plugin
7
+
8
+ A backoffice plugin is a mini-app's admin dashboards. It lives in the mini-app repo, in `backoffice-plugin/`, is built into one ES module (`dist/plugin.js`), published to the Up hub backend, and loaded at runtime by the backoffice (`up/backoffice`), which renders its pages inside its own layout. The plugin runs with the admin's session on purpose: it is admin code.
9
+
10
+ ## Workflow
11
+
12
+ 1. **Scaffold** (new plugin): `/new-backoffice-plugin <id>` or
13
+ ```sh
14
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/scaffold.mjs" <mini-app repo>/backoffice-plugin --id <id> [--name "<Name>"]
15
+ ```
16
+ Without `CLAUDE_PLUGIN_ROOT`, use `../../scripts/scaffold.mjs` relative to this skill.
17
+ 2. **Install and build**: `npm install && npm run build`.
18
+ 3. **Implement pages**. Before using any SDK export, check its exact props in `references/sdk-api.md`. Copy the closest pattern from `references/recipes.md`.
19
+ 4. **Publish locally**: `sp task backoffice plugins` from the starter-pack (the plugin must be listed in that task), then open `http://localhost:3000/dashboard/plugins/<applicationUuid>`.
20
+ 5. **Verify** with `npm run lint` and `npm run build`, then walk `references/plugin-checklist.md`.
21
+
22
+ ## Must-know rules
23
+
24
+ Full list with rationale: `references/rules-and-pitfalls.md`. The essentials:
25
+
26
+ - Default-export `definePlugin({ id, name, pages, styles })`; `styles` comes from `import styles from "./styles.css?inline"`.
27
+ - Use the SDK UI kit, never re-create a modal, table, header, spinner, delete flow or image picker. No `alert()`/`confirm()`/`prompt()`.
28
+ - Backend calls only through `miniappApi` (mini-app backend) or `hubApi` (Up hub). Paths are relative to the application's `httpBackendUrl`, which already ends with `/api/v1`.
29
+ - `isApiError(err)`, never `instanceof ApiError`. No React context shared with the host: read the host with `usePluginHost()`.
30
+ - English UI text, Tailwind theme tokens, no arbitrary values (`text-[10px]`), no `any`, WebP-only images.
31
+ - Never import `next/*`: a plugin runs outside Next.js.
32
+
33
+ ## Reference map
34
+
35
+ | File | Read it when |
36
+ |---|---|
37
+ | `references/sdk-api.md` | Before using any export: names and props. |
38
+ | `references/recipes.md` | Building a page: list + delete, form modal, image upload, settings, KPIs, GraphQL playground, several pages. |
39
+ | `references/rules-and-pitfalls.md` | Before writing code, and when something misbehaves (styles, auth, React errors). |
40
+ | `references/plugin-checklist.md` | Before declaring the work done. |
@@ -0,0 +1,14 @@
1
+ # Plugin checklist
2
+
3
+ Before saying a plugin change is done:
4
+
5
+ - [ ] `npm run lint` and `npm run build` pass in `backoffice-plugin/`.
6
+ - [ ] `grep -rn "alert(\|confirm(\|prompt(" src` is empty.
7
+ - [ ] `grep -c __UP_BACKOFFICE_SHARED__ dist/plugin.js` prints 3 (React is not bundled).
8
+ - [ ] No `any`, no arbitrary Tailwind values, no `next/*` import, no hardcoded backend URL.
9
+ - [ ] Every backend call goes through `miniappApi`/`hubApi`, every error check uses `isApiError`.
10
+ - [ ] Lists: `TableContainer`/`Table*`, `TableEmpty` for no rows, `RowActions` + `IconButton`, `LoadMoreButton` for cursor pages.
11
+ - [ ] Hard deletes: `useDangerZoneDelete` + `DangerZone` + `confirmModal` + `Banner` for its error.
12
+ - [ ] Forms: `Modal dismissible={!saving}` + `ModalActions` inside the `<form>`; images through `ImageUpload` (WebP), uploaded on save.
13
+ - [ ] Page title through `PageHeader`, with `AuthStatusBadge` when the page depends on the mini-app backend.
14
+ - [ ] Published locally (`sp task backoffice plugins`) and checked in the backoffice at `/dashboard/plugins/<applicationUuid>`: pages load, actions work, no console error, the backoffice layout (sidebar) is unchanged.
@@ -0,0 +1,147 @@
1
+ # Recipes
2
+
3
+ All snippets assume `import { ... } from "@cloudparse/up-backoffice-sdk";` and the `@plugin/*` alias for `src/*`.
4
+
5
+ ## Service on the mini-app backend
6
+
7
+ ```ts
8
+ // src/services/explore.ts
9
+ import { miniappApi } from "@cloudparse/up-backoffice-sdk";
10
+ import { mapCollectionDTOToFrontend, type CollectionDTO } from "@plugin/features/explore/types";
11
+
12
+ export const exploreService = {
13
+ // httpBackendUrl ends with /api/v1: the path starts after it.
14
+ getCollections: async () =>
15
+ (await miniappApi.get<CollectionDTO[]>("/admin/collections")).map(mapCollectionDTOToFrontend),
16
+ deleteCollection: (uuid: string) => miniappApi.delete<void>(`/admin/collections/${uuid}`),
17
+ };
18
+ ```
19
+
20
+ Keep parallel `XDTO` / `X` types with a typed `mapXDTOToFrontend` in `features/<x>/types.ts`.
21
+
22
+ ## List page with row actions and the delete flow
23
+
24
+ The scaffolded `AdminPage.tsx` is the reference. Key parts:
25
+
26
+ ```tsx
27
+ const deletion = useDangerZoneDelete({
28
+ entityLabel: "a collection",
29
+ onDelete: async (uuid) => {
30
+ await exploreService.deleteCollection(uuid);
31
+ await fetchData();
32
+ },
33
+ resolveName: (uuid) => collections.find((c) => c.uuid === uuid)?.name ?? null,
34
+ });
35
+
36
+ <PageHeader actions={<AuthStatusBadge authError={authError} />} bordered icon={Compass} title="Explore management" />
37
+ {deletion.error && <Banner message={deletion.error} onClose={deletion.clearError} variant="error" />}
38
+ <TableContainer>
39
+ <Table>
40
+ <TableHead><tr><TableHeaderCell>Name</TableHeaderCell><TableHeaderCell align="right">Actions</TableHeaderCell></tr></TableHead>
41
+ <TableBody>
42
+ {rows.length === 0 ? <TableEmpty colSpan={2} icon={Inbox} title="No collections" /> : rows.map((row) => (
43
+ <TableRow key={row.uuid}>
44
+ <TableCell>{row.name}<CopyableUuid uuid={row.uuid} /></TableCell>
45
+ <TableCell align="right">
46
+ <RowActions>
47
+ <IconButton icon={Pencil} label="Edit" onClick={() => setEditing(row)} />
48
+ <IconButton icon={Trash2} label="Delete" onClick={() => deletion.request(row.uuid)} variant="danger" />
49
+ </RowActions>
50
+ </TableCell>
51
+ </TableRow>
52
+ ))}
53
+ </TableBody>
54
+ </Table>
55
+ </TableContainer>
56
+ <DangerZone {...deletion.dangerZoneProps} />
57
+ {deletion.confirmModal}
58
+ ```
59
+
60
+ Detect auth problems: `if (isApiError(err) && (err.status === 401 || err.status === 403)) setAuthError(true);`
61
+
62
+ ## Form in a modal
63
+
64
+ ```tsx
65
+ {isOpen && (
66
+ <Modal dismissible={!saving} icon={Layers} onClose={close} size="md" title={editing ? "Edit collection" : "New collection"}>
67
+ <form className="space-y-6" onSubmit={handleSubmit}>
68
+ {error && <Banner message={error} variant="error" />}
69
+ <Input label="Name" onChange={(e) => setName(e.target.value)} required value={name} />
70
+ <Textarea label="Description" onChange={(e) => setDescription(e.target.value)} value={description} />
71
+ <ModalActions isSubmitting={saving} onCancel={close} submitLabel={editing ? "Save" : "Create"} />
72
+ </form>
73
+ </Modal>
74
+ )}
75
+ ```
76
+
77
+ `ModalActions` must be inside the `<form>` so the submit button submits it. `dismissible={!saving}` keeps the modal open (Escape, close button) while the request runs.
78
+
79
+ ## Image upload (upload on save, not on select)
80
+
81
+ ```tsx
82
+ const [file, setFile] = useState<File | null>(null);
83
+ const preview = useMemo(() => (file ? URL.createObjectURL(file) : initial?.imageUrl ?? null), [file, initial]);
84
+ useEffect(() => () => { if (file && preview) URL.revokeObjectURL(preview); }, [file, preview]);
85
+
86
+ <ImageUpload label="Cover" onError={setError} onFile={setFile} previewUrl={preview} uploading={saving} />
87
+
88
+ // in handleSubmit: upload `file` first (service calls assertWebp), then save the entity with the returned id.
89
+ ```
90
+
91
+ ## Settings with switches
92
+
93
+ ```tsx
94
+ <SettingRow
95
+ control={<Switch checked={!form.isDisabled} label="Active" onChange={(active) => setForm({ ...form, isDisabled: !active })} />}
96
+ description="Visible to players"
97
+ label="Active"
98
+ />
99
+ ```
100
+
101
+ ## KPI tiles
102
+
103
+ ```tsx
104
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
105
+ <StatTile icon={Layers} label="Collections" value={collections.length} />
106
+ <StatTile active={tab === "events"} icon={Calendar} label="Events" onClick={() => setTab("events")} value={events.length} />
107
+ </div>
108
+ ```
109
+
110
+ ## GraphQL playground page
111
+
112
+ ```tsx
113
+ export function GraphQLPage() {
114
+ const [hasToken, setHasToken] = useState(false);
115
+ const refresh = useCallback(async () => setHasToken(Boolean(await getScopeToken())), []);
116
+ useEffect(() => { refresh(); }, [refresh]);
117
+ return (
118
+ <GraphQLPlayground
119
+ hasToken={hasToken}
120
+ onConfigureToken={refresh}
121
+ onExecute={(query, variables) => miniappApi.post("/graphql", { query, variables })}
122
+ presets={PRESETS}
123
+ />
124
+ );
125
+ }
126
+ ```
127
+
128
+ ## Several pages
129
+
130
+ ```tsx
131
+ export default definePlugin({
132
+ id: "explore",
133
+ name: "Explore",
134
+ pages: [
135
+ { path: "", title: "Admin Management", component: AdminPage, icon: Compass, badge: "Backoffice CRUD" },
136
+ { path: "graphql", title: "GraphQL Playground", component: GraphQLPage, icon: Terminal, badge: "Dev Sandbox" },
137
+ ],
138
+ styles,
139
+ });
140
+ ```
141
+
142
+ The host shows tabs for the pages. Navigate from code with `usePluginHost().navigate("graphql")`.
143
+
144
+ ## Publish
145
+
146
+ - Local: add the plugin to the `backoffice-plugins` task of `starter-pack/orgs/up/services.yaml` (`-plugin APP_NAME=../miniapps/<repo>/backoffice-plugin/dist/plugin.js`), then `sp task backoffice plugins`.
147
+ - Any environment: `curl -X POST "$HUB/api/v1/admin/applications/$APP_UUID/backoffice-plugin/artifacts" -H "Authorization: Bearer $ADMIN_TOKEN" -H "X-App-Secret: $APP_SECRET" -F version=1.2.0 -F changelog="..." -F file=@dist/plugin.js` (activates the version; `-F activate=false` to stage it). Manage versions in the backoffice at `/dashboard/plugins`.
@@ -0,0 +1,25 @@
1
+ # Rules and pitfalls
2
+
3
+ ## Rules
4
+
5
+ 1. **One ES module.** `vite build` with `backofficePlugin()` outputs `dist/plugin.js`. No code splitting and no dynamic `import()` in plugin code: a lazy chunk cannot be resolved from the blob URL the host imports.
6
+ 2. **React comes from the host.** `react`, `react-dom` and `react/jsx-runtime` are replaced by the host's instances at runtime; keep them as devDependencies only. Everything else is bundled into the plugin.
7
+ 3. **Use the SDK UI kit.** Modals, tables, headers, spinners, delete flows, switches, image pickers and badges come from the SDK. Copy-pasting their markup brings back the drift the kit removed.
8
+ 4. **No `alert()`, `confirm()`, `prompt()`.** Errors go in a `Banner`; confirmations in `ConfirmModal`; hard deletes through `useDangerZoneDelete` + `DangerZone`.
9
+ 5. **Backend access only through `miniappApi` / `hubApi`.** No `fetch`, no hardcoded URL, no `process.env`/`import.meta.env` backend URL: the base URL is the application's `httpBackendUrl`, configured in the backoffice (Mini-Apps page).
10
+ 6. **`isApiError()`, never `instanceof ApiError`.** Errors are thrown by the host's copy of the SDK.
11
+ 7. **Backoffice conventions apply** (it is admin code, not mini-app WebView code): English UI text, Outfit (inherited), typography scale (`PageHeader`/`SectionHeader`/`Badge`...), Tailwind theme tokens, no arbitrary values (`text-[10px]`, `rounded-[2rem]`), no `any`, parallel DTO/model types with typed mappers, one component per file, alphabetical dynamic `Select` options.
12
+ 8. **WebP only** for every image upload (`ImageUpload` or `assertWebp`). Upload on save, never on select.
13
+ 9. **No `next/*` imports**, no Node APIs: the plugin runs in the browser outside Next.js.
14
+ 10. **Stable id.** `definePlugin({ id })` names the plugin's style slot and CSS scope; never change it between versions.
15
+
16
+ ## Pitfalls
17
+
18
+ - **Styles missing for a class**: Tailwind only generates classes it finds in `src/` and in the SDK. A class built by string concatenation (`` `text-${color}` ``) is never generated: write full class names.
19
+ - **Plugin styles leaking**: the host scopes the plugin's utilities to the plugin root with `@scope`. A portal to `document.body` renders outside that root and loses plugin-only classes: use the SDK `Modal` (no portal). The SDK `Select` menu is portaled but only uses classes the host already has.
20
+ - **"Plugin bundle checksum mismatch"**: the file served differs from the published one. Re-publish; never edit a bundle in storage.
21
+ - **"Shared module react is not provided"**: the bundle was loaded outside the backoffice, or built without `backofficePlugin()`.
22
+ - **"Invalid hook call" / two Reacts**: React got bundled (plugin order in `vite.config.ts`, or a `react` import aliased elsewhere). `grep -c __UP_BACKOFFICE_SHARED__ dist/plugin.js` must be 3.
23
+ - **401 from the mini-app backend**: the admin scoped token could not be minted (the admin is not admin anymore, or the application UUID is wrong). Show `AuthStatusBadge` and keep the page usable.
24
+ - **Empty page and a warning about `httpBackendUrl`**: the application has no backend URL in the hub; set it on the Mini-Apps page.
25
+ - **SDK not published yet**: depend on a local checkout with `"@cloudparse/up-backoffice-sdk": "file:<path>"` and `install-links=true` in `.npmrc` (a symlink would duplicate React). Re-run `npm install` after each SDK change.