diff --git a/apps/docs/src/content/contributing/demo-apps.md b/apps/docs/src/content/contributing/demo-apps.md index 608a1883..303c59de 100644 --- a/apps/docs/src/content/contributing/demo-apps.md +++ b/apps/docs/src/content/contributing/demo-apps.md @@ -116,6 +116,7 @@ It listens on port 4000, or on `PORT` when set. - API routes under `src/server/routes/api/v1`, with method suffixes such as `index.get.ts` and `index.post.ts`, and a timing middleware. - Markdown content under `src/content/blog` and `src/content/docs`. - Prerendered routes listed in `vite.config.ts`, and `/dashboard` as client only (`ssr: false`). +- A **Feature flags** tab from the example plugin package `examples/pangular-plugin-example`, with its `promo-banner` and `blog-teaser` flags on the home page. See [Ship a plugin from a library](../guides/ship-a-plugin.md). ### Run Analog in development @@ -127,7 +128,7 @@ The script builds the devtools package, then starts the Vite dev server. That de ### Type-check the Analog demo -`pnpm typecheck` runs `ngc -p examples/analog/tsconfig.app.json --noEmit`, so CI type-checks the demo's pages, templates, loaders, API routes and middleware. The demo resolves `@pangular-inspector/devtools` to the package source, which imports with `.ts` extensions, so `tsconfig.app.json` sets `rewriteRelativeImportExtensions`. +`pnpm typecheck` runs `ngc -p examples/analog/tsconfig.app.json --noEmit`, so CI type-checks the demo's pages, templates, loaders, API routes and middleware. The demo resolves `@pangular-inspector/devtools` to the package source, which imports with `.ts` extensions, so `tsconfig.app.json` sets `rewriteRelativeImportExtensions`. It also includes the sources of `examples/pangular-plugin-example`, which the demo imports as TypeScript, so the Analog compiler builds them. ### Build and preview diff --git a/apps/docs/src/content/guides/ship-a-plugin.md b/apps/docs/src/content/guides/ship-a-plugin.md new file mode 100644 index 00000000..a22e135a --- /dev/null +++ b/apps/docs/src/content/guides/ship-a-plugin.md @@ -0,0 +1,246 @@ +--- +title: Ship a plugin from a library +description: Package a Pangular tab and its agent tools with your library, so every app that uses the library gets them. +--- + + + Publish the tab with your package. An app adds one provider and one Vite option, and the panel shows your library's state. + + +# Ship a plugin from a library + +[Write a plugin](./write-a-plugin.md) builds a plugin inside one app. This guide puts the same parts in a library package, so the apps that install the library get its tab without writing one. + +The repository has a working example: `examples/pangular-plugin-example`, a small feature flag store with its own **Feature flags** tab and two agent tools. The Analog demo (`examples/analog`) uses it. The code on this page comes from those two folders. + +## Lay out the package + +Keep the devtools code out of the library's main entry point. An app that never loads Pangular Inspector then never loads the plugin either. + +| Entry point | File | What it holds | +| ------------------- | ------------------------ | --------------------------------------------------------------- | +| `.` | `src/index.ts` | The library itself. It imports nothing from Pangular Inspector. | +| `./pangular` | `src/pangular.ts` | The page plugin and a `register…` helper. Runs in the browser. | +| `./pangular-server` | `src/pangular-server.ts` | The server plugin with the agent tools. Runs in Node. | + +Both devtools entry points import `@pangular-inspector/devtools/plugin` only. That entry point is small and imports neither the overlay nor the server. + +Declare the devtools as an optional peer dependency, so apps without them install the library without a warning. The example's `package.json`: + +```json +{ + "name": "pangular-plugin-example", + "type": "module", + "sideEffects": false, + "exports": { + ".": "./src/index.ts", + "./pangular": "./src/pangular.ts", + "./pangular-server": "./src/pangular-server.ts" + }, + "peerDependencies": { + "@pangular-inspector/devtools": "^1.0.0" + }, + "peerDependenciesMeta": { + "@pangular-inspector/devtools": { + "optional": true + } + } +} +``` + +The example points `exports` at TypeScript sources because it lives in this workspace. A published library points them at its built JavaScript and type declarations. + + + The registry lives on globalThis, and every copy of the /plugin entry point shares it. If your build bundles its own copy of the entry point, the overlay still finds your plugin. + + +## Write the page entry + + + + Turn your library's state into a PluginView: a summary, badges, sections and the actions the panel shows as buttons. + + + Give it an id, a version, a collect function and the page actions. If your state changes outside Angular, push a view from setup on each change. + + + Wrap registerPangularPlugin(), so apps don't build the plugin themselves. + + + +The flag store calls its listeners on each change, which Angular does not see. The plugin subscribes in `setup` and returns the unsubscribe function as its cleanup: + +```ts +// examples/pangular-plugin-example/src/pangular.ts +import {registerPangularPlugin, type PangularPagePlugin} from '@pangular-inspector/devtools/plugin'; +import {FLAGS_PLUGIN_ID, FLAGS_PLUGIN_VERSION} from './ids.ts'; +import type {FlagStore} from './index.ts'; + +// flagsView(store) builds the PluginView; it is defined just above this in the same file. +export function flagsPangularPlugin(store: FlagStore): PangularPagePlugin { + return { + id: FLAGS_PLUGIN_ID, + version: FLAGS_PLUGIN_VERSION, + title: 'Feature flags', + description: 'Flags from the example feature flag store, with their defaults and overrides.', + setup: (ctx) => store.subscribe(() => ctx.push(flagsView(store))), + collect: () => flagsView(store), + actions: { + set: (args) => { + const {name, value} = (args ?? {}) as {name?: unknown; value?: unknown}; + if (typeof name !== 'string' || typeof value !== 'boolean') { + throw new Error('Pass { name: string, value: boolean }.'); + } + if (!store.set(name, value)) throw new Error(`There is no flag ${name}.`); + return {name, value}; + }, + reset: () => ({reset: store.reset()}), + }, + }; +} + +export function registerFlagsPangularPlugin(store: FlagStore): () => void { + return registerPangularPlugin(flagsPangularPlugin(store)); +} +``` + +`flagsView()`, in the same file, returns a stats section and a table of flags. Its full source is in [`examples/pangular-plugin-example/src/pangular.ts`](https://github.com/pangular-inspector/devtools/blob/main/examples/pangular-plugin-example/src/pangular.ts). It lists the `reset` action while a flag is overridden. An error a page action throws reaches the agent as the tool's answer. The [sections table](./write-a-plugin.md#sections) lists every section kind. + +Keep the plugin id and version in a file both entry points import (`src/ids.ts` in the example), so the page plugin and the server plugin always match. + +## Write the server entry + +The server plugin adds agent tools over what the page reports. A tool that runs a page action declares `safety: 'action'`, so `agent.readOnly` and the action switches drop it: + +```ts +// examples/pangular-plugin-example/src/pangular-server.ts +import {definePangularServerPlugin} from '@pangular-inspector/devtools/plugin'; +import {FLAGS_PLUGIN_ID, FLAGS_PLUGIN_VERSION} from './ids.ts'; + +const PAGE = { + type: 'string', + description: 'Page id, when more than one tab reports (see pangular:list-pages).', +}; +const pageArg = (args: Record) => + typeof args['page'] === 'string' ? args['page'] : undefined; + +export const flagsServerPlugin = definePangularServerPlugin({ + id: FLAGS_PLUGIN_ID, + version: FLAGS_PLUGIN_VERSION, + title: 'Feature flags', + tools: [ + { + name: 'flags', + description: 'Every flag in the feature flag store on the running page.', + inputSchema: {type: 'object', properties: {page: PAGE}}, + handler: (args, ctx) => { + const page = ctx.page(pageArg(args)); + if (!page?.view) return 'No page runs the feature flag store. Open the app in a browser.'; + return ctx.markdown(page.view); + }, + }, + { + name: 'set', + safety: 'action', + description: 'Turn one flag on or off on the running page until it reloads.', + inputSchema: { + type: 'object', + properties: {name: {type: 'string'}, value: {type: 'boolean'}, page: PAGE}, + required: ['name', 'value'], + }, + handler: async (args, ctx) => { + const result = await ctx.runPageAction( + 'set', + {name: args['name'], value: args['value']}, + {page: pageArg(args)}, + ); + if (!result.ok) return result.error ?? 'The action failed.'; + return `Turned \`${String(args['name'])}\` ${args['value'] ? 'on' : 'off'} on page \`${result.pageId}\`.`; + }, + }, + ], +}); +``` + +The tools register as `pangular:plugin:feature-flags:flags` and `pangular:plugin:feature-flags:set`. See [Add agent tools](./write-a-plugin.md#add-agent-tools) for the naming and length rules. + +## Use it in an app + +Your library lists `@pangular-inspector/devtools` as an optional peer dependency, so an app that wants the tab installs it as its own development dependency first: + +```bash group="install" name="pnpm" image="https://cdn.simpleicons.org/pnpm/F69220" active +pnpm add -D @pangular-inspector/devtools +``` + +```bash group="install" name="npm" image="https://cdn.simpleicons.org/npm/CB3837" +npm install -D @pangular-inspector/devtools +``` + +```bash group="install" name="yarn" image="https://cdn.simpleicons.org/yarn/2C8EBB" +yarn add -D @pangular-inspector/devtools +``` + +```bash group="install" name="bun" image="https://bun.sh/logo.svg" +bun add -D @pangular-inspector/devtools +``` + +Then tell the apps that use your library to make two changes. + + + + Load the ./pangular entry point with a dynamic import() in the browser, in development builds only. + + + Add it to serverPlugins of the Vite plugin or of initPangularHub(). + + + +The Analog demo keeps its flags in a `FeatureFlags` service and registers the tab from an app initializer. The dynamic import keeps the page entry out of the main bundle: + +```ts +// From examples/analog/src/app/shared/feature-flags.ts +export function provideFeatureFlagsPangularPlugin(): EnvironmentProviders { + return provideAppInitializer(() => { + if (typeof ngDevMode !== 'undefined' && !ngDevMode) return; + if (!isPlatformBrowser(inject(PLATFORM_ID))) return; + const flags = inject(FeatureFlags); + const destroyRef = inject(DestroyRef); + void import('pangular-plugin-example/pangular').then(({registerFlagsPangularPlugin}) => { + if (destroyRef.destroyed) return; + destroyRef.onDestroy(registerFlagsPangularPlugin(flags.store)); + }); + }); +} +``` + +The complete file, with its imports and the `FeatureFlags` service, is [`examples/analog/src/app/shared/feature-flags.ts`](https://github.com/pangular-inspector/devtools/blob/main/examples/analog/src/app/shared/feature-flags.ts). It needs Angular 22 or later, since it uses `@Service()`, `DestroyRef.destroyed` and `provideAppInitializer()`. Add `provideFeatureFlagsPangularPlugin()` to the app's providers. Then pass the server plugin to the Vite plugin: + +```ts {4,8} +// examples/analog/vite.config.ts +import analog from '@analogjs/platform'; +import pangular from '@pangular-inspector/devtools/vite'; +import {flagsServerPlugin} from 'pangular-plugin-example/pangular-server'; +import {defineConfig} from 'vite'; + +export default defineConfig(() => ({ + plugins: [analog(), pangular({serverPlugins: [flagsServerPlugin]})], +})); +``` + +An Express app passes the same array to `initPangularHub({serverPlugins})`, as [Add agent tools](./write-a-plugin.md#add-agent-tools) shows. Either way, the app must load the [overlay](../getting-started/overlay.md), or no plugin view appears in the panel. + +Run `pnpm analog:dev` and open the panel. The **Plugins** tab lists **Feature flags**. Ask an agent to turn `promo-banner` on, and the banner appears on the home page. + +## Test the plugin + +Test the plugin the way the repository tests the example: `packages/devtools/src/__tests__/plugin-example.test.ts` registers the page plugin, runs it with the overlay's plugins collector, boots a devframe with the server plugin, and wires the two together. An agent tool call then runs the page action and returns its answer, with no browser. + +For a library outside this repository, test `flagsView()` and the actions against your own store, and the tool handlers against a stub context that returns a page from `page()`. + +## Where to next + + + + + + diff --git a/apps/docs/src/content/guides/write-a-plugin.md b/apps/docs/src/content/guides/write-a-plugin.md index 82600399..fcee4ca4 100644 --- a/apps/docs/src/content/guides/write-a-plugin.md +++ b/apps/docs/src/content/guides/write-a-plugin.md @@ -22,7 +22,7 @@ A plugin has up to two parts: -The demo app ships an example plugin for its `TravelStore`: `src/app/devtools/travel-plugin.ts` for the page and `src/app/devtools/travel-plugin.server.ts` for the server. This guide builds it step by step. +The demo app ships an example plugin for its `TravelStore`: `src/app/devtools/travel-plugin.ts` for the page and `src/app/devtools/travel-plugin.server.ts` for the server. This guide builds it step by step. To publish a plugin with a library instead, see [Ship a plugin from a library](./ship-a-plugin.md). ## Write the page plugin diff --git a/apps/docs/src/ngmd.config.ts b/apps/docs/src/ngmd.config.ts index 6d4a0a23..f8fbd0a5 100644 --- a/apps/docs/src/ngmd.config.ts +++ b/apps/docs/src/ngmd.config.ts @@ -233,6 +233,7 @@ const config: NgmdConfig = { {label: 'Set up Angular Native', href: '/guides/angular-native'}, {label: 'Set up Capacitor', href: '/guides/capacitor'}, {label: 'Write a plugin', href: '/guides/write-a-plugin'}, + {label: 'Ship a plugin from a library', href: '/guides/ship-a-plugin'}, {label: 'Inspect, fix and verify', href: '/guides/inspect-fix-verify'}, ], }, diff --git a/examples/analog/package.json b/examples/analog/package.json index aa75091f..f6460abd 100644 --- a/examples/analog/package.json +++ b/examples/analog/package.json @@ -24,6 +24,7 @@ "marked-gfm-heading-id": "^4.1.1", "marked-highlight": "^2.2.1", "marked-mangle": "^1.1.10", + "pangular-plugin-example": "workspace:*", "prismjs": "^1.29.0", "rxjs": "~7.8.0", "tslib": "^2.3.0" diff --git a/examples/analog/src/app/app.config.ts b/examples/analog/src/app/app.config.ts index 866a6061..cf9f0bb8 100644 --- a/examples/analog/src/app/app.config.ts +++ b/examples/analog/src/app/app.config.ts @@ -5,6 +5,7 @@ import { withComponentInputBinding } from '@angular/router'; import { provideContent, withMarkdownRenderer } from '@analogjs/content'; import { provideFileRouter, requestContextInterceptor } from '@analogjs/router'; import { providePangularHttp } from '@pangular-inspector/devtools/http'; +import { provideFeatureFlagsPangularPlugin } from './shared/feature-flags'; export const appConfig: ApplicationConfig = { providers: [ @@ -14,5 +15,6 @@ export const appConfig: ApplicationConfig = { provideClientHydration(withEventReplay()), provideContent(withMarkdownRenderer()), providePangularHttp(), + provideFeatureFlagsPangularPlugin(), ], }; diff --git a/examples/analog/src/app/pages/index.page.ts b/examples/analog/src/app/pages/index.page.ts index f4a1527c..b41650bf 100644 --- a/examples/analog/src/app/pages/index.page.ts +++ b/examples/analog/src/app/pages/index.page.ts @@ -1,8 +1,9 @@ import { NgOptimizedImage } from '@angular/common'; -import { Component, input } from '@angular/core'; +import { Component, inject, input } from '@angular/core'; import { RouterLink } from '@angular/router'; import type { LoadResult, RouteMeta } from '@analogjs/router'; import { injectContentFiles } from '@analogjs/content'; +import { FeatureFlags } from '../shared/feature-flags'; import { ProductCard } from '../shared/product-card'; import type { load } from './index.server'; @@ -19,6 +20,9 @@ export const routeMeta: RouteMeta = { @Component({ imports: [ProductCard, RouterLink, NgOptimizedImage], template: ` + @if (flags.enabled('promo-banner')) { +

Free shipping on every order this week.

+ }
} -

From the blog

- + @if (flags.enabled('blog-teaser')) { +

From the blog

+ + } `, }) export default class Home { readonly load = input.required>(); + protected readonly flags = inject(FeatureFlags); protected readonly posts = injectContentFiles((file) => file.filename.includes('content/blog/'), ) diff --git a/examples/analog/src/app/shared/feature-flags.ts b/examples/analog/src/app/shared/feature-flags.ts new file mode 100644 index 00000000..2b8efa3c --- /dev/null +++ b/examples/analog/src/app/shared/feature-flags.ts @@ -0,0 +1,60 @@ +import { isPlatformBrowser } from '@angular/common'; +import { + DestroyRef, + PLATFORM_ID, + Service, + inject, + provideAppInitializer, + signal, + type EnvironmentProviders, +} from '@angular/core'; +import { createFlagStore } from 'pangular-plugin-example'; + +/** + * The shop's feature flags, kept in the example library's store. The store + * knows nothing about Angular, so this service bumps a signal on each change + * and templates that read `enabled()` update. + */ +@Service() +export class FeatureFlags { + readonly store = createFlagStore({ + 'promo-banner': { + default: false, + description: 'Shows the free shipping banner on the home page.', + }, + 'blog-teaser': { + default: true, + description: 'Lists the latest blog posts on the home page.', + }, + }); + + private readonly changes = signal(0); + + constructor() { + const stop = this.store.subscribe(() => this.changes.update((count) => count + 1)); + inject(DestroyRef).onDestroy(stop); + } + + enabled(name: string): boolean { + this.changes(); + return this.store.enabled(name); + } +} + +/** + * Registers the flag store's Pangular tab in development builds in the + * browser. The library's `./pangular` entry is loaded on demand, so the main + * bundle never carries it. + */ +export function provideFeatureFlagsPangularPlugin(): EnvironmentProviders { + return provideAppInitializer(() => { + if (typeof ngDevMode !== 'undefined' && !ngDevMode) return; + if (!isPlatformBrowser(inject(PLATFORM_ID))) return; + const flags = inject(FeatureFlags); + const destroyRef = inject(DestroyRef); + void import('pangular-plugin-example/pangular').then(({ registerFlagsPangularPlugin }) => { + if (destroyRef.destroyed) return; + destroyRef.onDestroy(registerFlagsPangularPlugin(flags.store)); + }); + }); +} diff --git a/examples/analog/src/styles.css b/examples/analog/src/styles.css index a9ecf790..d0dbe6d2 100644 --- a/examples/analog/src/styles.css +++ b/examples/analog/src/styles.css @@ -155,6 +155,15 @@ h2 { font-size: 1.3rem; } +.promo { + margin: 16px 0 0; + padding: 10px 14px; + border: 1px solid var(--line); + border-radius: 8px; + background: var(--soft); + text-align: center; +} + .hero { display: grid; justify-items: center; diff --git a/examples/analog/tsconfig.app.json b/examples/analog/tsconfig.app.json index e803ab91..3e91173a 100644 --- a/examples/analog/tsconfig.app.json +++ b/examples/analog/tsconfig.app.json @@ -2,9 +2,15 @@ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/app", + "rootDir": "..", "types": [], "rewriteRelativeImportExtensions": true }, "files": ["src/main.ts", "src/main.server.ts"], - "include": ["src/**/*.d.ts", "src/app/pages/**/*.page.ts", "src/server/**/*.ts"] + "include": [ + "src/**/*.d.ts", + "src/app/pages/**/*.page.ts", + "src/server/**/*.ts", + "../pangular-plugin-example/src/**/*.ts" + ] } diff --git a/examples/analog/vite.config.ts b/examples/analog/vite.config.ts index 1b6571fb..3dd3a122 100644 --- a/examples/analog/vite.config.ts +++ b/examples/analog/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url'; import { defineConfig } from 'vite'; import analog from '@analogjs/platform'; import pangular from '@pangular-inspector/devtools/vite'; +import { flagsServerPlugin } from 'pangular-plugin-example/pangular-server'; export default defineConfig(() => ({ build: { @@ -40,6 +41,6 @@ export default defineConfig(() => ({ highlighter: 'prism', }, }), - pangular(), + pangular({ serverPlugins: [flagsServerPlugin] }), ], })); diff --git a/examples/pangular-plugin-example/README.md b/examples/pangular-plugin-example/README.md new file mode 100644 index 00000000..adc7d915 --- /dev/null +++ b/examples/pangular-plugin-example/README.md @@ -0,0 +1,13 @@ +# pangular-plugin-example + +An example library that ships its own Pangular Inspector tab. It is a small feature flag store, standing in for any library (a store add-on, a query cache, a UI kit) that wants to show its state in the panel and to agents. + +| Entry point | File | What it holds | +| ------------------- | ------------------------ | ----------------------------------------------------------------------------------------------- | +| `.` | `src/index.ts` | `createFlagStore()`, the library. It imports nothing from Pangular Inspector. | +| `./pangular` | `src/pangular.ts` | The page plugin (`flagsPangularPlugin`, `registerFlagsPangularPlugin`) for the **Plugins** tab. | +| `./pangular-server` | `src/pangular-server.ts` | `flagsServerPlugin`, with the `flags` (read) and `set` (action) agent tools. | + +The Analog demo (`examples/analog`) uses it: `src/app/shared/feature-flags.ts` registers the tab and `vite.config.ts` passes `flagsServerPlugin` to the Vite plugin. `packages/devtools/src/__tests__/plugin-example.test.ts` loads both entry points and runs a tool call through to the page action. + +The guide is [Ship a plugin from a library](../../apps/docs/src/content/guides/ship-a-plugin.md). diff --git a/examples/pangular-plugin-example/package.json b/examples/pangular-plugin-example/package.json new file mode 100644 index 00000000..6ae4500b --- /dev/null +++ b/examples/pangular-plugin-example/package.json @@ -0,0 +1,25 @@ +{ + "name": "pangular-plugin-example", + "version": "1.0.0", + "private": true, + "description": "An example library that ships its own Pangular Inspector tab and agent tools through the plugin API.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "exports": { + ".": "./src/index.ts", + "./pangular": "./src/pangular.ts", + "./pangular-server": "./src/pangular-server.ts" + }, + "peerDependencies": { + "@pangular-inspector/devtools": "^1.0.0" + }, + "peerDependenciesMeta": { + "@pangular-inspector/devtools": { + "optional": true + } + }, + "devDependencies": { + "@pangular-inspector/devtools": "workspace:*" + } +} diff --git a/examples/pangular-plugin-example/src/ids.ts b/examples/pangular-plugin-example/src/ids.ts new file mode 100644 index 00000000..e4c60afc --- /dev/null +++ b/examples/pangular-plugin-example/src/ids.ts @@ -0,0 +1,3 @@ +// Shared by the page and server entries, so both name the same plugin. +export const FLAGS_PLUGIN_ID = 'feature-flags'; +export const FLAGS_PLUGIN_VERSION = '1.0.0'; diff --git a/examples/pangular-plugin-example/src/index.ts b/examples/pangular-plugin-example/src/index.ts new file mode 100644 index 00000000..e1cbcdd2 --- /dev/null +++ b/examples/pangular-plugin-example/src/index.ts @@ -0,0 +1,72 @@ +// A tiny feature flag store, standing in for any library that wants its own +// Pangular tab. It knows nothing about Pangular Inspector: the tab lives in +// the `./pangular` entry and the agent tools in `./pangular-server`, so an app +// that never loads the devtools never loads them either. + +export interface FlagDefinition { + /** Whether the flag is on until something overrides it. */ + default: boolean; + description?: string; +} + +export interface FlagState { + name: string; + description: string; + default: boolean; + value: boolean; + /** Whether `set()` changed it away from its default. */ + overridden: boolean; +} + +export interface FlagStore { + /** Every flag in the order it was defined. */ + list(): FlagState[]; + /** Whether a flag is on. An unknown flag is off. */ + enabled(name: string): boolean; + /** Turns a known flag on or off. Returns `false` for an unknown flag. */ + set(name: string, value: boolean): boolean; + /** Puts every flag back to its default and returns how many changed. */ + reset(): number; + /** Calls `listener` after every change; returns a function that stops it. */ + subscribe(listener: () => void): () => void; +} + +/** Creates a store from flag definitions, keyed by flag name. */ +export function createFlagStore(definitions: Record): FlagStore { + const overrides = new Map(); + const listeners = new Set<() => void>(); + const known = (name: string) => Object.hasOwn(definitions, name); + const notify = () => { + for (const listener of [...listeners]) listener(); + }; + const valueOf = (name: string) => overrides.get(name) ?? definitions[name]!.default; + + return { + list: () => + Object.entries(definitions).map(([name, definition]) => ({ + name, + description: definition.description ?? '', + default: definition.default, + value: valueOf(name), + overridden: overrides.has(name), + })), + enabled: (name) => known(name) && valueOf(name), + set(name, value) { + if (!known(name)) return false; + if (value === definitions[name]!.default) overrides.delete(name); + else overrides.set(name, value); + notify(); + return true; + }, + reset() { + const changed = overrides.size; + overrides.clear(); + if (changed) notify(); + return changed; + }, + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + }; +} diff --git a/examples/pangular-plugin-example/src/pangular-server.ts b/examples/pangular-plugin-example/src/pangular-server.ts new file mode 100644 index 00000000..b0a5a0f9 --- /dev/null +++ b/examples/pangular-plugin-example/src/pangular-server.ts @@ -0,0 +1,57 @@ +// The server side of the feature flag store's Pangular tab: agent tools over +// what the page side reports. An app passes `flagsServerPlugin` to the hub or +// the Vite plugin as `serverPlugins`. It runs in Node. +import { definePangularServerPlugin } from '@pangular-inspector/devtools/plugin'; +import { FLAGS_PLUGIN_ID, FLAGS_PLUGIN_VERSION } from './ids.ts'; + +const PAGE = { + type: 'string', + description: 'Page id, when more than one tab reports (see pangular:list-pages).', +}; + +const pageArg = (args: Record) => + typeof args['page'] === 'string' ? args['page'] : undefined; + +export const flagsServerPlugin = definePangularServerPlugin({ + id: FLAGS_PLUGIN_ID, + version: FLAGS_PLUGIN_VERSION, + title: 'Feature flags', + description: 'Reads and changes the example feature flag store on the running page.', + tools: [ + { + name: 'flags', + description: + 'Every flag in the feature flag store on the running page, with its state, default and description. Says so when no page runs the store.', + inputSchema: { type: 'object', properties: { page: PAGE } }, + handler: (args, ctx) => { + const page = ctx.page(pageArg(args)); + if (!page?.view) return 'No page runs the feature flag store. Open the app in a browser.'; + return ctx.markdown(page.view); + }, + }, + { + name: 'set', + safety: 'action', + description: + 'Turn one flag on or off on the running page until it reloads. Use the `flags` tool first for the names.', + inputSchema: { + type: 'object', + properties: { + name: { type: 'string', description: 'The flag name.' }, + value: { type: 'boolean', description: 'true turns it on, false turns it off.' }, + page: PAGE, + }, + required: ['name', 'value'], + }, + handler: async (args, ctx) => { + const result = await ctx.runPageAction( + 'set', + { name: args['name'], value: args['value'] }, + { page: pageArg(args) }, + ); + if (!result.ok) return result.error ?? 'The action failed.'; + return `Turned \`${String(args['name'])}\` ${args['value'] ? 'on' : 'off'} on page \`${result.pageId}\`.`; + }, + }, + ], +}); diff --git a/examples/pangular-plugin-example/src/pangular.ts b/examples/pangular-plugin-example/src/pangular.ts new file mode 100644 index 00000000..1ec9623d --- /dev/null +++ b/examples/pangular-plugin-example/src/pangular.ts @@ -0,0 +1,91 @@ +// The page side of the feature flag store's Pangular tab. An app imports this +// entry in development only and calls `registerFlagsPangularPlugin(store)`. +// The overlay picks the plugin up whether it loads before or after, and the +// panel shows the view in its Plugins tab. +import { + registerPangularPlugin, + type PangularPagePlugin, + type PluginView, +} from '@pangular-inspector/devtools/plugin'; +import { FLAGS_PLUGIN_ID, FLAGS_PLUGIN_VERSION } from './ids.ts'; +import type { FlagStore } from './index.ts'; + +export { FLAGS_PLUGIN_ID, FLAGS_PLUGIN_VERSION }; + +/** The view the panel renders and agents read. */ +export function flagsView(store: FlagStore): PluginView { + const flags = store.list(); + const on = flags.filter((flag) => flag.value).length; + const overridden = flags.filter((flag) => flag.overridden).length; + return { + summary: `${flags.length} ${flags.length === 1 ? 'flag' : 'flags'}, ${on} on, ${overridden} overridden`, + badges: overridden ? [{ label: `${overridden} overridden`, tone: 'warn' }] : [], + sections: [ + { + kind: 'stats', + title: 'Totals', + items: [ + { label: 'Flags', value: flags.length }, + { label: 'On', value: on, tone: on ? 'ok' : 'neutral' }, + { label: 'Overridden', value: overridden, tone: overridden ? 'warn' : 'neutral' }, + ], + }, + { + kind: 'table', + title: 'Flags', + columns: [ + { key: 'name', label: 'Flag' }, + { key: 'value', label: 'State' }, + { key: 'default', label: 'Default' }, + { key: 'description', label: 'Description' }, + ], + rows: flags.map((flag) => ({ + name: flag.name, + value: { text: flag.value ? 'on' : 'off', tone: flag.overridden ? 'warn' : 'neutral' }, + default: flag.default ? 'on' : 'off', + description: flag.description, + })), + empty: 'The store defines no flags.', + }, + ], + actions: overridden + ? [ + { + name: 'reset', + label: 'Reset every flag', + confirm: 'Put every flag back to its default?', + }, + ] + : [], + }; +} + +/** The page plugin for one store. */ +export function flagsPangularPlugin(store: FlagStore): PangularPagePlugin { + return { + id: FLAGS_PLUGIN_ID, + version: FLAGS_PLUGIN_VERSION, + title: 'Feature flags', + description: 'Flags from the example feature flag store, with their defaults and overrides.', + // The store changes outside Angular's change detection, so report on each + // change instead of waiting for the next collect. + setup: (ctx) => store.subscribe(() => ctx.push(flagsView(store))), + collect: () => flagsView(store), + actions: { + set: (args) => { + const { name, value } = (args ?? {}) as { name?: unknown; value?: unknown }; + if (typeof name !== 'string' || typeof value !== 'boolean') { + throw new Error('Pass { name: string, value: boolean }.'); + } + if (!store.set(name, value)) throw new Error(`There is no flag ${name}.`); + return { name, value }; + }, + reset: () => ({ reset: store.reset() }), + }, + }; +} + +/** Registers the store's tab and returns a function that removes it. */ +export function registerFlagsPangularPlugin(store: FlagStore): () => void { + return registerPangularPlugin(flagsPangularPlugin(store)); +} diff --git a/examples/pangular-plugin-example/tsconfig.json b/examples/pangular-plugin-example/tsconfig.json new file mode 100644 index 00000000..7a9e151a --- /dev/null +++ b/examples/pangular-plugin-example/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "preserve", + "moduleResolution": "bundler", + "strict": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "skipLibCheck": true, + "isolatedModules": true, + "types": [], + "lib": ["ES2022", "DOM"] + }, + "include": ["src/**/*.ts"] +} diff --git a/package.json b/package.json index abec0fe4..9a295751 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "test:coverage": "pnpm test:devtools --coverage --testTimeout=20000 && pnpm test:panel --coverage --testTimeout=20000", "test:axe": "pnpm devtools:build-pkg && node bin.mjs build --outDir dist/panel-axe && node scripts/panel-axe.mjs dist/panel-axe", "test:axe:extension": "node scripts/extension-axe.mjs dist/panel-axe", - "typecheck": "tsc -p tsconfig.app.json --noEmit && tsc -p tsconfig.spec.json --noEmit && ngc -p app/tsconfig.json --noEmit && ngc -p examples/analog/tsconfig.app.json --noEmit && tsc -p packages/devtools", + "typecheck": "tsc -p tsconfig.app.json --noEmit && tsc -p tsconfig.spec.json --noEmit && ngc -p app/tsconfig.json --noEmit && ngc -p examples/analog/tsconfig.app.json --noEmit && tsc -p packages/devtools && tsc -p examples/pangular-plugin-example", "format": "prettier --write .", "format:check": "prettier --check .", "serve:ssr:pangular-inspector": "node dist/pangular-inspector/server/server.mjs", diff --git a/packages/devtools/CHANGELOG.md b/packages/devtools/CHANGELOG.md index 43afea64..93072b8f 100644 --- a/packages/devtools/CHANGELOG.md +++ b/packages/devtools/CHANGELOG.md @@ -298,6 +298,7 @@ What remains: `/config` exports `DEFAULT_POPUP_HOTKEY`, `PANGULAR_ACTIONS`, `PAN - A quick start, and a panel screenshot on every inspector page. - Pages for the command palette, settings, terminals, the popup and hub, configuration, other servers (Hono, h3, Fastify), Capacitor, the timeline, errors, audit, TanStack Query, agent skills, browser agents and writing a plugin. +- A guide to shipping a plugin from a library, built on the example plugin package `examples/pangular-plugin-example` (a feature flag store with its own tab and agent tools), which the Analog demo uses (#404). - A roadmap page. - The Capacitor and NativeScript guides show the Android network security config and the iOS App Transport Security and local network settings a device needs to reach the devtools over the LAN (#373). - The Express and other servers pages say which port the WebSocket side-car uses (the first free one from 9777), how to pin it with `ws: {port}`, and how to serve the socket on the app's own server with `attach(server)` (#426). diff --git a/packages/devtools/src/__tests__/plugin-example.test.ts b/packages/devtools/src/__tests__/plugin-example.test.ts new file mode 100644 index 00000000..76e5d42e --- /dev/null +++ b/packages/devtools/src/__tests__/plugin-example.test.ts @@ -0,0 +1,230 @@ +// @vitest-environment jsdom +// Loads the example plugin package (`examples/pangular-plugin-example`) the +// way an app does: its page entry registers through the public registry, the +// overlay's plugins collector runs it, and its server entry adds agent tools +// to a real devframe. The page and server RPCs are wired to each other, so a +// tool call goes all the way to the page action and back. +import { createHostContext } from 'devframe/node'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { resolvePangularConfig, type PangularConfig } from '../config.ts'; +import { createPangular } from '../devframe.ts'; +import { pangularPluginRegistry } from '../plugin.ts'; +import { attachPlugins, type PluginsReport } from '../plugins-collector.ts'; +import type { PluginsState } from '../rpc/plugins-register.ts'; +import { createFlagStore } from '../../../../examples/pangular-plugin-example/src/index.ts'; +import { + FLAGS_PLUGIN_ID, + flagsView, + registerFlagsPangularPlugin, +} from '../../../../examples/pangular-plugin-example/src/pangular.ts'; +import { flagsServerPlugin } from '../../../../examples/pangular-plugin-example/src/pangular-server.ts'; +import { answerText } from './tool-answer.ts'; + +type Handler = (...args: any[]) => unknown; + +const store = () => + createFlagStore({ + 'promo-banner': { default: false, description: 'Shows the promo banner.' }, + 'blog-teaser': { default: true }, + }); + +async function server(config: PangularConfig = {}) { + const host = { + mountStatic: () => {}, + resolveOrigin: () => 'http://localhost', + getStorageDir: () => '', + }; + const ctx = await createHostContext({ cwd: process.cwd(), mode: 'dev', host: host as never }); + await createPangular(config, { serverPlugins: [flagsServerPlugin] }).setup(ctx as never); + const call = (name: string, payload: unknown) => + ctx.rpc.invokeLocal(`pangular:${name}` as never, ...([payload] as never)); + const invoke = (id: string, args: Record = {}) => + answerText(ctx.agent.invoke(id, args)); + const sharedState = ( + ctx.rpc as unknown as { + sharedState: { get: (key: string) => Promise<{ value: () => unknown }> }; + } + ).sharedState; + const state = async () => (await sharedState.get('pangular:plugins')).value() as PluginsState; + return { ctx, call, invoke, state }; +} + +/** Starts the plugins collector for one page, with its RPC wired to the server. */ +function page( + pageId: string, + backend: Awaited>, + config: PangularConfig = {}, +) { + const handlers = new Map(); + const pushes: PluginsReport[] = []; + const calls: { name: string; payload: unknown }[] = []; + const collector = attachPlugins( + { + rpc: { + call: async (name: string, ...args: unknown[]) => { + calls.push({ name, payload: args[0] }); + if (name === 'push-plugins') pushes.push(args[0] as PluginsReport); + return backend.call(name, args[0]); + }, + register: (definition: { name: string; handler: Handler }) => { + handlers.set(definition.name, definition.handler); + }, + }, + }, + pageId, + () => undefined, + { config: resolvePangularConfig(config) }, + ); + cleanups.push(() => collector.stop()); + // The server broadcasts page actions; this page answers the ones for it. + vi.spyOn(backend.ctx.rpc, 'broadcast').mockImplementation(((request: { + method: string; + args: unknown[]; + }) => { + if (request.method === 'pangular:plugin-action') + handlers.get('plugin-action')?.(request.args[0]); + }) as never); + return { collector, pushes, handlers, calls }; +} + +const cleanups: (() => void)[] = []; +afterEach(() => { + for (const cleanup of cleanups.splice(0)) cleanup(); + vi.restoreAllMocks(); +}); + +describe('the example plugin package', () => { + it('registers its page plugin through the public registry and removes it again', () => { + const unregister = registerFlagsPangularPlugin(store()); + expect(pangularPluginRegistry().plugins.map((plugin) => plugin.id)).toEqual([FLAGS_PLUGIN_ID]); + unregister(); + expect(pangularPluginRegistry().plugins).toEqual([]); + }); + + it('describes the flags as a view the panel can render', () => { + const flags = store(); + expect(flagsView(flags)).toMatchObject({ + summary: '2 flags, 1 on, 0 overridden', + badges: [], + actions: [], + }); + flags.set('promo-banner', true); + const view = flagsView(flags); + expect(view.summary).toBe('2 flags, 2 on, 1 overridden'); + expect(view.sections.map((section) => section.kind)).toEqual(['stats', 'table']); + expect(view.actions).toEqual([expect.objectContaining({ name: 'reset' })]); + // Setting a flag back to its default is no override. + flags.set('promo-banner', false); + expect(flagsView(flags).summary).toBe('2 flags, 1 on, 0 overridden'); + }); + + it("reports the store's tab from the page, with the page id, and pushes each change", async () => { + const backend = await server(); + const flags = store(); + cleanups.push(registerFlagsPangularPlugin(flags)); + const { collector, pushes } = page('tab1', backend); + await collector.push(true); + expect(pushes[0]).toMatchObject({ + pageId: 'tab1', + plugins: [ + { + id: 'feature-flags', + version: '1.0.0', + title: 'Feature flags', + status: 'running', + actions: ['set', 'reset'], + }, + ], + }); + expect((await backend.state()).pages['tab1']).toBeDefined(); + + // The store changes outside Angular; the plugin pushes on its own. + flags.set('promo-banner', true); + await vi.waitFor(() => + expect(pushes.at(-1)?.plugins[0]?.view?.summary).toBe('2 flags, 2 on, 1 overridden'), + ); + }); + + it('adds read and action tools under its own namespace', async () => { + const backend = await server(); + const ids = backend.ctx.agent + .list() + .tools.filter((tool) => tool.id.startsWith('pangular:plugin:')) + .map((tool) => [tool.id, tool.safety]); + expect(ids).toEqual([ + ['pangular:plugin:feature-flags:flags', 'read'], + ['pangular:plugin:feature-flags:set', 'action'], + ]); + const readOnly = await server({ agent: { readOnly: true } }); + expect( + readOnly.ctx.agent + .list() + .tools.map((tool) => tool.id) + .filter((id) => id.startsWith('pangular:plugin:')), + ).toEqual(['pangular:plugin:feature-flags:flags']); + }); + + it('answers the read tool from the page report, and says so when no page runs it', async () => { + const backend = await server(); + expect(await backend.invoke('pangular:plugin:feature-flags:flags')).toContain( + 'No page runs the feature flag store', + ); + cleanups.push(registerFlagsPangularPlugin(store())); + const { collector } = page('tab1', backend); + await collector.push(true); + const text = await backend.invoke('pangular:plugin:feature-flags:flags'); + expect(text).toContain('This answer comes from the feature-flags plugin'); + expect(text).toContain('| promo-banner | off | off | Shows the promo banner. |'); + }); + + it('turns a flag on from an agent tool through the page action', async () => { + const backend = await server(); + const flags = store(); + cleanups.push(registerFlagsPangularPlugin(flags)); + const { collector } = page('tab1', backend); + await collector.push(true); + const answer = await backend.invoke('pangular:plugin:feature-flags:set', { + name: 'promo-banner', + value: true, + }); + expect(answer).toContain('Turned `promo-banner` on on page `tab1`.'); + expect(flags.enabled('promo-banner')).toBe(true); + const unknown = await backend.invoke('pangular:plugin:feature-flags:set', { + name: 'nope', + value: true, + }); + expect(unknown).toContain('There is no flag nope.'); + }); + + it('keeps the page action from running while actions are off', async () => { + const config: PangularConfig = { plugins: { 'feature-flags': { actions: false } } }; + const backend = await server(config); + const flags = store(); + cleanups.push(registerFlagsPangularPlugin(flags)); + const { collector, handlers, calls } = page('tab1', backend, config); + await collector.push(true); + handlers.get('plugin-action')?.({ + requestId: 'r1', + pageId: 'tab1', + pluginId: 'feature-flags', + action: 'set', + args: { name: 'promo-banner', value: true }, + }); + await vi.waitFor(() => + expect(calls.find((call) => call.name === 'plugin-action-result')?.payload).toMatchObject({ + requestId: 'r1', + result: { + ok: false, + error: 'Actions of the feature-flags plugin are turned off in the devtools config.', + }, + }), + ); + expect(flags.enabled('promo-banner')).toBe(false); + expect( + backend.ctx.agent + .list() + .tools.map((tool) => tool.id) + .filter((id) => id.startsWith('pangular:plugin:')), + ).toEqual(['pangular:plugin:feature-flags:flags']); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f6cb0f4d..46f5aea0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -314,6 +314,9 @@ importers: marked-mangle: specifier: ^1.1.10 version: 1.1.14(marked@15.0.12) + pangular-plugin-example: + specifier: workspace:* + version: link:../pangular-plugin-example prismjs: specifier: ^1.29.0 version: 1.30.0 @@ -346,6 +349,12 @@ importers: specifier: ^8.3.0 version: 8.3.0(@types/node@24.13.6)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.105.0)(terser@5.51.2)(yaml@2.9.0) + examples/pangular-plugin-example: + devDependencies: + '@pangular-inspector/devtools': + specifier: workspace:* + version: link:../../packages/devtools + packages/devtools: dependencies: '@devframes/agentic':