Polarion Applications
Polarion Applications
Early Access in Polarion 2612
Polarion Applications and the Polarion Application SDK are part of the Early Access Program. The feature is switched off by default, and the API, the manifest format and the details documented here may change in later releases.
To try it, set polarionapp.enabled=true in Global Administration → Configuration Properties, and enable REST API token authentication in polarion.properties. Enable Applications in Polarion · Roadmap
The new way to extend Polarion. Build rich applications with the web technology you know, add your own REST endpoints on the server, package everything as one unit and install it through Administration.
Build your first application What is the framework?
From code to Polarion in minutes
Write it like any web app. Upload it once. Watch it run inside Polarion, from a panel in a work item to a full-page editor on top of the REST API.
-
From code to work item in one loop
Video: 2:48. Build a form extension with Vite and React, package it, upload it in Administration and see it rendered inside a work item.
-
A navigation topic: the Work Items Grid
Video: 1:24. A spreadsheet-style editor for work items delivered as an application, with inline editing and batched saves through the REST API.
Where your application appears
-
Form extension
A panel inside the Work Item form. It knows which work item is open and can read or update it.
-
Sidebar
A panel next to the Work Items table or a Document. It follows the user's selection in real time.
-
Navigation topic
A full page in the project navigation: dashboards, reports, editors.
Coming next: widgets for pages and reports, administration views, and packages that also carry scripts and templates. See Upcoming: widgets and administration.
Two ways to work with Polarion data
-
Polarion REST API
Call the complete, documented REST API directly from your view. The framework supplies the token; you supply the fetch.
-
Your own REST endpoints
Declare endpoints in the manifest and implement them in JavaScript that runs on the server with the full Polarion Java API.
-
Which one when?
Most things are a REST call away. Endpoints are for logic that must run on the server, with the Java API, or that reads many objects at once.
Find your way
-
Getting started
Prerequisites, enabling the feature, and a complete walkthrough from an empty folder to a panel in a work item.
-
Examples
Seven complete applications: from hello world to a release checklist driven by your own endpoints, each with a downloadable package and source.
-
Performance and load
Keep an application light on a shared server: fewer requests, bounded scripts and SQL, tests with realistic data.
-
Reference
manifest.json, the SDK API, the context object, the endpoint runtime and the configuration XML.
Introduction
The extensibility framework
Polarion Applications are the new extensibility framework of Polarion. An application is a self-contained package that adds functionality to Polarion: user interface that appears inside the Polarion UI, and server-side logic exposed as your own REST endpoints. You build it with standard web technology, package it as a ZIP, and an administrator installs it in Global Administration → Applications. No Java plug-in, no server file-system access, no restart.
Polarion 2612 ships the first generation of the framework as a preview. It is the foundation on which the next releases will deliver more: additional places in the UI where applications can appear, and additional kinds of content that an application can carry, such as scripts and templates. Applications are how Polarion is meant to be extended from now on.
What an application is
An application bundles three things:
| Part | What it is | Where it runs |
|---|---|---|
| Views | Web pages that Polarion shows in defined places of its UI: a panel in the work item form, a sidebar next to a table or document, a page in the project navigation. | In the user's browser, inside the Polarion page |
| Your own REST endpoints | HTTP endpoints under your application's URL, implemented as JavaScript that runs on the Polarion server with access to the Polarion Java API. | On the Polarion server |
| Manifest | manifest.json: the identity of the application and the list of its views and endpoints. |
Read by Polarion on upload |
Views and endpoints are both optional in principle, but together they are what makes an application rich: the view is the experience, the endpoints are the capability.
- com.example.releasechecklist/
- manifest.json
- checklist/ (a sidebar view (static web site))
- index.html
- assets/
- …
- server-scripts/ (your REST endpoints)
- validate.js (POST /polarion/apps/com.example.releasechecklist/rest/validate)
- assign-to-me.js (POST /polarion/apps/com.example.releasechecklist/rest/assign-to-me)
Two ways to work with Polarion data
From a view you can reach Polarion data in two ways, and most applications use both:
- The Polarion REST API. The complete, documented API of Polarion, called directly from the browser. The application receives an authentication token for the current user from the framework, so there is nothing to configure. Use it for everything it covers: reading and writing work items, documents, test runs, plans, users.
- Your own REST endpoints. When the REST API is not enough, you write the endpoint yourself. The script runs on the server, as the current user, with the full Polarion Java API. Aggregate across hundreds of objects in one request, implement rules and validations, talk to external systems with server-side secrets. The framework handles routing, authentication and JSON serialization.
The Polarion REST API and Your own REST endpoints sections cover both in depth. REST API or your own endpoints? helps you decide.
Where applications appear: views
The places in the Polarion UI that accept applications are called view types. Polarion 2612 provides three:
| View type | Where it appears | Typical use |
|---|---|---|
| Form extension | A panel in the Work Item form, positioned by the administrator in the form layout. | Everything that is about the open work item: related data, visualizations, guided editing. |
| Sidebar | The sidebar next to the Work Items table and inside Documents. Follows the user's selection. | Inspectors, bulk actions, checks on the selected items. |
| Navigation topic | A full page in the project navigation. | Dashboards, reports, editors that need the whole screen. |
More view types are planned, among them widgets for pages and reports and administration views. See Upcoming: widgets and administration.

How a view talks to the framework
The view runs in an iframe inside the Polarion page. A small npm package, the Polarion Application SDK (polarion-app-sdk), connects it to the host: it tells the view which project, work item, document or selection it is embedded in, delivers events such as selection changed, and supplies the base URLs and the token for calling the REST API and your endpoints. See How an application works.
Who this guide is for
This guide assumes you have never seen a Polarion Application before. It expects that you can use a terminal, Node.js and npm, that you can write a small web page in JavaScript or TypeScript (the examples use React and Vite), and that you can log in to a Polarion 2612 server as an administrator or ask one for help with the installation steps. You do not need Java, the Polarion Java SDK, or knowledge of Polarion's internals.
How this differs from older extension options
| Option | Deployment | Language | Where it runs |
|---|---|---|---|
| Polarion Application | ZIP upload in Administration | Web technology + JavaScript endpoints | Browser iframe; endpoints on the server |
| Java plug-in (form extension, widget, servlet) | Bundle copied to the server, restart | Java | Server |
| Velocity / JavaScript custom panels | Configuration XML | Velocity, HTML | Server-side rendering |
| External REST client | Separate system | Any | Outside Polarion |
Applications combine the reach of a plug-in (inside the UI, with server-side logic) with the deployment model of a web application. They are the recommended path for new extensions.
Where to go next
- Your first application: from an empty folder to a panel in a work item in about thirty minutes.
- Views: pick the place where your application should appear.
- Your own REST endpoints: add server-side capability.
- Examples: seven complete applications, from hello world to an endpoint-driven release checklist.
Introduction
How an application works
This page describes the mechanism behind a Polarion Application. You do not need to understand all of it to build one, but it explains why the manifest, the SDK and the configuration XML look the way they do.
From ZIP to running page
-
An administrator uploads the ZIP in Global Administration → Applications. Polarion validates the structure, reads
manifest.json, computes a SHA-2 hash and shows the identity of the application for confirmation. -
Polarion unpacks the files and serves them from
https://<polarion-host>/polarion/apps/<identifier>/Each view also gets a stable entry URL that resolves to the
documentconfigured for it:https://<polarion-host>/polarion/apps/<identifier>/views/<viewId> -
An administrator places the view in the Polarion UI. Form extensions and navigation topics are referenced from configuration XML with an
<applicationView id="p-introduction-how-it-works-<identifier>.<viewId>"/>element. Sidebars need no configuration: they appear in the Show Sidebar menu as soon as the application is uploaded. -
When a user opens that place, Polarion creates an iframe pointing at the view URL. Your
index.htmlloads, your JavaScript runs, and the page is shown inside the Polarion layout.
Inside the iframe
Because the view is served from the same origin as Polarion, the browser applies no cross-origin restrictions between your page and the host page. The iframe is a structural boundary, not a security boundary: a same-origin frame could reach into the parent document. Treat an application as code that runs with the user's privileges, install only applications you trust, and communicate with Polarion through the defined protocol rather than by reaching into the parent window.
The host bridge and the SDK
The Polarion page contains a small host bridge that listens for postMessage calls from application iframes. The Polarion Application SDK (polarion-app-sdk) wraps that protocol:
fetchContext()sends aget-contextrequest and resolves with aPolarionContext: the application and view identifiers, the project, work item, space and document the view is embedded in, the initial selection, and the URLs and token you need for HTTP calls.events.subscribe(EventTypes.SELECTION_CHANGED, callback)registers for host events. Polarion pushes a new list of selected work item identifiers whenever the selection in a table changes.destroy()tears the bridge down when your view unmounts.
The protocol itself (message types such as polarion-view-bridge) is an implementation detail. Always go through the SDK rather than posting messages yourself.
Warning: First version of the SDK
The SDK API of Polarion 2612 is a first version and is subject to change, including the functions above. Changes will be announced with the release that brings them, together with clear migration steps.
HTTP calls
Everything else is ordinary fetch():
| Target | URL | Authentication |
|---|---|---|
| Polarion REST API | context.restBaseUrl + /projects/… |
Header X-Polarion-REST-Token: <context.restToken> |
| Your own endpoints | context.appEndpoint + /<urlPath> |
Required X-Polarion-REST-Token header; no session authentication |
| Your own static files | relative URLs inside the view folder | Polarion session |
The token identifies the user who is logged in to Polarion. Every REST call and every server script runs with that user's permissions. See Security model.
Server scripts
A server script is a JavaScript file in the server-scripts/ folder of the package, mapped to an HTTP method and path in the manifest. Polarion executes it with GraalVM on the server when the endpoint is called. The script receives the request parameters through an arguments object and gets the Polarion Java API through context.scriptContext(). Whatever object the script evaluates to is returned to the caller as JSON, wrapped in a small envelope.
Server scripts are optional. Many applications only need the REST API. Reach for a script when you need to aggregate across many objects in one round trip, walk link structures, or use an API that REST does not expose. See Your own REST endpoints.
Life cycle of a view
- Polarion creates the iframe and loads
index.html. - Your code calls
fetchContext()and renders. - Optionally your code subscribes to events and keeps rendering as they arrive.
- When the user navigates away, the iframe is destroyed. Call
destroy()from your framework's unmount hook so pending requests and subscriptions are cleaned up; this matters mostly during local development with hot reloading.
Views are stateless from Polarion's point of view. If you need to persist data, use work item fields, custom fields, comments or attachments through the REST API, or an external service of your own.
Info: Session Expiry and Reload Behavior
When a user's session expires and they log back in, the Polarion Application frame reloads automatically. (All unsaved changes within the application view are lost.)
Introduction
Roadmap and release notes
Polarion Applications are designed as the long-term extensibility framework of Polarion. This page describes what the 2612 preview contains, the direction for the next releases, and the differences to earlier internal previews.
Shipped in Polarion 2612 (preview)
- Upload and management under Global Administration → Applications: upload, update, inspect properties, delete.
- Three view types: form extensions, sidebars and navigation topics, declared under
viewsinmanifest.json. - Your own REST endpoints: GET and POST endpoints declared under
serverScripts.endpointsand implemented as GraalVM JavaScript with access to the Polarion Java API. - Polarion Application SDK 0.5.2-preview (
polarion-app-sdk), downloadable from every 2612 server at/polarion/sdk/applications/. - Framework-managed authentication: the context carries a REST token for the current user; views call the REST API and your endpoints without handling credentials.
The feature is disabled by default and is switched on with the polarionapp.enabled configuration property. See Enable Applications in Polarion.
Direction
The framework is built to grow along two axes. Dates and scope are indicative and subject to change; the manifest format is versioned (manifestVersion) so that applications can declare what they need.
More places in the UI
| View type | Status | Purpose |
|---|---|---|
| Form extension | 2612 | Panel in the Work Item form |
| Sidebar | 2612 | Sidebar in the Work Items table and in Documents |
| Navigation topic | 2612 | Full page in the project navigation |
| Widget | planned | Application-provided widgets for LiveReport pages, dashboards and Documents |
| Administration view | planned | Pages in Project and Global Administration for configuring the application itself |
See Upcoming: widgets and administration for how to prepare.
More content an application can deliver
| Content | Status | Purpose |
|---|---|---|
| Views and endpoints | 2612 | UI and server-side capability |
| Scripts | planned | Workflow functions, conditions and scheduled scripts shipped and versioned with the application |
| Templates | planned | Project templates, document templates and configuration delivered by the application |
| Further resource types | planned | Enumerations, custom fields and other configuration as part of a package |
The goal is that everything an extension needs travels in one package, is installed in one step, and is updated as a unit.
SDK
The SDK will gain events beyond selection-changed and calls from the view into the host (refreshing a form, navigating, notifications). The current API (fetchContext, events.subscribe, destroy) is a first version and is subject to change; each change will come with clear migration steps.
Changes compared with earlier previews
If you have seen pre-release material (for example workshop starters that used a polarion.js helper file), note the following differences. Applications built against the earlier protocol do not work on 2612 without changes.
| Earlier preview | Polarion 2612 |
|---|---|
Manifest sections workItemForms and viewlets.navigation |
views.formExtensions, views.sidebars, views.navigationTopics |
Manifest section endpoints |
serverScripts.endpoints |
| No publisher field | publisherName (shown in the upload dialog and in Properties) |
Copy of a polarion.js helper in every app |
npm package polarion-app-sdk |
Bridge messages polarion-viewlet-bridge* (internal names) |
polarion-view-bridge* (internal to the SDK) |
Context { data: { restBase, objectId } } |
Flat PolarionContext with projectId, workItemId, restBaseUrl, appEndpoint, restToken, … |
Form layout element <extension applicationId="…" viewletId="…"/> |
<applicationView id="p-introduction-roadmap-<identifier>.<viewId>"/> |
REST token obtained from window.getRestApiToken() |
context.restToken from fetchContext() |
ZIP with manifest.json at the root (some drafts) |
ZIP with one top-level folder named after the identifier |
Known limitations in 2612
See Limitations and known issues for the complete list. The most important ones:
- The SDK only supports
fetchContext()and theselection-changedevent. There is no API yet to call back into the host (for example to refresh the form). - One subscription per event type per view.
Getting started
Prerequisites
Before building an application, make sure the following is available on your computer and on the Polarion server.
On your computer
| Requirement | Notes |
|---|---|
| Node.js 20.19 or newer (22 LTS recommended) | Vite 7 requires Node 20.19+. Check with node --version. |
| npm | Ships with Node.js. The SDK is installed with npm from a URL on your Polarion server. |
| A code editor | Visual Studio Code or any editor with TypeScript support. |
| A way to create ZIP files | The examples include a small Node script; a plain zip command or the operating system's Compress function works as well, as long as the folder layout is correct. |
| Network access to the Polarion server | To download the SDK package and to upload the application. |
You do not need Java, Maven, the Polarion Java SDK or server file-system access.
On the Polarion server
| Requirement | Notes |
|---|---|
| Polarion 2612 | Earlier releases do not contain the Applications feature. The server version is shown on the login page. |
| Applications enabled | The global configuration property polarionapp.enabled=true must be set in Global Administration. See Enable Applications in Polarion. |
| REST API enabled with token authentication | The properties com.siemens.polarion.rest.enabled=true and com.siemens.polarion.rest.security.restApiToken.enabled=true in polarion.properties. Required for views that call the REST API or server scripts. |
| Administrator access | Uploading an application requires Global Administration. Placing views in forms and navigation requires project administration. |
A project to work in
Pick or create a project you can experiment in. The walkthrough uses a project with the identifier test and a work item type Task in its examples; the screenshots in this guide come from the Drive Pilot demo project (work item type Work Package). Adjust the names to your project. You need at least one work item of the type whose form you will extend.
Optional: the SDK source and a reference application
The SDK is open for inspection. Its TypeScript source and README are available in the repository polarion-app-sdk-preview, and a complete reference application (tsapp-1) demonstrates all three view types together with server scripts. The examples in this guide are smaller and build on the same conventions.
Getting started
Enable Applications in Polarion
Polarion Applications are part of the Early Access Program in Polarion 2612 and are switched off by default. Two settings are involved: one enables the feature itself, the other lets views authenticate against the REST API and application endpoints.
1. Enable the Applications feature
The global configuration property polarionapp.enabled controls whether the Applications topic exists in Global Administration and whether uploaded applications are served. It is set in the Polarion UI only; there is no corresponding entry in polarion.properties.
- Log in as a user with global administration rights.
- Open Global Administration (avatar menu → Global Administration, or the wrench icon).
- Open Configuration Properties at the bottom of the administration navigation.
-
Set the property
polarionapp.enabled=true -
Save and reload the browser page.
A new Applications entry appears in the Global Administration navigation. It is only available at the repository (global) level, not in project administration.

2. Enable REST API token authentication
Views receive a short-lived REST token in their context and must send it in the X-Polarion-REST-Token header for REST API and application endpoint calls. Application endpoints do not accept browser-session authentication. This requires the REST API and its token mechanism to be enabled in polarion.properties on the server:
com.siemens.polarion.rest.enabled=true
com.siemens.polarion.rest.security.restApiToken.enabled=true
These two properties are read at start-up, so Polarion must be restarted after changing them. Without them, Polarion shows the warning X-Rest-Token generation is not allowed on the server! when a view opens, context.restToken is empty and REST API and application endpoint calls from views fail.

The same properties are also needed if you plan to automate uploads through the REST API with a personal access token.
3. Verify
- Global Administration → Applications opens and shows either No Application found or the list of installed applications.
- The Upload button is enabled.
- After uploading an application and opening one of its views,
fetchContext()returns a context with a non-emptyrestToken.
If something is missing, see Troubleshooting.
Getting started
Your first application
In this walkthrough you build Hello Polarion: a form extension that shows a greeting and nothing else. No SDK, no state, no calls to Polarion; the point is the development loop, and you go through every step of it once: create the project, write the view, package the ZIP, upload it, and place it in a work item form. Reading the context and calling Polarion come next, in the Application context example.

The complete source is in examples/hello-polarion, where you can also download the finished application package and the source project. You can follow along from scratch or open the example side by side.
Tip: Before you start
Make sure the prerequisites are met and that an administrator has enabled Applications on your Polarion server. You need the host name of that server; the walkthrough uses polarion.example.com as a placeholder.
1. Create the project
-
Scaffold a Vite project with the React + TypeScript template and install its dependencies:
npm create vite@latest hello-polarion -- --template react-ts cd hello-polarion npm install -
Make Vite emit relative asset URLs. Polarion serves the view from a sub-path such as
/polarion/apps/com.example.hello/hello/, so absolute/assets/…URLs would not resolve. Replacevite.config.tswith:vite.config.tsimport { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; // https://vite.dev/config/ export default defineConfig({ plugins: [react()], // Polarion serves the view from a sub-path such as // /polarion/apps/<identifier>/<rootDirectory>/, so all asset URLs must be relative. base: "./", }); -
Remove the template files you do not need (
src/App.css,src/index.css,src/assets/,public/vite.svg) and make sureindex.htmlis a plain host page:index.html<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Hello Polarion</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html>
2. Describe the application: manifest.json
Create manifest.json in the project root. It tells Polarion what the application is called and which views it contains.
{
"manifestVersion": "1.0",
"identifier": "com.example.hello",
"title": "Hello Polarion",
"description": "The smallest possible Polarion Application: one form extension that says hello.",
"publisherName": "Example Publisher",
"applicationVersion": "0.2.0",
"views": {
"formExtensions": [
{
"identifier": "hello",
"title": "Hello Polarion",
"rootDirectory": "hello",
"document": "index.html"
}
]
}
}
What the fields mean:
| Field | Meaning |
|---|---|
identifier |
Unique name of the application on the server. Reverse-DNS style (com.example.hello) is recommended. It becomes part of every URL and configuration id, so keep it short and stable. |
manifestVersion, title, description, publisherName, applicationVersion |
Shown to the administrator during upload and in Properties. |
views.formExtensions[0].identifier |
The view id. Together with the application identifier it forms the id used in configuration: com.example.hello.hello. |
rootDirectory, document |
Where the view's files live inside the package and which file is the entry page. |
The full schema is in the manifest.json reference.
3. Write the view
-
Replace
src/main.tsx:src/main.tsximport { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import App from "./App"; import "./styles.css"; createRoot(document.getElementById("root")!).render( <StrictMode> <App /> </StrictMode>, ); -
Replace
src/App.tsx. The view is an ordinary React component; nothing in it is specific to Polarion:src/App.tsxexport default function App() { return ( <main> <h1>Hello, Polarion</h1> <p>This panel is a Polarion Application.</p> </main> ); }What makes it a Polarion Application is the packaging: the manifest, the ZIP layout and the place in the form layout, in the next steps. The page does not need the SDK to be shown; the SDK comes in when the view wants to know where it is or call Polarion.
-
Add
src/styles.csswith a little styling:src/styles.cssbody { margin: 0; padding: 12px; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 14px; color: #1f2933; } h1 { font-size: 1.4rem; margin: 0 0 8px; } -
Build once to check that everything compiles:
npm run buildVite writes
dist/index.htmlanddist/assets/…. Opendist/index.htmland confirm that the script and stylesheet paths start with./assets/.
4. Package the ZIP
Polarion expects a ZIP with one top-level folder named after the identifier. Inside it: manifest.json, one folder per view (named like rootDirectory), and optionally server-scripts/.
- com.example.hello.zip
- com.example.hello/
- manifest.json
- hello/
- index.html
- assets/
- index-….js
- index-….css
- com.example.hello/
A ZIP with manifest.json directly at its root is rejected with Application's zip structure is incorrect. For the file types a package may contain and its size limits, see Allowed file types and Validation and limits.
Node script (any OS)
Add scripts/package.mjs and the dev dependency adm-zip. The script copies the build into the right layout and writes the ZIP:
npm install --save-dev adm-zip
// Builds the upload-ready ZIP for Polarion.
//
// Layout inside the ZIP: one top-level folder named after the application
// identifier, with manifest.json, view content under each view's
// rootDirectory (which multiple views may share), and optional server-scripts/.
// Polarion rejects a ZIP that has manifest.json directly at its root
// ("Application's zip structure is incorrect").
//
// <identifier>/
// manifest.json
// <rootDirectory of each view>/ (index.html + assets)
// server-scripts/ (if present)
//
// Single-view projects build into dist/. Multi-view projects build one Vite
// mode per view into dist/<rootDirectory>/ (see "Set up the project" in the
// guide); this script copies whichever exists.
//
// Run with `npm run package` (which builds first).
import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import AdmZip from "adm-zip";
const projectRootPath = fileURLToPath(new URL("..", import.meta.url));
const distributionPath = join(projectRootPath, "dist");
function stageViews(appStagePath, manifest) {
const views = Object.values(manifest.views ?? {}).flat();
if (views.length === 0) {
throw new Error("manifest.json declares no views.");
}
for (const view of views) {
const viewDist = join(distributionPath, view.rootDirectory);
const source = existsSync(viewDist) ? viewDist : distributionPath;
const documentPath = join(source, view.document);
if (!existsSync(documentPath)) {
throw new Error(`Build output for view "${view.identifier}" not found: ${documentPath}`);
}
cpSync(source, join(appStagePath, view.rootDirectory), { recursive: true });
}
}
function stageServerScripts(appStagePath) {
const serverScripts = join(projectRootPath, "server-scripts");
if (existsSync(serverScripts)) {
cpSync(serverScripts, join(appStagePath, "server-scripts"), { recursive: true });
}
}
function writePackageZip(stageRoot, zipPath) {
const zip = new AdmZip();
zip.addLocalFolder(stageRoot);
zip.writeZip(zipPath);
}
function packageApplication() {
const manifest = JSON.parse(readFileSync(join(projectRootPath, "manifest.json"), "utf8"));
const stageRootPath = join(projectRootPath, "package");
const zipPath = join(projectRootPath, `${manifest.identifier}.zip`);
rmSync(stageRootPath, { recursive: true, force: true });
try {
const appStagePath = join(stageRootPath, manifest.identifier);
mkdirSync(appStagePath, { recursive: true });
cpSync(join(projectRootPath, "manifest.json"), join(appStagePath, "manifest.json"));
stageViews(appStagePath, manifest);
stageServerScripts(appStagePath);
writePackageZip(stageRootPath, zipPath);
} finally {
rmSync(stageRootPath, { recursive: true, force: true });
}
console.log(`Packaged ${manifest.identifier} ${manifest.applicationVersion} -> ${zipPath}`);
}
packageApplication();
Then add two npm scripts to package.json and run the packaging:
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"package": "npm run build && node scripts/package.mjs"
}
npm run package
# Packaged com.example.hello 0.2.0 -> …/com.example.hello.zip
Shell (macOS / Linux)
npm run build
rm -rf package && mkdir -p package/com.example.hello
cp manifest.json package/com.example.hello/
cp -R dist package/com.example.hello/hello
(cd package && zip -r ../com.example.hello.zip com.example.hello)
PowerShell (Windows)
npm run build
Remove-Item -Recurse -Force package -ErrorAction Ignore
New-Item -ItemType Directory package\com.example.hello | Out-Null
Copy-Item manifest.json package\com.example.hello\
Copy-Item -Recurse dist package\com.example.hello\hello
Compress-Archive -Path package\com.example.hello -DestinationPath com.example.hello.zip -Force
5. Upload the application
-
In Polarion open Global Administration → Applications and click Upload.
-
Choose
com.example.hello.zipand click Next.
-
Polarion validates the package and shows what it is about to install: identifier, version, title, publisher and the SHA-2 hash of the file. Compare the hash with the one you computed if your organization requires it, then click Finish.

-
A green bar confirms Application 'com.example.hello' was uploaded and the tile appears in the list. Hover the tile to see the description; select it and click Properties to see the manifest data.

The application is now installed but not yet visible anywhere. Views have to be placed.
6. Place the view in a work item form
Form extensions are positioned by the administrator in the form layout of a work item type, per project.
-
Open your project and go to Administration → Work Items → Form Configuration.
-
In the Form Layouts table at the bottom of the page, click Edit next to the work item type you want to extend (for example Task). If the type has no layout yet, click Create New Form Layout first.
-
In the XML editor, insert an
applicationViewelement where the panel should appear. Theidis<identifier>.<viewId>:Form layout (excerpt)<formLayout …> <horizontal> … </horizontal> <applicationView id="com.example.hello.hello" label="Hello Polarion" height="320px"/> <field id="description"/> <field id="comments"/> … </formLayout>labelsets the heading of the panel (default: Polarion Application).heightsets the height of the iframe.
-
Click Save. The message Configuration has been saved appears.
-
Open any work item of that type. Reload the page if it was already open. The Hello Polarion panel shows the greeting.

Note: If a Warning dialog appears
A dialog saying X-Rest-Token generation is not allowed on the server means the server lacks REST token authentication. The panel still renders, but REST calls will fail; see Enable Applications in Polarion.
What you have learned
- An application is a ZIP with a manifest and static views; Polarion serves it from
/polarion/apps/<identifier>/. - The view itself is an ordinary web page; it needs no SDK to be shown.
- Views are placed with
<applicationView id="p-getting-started-first-application-<identifier>.<viewId>"/>in configuration XML.
Continue with Iterate: change, rebuild, re-upload to learn the development loop. To see what a view learns about its surroundings, install the Application context example; the Work item card then shows the REST API in action.
Getting started
Iterate: change, rebuild, re-upload
Once the first version is installed, every further change follows the same short loop.
The loop
- Edit the source.
npm run package(build + ZIP).- Global Administration → Applications → Upload the new ZIP.
- Reload the Polarion page that shows the view (hard reload:
Ctrl+Shift+RorCmd+Shift+R).
Configuration XML does not have to be touched again unless you rename the application identifier or add a new view.
Updating an installed application
Uploading a ZIP whose identifier matches an installed application updates it in place. The confirmation step of the upload dialog changes accordingly: it reads You are going to UPDATE the following application and shows two columns, New Version and Current Version, with the manifest data of both.

Bump applicationVersion with every upload. The update dialog shows it next to the installed version, administrators see it in Properties, and it is the only reliable way to tell two builds apart.
Browser caching: Vite gives every build output a content hash in its file name, so a new build never collides with cached assets. The entry index.html itself is small and is reloaded with the page.
Checking what is installed
Select a tile on the Applications page and click Properties. The dialog shows the identifier, version, title, publisher, manifest version and description taken from the installed manifest.

The static files are also reachable directly, which is useful for a quick check that a build made it to the server:
https://<polarion-host>/polarion/apps/<identifier>/<rootDirectory>/index.html
Opening a view this way shows your page without the Polarion host around it. fetchContext() cannot succeed there; a well-written view reports that instead of hanging (see the error state in Your first application).
Removing an application
Select the tile and click Delete. Polarion removes the application and its files immediately and confirms with Application <identifier> was deleted; treat the button as final. Configuration XML that still references a view of the deleted application is not changed; the corresponding panel simply disappears from forms and the entry vanishes from the Show Sidebar menu. Remove the applicationView elements by hand to keep the configuration clean.
Several developers, one server
Application identifiers are global on a server. Two people uploading com.example.hello overwrite each other. During development, give every developer or feature branch its own identifier (for example com.example.hello.jdoe) and switch to the final identifier when the application is ready. Remember that the identifier is part of the configuration id, so the applicationView elements must follow.
Local development without uploading
Rebuilding and uploading for every CSS tweak is slow. For UI work, run npm run dev and open the Vite dev server in a browser; fetchContext() fails there, so give your code a mock context in development mode. The pattern is described in Develop locally.
Getting started
Build an application with AI
AI coding assistants can write a Polarion Application for you, but they do not know Polarion Applications from their training: the framework is new in 2612. The AI kit gives them what they need. It contains this whole guide, the seven example applications and a set of instructions for the assistant, all in one folder that works offline.
Three steps
- Unzip the kit and open the folder in your AI coding assistant, for example Claude Code, GitHub Copilot in VS Code, or Cursor. The assistant reads
AGENTS.md(also provided asCLAUDE.mdand.github/copilot-instructions.md), which explains how Polarion Applications work and which rules they follow. - Paste the prompt below and replace the part in angle brackets with what you want: what the application shows or does, where it appears, and what it reads or changes.
- Upload the result. The assistant builds a ZIP file. Upload it in Global Administration → Applications and place it as the assistant describes, first on a test server. See Package and upload.
Read AGENTS.md in this folder and follow it. Then build a Polarion Application that <describe what it should show or do, where it should appear (on the work item form, next to the Work Items table, or as a page in the project navigation), and what it reads or changes>. Start from the closest example, build and package it, and tell me how to upload and place it.
The assistant needs Node.js 20.19 or newer (22.12 or newer on Node 22) to build the application; see Prerequisites. Your Polarion server needs Applications enabled and REST token authentication on; see Enable Applications in Polarion.
Example requests
Each of these replaces the part in angle brackets:
- a sidebar next to the Work Items table that shows the total initial estimate and the number of open items of the selected work items
- a panel on the work item form that lists the linked test cases with their last test result
- a page in the project navigation that shows how many requirements are in each status, as a bar chart
- a panel on the work item form with a button that copies the work item's title into its description, using an endpoint on the server
The more precise the request, the better the result: name the work item types, fields and link roles your project uses.
What is in the kit
| File or folder | For | Content |
|---|---|---|
START-HERE.html |
you | These steps and the prompt, to open in a browser |
Guide.html |
you | This guide as one page, readable offline |
AGENTS.md |
the assistant | How to work, the view types, and the rules that a Polarion Application must follow: package layout, allowed file types, SDK, context, REST API and endpoints |
guide/ |
the assistant | Every page of this guide as plain Markdown, and guide/ALL.md with all pages in one file |
examples/ |
both | The sources of the seven examples and the SDK package |
The kit is generated from this guide and its examples whenever they change, so the download always matches the pages you are reading.
What to expect
- The assistant starts from the closest example and keeps its structure:
manifest.json, the React view insrc/, the packaging script, and server scripts when the application needs its own endpoints. - It cannot upload or test in Polarion. It tells you how to upload and place the application; whether it works, you check on the server. Describe what you see, including messages from the browser's developer console, and let the assistant fix it.
- Review what the application changes. An application acts with the rights of the user who opens it. Read the code that writes data before you use it on a production server, as you would for code from a colleague; see Security model.
- Bump the version for every update. Polarion recognizes the application by its identifier and accepts the same version again, so
applicationVersionis the only way to tell two builds apart (see Iterate). Ask the assistant to raise it when you change the application.
Views
Views: where your application lives
A view is one web page of your application placed at one kind of location in the Polarion UI. (If you have not read it yet, Application context explains the context object the view pages refer to.) The location is the first decision of every application: it determines what the user is looking at when your page opens, what the framework tells you about the surroundings, and how the administrator switches it on. Polarion 2612 offers three view types; an application may contain any number of each. Sidebars inside Documents and the create form of a new work item are described as the SDK documents them; the screenshots in this guide were taken in the Work Items table and in saved work items.
The three view types
Form extension

A collapsible panel inside the Work Item form, placed among the fields by the administrator. The view knows which work item is open. Use it for everything that is about this work item: data from other systems, link visualizations, guided editing, checklists.
Sidebar

A panel in the sidebar area next to the Work Items table and inside Documents, chosen by the user from the Show Sidebar menu. The view receives the current selection and every change to it. Use it for inspectors, bulk actions and checks on whatever the user selects.
Navigation topic

A full page with its own entry in the project navigation. The view gets the whole content area and knows the project. Use it for dashboards, reports, planning boards and editors.
Comparison
| Form extension | Sidebar | Navigation topic | |
|---|---|---|---|
| Manifest list | views.formExtensions |
views.sidebars |
views.navigationTopics |
| Switched on by | applicationView in the form layout |
nothing (listed in Show Sidebar) | applicationView in the Topics configuration |
| Context knows | project, work item | project, selection, document | project |
| Events | – | selection-changed |
– |
| Space | panel of configurable height | narrow column, full height | whole content area |
| Lifetime | per work item | while the table or document is open | while the page is open |
Choosing a view type
| You want to… | Use |
|---|---|
| Show or edit something about the work item the user is looking at | Form extension |
| React to what the user selects in a table or document | Sidebar |
| Offer a tool or report at project level | Navigation topic |
| Do several of the above | Several views in one application, sharing code |
A common combination is a sidebar for selection-driven actions plus a navigation topic for the overview, or a form extension plus endpoints that compute something per work item on the server.
What all views have in common
- Each view is an independent page load. Views of the same application do not share JavaScript state; share data through Polarion (REST or your endpoints) or
localStorageof the common origin. - The context always contains
applicationId,viewId,restBaseUrl,appEndpointand, with token authentication enabled,restToken. - A view opened directly by its URL, outside Polarion, gets no context and no events.
- Views do not inherit Polarion's styles. Use a neutral system look so the page feels native; the examples'
styles.cssis a starting point. - The context carries no UI language or locale. Set
langon your page, keep strings in one place if you plan to translate, and make sure keyboard focus works inside the iframe; Polarion does not manage focus for you.
Coming next
The framework is designed to accept more view types. Widgets for pages and reports and administration views are planned; see Upcoming: widgets and administration for what to expect and how to structure an application so that adding them later is cheap.
Views
Form extension
A form extension is a panel inside the Work Item form. Polarion renders it as a collapsible section with a heading, like Description or Comments, and loads your view in an iframe inside it.

Declare the view
"views": {
"formExtensions": [
{
"identifier": "card",
"title": "Work item card",
"rootDirectory": "card",
"document": "index.html"
}
]
}
title appears to be informational in 2612; the panel heading comes from the label attribute in the form layout.
Place it in a form layout
Form layouts are configured per project, per work item type, and per Polarion View (hat; most projects only use Default).
- Open the project and go to Administration → Work Items → Form Configuration.
- Scroll to Form Layouts. Click Edit for the work item type, or Create New Form Layout if the type has none yet (then choose the View and type).
- Insert the element where the panel should appear and click Save.
<?xml version="1.0" encoding="UTF-8"?>
<formLayout xmlns="http://polarion.com/schema/WorkItems/FormLayout" …>
<horizontal>
<vertical>
<section>…</section>
</vertical>
</horizontal>
<field id="description"/>
<applicationView id="com.example.workitemcard.card" label="Work item card" height="640px"/>
<field id="comments"/>
<field id="linkedWorkItems"/>
</formLayout>

Attributes
| Attribute | Required | Meaning |
|---|---|---|
id |
yes | <application identifier>.<view identifier> |
label |
no | Heading of the panel. Default: Polarion Application. |
height |
no | CSS height of the iframe, for example 320px. Default: 600px. The iframe does not grow with its content; size it for your view or make the view scroll internally. |
applicationView is a top-level element of the layout, a sibling of <field>, <horizontal> and <extension>. It cannot be placed inside <section> or <panel>.
The same view can be referenced in several layouts (several types, several projects). Each occurrence gets its own iframe.
Where the panel shows up
The form layout applies to every place that renders the Work Item form: the editor below the Work Items table, the full-page work item view and, as far as the layout is shared, the work item editor opened from a Document. Your view is loaded in each of them.
Context in a form extension
{
"applicationId": "com.example.workitemcard",
"viewId": "card",
"projectId": "test",
"workItemId": "TEST-514",
"selectedWorkItemIds": ["test/TEST-514"],
"appEndpoint": "…/polarion/apps/com.example.workitemcard/rest",
"restBaseUrl": "…/polarion/rest/v1",
"restToken": "…"
}
When the form is opened from a Document, spaceId and documentId are also set. In the multi-item edit form below the Work Items table, opened by ticking several rows, a form extension gets all ticked items in selectedWorkItemIds (for example ["drivepilot/DP-477", "drivepilot/DP-461", "drivepilot/DP-393"]), while workItemId is the current item (DP-477). Observed on Polarion 2612.
Creating a new work item
In the create form (a work item that is not saved yet) there is no workItemId. Handle the missing field by rendering a short hint; most panels have nothing useful to show before the item exists.
Design notes
- The panel inherits nothing from Polarion's styles. Use a system font stack and neutral colors so that it looks native; the examples'
styles.cssis a starting point. - The form is often shown in a narrow column next to a table. Make the view responsive down to about 600 px.
- Lazy-load heavy data. The panel renders together with the rest of the form; a slow first request delays nothing but looks sluggish.
- The iframe is destroyed when the user opens another work item. Do not rely on in-memory state across items.
Removing
Delete the applicationView element from the layout and save. Deleting the application without editing the layout also removes the panel, but leaves a dangling reference in the configuration.
Views
Upcoming: widgets and administration
The three view types of Polarion 2612 cover the work item form, the table and document sidebars, and the project navigation. Two further view types are planned. This page describes their intended role so that you can design applications with them in mind. Details are subject to change until they ship.
Widget
A widget view will let an application contribute widgets to the places where Polarion renders widgets today: LiveReport pages, dashboards and rich pages, and Document content. Each widget is a small web page with parameters that the page author sets when placing it. Expected characteristics:
- Declared in the manifest like other views, with a parameter definition so that the page editor can offer a configuration dialog.
- The context will carry the parameters, the page or document the widget is embedded in, and the project.
- Rendering inside the page's layout grid, at the size the page author chooses.
Typical uses: KPI tiles fed by your own endpoints, charts over data from external systems, interactive tables with actions.
Administration view
An administration view will give an application pages in Project Administration and Global Administration. This is where an application configures itself: connection settings for an external system, mapping tables, feature switches, per-project rules. Expected characteristics:
- Declared in the manifest with a scope (project or global).
- The context will carry the scope and the project, and the user is guaranteed to be an administrator of that scope.
- Settings persist through your own endpoints, which can store them in Polarion's configuration repository or in a location of your choice.
Typical uses: an Integration settings page next to the built-in administration topics; a rule editor for a validation application; a place to enter the webhook of a chat tool.
Designing for what is coming
- Keep the UI in views and the logic in endpoints. A dashboard widget and a navigation topic can share the same endpoint; only the page around it differs.
- Read everything from the context. Code that derives what to show from
context(project, work item, selection) ports to new view types with few changes. - One Vite project per view, shared source folder. Adding a view then means adding an entry point and a manifest line. See Set up the project.
- Store configuration in Polarion. Until administration views arrive, an application can keep settings in a dedicated work item, a document, or a global configuration file read by an endpoint. Moving that to an administration view later is a UI change, not a data migration.
Also on the roadmap
Beyond views, applications will carry more kinds of content: scripts (workflow functions, scheduled scripts), templates and other configuration, so that an extension ships as one versioned package. See Roadmap and release notes.
Polarion REST API
Calling the REST API from a view
Polarion's REST API is the main way for a view to read and change data. The context gives you everything you need to call it: restBaseUrl and restToken.
Note: REST API documentation
This page covers what is specific to calling the API from an application view. The API itself is documented in the Polarion REST API User Guide on the Siemens Xcelerator Developer Portal, and your server publishes its OpenAPI definition at https://<polarion-host>/polarion/rest/v1/definition.
A small helper
The examples that call the REST API use the same small helper, restFetch. Calls to your own endpoints go through its counterpart endpointFetch (see Call endpoints from a view). restFetch adds the token, sets the JSON headers, throws on HTTP errors and returns the parsed body:
import type { PolarionContext } from 'polarion-app-sdk';
/**
* Calls the Polarion REST API (JSON:API) on behalf of the logged-in user.
*
* `context.restBaseUrl` is the absolute base URL of the REST API, for example
* `https://host/polarion/rest/v1` (no trailing slash). `context.restToken` is a
* short-lived token that Polarion hands to the application view; it must be
* sent in the `X-Polarion-REST-Token` header.
*/
export async function restFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
const headers = new Headers(init.headers);
headers.set('X-Polarion-REST-Token', context.restToken ?? '');
headers.set('Accept', 'application/json');
if (init.body !== undefined && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json');
}
const response = await fetch(`${context.restBaseUrl}${path}`, { ...init, headers });
if (!response.ok) {
throw new Error(`REST ${response.status}: ${await response.text()}`);
}
if (response.status === 204) {
return null as T;
}
return (await response.json()) as T;
}
// WorkItemResponse and the other types live in src/types.ts of the examples.
const item = await restFetch<WorkItemResponse>(
context,
`/projects/${context.projectId}/workitems/${context.workItemId}?fields[workitems]=id,title,status`,
);
Authentication
Send the header on every request:
X-Polarion-REST-Token: <context.restToken>
The token represents the logged-in user. Calls fail with 401 if the token is missing, empty (token authentication not enabled on the server) or expired, and with 403 if the user lacks permission for the operation. On 401 after a long idle period, call fetchContext() again and retry once.
Do not send cookies or basic authentication; the token is sufficient and the recommended mechanism.
Reading a single resource
GET {restBaseUrl}/projects/test/workitems/TEST-514?fields[workitems]=id,title,status,type,description
{
"data": {
"type": "workitems",
"id": "test/TEST-514",
"attributes": {
"id": "TEST-514",
"title": "Brake pedal sensor",
"status": "open",
"type": "task",
"description": { "type": "text/html", "value": "<p>…</p>" }
},
"links": { "self": "…" }
}
}
Always ask for the fields you need with fields[<type>]=…. Without it the API returns a default set that omits most attributes; with @all it returns everything, which is slow for large items. Note that a sparse field set also filters relationships: to receive relationships.workItem on a link resource, workItem must be in fields[linkedworkitems].
Related resources: includes
Relationships are separate resources. To get the linked work items of an item together with their titles in one request:
GET {restBaseUrl}/projects/test/workitems/TEST-514/linkedworkitems
?fields[linkedworkitems]=role,suspect,workItem
&include=workItem
&fields[workitems]=id,title,status,type
The response has data (the link resources with a relationships.workItem.data.id) and included (the work items). Join them by id, as in the Work item card example.
Lists and queries
GET {restBaseUrl}/projects/test/workitems
?query=status:open AND type:task
&sort=-created
&fields[workitems]=id,title,status
&page[size]=100&page[number]=1
querytakes Polarion's Lucene query syntax, the same you type in the Work Items table.- Large page sizes may be capped by the server; the examples use
page[size]=100. Usepage[number]to walk further pages.meta.totalCountreports the total. sortaccepts a field name, prefixed with-for descending.
A selection of ids becomes one query: id:(TEST-514 TEST-513 TEST-511).
Writing
Updates use PATCH with a JSON:API document that repeats type and id:
await restFetch(context, `/projects/test/workitems/TEST-514`, {
method: 'PATCH',
body: JSON.stringify({
data: { type: 'workitems', id: 'test/TEST-514', attributes: { title: 'New title' } },
}),
});
Polarion answers with a 2xx status and no body on success (the examples expect 204 No Content). Creating resources uses POST on the collection URL with data as an array; deleting uses DELETE. Writes go through the same workflow and permission checks as the UI, so a field that is read-only for the user's role is also read-only through the API.
After a write, the Polarion form or table around your view does not know about the change. Tell the user to reload, or navigate with a target="_top" link; the host bridge has no "refresh" call yet.
Encoding
Use URLSearchParams for query strings. It encodes the brackets in fields[workitems] and the spaces in Lucene queries correctly:
const params = new URLSearchParams({
query: 'status:open AND type:task',
'fields[workitems]': 'id,title,status',
'page[size]': '100',
});
const url = `${context.restBaseUrl}/projects/${context.projectId}/workitems?${params}`;
Error handling
| Status | Meaning in a view | What to do |
|---|---|---|
| 400 | Bad request shape or unknown field | Fix the request; the body contains errors[].detail. |
| 401 | Missing or expired token | Check that token authentication is enabled; refetch the context. |
| 403 | User may not do this | Show a message; do not retry. |
| 404 | Wrong project/id, or no read permission | Verify ids from the context. |
| 409 | Concurrent modification or workflow conflict | Reload and let the user try again. |
The error body is JSON:API as well:
{ "errors": [ { "status": "403", "title": "Forbidden", "detail": "…" } ] }
Performance notes
- One request with
includebeats N requests for related items. - Keep
fields[…]tight;descriptionand other rich-text fields are large. - For aggregations over hundreds of items, a server script is usually faster than paging through the API from the browser.
More in Performance and load.
Polarion REST API
Cookbook
The snippets below use the restFetch helper from Calling the REST API from a view and a context obtained from fetchContext(). Resource names and attribute ids follow the Polarion REST API v1 and were exercised against a 2612 server for reading work items (including created and the assignee relationship), Lucene queries, linked work items with include=workItem, PATCH of attributes and POST of comments. For the remaining recipes the OpenAPI definition of your server (https://<host>/polarion/rest/v1/definition) is the authority for field names and optional parameters.
Read one work item with chosen fields
const { data } = await restFetch<WorkItemResponse>(
context,
`/projects/${context.projectId}/workitems/${context.workItemId}` +
`?fields[workitems]=id,title,type,status,priority,severity,description,created,updated`,
);
data.attributes.title;
data.attributes.description?.value; // HTML
Read the assignee and author (relationships)
const { data, included } = await restFetch<WorkItemResponse>(
context,
`/projects/${p}/workitems/${id}?fields[workitems]=id,title,assignee,author&include=assignee,author&fields[users]=id,name,email`,
);
const assigneeIds = data.relationships?.assignee?.data?.map((u) => u.id) ?? []; // ["admin"]
const users = new Map((included ?? []).map((u) => [u.id, u.attributes]));
Query work items
const params = new URLSearchParams({
query: 'type:requirement AND status:open AND NOT HAS_VALUE:assignee',
sort: '-updated',
'fields[workitems]': 'id,title,status,type,updated',
'page[size]': '100',
'page[number]': '1',
});
const list = await restFetch<WorkItemListResponse>(context, `/projects/${p}/workitems?${params}`);
list.data; // array of resources
list.meta?.totalCount; // total across pages
The query syntax is the Lucene syntax of the Work Items table. A set of ids: id:(TEST-1 TEST-2 TEST-3).
Page through a large result
async function allWorkItems(context: PolarionContext, p: string, query: string) {
const out: WorkItemResource[] = [];
for (let page = 1; ; page++) {
const params = new URLSearchParams({ query, 'fields[workitems]': 'id,title', 'page[size]': '100', 'page[number]': String(page) });
const r = await restFetch<WorkItemListResponse>(context, `/projects/${p}/workitems?${params}`);
out.push(...r.data);
// Stop on the reported total, not on a short page: a server may cap page[size] below 100.
const total = r.meta?.totalCount;
if (r.data.length === 0 || (total !== undefined && out.length >= total)) return out;
}
}
The loop ends when all items reported by meta.totalCount are collected, or when a page comes back empty. It does not rely on the requested page size, because the server can serve fewer items per page than requested.
For thousands of items, move the aggregation into an endpoint.
Update attributes
await restFetch(context, `/projects/${p}/workitems/${id}`, {
method: 'PATCH',
body: JSON.stringify({
data: { type: 'workitems', id: `${p}/${id}`, attributes: { title: 'New title', priority: '90.0' } },
}),
});
Enumeration fields take the option id (priority: '90.0', severity: 'must_have'), not the label.
Change the status
await restFetch(context, `/projects/${p}/workitems/${id}`, {
method: 'PATCH',
body: JSON.stringify({ data: { type: 'workitems', id: `${p}/${id}`, attributes: { status: 'inprogress' } } }),
});
The transition must be allowed by the workflow for the current status and the user's role; otherwise the API answers 400 or 403 with the reason in errors[].detail. Newer servers also expose explicit workflow actions (see …/workitems/{id}/actions in the definition).
Set the assignee
await restFetch(context, `/projects/${p}/workitems/${id}`, {
method: 'PATCH',
body: JSON.stringify({
data: {
type: 'workitems',
id: `${p}/${id}`,
relationships: { assignee: { data: [{ type: 'users', id: 'jdoe' }] } },
},
}),
});
Create a work item
const created = await restFetch<WorkItemListResponse>(context, `/projects/${p}/workitems`, {
method: 'POST',
body: JSON.stringify({
data: [
{ type: 'workitems', attributes: { type: 'task', title: 'Follow-up', description: { type: 'text/html', value: '<p>Created by the app.</p>' } } },
],
}),
});
created.data[0].id; // "test/TEST-600"
Link two work items
await restFetch(context, `/projects/${p}/workitems/${id}/linkedworkitems`, {
method: 'POST',
body: JSON.stringify({
data: [
{
type: 'linkedworkitems',
attributes: { role: 'relates_to' },
relationships: { workItem: { data: { type: 'workitems', id: `${p}/TEST-513` } } },
},
],
}),
});
Role ids come from the project's link role enumeration (relates_to, implements, verifies, …).
Read links with the linked items' titles
const r = await restFetch<LinkedWorkItemsResponse>(
context,
`/projects/${p}/workitems/${id}/linkedworkitems?fields[linkedworkitems]=role,suspect,workItem&include=workItem&fields[workitems]=id,title,status`,
);
const byId = new Map((r.included ?? []).map((wi) => [wi.id, wi]));
r.data.map((link) => ({ role: link.attributes.role, item: byId.get(link.relationships.workItem.data.id) }));
Add a comment
await restFetch(context, `/projects/${p}/workitems/${id}/comments`, {
method: 'POST',
body: JSON.stringify({
data: [{ type: 'workitem_comments', attributes: { text: { type: 'text/html', value: '<p>Reviewed by the app.</p>' } } }],
}),
});
Escape user input before putting it into HTML.
Read a Document and its work items
const doc = await restFetch<DocumentResponse>(
context,
`/projects/${p}/spaces/${context.spaceId}/documents/${context.documentId}?fields[documents]=title,type,status,updated`,
);
const parts = await restFetch<DocumentPartsResponse>(
context,
`/projects/${p}/spaces/${context.spaceId}/documents/${context.documentId}/parts?include=workItem&fields[workitems]=id,title,type`,
);
Test runs and records
const runs = await restFetch<TestRunListResponse>(context, `/projects/${p}/testruns?fields[testruns]=id,title,status,finishedOn&page[size]=50`);
const records = await restFetch<TestRecordListResponse>(
context,
`/projects/${p}/testruns/${runId}/testrecords?include=testCase&fields[testrecords]=result,executed&fields[workitems]=id,title`,
);
Enumerations (for select boxes)
const statuses = await restFetch<EnumerationResponse>(context, `/projects/${p}/enumerations/~/status/~`);
// options: statuses.data.attributes.options → [{ id, name, color, … }]
The exact path depends on the enumeration's context (work item type specific enumerations have their own path); check the definition.
Users
const me = await restFetch<UserResponse>(context, `/users/${userId}?fields[users]=id,name,email`);
Views do not know the current user's id directly; an endpoint can return it from the security service, or compare relationships.author of an item the user just created.
Error body
All errors share one shape:
{ "errors": [ { "status": "400", "title": "Bad Request", "detail": "…", "source": { "pointer": "$.data.attributes.status" } } ] }
Show detail to the user; it usually names the field or rule that failed.
Your own REST endpoints
Your own REST endpoints
An application is not limited to what the browser can do. It can declare its own REST endpoints: HTTP paths under the application's URL that Polarion routes to JavaScript files inside the package. The code runs on the Polarion server, as the user who made the call, with access to the Polarion Java API through the scripting bridge. This is how an application delivers functionality that goes beyond the standard REST API.
POST https://<host>/polarion/apps/com.example.releasechecklist/rest/validate
X-Polarion-REST-Token: <context.restToken>
{"objectId": "test/TEST-514", "objectIds": "[\"test/TEST-514\",\"test/TEST-513\"]"}
→ {"timestamp": "…", "success": true,
"data": {"results": [...], "summary": {"items": 2, "withFindings": 1, ...}}}

What an endpoint gives you
| Capability | Why it matters |
|---|---|
| One request, any amount of work | Walk a link tree of 300 items, validate a whole selection, build a report: one round trip instead of hundreds of REST calls from the browser. |
| The full Polarion Java API | Everything the tracker, project, security and document services offer, including what the REST API does not expose. |
| Server-side integration | Call external systems from the server, with credentials kept in the user account vault, never in the browser. |
| Your own contract | Request and response shapes that fit your UI, instead of assembling JSON:API documents in the view. |
| The user's identity | Calls run as the user identified by the REST token. Permissions, workflow rules and audit trails apply as in the UI. |
How it fits together
- Declare the endpoint in
manifest.json: a path, a method (GETorPOST) and the script file. Declare endpoints → - Write the script in
server-scripts/. It reads parameters fromarguments, usescontext.scriptContext()to reach Polarion, and evaluates to the response object. Write the server script → - Call it from the view with
fetch()atcontext.appEndpoint + '/<path>', sendingcontext.restTokenin the requiredX-Polarion-REST-Tokenheader. Call endpoints from a view →
Polarion takes care of routing, authentication, parameter parsing, JSON serialization and the response envelope.
Every endpoint request requires a valid X-Polarion-REST-Token header, for both GET and POST. A logged-in browser session or session cookie does not authenticate an endpoint call. Opening an endpoint URL in the address bar does not send the required header; use fetch() or an HTTP client that can set it. See Test and debug.
- com.example.releasechecklist/
- manifest.json ("serverScripts": { "endpoints": [… ] })
- checklist/ (the sidebar view)
- server-scripts/
- validate.js (POST …/rest/validate)
- assign-to-me.js (POST …/rest/assign-to-me)
When to write an endpoint, when to use the REST API
Use the Polarion REST API directly from the view when it covers the job: reading and writing single objects, lists with queries, standard relationships. Write an endpoint when you need aggregation, rules, Java-only APIs, server-side secrets, or simply a cleaner contract for your UI. Most real applications do both. REST API or your own endpoints? →
In this section
- Declare endpoints: the manifest section, URL scheme, GET versus POST.
- Write the server script: the runtime, the
contextandargumentsobjects, Java interop, results and errors. - Call endpoints from a view: the fetch helper, parameters, envelope handling, TypeScript types.
- Patterns: aggregation, validation, write operations, external systems, caching.
- Test and debug: calling endpoints directly, reading errors, the server log.
- Reference: Endpoint runtime.
Worked examples: Traceability with endpoints (a GET that computes a tree, a POST that writes) and Release checklist (validation and bulk update of a selection).
Your own REST endpoints
Declare endpoints
Endpoints are declared in manifest.json under serverScripts.endpoints. Each entry maps an HTTP method and a path segment to a script file in the server-scripts/ folder of the package.
{
"identifier": "com.example.releasechecklist",
"…": "…",
"serverScripts": {
"endpoints": [
{ "urlPath": "validate", "method": "POST", "script": "validate.js" },
{ "urlPath": "assign-to-me", "method": "POST", "script": "assign-to-me.js" },
{ "urlPath": "stats", "method": "GET", "script": "stats.js" }
]
}
}
| Field | Meaning |
|---|---|
urlPath |
Last path segment of the endpoint URL. Letters, digits and hyphens; lower-case by convention. Unique per method. |
method |
GET or POST. |
script |
File name inside server-scripts/. Keep one script per endpoint. |
The URL
Every endpoint lives under the application's endpoint base, which the framework hands to views as context.appEndpoint:
https://<host>/polarion/apps/<identifier>/rest/<urlPath>
For com.example.releasechecklist the three endpoints above are:
POST https://<host>/polarion/apps/com.example.releasechecklist/rest/validate
POST https://<host>/polarion/apps/com.example.releasechecklist/rest/assign-to-me
GET https://<host>/polarion/apps/com.example.releasechecklist/rest/stats?objectId=test
The identifier namespaces your endpoints; two applications can both declare validate without conflict.
GET or POST
| GET | POST | |
|---|---|---|
| Parameters | query string (?objectId=test/TEST-514&depth=2) |
Flat JSON object in the body ({"objectId": "test/TEST-514", "text": "…"}), Content-Type: application/json |
| Reading them in the script | arguments.getAsString('objectId') |
arguments.getAsString('text'); every value must be a string. Send lists and objects JSON-encoded in a string and JSON.parse them in the script. |
| Use for | reads, computations, reports | writes, anything with side effects, requests with structured or long input |
| Cacheable by the browser | yes (add a cache-busting parameter if that is unwanted) | no |
Rules of thumb:
- Reads with a handful of scalar parameters: GET.
- Anything that saves, and anything whose input is long or structured: POST. Encode lists and objects as JSON strings; a body with a nested array or object is rejected with HTTP 500 (Expected a string but was BEGIN_ARRAY).
- Never change data in a GET endpoint. Whether the server rejects a save in a GET script depends on configuration; design as if it did.
The objectId parameter
Every endpoint call must carry a parameter named objectId, in the query string for GET and in the body for POST. Polarion rejects a call without it before the script runs, with HTTP 400 and Argument objectId is missing in workflow definition. Use the id of the object the call is about in the form PROJECT/WI-ID (for example drivepilot/DP-477); a project id alone is also accepted. Your script reads it like any other parameter.
GET …/rest/linked-tree?objectId=drivepilot/DP-477&depth=2
POST …/rest/validate {"objectId": "drivepilot/DP-461", "objectIds": "[\"drivepilot/DP-461\",\"drivepilot/DP-527\"]"}
Authentication
Every GET and POST call must send a valid REST token in the X-Polarion-REST-Token header. From a view, use context.restToken:
X-Polarion-REST-Token: <context.restToken>
A browser session or session cookie cannot replace this header. Requests without a valid token are rejected before the script runs, even when the caller is logged in to Polarion. The script executes as the user identified by the token; see Security model.
Package layout
/ - manifest.json
/ (one folder per view) - server-scripts/
- validate.js
- assign-to-me.js
- stats.js
Upload validation checks that every script exists. Scripts are read from the uploaded package; changing them means re-uploading the application, which takes effect immediately.
Versioning your contract
Views and endpoints ship together in one package, so they are always in sync; there is no need for URL versioning between them. If other clients (automation, another application) call your endpoints, treat the request and response shapes as a public contract: add fields rather than renaming them, and document them in the application's README as the examples do.
Your own REST endpoints
Write the server script
An endpoint is implemented by one JavaScript file in server-scripts/. Polarion executes it with GraalVM JavaScript on the server when the endpoint is called, using the same scripting bridge that workflow functions and scheduled scripts use.
The shape of a script
// Globals provided by Polarion:
// context – entry point to the Polarion API
// arguments – the request parameters (IArguments)
const trackerService = context.scriptContext().services().tracker();
const scriptArguments = arguments; // inside functions, `arguments` means something else
let result = {};
// Reads a parameter that may be absent (getAsString throws for missing ones).
function optionalParam(name, fallback) {
try {
const value = scriptArguments.getAsString(name);
return value === null || value === undefined || String(value) === '' ? fallback : String(value);
} catch (e) {
return fallback;
}
}
try {
// objectId is sent on every call; here it carries the project id.
const projectId = scriptArguments.getAsString('objectId');
const limit = parseInt(optionalParam('limit', '50'), 10);
const project = trackerService.getTrackerProject(projectId);
// … compute …
result = { projectId: project.getId(), name: project.getName(), limit: limit };
} catch (e) {
// An `error` key turns the response into an error response.
result = { error: 'stats failed: ' + e };
}
result; // the last expression is the response
Five conventions matter:
- Read input from
arguments.arguments.getAsString('name')returns the parameter as a string and throws when the parameter was not sent (see rule 5). For POST, the fields of the JSON body are the parameters. Polarion accepts only string values in the body; a nested array or object is rejected before the script runs. Send structured input JSON-encoded in a string andJSON.parseit in the script. - Wrap the body in
try/catchand put the message into anerrorproperty. Uncaught exceptions also produce an error response, but a message you wrote is easier to act on in the view. - End with the result expression. Whatever the last statement evaluates to is serialized as JSON and wrapped in the response envelope.
- Capture
argumentsat the top level. Inside a JavaScript function,argumentsis the function's own arguments object, not Polarion's. Assignconst scriptArguments = arguments;at the top of the script and use that in helper functions; otherwise you get arguments.getAsString is not a function. - Guard optional parameters.
arguments.getAsString('name')throws Argument name is missing in workflow definition when the parameter was not sent, and the whole call fails with HTTP 400. Read optional parameters through a small helper that catches that case (seeoptionalParam()in the traceability script below).
The context global
context.scriptContext() returns the script context. Its two entry points:
| Expression | Returns |
|---|---|
context.scriptContext().services() |
The Polarion services: tracker() (work items, projects, links), security() (current user, permissions), project() (users, projects) and others listed in IScriptServices. |
context.scriptContext().utils() |
Utilities, for example httpClient() for outbound HTTP. |
The most used service is the tracker:
const trackerService = context.scriptContext().services().tracker();
const wi = trackerService.getWorkItem('test', 'TEST-514'); // IWorkItem
wi.getTitle(); wi.getStatus().getName(); wi.getDescription();
const project = trackerService.getTrackerProject('test'); // ITrackerProject
The API is Polarion's Java API. The javadoc on your server (https://<host>/polarion/sdk/doc/javadoc/, package com.polarion.alm.tracker.model) documents IWorkItem, ITrackerProject, ILinkedWorkItemStruct, IComment and the rest; the scripting API documentation (sdk/doc/scripting-api/) documents IScriptContext, IScriptServices and IArguments.
Working with Java objects from JavaScript
- Collections. Convert with
.toArray()before iterating:const links = wi.getLinkedWorkItemsStructsDirect().toArray(); for (let i = 0; i < links.length; i++) { … }. - Null checks. Java methods return
nullwhere JavaScript code would expectundefined:wi.getType() ? wi.getType().getName() : null. - Unresolvable objects. A lookup for an id that does not exist returns a placeholder; check
wi.isUnresolvable(). - Classes.
Java.type('fully.qualified.Name')loads any Polarion or JDK class, for exampleJava.type('com.polarion.core.util.types.Text')to build rich text. - Dates.
wi.getCreated()is ajava.util.Date;new Date(wi.getCreated().getTime())converts it. - Strings behave like JavaScript strings.
A GET script that computes
The traceability example walks the link structure of a work item and returns a nested tree in one response:
// GET /polarion/apps/com.example.traceability/rest/linked-tree?objectId=PROJECT/WI-ID&depth=2[&role=implements]
//
// Runs on the Polarion server (GraalVM JavaScript) as the logged-in user.
// Walks the work item links in both directions and returns a nested tree.
// The optional `role` filter applies to links in both directions.
//
// Globals provided by Polarion:
// context – IScriptContext access: context.scriptContext().services().tracker()
// arguments – IArguments: request parameters (query string for GET, JSON body for POST)
const trackerService = context.scriptContext().services().tracker();
let result = {};
// Polarion's IArguments throws ("Argument <name> is missing in workflow definition")
// when a parameter is absent. Optional parameters are therefore read through a guard.
const scriptArguments = arguments;
function getOptionalParam(name, defaultValue) {
try {
const value = scriptArguments.getAsString(name);
return value === null || value === undefined || String(value) === '' ? defaultValue : String(value);
} catch (e) {
return defaultValue;
}
}
function readParameters() {
const objectId = scriptArguments.getAsString('objectId');
if (!objectId) {
throw new Error('objectId parameter is required (PROJECT/WI-ID)');
}
const depth = Math.min(3, Math.max(1, parseInt(getOptionalParam('depth', '2'), 10) || 2));
const roleParam = getOptionalParam('role', '');
const roleFilter = roleParam ? String(roleParam).trim().toLowerCase() : '';
return { objectId, depth, roleFilter };
}
function findWorkItem(objectId) {
const [projectId, workItemId] = objectId.split('/');
const workItem = trackerService.getWorkItem(projectId, workItemId);
if (workItem.isUnresolvable()) {
throw new Error('Work item not found: ' + objectId);
}
return workItem;
}
/** Suspect flag of a link; defaults to false if the API call is unavailable. */
function isSuspect(link) {
try {
return link.isSuspect() === true;
} catch (e) {
return false;
}
}
/** Id, name and opposite name of a link role, e.g. "verifies", "verifies", "is verified by". */
function roleInfo(link) {
const role = link.getLinkRole();
if (!role) return { id: '', name: '', oppositeName: '' };
let oppositeName = '';
try {
oppositeName = role.getOppositeName() ? String(role.getOppositeName()) : '';
} catch (e) {
// Without an opposite name the filter matches the id and the name only.
}
return { id: String(role.getId()), name: String(role.getName()), oppositeName: oppositeName };
}
// Every role met while walking, so the view can offer them in its filter.
const rolesSeen = new Map();
function remember(info) {
if (info.id && !rolesSeen.has(info.id)) {
rolesSeen.set(info.id, info);
}
}
/**
* True when no role filter is set or the link role matches it (case-insensitive).
* The filter compares the role id, its name and its opposite name, so "verifies" also
* matches a back link that reads "is verified by" from this side.
*/
function roleMatches(info, roleFilter) {
if (!roleFilter) return true;
return [info.id, info.name, info.oppositeName].some((value) => value.toLowerCase() === roleFilter);
}
function toTreeNode(workitem) {
return {
id: workitem.getProjectId() + '/' + workitem.getId(),
title: workitem.getTitle(),
type: workitem.getType() ? workitem.getType().getName() : null,
status: workitem.getStatus() ? workitem.getStatus().getName() : null,
};
}
// Direct links ("this item implements X") become the downstream children.
// `ancestors` holds the items on the path from the root to here. Each branch gets its own
// copy, so a cycle stops the recursion but an item reached on two paths is expanded on both.
function buildDownstreamNodes(workitem, depth, ancestors, roleFilter) {
const workItemId = workitem.getProjectId() + '/' + workitem.getId();
if (depth <= 0 || ancestors.has(workItemId)) {
return [];
}
const path = new Set(ancestors);
path.add(workItemId);
const downstream = [];
// Java collections are easiest to iterate as arrays from GraalVM JavaScript.
const direct = workitem.getLinkedWorkItemsStructsDirect().toArray();
for (let i = 0; i < direct.length; i++) {
const link = direct[i];
const info = roleInfo(link);
remember(info);
if (!roleMatches(info, roleFilter)) {
continue;
}
const linkedWorkItem = link.getLinkedItem();
const node = toTreeNode(linkedWorkItem);
node.role = info.name;
node.suspect = isSuspect(link);
if (depth > 1 && !path.has(node.id)) {
node.downstream = buildDownstreamNodes(linkedWorkItem, depth - 1, path, roleFilter);
}
downstream.push(node);
}
return downstream;
}
function buildUpstreamNodes(workItem, roleFilter) {
const upstream = [];
const back = workItem.getLinkedWorkItemsStructsBack().toArray();
for (let i = 0; i < back.length; i++) {
const link = back[i];
const info = roleInfo(link);
remember(info);
// The role filter applies in both directions: a requirement filtered by "verifies"
// shows the test cases that verify it, which are back links seen from here.
if (!roleMatches(info, roleFilter)) {
continue;
}
const node = toTreeNode(link.getLinkedItem());
// Seen from this item a back link reads in the opposite direction ("is verified by").
node.role = info.oppositeName || info.name;
node.suspect = isSuspect(link);
upstream.push(node);
}
return upstream;
}
try {
const { objectId, depth, roleFilter } = readParameters();
const workItem = findWorkItem(objectId);
const rootWorkItemNode = toTreeNode(workItem);
rootWorkItemNode.downstream = buildDownstreamNodes(workItem, depth, new Set(), roleFilter);
rootWorkItemNode.upstream = buildUpstreamNodes(workItem, roleFilter);
result = { item: rootWorkItemNode, roles: Array.from(rolesSeen.values()) };
} catch (e) {
// An `error` key turns the response into an error response for the caller.
result = { error: 'linked-tree failed: ' + e };
}
result;
A POST script that writes
Writes follow the same pattern plus save():
// POST /polarion/apps/com.example.traceability/rest/add-comment
// Body: { "objectId": "PROJECT/WI-ID", "text": "…" }
//
// Adds a plain-text comment to the work item. Runs as the logged-in user, who
// therefore needs permission to comment on the item.
const trackerService = context.scriptContext().services().tracker();
const Text = Java.type('com.polarion.core.util.types.Text');
let result = {};
try {
const fullId = arguments.getAsString('objectId');
const text = arguments.getAsString('text');
if (!fullId) {
throw new Error('objectId parameter is required (PROJECT/WI-ID)');
}
if (!text || text.trim() === '') {
throw new Error('text parameter is required');
}
const [projectId, workitemId] = fullId.split('/');
const workitem = trackerService.getWorkItem(projectId, workitemId);
if (workitem.isUnresolvable()) {
throw new Error('Work item not found: ' + fullId);
}
// createComment(IText text, String title, IComment parent) returns the new
// IComment. Saving the work item alone does not persist it; save the comment.
const comment = workitem.createComment(Text.plain(text), 'Traceability app', null);
comment.save();
// The id may not be assigned yet right after save; report it when available.
const commentId = comment.getId();
result = { ok: true, commentId: commentId ? String(commentId) : null };
} catch (e) {
result = { error: 'add-comment failed: ' + e };
}
result;
Warning
Keep writes in POST endpoints. Treat GET endpoints as read-only; whether a save in a GET script is rejected depends on the server configuration.
Results and the envelope
Polarion wraps the result:
{ "timestamp": "2026-10-05T10:15:42.945Z", "success": true, "data": { "…": "…" } }
With an error key, or after an uncaught exception:
{ "timestamp": "…", "success": false, "error": "stats failed: Error: projectId parameter is required" }
Return plain objects, arrays, strings, numbers and booleans. Do not return Java objects; map them to plain data first (describe(wi) in the example above).
Permissions
The script runs as the user who called the endpoint. trackerService.getWorkItem() on an item the user may not read fails exactly as it would in the UI, and save() is subject to the user's permissions and the workflow. Validate all input: arguments is data from the browser. See Security model.
Secrets and external calls
Never embed credentials in a script. Read them from the user account vault through the services, and perform outbound HTTP with context.scriptContext().utils().httpClient(). The reference application tsapp-1 contains a script that posts an Adaptive Card to Microsoft Teams this way.
Note
The scripts shown in this guide were executed against a Polarion 2612 server. When your server version differs, verify method names against its javadoc.
Your own REST endpoints
Call endpoints from a view
The context gives a view everything it needs to call the application's endpoints: appEndpoint (the base URL) and restToken (the authentication token). The rest is fetch().
Every GET and POST request must send a valid context.restToken in the X-Polarion-REST-Token header. The browser's Polarion session and cookies do not authenticate endpoint calls. If the token is empty, enable REST token authentication before calling endpoints.
The helper
import type { PolarionContext } from 'polarion-app-sdk';
/** Envelope that Polarion wraps around every server-script response. */
interface Envelope<T> {
timestamp?: string;
success?: boolean;
error?: string;
data?: T;
}
/**
* Calls one of the application's own endpoints declared in
* manifest.json under `serverScripts.endpoints`.
*
* `context.appEndpoint` is the absolute base URL of those endpoints, for example
* `https://host/polarion/apps/com.example.traceability/rest` (no trailing slash), so `path`
* starts with a slash, as in `restFetch`: `"/validate"`. The same
* `X-Polarion-REST-Token` header as for the REST API authenticates the call.
* The response envelope is unwrapped so callers only see the script's result.
*/
export async function endpointFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
const headers = new Headers(init.headers);
headers.set('X-Polarion-REST-Token', context.restToken ?? '');
headers.set('Accept', 'application/json');
if (init.body !== undefined && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json');
}
const response = await fetch(`${context.appEndpoint}${path}`, { ...init, headers });
// Script errors come back as HTTP 400 with the envelope, so parse the body
// whenever it is JSON and surface the script's own message.
const text = await response.text();
let envelope: Envelope<T> | undefined;
try {
envelope = JSON.parse(text) as Envelope<T>;
} catch {
envelope = undefined;
}
if (envelope && (envelope.success === false || envelope.error)) {
throw new Error(envelope.error ?? 'Server script reported an error.');
}
if (!response.ok || !envelope) {
throw new Error(`Endpoint ${response.status}: ${text}`);
}
return envelope.data as T;
}
The helper does four things: builds the URL from appEndpoint, sets the X-Polarion-REST-Token header, sets Content-Type: application/json when there is a body, and unwraps the envelope. Script errors arrive as HTTP 400 with the envelope, so the helper parses the body on every status and throws an Error with the script's own message when success is false.
endpointFetch is the counterpart of restFetch from Calling the REST API from a view: the same arguments, a path that starts with /, and the same token header. The examples keep both in src/polarion.ts under these two names.
GET with query parameters
import type { PolarionContext } from 'polarion-app-sdk';
import { endpointFetch } from './polarion';
interface LinkedTreeResult { item: TreeNode }
async function loadTree(context: PolarionContext) {
const params = new URLSearchParams({
objectId: `${context.projectId}/${context.workItemId}`, // required on every call
depth: '2',
});
return endpointFetch<LinkedTreeResult>(context, `/linked-tree?${params}`);
}
URLSearchParams encodes slashes and spaces correctly.
POST with a JSON body
interface ValidateResult {
results: { id: string; title: string; status: string; findings: { code: string; message: string }[] }[];
summary: { items: number; withFindings: number; byCode: Record<string, number> };
}
async function validate(context: PolarionContext, objectIds: string[]) {
return endpointFetch<ValidateResult>(context, '/validate', {
method: 'POST',
// objectId is required on every call; the body must be a flat object with
// string values, so the list is encoded as a JSON string.
body: JSON.stringify({ objectId: objectIds[0], objectIds: JSON.stringify(objectIds) }),
});
}
Polarion parses the POST body as a flat object of string parameters. A nested array or object is rejected with HTTP 500 (Expected a string but was BEGIN_ARRAY) before the script runs. Encode structured input as a JSON string and parse it in the script with JSON.parse(arguments.getAsString('objectIds')).
Types for your contract
Declare the request and response shapes once in src/types.ts and use them in both the helper calls and the components. Because view and endpoint ship together, the TypeScript types are the documentation of the contract; keep them next to the script that implements it.
Handling the outcome
try {
const result = await validate(context, ids);
setResults(result.results);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
Three kinds of failure reach the catch:
| Failure | Message |
|---|---|
| HTTP error before the script ran (unknown endpoint, missing token, bad content type, non-string body value) | Endpoint 404: …, Endpoint 401: …, Endpoint 400: …, Endpoint 500: {"error":"… Expected a string but was BEGIN_ARRAY …"} |
The script returned { error } or threw (HTTP 400 with the envelope) |
the script's message, for example validate failed: Error: objectIds: expected "PROJECT/WI-ID", got "DP-461" |
| Network problem | the browser's fetch error |
Show the message; for 401, call fetchContext() again to refresh the token and retry once.
Loading state and cancellation
Endpoint calls can take longer than REST reads because they do more work. Show a loading state ("Computing the link tree on the server…") and, in views that react to selection changes, debounce calls and ignore stale responses:
useEffect(() => {
let cancelled = false;
const timer = setTimeout(() => {
validate(context, ids).then((r) => { if (!cancelled) setResults(r.results); });
}, 200);
return () => { cancelled = true; clearTimeout(timer); };
}, [context, ids]);
Calling endpoints from outside a view
Other clients must also send a valid REST token in the X-Polarion-REST-Token header. Session cookies and personal access tokens sent as Authorization: Bearer are not substitutes. Do not assume that an authentication method accepted by the standard REST API is accepted by application endpoints. See Test and debug for an HTTP client example.
Your own REST endpoints
Patterns
This page collects the shapes that endpoint-backed applications take in practice. Each pattern names the problem, sketches the script and says what the view does with the result.
1. Aggregation: one request instead of many
Problem. The view needs data from many objects: the link tree of a work item, all test cases of a requirement with their last result, the work items of a plan with their time records.
Script. Walk the objects on the server and return a compact structure shaped for the UI.
const trackerService = context.scriptContext().services().tracker();
let result = {};
try {
const [projectId, wiId] = arguments.getAsString('objectId').split('/');
const wi = trackerService.getWorkItem(projectId, wiId);
const links = wi.getLinkedWorkItemsStructsDirect().toArray();
const children = [];
for (let i = 0; i < links.length; i++) {
const target = links[i].getLinkedItem();
children.push({ id: target.getId(), title: target.getTitle(), role: links[i].getLinkRole().getName() });
}
result = { id: wi.getId(), children: children };
} catch (e) {
result = { error: 'aggregate failed: ' + e };
}
result;
View. One endpointFetch, then render. See Traceability with endpoints.
2. Validation and rules
Problem. Check a set of work items against rules that need several fields, links or history: "every requirement has a test", "no open item older than 90 days without an assignee".
Script. Accept a list of ids (POST), evaluate the rules, return findings per item plus a summary. Keep rule code in small functions so that adding a rule is one function and one entry in a list.
const rules = [
{ code: 'no-description', check: (wi) => !wi.getDescription() || wi.getDescription().getContent().trim() === '' },
{ code: 'unassigned', check: (wi) => wi.getAssignees().isEmpty() },
];
View. A sidebar that validates the selection as it changes and offers fixes. See Release checklist.
3. Bulk writes with a clear outcome
Problem. Apply the same change to many items: assign, set a field, add a link, transition the workflow.
Script. POST with the ids (as a JSON string, plus the mandatory objectId) and the change; loop, save() each item, collect successes and failures instead of aborting on the first error.
const updated = [], failed = [];
for (const fullId of ids) {
try {
const [p, id] = fullId.split('/');
const wi = trackerService.getWorkItem(p, id);
wi.addAssignee(user);
wi.save();
updated.push(fullId);
} catch (e) {
failed.push({ id: fullId, error: String(e) });
}
}
result = { updated: updated, failed: failed };
View. Report both lists; re-run the read afterwards. The REST API can also do bulk updates, but an endpoint gives one round trip and a single, tailored result.
4. External systems with server-side secrets
Problem. Notify a chat channel, create a ticket in another tool, fetch data from an internal service that must not be reachable from the browser.
Script. Read the secret from the user account vault, call the system with context.scriptContext().utils().httpClient(), return a summary.
const httpClient = context.scriptContext().utils().httpClient();
const HttpRequest = Java.type('java.net.http.HttpRequest');
const BodyPublishers = Java.type('java.net.http.HttpRequest$BodyPublishers');
const URI = Java.type('java.net.URI');
// const webhook = <read from the vault>;
const request = HttpRequest.newBuilder(URI.create(webhook))
.header('Content-Type', 'application/json')
.POST(BodyPublishers.ofString(JSON.stringify(card)))
.build();
const response = httpClient.sendRequest(request);
View. A button and a status line. The reference application tsapp-1 contains a complete Teams notification script.
5. Computed data for dashboards
Problem. A navigation topic needs counts, trends or groupings over the whole project.
Script. Query with the tracker service, aggregate in a loop, return the numbers. Add parameters for the query and the grouping so that one endpoint serves several widgets.
View. Render tiles and charts; refresh on demand. Combine with the REST API for the detail table below the charts.
6. Configuration without an administration view
Problem. The application needs settings (a mapping table, thresholds, a target URL) until administration views arrive.
Script. A GET endpoint reads the settings from a known place: a document in a configuration space, a work item of a dedicated type, or a JSON file in the global configuration repository. A POST endpoint writes them, checking that the caller is an administrator through the security service.
View. A small settings form in a navigation topic, visible only to administrators.
7. Caching expensive results
Endpoints hold no state between calls. For results that are expensive and change rarely:
- cache in the view for the lifetime of the page (
useMemo, a module-level map keyed by parameters); - let the browser cache GET responses by making the URL stable (same parameters, no timestamp);
- for shared, long-lived caches, store the computed data in Polarion (a document or attachment) with a time stamp and let the endpoint return it when fresh enough.
Anti-patterns
- A single "do everything" endpoint with a
commandparameter. Separate endpoints are easier to secure, test and document. - Returning Java objects or deeply nested raw structures. Map to the fields the UI needs.
- Writes in GET endpoints.
- Trusting input. Validate ids, lengths and enumerations before touching data.
- Long-running loops without limits. Cap the depth or page the work; the caller waits for the whole script. See Performance and load.
Your own REST endpoints
Test and debug
Endpoints are plain HTTP. Every test request must include a valid X-Polarion-REST-Token header; a browser session alone does not authenticate the request.
Call a GET endpoint from the developer tools
With an application view open in Polarion, select the view's frame in the browser console. Use the context fetched by your view to set the token header:
const params = new URLSearchParams({ objectId: 'test/TEST-514', depth: '1' });
const r = await fetch(`${ctx.appEndpoint}/linked-tree?${params}`, {
headers: { 'X-Polarion-REST-Token': ctx.restToken, Accept: 'application/json' },
});
console.log(await r.json());
ctx is the context your view fetched. Opening the URL directly in a new tab does not send this header and cannot authenticate the request. An authenticated call returns the raw envelope:
{"timestamp":"2026-10-05T10:15:42.945Z","success":true,"data":{"item":{…}}}
Call any endpoint from the developer tools
With a view open in Polarion, the context is in memory. In the browser console, select the view's frame and run:
const r = await fetch(`${ctx.appEndpoint}/validate`, {
method: 'POST',
headers: { 'X-Polarion-REST-Token': ctx.restToken, 'Content-Type': 'application/json' },
body: JSON.stringify({ objectId: 'test/TEST-514', objectIds: JSON.stringify(['test/TEST-514']) }),
});
console.log(await r.json());
ctx is the context your view fetched; expose it on window in development builds if that is convenient.
Call from an HTTP client with a REST token
For a diagnostic call with curl, supply a current REST token as POLARION_REST_TOKEN in your local shell. Use the token provided to the view as context.restToken; keep it out of saved scripts, logs and version control:
curl -s -X POST "https://<host>/polarion/apps/com.example.releasechecklist/rest/validate" \
-H "X-Polarion-REST-Token: $POLARION_REST_TOKEN" \
-H "Content-Type: application/json" \
-d '{"objectId":"test/TEST-514","objectIds":"[\"test/TEST-514\"]"}'
Application endpoints require this header. A session cookie or an Authorization: Bearer personal access token does not replace it. Do not assume that authentication methods supported by the standard REST API also authenticate application endpoints.
Reading errors
| What you see | Where it comes from | What to do |
|---|---|---|
success: false, error: "… failed: Error: objectId parameter is required" |
Your own throw inside try/catch |
The view did not send the parameter, or sent it in the wrong place (query string vs body). |
HTTP 400, error: "Argument objectId is missing in workflow definition." |
The call did not include objectId |
Add objectId=PROJECT/WI-ID to every call. |
HTTP 400, error: "… Argument role is missing in workflow definition." |
arguments.getAsString() for a parameter that was not sent |
Send the parameter or read it through a guarded helper. |
error: "… TypeError: arguments.getAsString is not a function" |
arguments used inside a function |
Capture const scriptArguments = arguments; at the top of the script. |
success: false, error: "… TypeError: wi.getFoo is not a function" |
A Java method name that does not exist | Check the javadoc for the class; Java methods are case-sensitive and need parentheses. |
success: false, error: "… java.lang.SecurityException …" or a permission message |
The user may not perform the operation | Expected for users without rights; show it. |
| HTTP 400 before any envelope | Request shape (missing JSON content type or body on POST) | Set Content-Type: application/json and send a JSON body, {} if empty. |
| HTTP 401 | Missing, invalid or expired X-Polarion-REST-Token |
Send the header with a valid token; refresh the context and check that token authentication is enabled. A logged-in browser session is insufficient. |
| HTTP 404 | Wrong urlPath, wrong method, or application not installed |
Compare with the manifest and Properties. |
The server log
Uncaught exceptions and the output of console.log() in scripts are expected in Polarion's main log (data/logs/main/log4j-*.log). Prefix log lines with the application identifier so that they can be filtered.
Iterating on a script
- Edit the script in
server-scripts/. npm run package(the view does not need to change; the script is just copied).- Upload. The new script is active immediately.
- Repeat the call.
For faster iteration on logic that does not depend on request parameters, the Scripting topic in Global Administration can run GraalVM scripts interactively against the same services; move the code into the endpoint once it works.
Checklist before shipping an endpoint
- [] Every parameter validated; helpful messages for missing ones.
- []
try/catcharound the body; errors include the endpoint name. - [] No writes in GET endpoints.
- [] Result mapped to plain data; no Java objects.
- [] Contract (request, response) documented in the README and typed in
src/types.ts. - [] Tested as a user without administrator rights.
Concepts
Application package
An application package is a ZIP file. Polarion validates its structure during upload, unpacks it, and serves its content.
Layout
- com.example.inspector.zip
- com.example.inspector/ (the identifier from manifest.json)
- manifest.json
- card/ (the folder named in a view's rootDirectory; views may share one)
- index.html
- assets/
- index-….js
- index-….css
- sidebar/
- index.html
- icon16.png
- icon32.png
- assets/
- …
- server-scripts/ (optional)
- linked-tree.js
- add-comment.js
- com.example.inspector/ (the identifier from manifest.json)
Rules that Polarion checks:
- Exactly one top-level folder, and its name must equal the
identifierin the manifest. manifest.jsonmust be directly inside that folder and must be valid JSON.- Every
rootDirectoryreferenced by a view must exist and contain the file named indocument. Several views may name the same folder. - Every
scriptreferenced by an endpoint must exist inserver-scripts/.
A ZIP that puts manifest.json at the root, or that nests the application one level deeper, fails with Application's zip structure is incorrect.
Validation and limits
On every upload and update, Polarion checks the ZIP against limits that protect the server. A package that exceeds one of them is rejected as a whole.
| Check | Default limit | Global configuration property |
|---|---|---|
| Directory depth | 10 levels inside the ZIP | polarionapp.directoryDepthLimit |
| Number of entries | 1,000 files and folders | polarionapp.maxNumberOfEntries |
| Size of one entry | 10 MB per file, unpacked | polarionapp.entrySizeLimitMB |
| Total size | 30 MB, unpacked | polarionapp.totalSizeLimitMB |
| Length of an entry name | 128 characters | polarionapp.entryNameLengthLimit |
| Length of the ZIP file name | 64 characters | polarionapp.zipFileNameLengthLimit |
A typical view built with Vite stays far below these limits: the example applications in this guide have 4 to 8 files and about 250 KB unpacked.
To change a limit, set the property in the global configuration:
- Log in as a user with global administration rights.
- Open Global Administration (avatar menu → Global Administration, or the wrench icon).
- Open Configuration Properties at the bottom of the administration navigation.
-
Add the property to Current Configuration, for example:
polarionapp.totalSizeLimitMB=50 -
Save and reload the browser page.
Allowed file types
A package may contain only static web assets and images. Polarion checks the extension and the content type of every file; if one file is not on the list below, the whole package is rejected.
| Category | Extensions | Accepted MIME types |
|---|---|---|
| Web pages | .html, .htm |
text/html, application/xhtml+xml, text/plain |
| Stylesheets | .css |
text/css, text/plain |
| Scripts | .js |
text/javascript, application/javascript, text/plain |
| Data and configuration | .json |
application/json, text/x-json, text/plain |
| Raster images | .png |
image/png |
.jpg, .jpeg, .jpe |
image/jpeg |
|
.gif |
image/gif |
|
.webp |
image/webp |
|
.ico |
image/x-icon |
|
| Vector images | .svg |
image/svg+xml |
Server scripts are .js files and therefore allowed. Executable and back-end formats such as .java, .py, .php, .sh or .exe are never accepted; this prevents remote code execution through an uploaded package.
Some build outputs are not on the list and have to stay out of the package:
- Source maps (
.map). Inline them into the JavaScript instead, or leave them out; see Local development. - Web fonts (
.woff,.woff2,.ttf). Use system fonts, or load the font from a server outside the package. - Other files that tools place in the build folder, such as
.txtlicense notes or.mdfiles.
The manifest
manifest.json has three parts: identity, views and server scripts.
{
"manifestVersion": "1.0",
"identifier": "com.example.inspector",
"title": "Work item inspector",
"description": "Shows details and links of the selected work items.",
"publisherName": "Example Publisher",
"applicationVersion": "1.2.0",
"views": {
"formExtensions": [
{ "identifier": "card", "title": "Inspector", "rootDirectory": "card", "document": "index.html" }
],
"sidebars": [
{ "identifier": "sidebar", "title": "Inspector", "rootDirectory": "sidebar", "document": "index.html",
"menuIcon": "icon16.png", "icon": "icon32.png" }
],
"navigationTopics": []
},
"serverScripts": {
"endpoints": [
{ "urlPath": "linked-tree", "method": "GET", "script": "linked-tree.js" },
{ "urlPath": "add-comment", "method": "POST", "script": "add-comment.js" }
]
}
}
Every field is described in the manifest.json reference.
Identifiers and what they become
The application identifier and the view identifiers are combined into several other names. Choosing them well avoids renaming later.
| Name | Built from | Example |
|---|---|---|
| Static file URL | identifier, rootDirectory |
/polarion/apps/com.example.inspector/card/index.html |
| View entry URL | identifier, view identifier |
/polarion/apps/com.example.inspector/views/card |
Endpoint URL (appEndpoint) |
identifier, urlPath |
/polarion/apps/com.example.inspector/rest/linked-tree |
Configuration id (applicationView id) |
identifier + . + view identifier |
com.example.inspector.card |
| Sidebar URL parameter | polarion-application. + configuration id |
?sidebar=polarion-application.com.example.inspector.sidebar |
| Navigation topic URL | project URL + configuration id | /polarion/#/project/test/com.example.inspector.overview |
Recommendations:
- Use reverse-DNS identifiers (
com.company.product). Dots are allowed and conventional; stay with letters, digits, dots and hyphens, because the identifier also appears in URLs. - Keep view identifiers short and descriptive (
card,sidebar,dashboard). Using the same value foridentifierandrootDirectorykeeps the package easy to navigate. - Do not rename an identifier after the application is in use. Polarion treats a changed identifier as a new application; the old one stays installed and every
applicationViewreference must be updated.
Views are static sites
A view folder is a self-contained static web site. Polarion does nothing to its content beyond serving it; there is no server-side templating or injection. Consequences:
- All URLs inside the view must be relative (
./assets/x.js,./icon.png). With Vite, setbase: './'. - Several views may share code at build time, but the package must contain the built output for each view in its own folder. Two views that need the same bundle simply contain two copies.
- Only files inside view folders are guaranteed to be served; do not rely on files outside every
rootDirectory. - The entry
documentis usuallyindex.html, but any file name works.
Server scripts folder
Scripts in server-scripts/ are not served as static files. They are executed on the server when their endpoint is called. See Your own REST endpoints.
Size and content
Keep packages small: a typical React view is a few hundred kilobytes. Large media files belong on a separate server. The limits and the allowed file types are listed in Validation and limits and Allowed file types. Polarion stores the unpacked package itself; nothing is placed in the extensions/ folder and no restart is needed.
Concepts
Application context
When Polarion embeds a view, the view starts with no knowledge of its surroundings. The context is the answer to "where am I?": which application and view this is, which project, which work item or document, what is selected, and how to call back into Polarion.
Obtaining the context
import { fetchContext } from 'polarion-app-sdk';
const context = await fetchContext();
fetchContext() sends a request to the Polarion host page and resolves with a PolarionContext object. It rejects with an error if no answer arrives within five seconds, which is what happens when the page is not embedded by Polarion.
Call it once when the view starts. It is safe to call it again later; the answer reflects the state at that moment.
The object
interface PolarionContext {
applicationId: string; // "com.example.inspector"
viewId: string; // "card"
projectId?: string; // "test"
spaceId?: string; // "_default" (Document views)
documentId?: string; // "Requirements" (Document views)
workItemId?: string; // "TEST-514" (form extensions)
selectedWorkItemIds: string[];// ["test/TEST-514"] in a form (all ticked items in a multi-item edit form); empty in sidebars
appEndpoint: string; // "https://host/polarion/apps/com.example.inspector/rest"
restBaseUrl: string; // "https://host/polarion/rest/v1"
restToken?: string; // token for the X-Polarion-REST-Token header
}
A real example, captured from a form extension (names shortened):
{
"applicationId": "com.example.context",
"viewId": "form",
"projectId": "test",
"workItemId": "TEST-514",
"selectedWorkItemIds": ["test/TEST-514"],
"appEndpoint": "https://polarion.example.com/polarion/apps/com.example.context/rest",
"restBaseUrl": "https://polarion.example.com/polarion/rest/v1",
"restToken": "UE9M…"
}
The field-by-field description is in the PolarionContext reference.
What is set where
| Field | Form extension | Sidebar (table) | Sidebar (document) | Navigation topic |
|---|---|---|---|---|
projectId |
✔ | ✔ | ✔ | ✔ |
workItemId |
✔ | – | – | – |
spaceId, documentId |
only inside a Document | – | ✔ | – |
selectedWorkItemIds |
the open item; all ticked items in the multi-item edit form | empty | empty | empty |
restBaseUrl, appEndpoint |
✔ | ✔ | ✔ | ✔ |
restToken |
✔ when token auth is enabled | ✔ | ✔ | ✔ |
In the multi-item edit form below the Work Items table, opened by ticking several rows, a form extension gets all ticked items in selectedWorkItemIds (for example ["drivepilot/DP-477", "drivepilot/DP-461", "drivepilot/DP-393"]), while workItemId is the current item (DP-477). Observed on Polarion 2612.
The selection in a sidebar does not come from the context: on Polarion 2612 selectedWorkItemIds is empty in a sidebar even when rows are selected, also when the context is read again. The selection arrives through selection-changed events; see React to selection changes. The Application context example shows the empty selectedWorkItemIds in a sidebar; the Selection sidebar example follows the selection with events.
Write code that tolerates missing optional fields. A form extension that is also declared as a navigation topic, for instance, must handle workItemId being undefined.
Work item identifiers
workItemId is a project-local identifier such as TEST-514. The entries of selectedWorkItemIds and of the selection-changed event, in contrast, carry the project: test/TEST-514. Both forms were observed on Polarion 2612, in a form extension, the Work Items table and a Document. Code that accepts both is safest: add the project when an id has no /, strip it where the REST API expects the local id. The REST API addresses work items as projectId/workItemId in resource ids and as separate path segments in URLs; server script examples in this guide use the combined form "test/TEST-514" in an objectId parameter. Build those strings from projectId and the local id:
const fullId = `${context.projectId}/${context.workItemId}`;
The context is a snapshot
The context is static. The host answers fetchContext() with the state at the time of the call, and nothing in the object changes while the view is open; reading it again returns the same kind of snapshot, not a live view. For anything that changes while the view is open, use events:
- The selection in a table changes constantly. Sidebars subscribe to
selection-changedand keep their own copy of the selected ids. See React to selection changes. - The work item of a form extension does not change while the panel is mounted; opening another work item loads the form again and the view starts over.
- The REST token is tied to the logged-in session. If a REST call fails with HTTP 401 after a long idle period, call
fetchContext()again to obtain a fresh token before retrying.
How the token flows
Polarion creates the REST token when it loads a view: the host bridge mints it for the logged-in user and hands it over in the context. That is why a server without token authentication shows the warning X-Rest-Token generation is not allowed on the server at the moment a view opens, and why restToken is empty there. A fresh token is issued on every view load. Calls to the application's own endpoints require this token in the X-Polarion-REST-Token header. The Polarion session alone does not authenticate those calls, so they cannot be tested by opening the URL in the browser's address bar.
The token is a credential
restToken grants the current user's rights to anyone who holds it. Keep it in memory, send it only to restBaseUrl and appEndpoint on the same origin, and never log it, store it or forward it to third parties. See Security model.
Concepts
REST API or your own endpoints?
A view reaches Polarion data in two ways. Both are authenticated with the same token from the context, both run as the logged-in user, and most applications use both. This page helps you decide which one to use for a given task; the SDK (context and events) is the third channel and is covered in How an application works.
Side by side
| Polarion REST API | Your own endpoints | |
|---|---|---|
| What it is | Polarion's documented API, JSON:API style, under /polarion/rest/v1 |
HTTP endpoints under /polarion/apps/<identifier>/rest/, implemented by your JavaScript on the server |
| Code to write | Only in the view | Script on the server plus the call in the view |
| Covers | Projects, work items, documents, test runs, plans, users, enumerations, … | Anything the Polarion Java API can do, plus external systems |
| Request shape | Fixed by the API (sparse fields, includes, pagination) | Defined by you |
| Work per request | One resource or one list | Unlimited (within reason) |
| Runs as | The user | The user |
| Deployed with | Nothing extra | The application package |
| Documentation | REST API User Guide, OpenAPI definition on the server | Your README and TypeScript types |
Use the REST API when…
- the data is a single object or a list the API offers directly;
- the operation is a standard create, update, link or comment;
- you want zero server-side code, for example in a prototype or a purely presentational view.
See Calling the REST API from a view and the Cookbook.
Write an endpoint when…
- the view would need many requests to assemble its data (trees, cross-project views, per-item computations);
- the logic is a rule or validation that should live in one place and run on the server;
- you need an API that REST does not expose (a utility, a service, history details);
- the operation involves external systems and secrets;
- you want a contract tailored to the UI rather than JSON:API documents;
- the work is heavy and should not run in the browser.
See Your own REST endpoints and Patterns.
Typical split in an application
| Task | Channel |
|---|---|
| Show the open work item's fields | REST API |
| Show its full link tree with status of each node | Endpoint |
| Rename, set a field, add a comment | REST API |
| Validate the selected items against project rules | Endpoint |
| Assign all items with a finding to the current user | Endpoint (one call, one result) or REST API (one PATCH per item) |
| Dashboard counts by status, type, assignee | REST API for small projects, endpoint for large ones |
| Notify a chat channel | Endpoint |
What is not available in 2612
- No channel from the view back into the host UI: a view cannot refresh the form, open another work item or show a Polarion notification. Navigate with
target="_top"links. - No events other than
selection-changed. - No server push: views poll if they need to observe changes made by others.
These are preview limitations; see Limitations and known issues.
Concepts
Security model
This page describes who can install applications, whose permissions views and server scripts run with, and what application authors must take care of.
Installation is an administrative act
Only users with Global Administration rights see the Applications topic and can upload, update or delete applications. There is no per-project installation and no self-service for end users.
Uploading an application means trusting its author: the static files are served to every user who opens a view, and server scripts run on the Polarion server with the Java API available. Treat an application ZIP like any other software you deploy: review it, keep the SHA-2 hash shown during upload with your change records, and only install packages from sources you trust.
Views run in the user's browser as the user
A view is a web page inside Polarion's origin and receives a REST token in the context for the logged-in user. Calls from the view to the REST API and application endpoints must send this token in the X-Polarion-REST-Token header. The token identifies the user, and calls are subject to that user's permissions, workflow rules and license. A view cannot escalate privileges.
Application endpoints do not authenticate requests through the browser session or session cookies. Being logged in to Polarion does not remove the token-header requirement, for either GET or POST requests.
Consequences for authors:
- Do not assume write access. A user who may read a work item may not be allowed to change it; handle HTTP 403 gracefully.
- Keep the token in memory only. Do not write it to
localStorage, cookies, logs or analytics, and do not send it to any host other than the Polarion server. - Call
fetchContext()again if a call fails with 401; tokens are bound to the session.
Server scripts run on the server as the user
A server script executes with the identity of the user identified by the endpoint request's REST token. context.scriptContext().services().security() reports that user, and all tracker operations check permissions as usual. A script therefore cannot read data the user could not read in the UI.
Scripts do have server-side capabilities that the browser does not: HTTP access from the server, reading project vault secrets, and the whole Java API. Review scripts carefully for:
- Unvalidated input: everything in
argumentscomes from the browser. Validate ids and lengths, and never build queries or Java calls from raw strings without checking them. - Side effects on GET: GET endpoints should not modify data. Use POST for anything that saves.
- Secrets: keep webhook URLs and API keys in the user account vault and read them in the script; never ship them in the ZIP.
Same-origin, iframe isolation
Views are served from the Polarion origin, so the browser's same-origin policy does not separate the view from the host page. Polarion isolates the view in an iframe and defines a narrow message protocol (the host bridge). Stay within that protocol through the SDK; do not reach into window.parent to read or modify the Polarion UI. Such code breaks with every Polarion release and bypasses the design that keeps applications supportable.
The SDK verifies the origin of every message it receives and ignores messages from other origins.
Content Security Policy and external resources
Polarion serves application files with the same HTTP headers as its own UI. If your server enforces a Content Security Policy that blocks external scripts or styles, a view that loads libraries from a public CDN is expected to fail (check the browser console for Refused to load); this was not exercised in this guide. Bundle everything with Vite instead of loading from CDNs; that also avoids the dependency on internet access from the user's browser.
Calls from a view to other origins are subject to CORS on that origin. If your application needs an external service, call it from a server script or make sure the service allows the Polarion origin.
Data protection
Views see personal data (user names, assignees, comments) exactly as the user does. Do not send Polarion data to third-party services from the browser without the same approval you would need for any other integration. Server scripts that forward data (for example to a chat tool) should be limited to what the use case needs.
Checklist for application authors
- [] No credentials, tokens or secrets in the package.
- [] Token only used for
restBaseUrlandappEndpoint. - [] All HTTP errors handled; 401 and 403 produce a helpful message.
- [] Server scripts validate their inputs and keep writes on POST.
- [] No access to
window.parentoutside the SDK. - [] Dependencies bundled, no runtime CDN loads.
- []
applicationVersionbumped and SHA-2 hash recorded for every release. - [] Tested with a project user without administrator rights: panels and sidebars visible, 403 handled where writes are not allowed.
Concepts
Performance and load
An application runs on a server that a whole organization shares. A form extension loads every time anyone opens a work item of the configured type, a sidebar every time someone opens a table, and each load sends its requests again. Server scripts run in the same Java process as Polarion and read from the same repository, index and database. A slow or chatty application therefore costs more than its own users' time: it slows down Polarion for everybody on the server.
This page collects what keeps an application light. Most of it is ordinary web practice. The Polarion-specific parts are the Lucene and SQL queries and the server scripts.
Rules of thumb
The numbers below are not limits that Polarion enforces. They are reasonable targets for a view that opens automatically with a page. Go beyond them when the use case needs it and you have measured the result.
| Target | |
|---|---|
| REST requests when a view opens | 1 to 3; never one request per item |
| Items loaded by a view | what it shows, usually up to 100; offer Load more or a search beyond that |
| Response size | under about 100 KB for a view that opens automatically |
| Debounce on selection changes and typing | 150 to 300 ms |
| Polling | none by default; if unavoidable, 60 s or more and only while the view is visible |
| Server script run time | under 1 s for a view that opens automatically, a few seconds for an action the user started |
| Retries | at most one, after a delay, and only for temporary errors |
Load only what the view shows
Name the fields. Ask with fields[workitems] for the fields the view shows. Rich-text fields such as description can be large; leave them out unless the view renders them.
// Don't: every field of up to 100 work items, then filtered in the browser.
const all = await restFetch(context, `/projects/${p}/workitems?page[size]=100`);
const open = all.data.filter((w) => w.attributes.status === "open");
// Do: let the server filter, and ask only for the columns the table shows.
const params = new URLSearchParams({
query: "status:open AND type:task",
"fields[workitems]": "id,title,status",
"page[size]": "50",
});
const open = await restFetch(context, `/projects/${p}/workitems?${params}`);
Filter on the server. A Lucene query runs against the index. Filtering in the browser means the server has already read, serialized and sent every item you throw away.
One request for related items. include returns the work item and its linked items in one response. A loop that requests each linked item separately sends N + 1 requests for the same data.
Batch by id. A selection of 40 work items is one request with query=id:(DP-1 DP-2 …), not 40. Split very long id lists into chunks of 100, as the selection sidebar and the release checklist do.
Page, but stop. Walk pages only as far as the user needs. A view that silently reads every page of a 20,000-item project reads 200 pages of 100 items each time it opens.
Search instead of listing. For a user or plan picker, send what the user typed as a query and show the first matches. Loading every user of a large installation into a select list is slow for the server and unusable for the user.
Send fewer requests
- Load once, refresh on request. Load when the view opens and when the user presses Refresh. Data that changes rarely (field metadata, enumeration options, status names) can be loaded once per page.
- Debounce. Keyboard navigation in a table fires a selection event per row. Wait until the selection has been stable for 150 to 300 ms before you load, as described in React to selection changes.
- Drop stale requests. When a newer request replaces an older one, ignore the older response or abort it with an
AbortController. Otherwise a slow old response can overwrite a newer result, and the user tends to click again. - Don't poll by default. A sidebar that reloads every 10 s on 200 open browsers sends 1,200 requests a minute and changes nothing for most users. If the view must follow changes, poll rarely, and stop while the page is hidden:
useEffect(() => {
const tick = () => {
if (document.visibilityState === "visible") void load();
};
const timer = setInterval(tick, 60_000);
return () => clearInterval(timer);
}, [load]);
- Cache in the page. Keep results in a module-level map or in state, keyed by their parameters. GET requests to your own endpoints can be cached by the browser if the URL stays the same; see Caching expensive results.
Errors and retries
A retry loop turns one failed request into many at the moment the server is already struggling.
- Do not retry
400,401,403or404. The next attempt fails the same way. - For
429,502,503and504, retry at most once, after a delay of one or two seconds. If the response carries aRetry-Afterheader, wait at least that long. - Show the error and let the user try again. A Retry button costs nothing when nobody presses it.
// Don't: retries forever, immediately, for every kind of error.
while (true) {
try { return await restFetch(context, url); } catch { /* try again */ }
}
Server scripts
An endpoint script runs inside Polarion with the caller's permissions, and the caller waits until it finishes. See Endpoint runtime.
- Bound every loop. Cap the number of items, the depth of a link walk and the number of pages. Return the cap in the response, so the view can say "Showing the first 500".
- Query, don't walk. Find work items with a Lucene query through the tracker service. Iterating over all work items of a project to find a few is a full scan of the project.
- Return what the view needs. Map objects to small JSON with the fields the view renders. Do not return whole objects or long rich-text values the view never shows.
- Save once. Set all fields of an object, then call
save()once. Eachsave()is a separate change in the repository. - Keep writes on POST and small. A bulk change of hundreds of items belongs in a job or a scheduled script, not in a request a user waits for.
SQL
Polarion keeps a PostgreSQL database next to its index, and SQL can be faster than Lucene for counting and joining across work items, documents, links and test runs. The same power makes a careless query expensive: it runs on the database every Polarion user depends on.
- Filter by project first, and by type or other indexed columns.
- Select only the columns you need. Inside Polarion, a query that returns objects selects
c_uri. - Join Polarion tables on
c_uri. When you combine SQL with a Lucene query throughLUCENE_QUERY(...), join its result onc_pk, as the SDK examples show. - Use
EXISTSinstead of joining a large table only to check that a row exists. - Add
LIMITwhen the view shows a fixed number of rows. - Avoid leading wildcards (
LIKE '%text%') on large text columns such asc_description; they read every row. Use the Lucene full-text search for text. - Run the query with
EXPLAIN ANALYZEon a copy of production data before it goes into an application.
-- Don't: every column of every work item in every project, joined to all links,
-- filtered by a leading wildcard on the description.
SELECT *
FROM workitem w
LEFT JOIN struct_workitem_linkedworkitems l ON l.fk_uri_p_workitem = w.c_uri
WHERE w.c_description LIKE '%brake%'
-- Do: one project, one type, one link role, EXISTS instead of a join,
-- and only the column Polarion needs to return the objects.
SELECT w.c_uri
FROM workitem w
INNER JOIN project p ON p.c_uri = w.fk_uri_project
AND p.c_id = 'drivepilot'
WHERE w.c_type = 'requirement'
AND EXISTS (
SELECT 1
FROM struct_workitem_linkedworkitems link
WHERE link.fk_uri_workitem = w.c_uri
AND link.c_role = 'verifies'
)
LIMIT 200
The schema, the join rules and more examples are in the SDK documentation of every installation, at https://<polarion>/polarion/sdk/doc/database/.
Test before production
- Use a test server with realistic data. A view that is fast on a demo project with 50 work items can be slow on a project with 50,000. Copy a production-sized project to the test server, or generate one.
- Watch the network tab. Open the view and count the requests, their size and their duration. Then click through a table quickly with the arrow keys and count again.
- Try more than one user. Open the view in several browsers or for several users at once, especially if it runs a server script.
- Measure the script. Log the start and end time of an endpoint script on the test server, and try it with the largest input a user can send.
- Roll out step by step. Configure the view for one project or one work item type first, and watch the server before you add it everywhere.
Checklist
- [] Every REST request names its fields with
fields[…]. - [] Filtering happens in the Lucene
query, not in the browser. - [] No request per item: related items through
include, selections throughid:(…). - [] Lists are capped, with Load more or a search beyond the cap.
- [] Selection and typing are debounced; stale responses are ignored.
- [] No polling, or a long interval that stops while the page is hidden.
- [] No automatic retries for client errors; at most one delayed retry for temporary errors.
- [] Server scripts cap items, depth and pages, and return only what the view shows.
- [] SQL queries filter by project, select
c_uri, and were checked withEXPLAIN ANALYZE. - [] Tested on a test server with production-sized data and more than one user.
Development guides
Set up the project
This guide describes the layout used by all examples in this documentation. It is a plain Vite project with a manifest.json and a packaging script added. Any other toolchain works as long as the output is a static site with relative URLs.
Single-view application
- hello-polarion/
- manifest.json (application identity and views)
- package.json
- vite.config.ts (base './')
- tsconfig.json
- index.html (Vite entry page)
- src/
- main.tsx
- App.tsx
- styles.css
- polarion.ts (small REST / endpoint helper (optional))
- types.ts (REST response shapes (optional))
- server-scripts/ (optional)
- …
- scripts/
- package.mjs (builds the ZIP)
- public/ (files copied as-is into the view (icons))
package.json
{
"name": "hello-polarion",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"package": "npm run build && node scripts/package.mjs",
"preview": "vite preview"
},
"dependencies": {
"polarion-app-sdk": "file:../_sdk/polarion-app-sdk-0.5.2-preview.tgz",
"react": "^19.2.0",
"react-dom": "^19.2.0"
},
"devDependencies": {
"@types/node": "^24.10.1",
"@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"adm-zip": "^0.5.16",
"typescript": "~5.9.3",
"vite": "^7.2.4"
}
}
Notes:
polarion-app-sdkis installed from a tarball. The examples vendor the file underexamples/_sdk/and reference it withfile:; a project of your own would normally use the URL of your server (see Install the SDK).adm-zipis only needed by the packaging script.npm run packagebuilds first, then zips.
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"types": ["vite/client"],
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"verbatimModuleSyntax": true,
"allowImportingTsExtensions": true
},
"include": ["src"]
}
moduleResolution: "bundler" is what lets TypeScript find the SDK's type definitions through the exports field of its package.json.
vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
base: './',
});
base: './' is mandatory. Polarion serves the view under /polarion/apps/<identifier>/<rootDirectory>/, and Vite's default absolute /assets/… URLs would point at the Polarion root.
The packaging script
The script in scripts/package.mjs reads manifest.json, stages <identifier>/manifest.json, copies dist/ to <identifier>/<rootDirectory>/ and server-scripts/ if present, and writes <identifier>.zip. It is deliberately small so that you can read and adapt it; see the full listing in Your first application.
Applications with several views
Each view needs its own folder in the package with its own index.html. Two approaches work well.
One Vite project per view
Keep one sub-folder per view, each a complete Vite project, and a top-level manifest.json:
- inspector/
- manifest.json
- card/ (Vite project for the form extension)
- package.json
- src/
- sidebar/ (Vite project for the sidebar)
- package.json
- src/
- server-scripts/
- scripts/
- package.mjs (builds every view, assembles the ZIP)
Simple to understand, and each view can use different libraries. Shared code lives in a third folder that both import with a relative path, or in a local npm workspace.
One project, several Vite entries
One package.json, one src/ with a folder per view, and a build script that runs Vite once per view with a mode:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'node:path';
const VIEWS = ['card', 'sidebar'] as const;
export default defineConfig(({ mode }) => {
const view = (VIEWS as readonly string[]).includes(mode) ? mode : VIEWS[0];
return {
plugins: [react()],
base: './',
root: resolve(__dirname, 'src', view), // src/card/index.html, src/sidebar/index.html
build: { outDir: resolve(__dirname, 'dist', view), emptyOutDir: true },
};
});
"scripts": {
"build": "tsc -b && vite build --mode card && vite build --mode sidebar",
"package": "npm run build && node scripts/package.mjs"
}
The packaging script then copies dist/<view>/ to <identifier>/<view>/ for every view in the manifest. Shared components live in src/shared/. The reference application tsapp-1 uses a variant of this layout.
Avoid Vite's multi-page mode with a shared dist/assets/ folder: the shared assets would sit outside every rootDirectory, and only files inside view folders are guaranteed to be served.
Icons and other static files
Put icons in public/; Vite copies them unchanged to the root of dist/, which becomes the root of the view folder. Reference them in the manifest by file name ("menuIcon": "icon16.png").
Linting and formatting
Nothing Polarion-specific. The reference application uses ESLint with typescript-eslint and the React hooks plugin; the examples here keep the toolchain minimal.
Source control
Commit manifest.json, the sources, package.json and package-lock.json. Ignore node_modules/, dist/, the staging folder and the generated ZIP:
node_modules
dist
package
*.zip
Development guides
Install the SDK
The Polarion Application SDK is the npm package polarion-app-sdk. It is small (one module, no dependencies) and provides the communication layer between your view and the Polarion host page.
Where the package comes from
The SDK is not published to the public npm registry. Every Polarion 2612 server serves the package from its SDK folder:
https://<polarion-host>/polarion/sdk/applications/polarion-app-sdk-0.5.2-preview.tgz
Open https://<polarion-host>/polarion/sdk/applications/ in a browser to see the versions available on your server. Using the package from the server you deploy to guarantees that the SDK and the host bridge speak the same protocol version.
Install from the server URL
npm install https://polarion.example.com/polarion/sdk/applications/polarion-app-sdk-0.5.2-preview.tgz
npm downloads the tarball and records the URL in package.json:
"dependencies": {
"polarion-app-sdk": "https://polarion.example.com/polarion/sdk/applications/polarion-app-sdk-0.5.2-preview.tgz"
}
Every later npm install (for example in CI) fetches it from the same URL, so the build machine needs HTTPS access to the Polarion server. The server's certificate must be trusted by Node.js; a self-signed certificate makes npm fail with SELF_SIGNED_CERT_IN_CHAIN. In that case either add the CA to NODE_EXTRA_CA_CERTS or use the local file variant below.
Install from a local file
Download the .tgz once and keep it next to the project (or in a shared folder of your repository):
npm install ./polarion-app-sdk-0.5.2-preview.tgz
"dependencies": {
"polarion-app-sdk": "file:polarion-app-sdk-0.5.2-preview.tgz"
}
The examples in this guide use this variant with the tarball vendored under examples/_sdk/, so that they build without network access.
Import
The package ships ES module and CommonJS builds plus TypeScript declarations. In a Vite project:
import {
fetchContext,
events,
destroy,
EventTypes,
type PolarionContext,
type SelectionChangedData,
} from 'polarion-app-sdk';
Plain JavaScript:
import { fetchContext, events, destroy, EventTypes } from 'polarion-app-sdk';
CommonJS (for tools that still need it):
const { fetchContext, events, destroy, EventTypes } = require('polarion-app-sdk');
What is inside
- node_modules/polarion-app-sdk/
- package.json
- README.md
- dist/
- HostBridge.js (ES module entry)
- HostBridge.cjs (CommonJS entry)
- HostBridge.d.ts (public API types)
- ApplicationGateway.d.ts
- Constants.d.ts
- types/
- PolarionContext.d.ts
- SelectionChangedData.d.ts
- ApplicationGatewayProtocol.d.ts
Only the exports of HostBridge are public API: fetchContext, events, destroy, EventTypes and the types PolarionContext and SelectionChangedData. The gateway and protocol files are internal.
Upgrading
When a server is upgraded, check /polarion/sdk/applications/ for a newer tarball, install it, rebuild and re-upload. The SDK version is printed in package.json of the installed package and in the README.md shipped with it.
Development guides
Read the context
fetchContext() is the first call every view makes. This guide shows the patterns that work well and the mistakes that are easy to make.
Plain JavaScript
import { fetchContext, destroy } from 'polarion-app-sdk';
async function start() {
try {
const context = await fetchContext();
render(context);
} catch (error) {
showError('This page must be opened inside Polarion.', error);
}
}
window.addEventListener('beforeunload', () => destroy());
start();
React
Fetch once on mount, keep the result in state, and release the bridge on unmount:
import { useEffect, useState } from 'react';
import { destroy, fetchContext, type PolarionContext } from 'polarion-app-sdk';
export function usePolarionContext() {
const [context, setContext] = useState<PolarionContext | null>(null);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
let cancelled = false;
fetchContext()
.then((ctx) => {
if (!cancelled) setContext(ctx);
})
.catch((e: unknown) => {
if (!cancelled) setError(e instanceof Error ? e : new Error(String(e)));
});
return () => {
// Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
cancelled = true;
destroy();
};
}, []);
return { context, error };
}
export default function App() {
const { context, error } = usePolarionContext();
if (error) return <p>Cannot reach Polarion: {error.message}</p>;
if (!context) return <p>Loading…</p>;
return <p>Work item {context.workItemId} in {context.projectId}</p>;
}
In React 18/19 development mode with StrictMode, effects run twice: the first run's fetchContext() is canceled by the cleanup's destroy() and rejects, then the second run creates a fresh instance and succeeds. The cancelled flag set in the cleanup makes the hook ignore everything the first run returns, the rejection included, without depending on the wording of the error. Production builds do not double-invoke effects.
Handling the failure case
fetchContext() rejects after five seconds when no host answers. That happens when:
- the page is opened directly by its URL, outside Polarion;
- the page runs on the Vite dev server;
- the Polarion host page failed to initialize the bridge (rare; reload the Polarion page).
Show a clear message rather than a spinner. Users and administrators who open the view URL to check a deployment should see "this view only works inside Polarion", not a hang.
Deriving identifiers
const { projectId, workItemId, spaceId, documentId } = context;
// REST URL for the open work item
const workItemUrl = `${context.restBaseUrl}/projects/${projectId}/workitems/${workItemId}`;
// Combined id used by server scripts in this guide and as JSON:API resource id
const fullId = `${projectId}/${workItemId}`;
// REST URL for the open document (sidebar in a Document)
const documentUrl = `${context.restBaseUrl}/projects/${projectId}/spaces/${spaceId}/documents/${documentId}`;
// Polarion UI link to a work item, for <a target="_top">
const uiLink = `${window.location.origin}/polarion/#/project/${projectId}/workitem?id=${workItemId}`;
All of these are optional in the type. Guard them according to the view type:
if (!context.workItemId) {
throw new Error('This view must be placed on a work item form.');
}
Refreshing
The context is a snapshot and does not change while the view is open. Call fetchContext() again when you need a fresh token (after a 401). Reading it again does not give a sidebar the current selection: selectedWorkItemIds stays empty there, and the selection arrives only through selection-changed events. Each call is a round trip to the host page and resolves in a few milliseconds.
Logging
During development it helps to print the context once:
console.log('[myapp] context', context);
Remove or guard such logs before release; the context contains the REST token.
Next
- React to selection changes
- Call the REST API
- PolarionContext reference
- Application context example: one page placed as a form extension, a sidebar and a navigation topic, showing what each placement receives
Development guides
React to selection changes
Sidebars live next to a Work Items table or inside a Document, where the user keeps changing what is selected. The SDK delivers those changes as events.

The event
import { events, EventTypes, type SelectionChangedData } from 'polarion-app-sdk';
const unsubscribe = events.subscribe<SelectionChangedData>(
EventTypes.SELECTION_CHANGED,
(data) => {
console.log(data.selectedWorkItemIds); // e.g. ["test/TEST-514", "test/TEST-513"]
},
);
EventTypes.SELECTION_CHANGEDis the only event type in SDK 0.5.2-preview.- The payload is
{ selectedWorkItemIds: string[] }. An empty array means nothing is selected. - The ids carry the project:
test/TEST-514, in the Work Items table and in Documents. Strip the prefix where the REST API expects the local id, for example in anid:(…)query; the Selection sidebar example does that inbareId(). subscribe()returns a function; call it to stop receiving events.- Only one subscription per event type is allowed. A second
subscribe()for the same type throwsAlready subscribed to event. Keep the subscription at the top of your application and distribute the data through your own state.
Initial state plus events
On Polarion 2612 the context of a sidebar has an empty selectedWorkItemIds, even when rows are selected; the selection arrives with the first event after the user changes it. Read the context for the project and the token, start with the context's list (empty in a sidebar) and replace it on every event:
const context = await fetchContext();
let selected = context.selectedWorkItemIds; // empty in a sidebar
const unsubscribe = events.subscribe<SelectionChangedData>(EventTypes.SELECTION_CHANGED, (data) => {
selected = data.selectedWorkItemIds; // updates
render(selected);
});
render(selected);
React pattern
Subscribe in an effect, store the ids in state, and derive everything else from the ids. This is App.tsx of the Selection sidebar example; the components it renders are in Components.tsx on that page:
import { useEffect, useState } from "react";
import { destroy, events, EventTypes, fetchContext, type PolarionContext, type SelectionChangedData } from "polarion-app-sdk";
import { ErrorMessage, SelectionContent, SelectionSummary } from "./Components";
import { restFetch } from "./polarion";
import type { WorkItemListResponse, WorkItemResource } from "./types";
/** Selection ids may arrive as "WI-1" or "PROJECT/WI-1"; the Lucene query needs the bare id. */
function bareId(id: string): string {
const separator = id.indexOf("/");
return separator === -1 ? id : id.slice(separator + 1);
}
function timeNow(): string {
return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
}
export default function App() {
const [context, setContext] = useState<PolarionContext | null>(null);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [items, setItems] = useState<WorkItemResource[]>([]);
const [lastEvent, setLastEvent] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
// Fetch context and subscribe to selection changes when the view mounts.
useEffect(() => {
let cancelled = false;
const loadContext = async () => {
try {
const data = await fetchContext();
if (cancelled) {
return;
}
setContext(data);
setSelectedIds(data.selectedWorkItemIds ?? []);
setError(null);
} catch (error: unknown) {
if (cancelled) {
return;
}
console.error("Unable to fetch the Polarion context:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to fetch the Polarion context: ${message}`);
}
};
loadContext();
const unsubscribe = events.subscribe<SelectionChangedData>(EventTypes.SELECTION_CHANGED, (data) => {
// The event contains work item IDs (<project_id>/<workitem_id>) only.
setSelectedIds(data.selectedWorkItemIds ?? []);
setLastEvent(timeNow());
});
return () => {
// Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
cancelled = true;
// Remove the subscription and release the message listener.
unsubscribe();
destroy();
};
}, []);
// Whenever the context or selection changes, load the selected work item details.
// The REST API returns at most 100 items per page, so request IDs in batches
// of up to 100 and combine the results.
// Wait 150 ms for rapid selection changes to settle and ignore outdated responses.
useEffect(() => {
const projectId = context?.projectId;
if (!context || !projectId || selectedIds.length === 0) {
setItems([]);
return;
}
let cancelled = false;
const loadItems = async () => {
try {
const pageSize = 100;
const requests: Promise<WorkItemListResponse>[] = [];
for (let i = 0; i < selectedIds.length; i += pageSize) {
const ids = selectedIds.slice(i, i + pageSize).map(bareId);
const params = new URLSearchParams({
"query": `id:(${ids.join(" ")})`,
"fields[workitems]": "id,title,status,type",
"page[size]": String(pageSize),
});
const path = `/projects/${encodeURIComponent(projectId)}/workitems?${params}`;
requests.push(restFetch<WorkItemListResponse>(context, path));
}
const responses = await Promise.all(requests);
if (cancelled) {
return;
}
setItems(responses.flatMap((response) => response.data));
setError(null);
} catch (error: unknown) {
if (cancelled) {
return;
}
console.error("Unable to fetch the selected work items:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to fetch the selected work items: ${message}`);
}
};
const timer = setTimeout(loadItems, 150);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [context, selectedIds]);
const byStatus = new Map<string, number>();
items.forEach((item) => {
const status = item.attributes.status;
byStatus.set(status, (byStatus.get(status) ?? 0) + 1);
});
return (
<div>
<ErrorMessage message={error} />
<SelectionSummary selectedCount={selectedIds.length} spaceId={context?.spaceId} documentId={context?.documentId} lastEvent={lastEvent} />
<SelectionContent selectedCount={selectedIds.length} items={items} byStatus={byStatus} />
</div>
);
}
Points worth noting:
- The subscription is created in the same effect as
fetchContext(), and the cleanup callsunsubscribe()beforedestroy(). - Loading the selected work items happens in a second effect that depends on
selectedIds. A Lucene queryid:(TEST-514 TEST-513)fetches them with a sparse field set; because the REST API serves at most 100 items per page, selections are split into chunks of 100 and requested in parallel. - The helper
bareId()strips the project prefix for the Lucene query: Polarion 2612 delivers ids with the project (drivepilot/DP-477) in the event, and the code also accepts bare ids (DP-477).
Keeping up with fast selection changes
Users can change the selection several times per second (keyboard navigation, shift-click). If every change triggers a REST call, responses may arrive out of order. Two simple defenses:
// 1. Debounce: wait until the selection has been stable for 150 ms.
useEffect(() => {
const timer = setTimeout(() => load(selectedIds), 150);
return () => clearTimeout(timer);
}, [selectedIds]);
// 2. Ignore stale responses.
useEffect(() => {
let cancelled = false;
load(selectedIds).then((items) => { if (!cancelled) setItems(items); });
return () => { cancelled = true; };
}, [selectedIds]);
Selection in Documents
In a Document, the selection is the work item the cursor is in. The event payload has the same shape, usually with one id. context.spaceId and context.documentId tell you which document; the work item itself is fetched through REST as usual.
Form extensions and navigation topics
Form extensions and navigation topics can subscribe, but they have no selection to follow: a form extension knows its work item from context.workItemId, and a navigation topic has no selection at all. Expect the event only in sidebars.
Unsubscribing
Call the returned function when the view no longer needs updates, and destroy() when the view unmounts. destroy() also unsubscribes everything that is still registered, so forgetting the individual call is not harmful, but doing both keeps the intent clear.
Development guides
Package and upload
This page covers the mechanics of getting an application onto a server: the archive layout Polarion accepts, the upload wizard, hash verification, updates and removal.
The ZIP layout
.zip / - manifest.json
/ (of view 1) - index.html
- assets/
- …
/ (of view 2) - …
- server-scripts/ (only if the manifest declares endpoints)
- *.js
Checks performed by Polarion during upload, and the message you see when they fail:
| Check | Message |
|---|---|
Exactly one top-level folder, manifest.json inside it |
Application's zip structure is incorrect |
manifest.json is valid JSON with the required fields |
Application validation failed with details |
Folder name equals identifier |
Application's zip structure is incorrect |
Each view's rootDirectory/document exists |
Application validation failed |
Each endpoint's script exists in server-scripts/ |
Application validation failed |
The ZIP file name itself should not matter; naming it after the identifier is a convention.
Building the ZIP
The examples use a Node script (scripts/package.mjs, listed in Your first application). Equivalent shell commands:
npm run build
rm -rf package && mkdir -p package/com.example.hello
cp manifest.json package/com.example.hello/
cp -R dist package/com.example.hello/hello
cp -R server-scripts package/com.example.hello/ # if present
(cd package && zip -r ../com.example.hello.zip com.example.hello -x '*.DS_Store')
On macOS, avoid Finder's Compress on the folder: it adds __MACOSX/ entries and resource-fork files that may fail validation. Use zip as above, or the Node script.
Uploading
- Global Administration → Applications → Upload.
- Choose the ZIP and click Next. Polarion reads the manifest and computes the SHA-2 hash.
- Review the summary. For a new identifier it reads You are going to INSTALL the following application; for an existing one, You are going to UPDATE with New Version and Current Version columns.
- Click Finish. A green bar confirms the upload; the tile appears or is refreshed.


The change is effective immediately: static files are served and server scripts are active without a restart. Users with an open view must reload the page.
Verifying the hash
The hash shown in step 3 is the SHA-2 digest of the ZIP file (128 hexadecimal digits, the SHA-512 variant). Compute it locally to confirm you are installing the file you built:
shasum -a 512 com.example.hello.zip # macOS / Linux
certutil -hashfile com.example.hello.zip SHA512 # Windows
The dialog refers to it as the SHA-2 hash.
Properties and delete
Select a tile to enable the Properties and Delete buttons.
- Properties shows identifier, version, title, publisher, manifest version and description.
- Delete removes the application and its files immediately (a green bar confirms Application '
' was deleted ). Configuration XML that references its views is not changed.
Versioning
Set applicationVersion to something you can trace back to a build (1.4.0, 2026.10.05, a git describe string). Polarion displays it but appears not to compare it; an update with the same or a lower version is accepted.
Automating uploads
Uploads can be scripted against the REST API with a personal access token when com.siemens.polarion.rest.enabled and com.siemens.polarion.rest.security.restApiToken.enabled are set. The endpoint and payload are part of the REST API definition of your server (/polarion/rest/v1/definition, search for applications). Interactive upload through the UI is the supported path in the 2612 preview; treat automation as something to validate against your server version.
Building in CI
The package is reproducible from a clean checkout. A minimal GitLab CI job that keeps the ZIP and its hash as artifacts:
package:
image: node:22
script:
- npm ci
- npm run package
- shasum -a 512 *.zip > SHA512SUMS
artifacts:
paths: ['*.zip', SHA512SUMS]
If the SDK is installed from your server's URL, the runner needs HTTPS access to it (or vendor the tarball as the examples do).
Removing an application cleanly
- Remove the
applicationViewelements that reference its views from form layouts and Topics configurations. - Tell users who bookmarked a table with
?sidebar=polarion-application.<identifier>.<viewId>that the sidebar goes away. - Global Administration → Applications: select the tile, Delete. The files are removed immediately.
Checklist before every upload
- []
npm run buildpasses with no TypeScript errors. - []
dist/index.htmlreferences./assets/…(relative paths). - []
manifest.jsonlists every view and endpoint that the package contains. - []
applicationVersionbumped. - [] ZIP has a single top-level folder named after the identifier.
- [] Hash recorded if your process requires it.
- [] Tested as a user without administrator rights.
Development guides
Develop locally
Uploading a ZIP for every change is fine for integration testing but slow for UI work. Two techniques make the loop faster.
1. Mock the context in development mode
Outside Polarion, fetchContext() rejects after five seconds. Short-circuit it in development builds with a mock, so that npm run dev renders your view immediately:
import { fetchContext, type PolarionContext } from 'polarion-app-sdk';
const mock: PolarionContext = {
applicationId: 'com.example.workitemcard',
viewId: 'card',
projectId: 'test',
workItemId: 'TEST-514',
selectedWorkItemIds: ['test/TEST-514'],
appEndpoint: 'http://localhost:5173/mock/rest',
restBaseUrl: 'http://localhost:5173/mock/v1',
restToken: 'dev',
};
export function getContext(): Promise<PolarionContext> {
return import.meta.env.DEV ? Promise.resolve(mock) : fetchContext();
}
import.meta.env.DEV is true under vite and false in vite build, so the production package always uses the real SDK.
With the mock in place, REST calls go to http://localhost:5173/mock/…, which does not exist. Either mock the data layer the same way (import.meta.env.DEV ? fakeItems : restFetch(...)), or proxy to a real server as described next.
2. Proxy the REST API to a real server (untested recipe)
Vite's dev server can forward /polarion/rest/… to your Polarion server. Combined with a personal access token (PAT) that you generate in Polarion under My Account → Personal Access Tokens, the view talks to real data while you edit:
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
return {
plugins: [react()],
base: './',
server: {
proxy: {
'/polarion/rest': {
target: env.POLARION_URL, // https://polarion.example.com
changeOrigin: true,
headers: { Authorization: `Bearer ${env.POLARION_PAT}` },
},
},
},
};
});
POLARION_URL=https://polarion.example.com
POLARION_PAT=…
Set the mock context's restBaseUrl to /polarion/rest/v1 (relative, so it hits the proxy) and leave restToken empty; the proxy adds the PAT. In production the real context's absolute restBaseUrl and token are used.
Keep the PAT out of source control and remove it when you are done. It carries your full Polarion permissions.
3. Testing inside Polarion still needs an upload
The view that Polarion loads is a static page under /polarion/apps/<identifier>/<rootDirectory>/. Polarion serves it from its own storage; there is no way to point an installed application at your dev server. The fastest loop for inside-Polarion testing is therefore:
npm run package # a few seconds
followed by the upload (which is an update, no configuration changes) and a hard reload of the Polarion page. Content-hashed asset names make cache problems impossible.
4. Open the view directly
https://<host>/polarion/apps/<identifier>/views/<viewId> opens the view in a tab of its own, without the Polarion page around it. The context fetch fails there, but static-file problems (404s, wrong base, missing icons) show up immediately in the browser's network panel.
Debugging inside Polarion
- Use the browser's developer tools; the iframe appears as a separate frame in the console's frame selector and in the network panel. Filter the network panel by
apps/to see your files and endpoint calls. console.logfrom the view appears in the same console as Polarion's own output. Prefix your messages ([myapp]) to find them.- React DevTools attaches to iframes on the same origin.
- Vite source maps:
build: { sourcemap: "inline" }invite.config.tsputs readable stack traces into the JavaScript files, at the cost of larger packages. Do not usesourcemap: true: it writes separate.mapfiles, which are not an allowed file type, so Polarion rejects the package. Turn source maps off for releases.
A note on hot reloading and the SDK
With the Vite dev server and React Fast Refresh, components remount often. The SDK tolerates this as long as your effect cleanup calls destroy(); otherwise the second mount's events.subscribe() throws Already subscribed to event.
Development guides
Troubleshooting
Symptoms are grouped by where they show up: the administration UI, the view in the browser, and HTTP calls.
Administration
No Applications entry in Global Administration
The feature is disabled. Set the global configuration property polarionapp.enabled=true in Global Administration → Configuration Properties and reload. See Enable Applications.
Upload fails with Application's zip structure is incorrect
The ZIP does not have exactly one top-level folder named like the identifier, or manifest.json is not directly inside it. Inspect the archive:
unzip -l com.example.hello.zip
The first entries must be com.example.hello/ and com.example.hello/manifest.json. See Package and upload.
Upload fails with Application validation failed
A field in manifest.json is missing or a referenced folder/file does not exist. Compare with the manifest reference. Common causes: trailing commas in JSON, rootDirectory not matching the folder name, script not present in server-scripts/.
The Next button stays disabled
No file selected, or the selected file is not a .zip.
Views
The panel is empty or shows Loading… forever
Open the browser console and the network panel, select the iframe.
- 404 on
assets/…: Vite built with absolute URLs. Setbase: './'invite.config.tsand rebuild. - Refused to load … Content Security Policy: the view loads a script or style from an external CDN that the server's CSP blocks. Bundle the dependency.
- No error, page blank: JavaScript crashed before rendering. Look for the exception in the console.
The view says it cannot reach Polarion (Timeout waiting for response to get-context)
The page is not embedded by Polarion (opened directly, or on the dev server), or the host page has not initialized the bridge. In Polarion, reload the page. If it persists in a form, check that the applicationView id matches <identifier>.<viewId> exactly.
The form layout was saved but the panel does not appear
- Reload the work item page; layouts are cached per session.
- Make sure you edited the layout of the right work item type and the right Polarion View (hat).
- The layout editor ignores text set programmatically (browser extensions, automation). Type or paste the change by hand.
The sidebar is missing from the Show Sidebar menu
The application's manifest has no sidebars entry, or the upload failed. Check Properties of the installed application and the manifest in the ZIP.
Already subscribed to event: selection-changed
Two subscribe() calls for the same event in one view. Subscribe once at the top level; in React make sure the effect cleanup unsubscribes and calls destroy().
HTTP calls
Polarion shows X-Rest-Token generation is not allowed on the server!

The dialog appears as soon as an application view opens, because Polarion could not create the REST token for the view. Set com.siemens.polarion.rest.security.restApiToken.enabled=true (and com.siemens.polarion.rest.enabled=true) in polarion.properties and restart. The view still loads, but context.restToken is empty and REST calls fail.
REST call returns 401
restTokenis empty: token authentication is not enabled. An administrator must setcom.siemens.polarion.rest.security.restApiToken.enabled=true(andcom.siemens.polarion.rest.enabled=true) inpolarion.propertiesand restart.- The token expired: call
fetchContext()again and retry. - Header name typo: it is
X-Polarion-REST-Token.
REST call returns 403
The user is not allowed to perform the operation. Test the same action in the UI with that user. Nothing in the application can change this.
A relationship is missing from a REST response (Cannot read properties of undefined)
Sparse field sets filter relationships as well as attributes. Add the relationship name to fields[<type>], for example fields[linkedworkitems]=role,suspect,workItem, otherwise relationships.workItem is absent.
REST call returns 400
Usually a malformed query string or an unknown field in fields[…]. Read errors[].detail in the response. Use URLSearchParams to encode parameters.
Server script returns success: false
The error string is the message from your script's catch block or from the uncaught exception. Typical: objectId not passed, wrong parameter location (POST parameters must be in the JSON body), or a Java method name that does not exist (check the javadoc).
Endpoint returns HTTP 400 with Argument objectId is missing in workflow definition
Every endpoint call needs an objectId parameter (PROJECT/WI-ID). Add it to the query string (GET) or the JSON body (POST).
Endpoint returns arguments.getAsString is not a function
The script reads arguments inside a function, where the name means the function's own arguments. Capture Polarion's object at the top level: const scriptArguments = arguments;.
Endpoint returns HTTP 400 with Argument … is missing in workflow definition
The script called arguments.getAsString('x') for a parameter the view did not send. Either send it, or read optional parameters through a guarded helper (try { … } catch { return fallback; }), as the traceability example does.
Endpoint POST fails before the script runs
POST requests need Content-Type: application/json and a JSON body, even if it is {}. The body must be a flat object whose values are strings: {"objectIds": ["a","b"]} is rejected with HTTP 500 and Expected a string but was BEGIN_ARRAY; send {"objectIds": "[\"a\",\"b\"]"} and parse it in the script.
SELF_SIGNED_CERT_IN_CHAIN when installing the SDK
Node.js does not trust the server's certificate. Point NODE_EXTRA_CA_CERTS at your CA bundle, or download the tarball with a browser and install it from disk.
Where to look
| Place | What you find |
|---|---|
| Browser console (iframe frame) | JavaScript errors, CSP violations, your own logs |
Browser network panel, filter apps/ |
Static file 404s, endpoint responses |
https://<host>/polarion/apps/<identifier>/views/<viewId> |
The raw view outside Polarion |
Polarion server log (data/logs/main/log4j-*.log) |
Server script exceptions, upload validation details |
| Global Administration → Applications → Properties | What is actually installed |
Examples
Examples
Every example is a standalone project; download its source archive below. Each builds with npm install && npm run package into an upload-ready ZIP, and each page shows the full source with explanations. The first four teach the basics one step at a time; the other three show what you can build with them.
Learn the basics
Start here. Each example adds one capability to the previous one, from a page that only shows text to a view with its own server-side endpoints.
| Example | View type | Adds | Talks to |
|---|---|---|---|
| Hello Polarion | Form extension | The smallest possible application: a manifest, a page and the packaging | nothing |
| Application context | Form extension + sidebar + navigation topic | The SDK, and what the context contains in each placement, from one build | SDK |
| Selection sidebar | Sidebar | Following the selection with events; REST API queries; icons | SDK events, REST API (query) |
| Traceability with endpoints | Form extension + endpoints | Your own server-side endpoints: a link tree computed on the server, and a POST that writes | SDK, your own endpoints (GET, POST) |
What you can build
Larger applications that combine the basics into something a team would use.
| Example | View type | Shows | Talks to |
|---|---|---|---|
| Work item card | Form extension | Reading a work item and its links; renaming it, changing its status, adding a comment | SDK, REST API (GET, PATCH, POST) |
| Project dashboard | Navigation topic | A full page with a query box, tiles, charts by status, type and assignee, and a table | SDK, REST API (list, relationships) |
| Release checklist | Sidebar + endpoints | Validation of the selection by server-side rules; bulk assignment through a writing endpoint | SDK events, your own endpoints (POST, POST) |
Downloads
Each example is available as an application package (upload it as it is in Global Administration → Applications) and as the source project (unzip, npm install, npm run package).
| Example | Identifier | Version | Application package | Source project |
|---|---|---|---|---|
| Hello Polarion | com.example.hello |
0.2.0 | com.example.hello.zip | hello-polarion-source.zip |
| Application context | com.example.context |
0.2.0 | com.example.context.zip | application-context-source.zip |
| Selection sidebar | com.example.selectionsidebar |
0.1.1 | com.example.selectionsidebar.zip | selection-sidebar-source.zip |
| Traceability with endpoints | com.example.traceability |
0.2.2 | com.example.traceability.zip | traceability-source.zip |
| Work item card | com.example.workitemcard |
0.2.1 | com.example.workitemcard.zip | work-item-card-source.zip |
| Project dashboard | com.example.dashboard |
0.2.1 | com.example.dashboard.zip | project-dashboard-source.zip |
| Release checklist | com.example.releasechecklist |
0.2.2 | com.example.releasechecklist.zip | release-checklist-source.zip |
The packages are the ones used for the screenshots in this guide. The source archives exclude node_modules; the SDK is installed from the vendored tarball on npm install, or replace it with your server's URL (see Install the SDK).
Common structure
All examples share the layout from Set up the project: Vite + React + TypeScript, manifest.json at the root, scripts/package.mjs for the ZIP, in the examples that call Polarion a src/polarion.ts with restFetch for REST API calls or endpointFetch for calls to the application's own endpoints, and the SDK installed from a vendored tarball in examples/_sdk/.
- examples/
- _sdk/
- polarion-app-sdk-0.5.2-preview.tgz
- hello-polarion/
- application-context/
- work-item-card/
- selection-sidebar/
- project-dashboard/
- traceability/
- release-checklist/
- _sdk/
To use an example as the starting point of your own application:
- Copy the folder.
- Change
identifier,titleandpublisherNameinmanifest.json. - Replace the SDK dependency with the URL of your server:
npm install https://<host>/polarion/sdk/applications/polarion-app-sdk-0.5.2-preview.tgz. npm run package, upload, place the view.
Trying them on a test server
Upload all seven; they use different identifiers and do not interfere. Then:
- add
<applicationView id="p-examples-overview-com.example.hello.hello" label="Hello Polarion" height="320px"/>,<applicationView id="p-examples-overview-com.example.context.form" label="Application context" height="460px"/>,<applicationView id="p-examples-overview-com.example.workitemcard.card" label="Work item card" height="640px"/>and<applicationView id="p-examples-overview-com.example.traceability.tree" label="Traceability" height="480px"/>to the form layout of a work item type; - add
<applicationView id="p-examples-overview-com.example.dashboard.dashboard"/>and<applicationView id="p-examples-overview-com.example.context.topic"/>to the project's Topics configuration; - open the Work Items table and pick Application context, Selection inspector or Release checklist from Show Sidebar.
Examples
Hello Polarion

| Aspect | Details |
|---|---|
| Folder | examples/hello-polarion |
| Identifier | com.example.hello |
| View | form extension hello |
| Placement | <applicationView id="p-examples-hello-polarion-com.example.hello.hello" label="Hello Polarion" height="320px"/> in a form layout |
| Uses | nothing from Polarion: no SDK, no REST API |
Source: the project is in examples/hello-polarion/ of this kit.
This is the application built step by step in Your first application. It contains only what every application needs: a manifest, a page and the packaging script. It does not use the SDK and does not talk to Polarion; the Application context example adds that.
Files
- hello-polarion/
- manifest.json
- package.json
- vite.config.ts
- tsconfig.json
- index.html
- src/
- main.tsx
- App.tsx
- styles.css
- scripts/
- package.mjs
manifest.json
{
"manifestVersion": "1.0",
"identifier": "com.example.hello",
"title": "Hello Polarion",
"description": "The smallest possible Polarion Application: one form extension that says hello.",
"publisherName": "Example Publisher",
"applicationVersion": "0.2.0",
"views": {
"formExtensions": [
{
"identifier": "hello",
"title": "Hello Polarion",
"rootDirectory": "hello",
"document": "index.html"
}
]
}
}
src/App.tsx
An ordinary React component. Nothing in it is specific to Polarion.
export default function App() {
return (
<main>
<h1>Hello, Polarion</h1>
<p>This panel is a Polarion Application.</p>
</main>
);
}
src/styles.css
body {
margin: 0;
padding: 12px;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
font-size: 14px;
color: #1f2933;
}
h1 {
font-size: 1.4rem;
margin: 0 0 8px;
}
src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import "./styles.css";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);
scripts/package.mjs
This script turns the build into the ZIP you upload to Polarion: one top-level folder named after the identifier, with manifest.json and each view's content under its rootDirectory. It stages the files under package/<identifier>/ and creates <identifier>.zip in the project root. Expand it to see how the packaging works, or read Application package for the format.
Example: scripts/package.mjs
// Builds the upload-ready ZIP for Polarion.
//
// Layout inside the ZIP: one top-level folder named after the application
// identifier, with manifest.json, view content under each view's
// rootDirectory (which multiple views may share), and optional server-scripts/.
// Polarion rejects a ZIP that has manifest.json directly at its root
// ("Application's zip structure is incorrect").
//
// <identifier>/
// manifest.json
// <rootDirectory of each view>/ (index.html + assets)
// server-scripts/ (if present)
//
// Single-view projects build into dist/. Multi-view projects build one Vite
// mode per view into dist/<rootDirectory>/ (see "Set up the project" in the
// guide); this script copies whichever exists.
//
// Run with `npm run package` (which builds first).
import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import AdmZip from "adm-zip";
const projectRootPath = fileURLToPath(new URL("..", import.meta.url));
const distributionPath = join(projectRootPath, "dist");
function stageViews(appStagePath, manifest) {
const views = Object.values(manifest.views ?? {}).flat();
if (views.length === 0) {
throw new Error("manifest.json declares no views.");
}
for (const view of views) {
const viewDist = join(distributionPath, view.rootDirectory);
const source = existsSync(viewDist) ? viewDist : distributionPath;
const documentPath = join(source, view.document);
if (!existsSync(documentPath)) {
throw new Error(`Build output for view "${view.identifier}" not found: ${documentPath}`);
}
cpSync(source, join(appStagePath, view.rootDirectory), { recursive: true });
}
}
function stageServerScripts(appStagePath) {
const serverScripts = join(projectRootPath, "server-scripts");
if (existsSync(serverScripts)) {
cpSync(serverScripts, join(appStagePath, "server-scripts"), { recursive: true });
}
}
function writePackageZip(stageRoot, zipPath) {
const zip = new AdmZip();
zip.addLocalFolder(stageRoot);
zip.writeZip(zipPath);
}
function packageApplication() {
const manifest = JSON.parse(readFileSync(join(projectRootPath, "manifest.json"), "utf8"));
const stageRootPath = join(projectRootPath, "package");
const zipPath = join(projectRootPath, `${manifest.identifier}.zip`);
rmSync(stageRootPath, { recursive: true, force: true });
try {
const appStagePath = join(stageRootPath, manifest.identifier);
mkdirSync(appStagePath, { recursive: true });
cpSync(join(projectRootPath, "manifest.json"), join(appStagePath, "manifest.json"));
stageViews(appStagePath, manifest);
stageServerScripts(appStagePath);
writePackageZip(stageRootPath, zipPath);
} finally {
rmSync(stageRootPath, { recursive: true, force: true });
}
console.log(`Packaged ${manifest.identifier} ${manifest.applicationVersion} -> ${zipPath}`);
}
packageApplication();
Build and deploy
cd examples/hello-polarion
npm install
npm run package # → com.example.hello.zip
Upload the ZIP in Global Administration → Applications, then add the applicationView element to a form layout as described in Form extensions.
Things to try
- Change
heightin the layout and watch the panel resize. - Remove the
labelattribute: the heading falls back to Polarion Application. - Open
https://<host>/polarion/apps/com.example.hello/views/hellodirectly. The page renders there too, because it does not depend on Polarion; a view that callsfetchContext()does not (see Application context).
Examples
Application context

| Aspect | Details |
|---|---|
| Folder | examples/application-context |
| Identifier | com.example.context |
| Views | form extension form, sidebar sidebar, navigation topic topic; one build for all three |
| Placement | <applicationView id="p-examples-application-context-com.example.context.form" label="Application context" height="460px"/> in a form layout; <applicationView id="p-examples-application-context-com.example.context.topic"/> in Topics; the sidebar needs no configuration |
| Uses | fetchContext(), destroy() |
Source: the project is in examples/application-context/ of this kit.
Hello Polarion shows a page and nothing else. This example adds the first thing most views need: knowing where they are. It reads the context once, shows every field, and makes the rules from Application context visible:
- which fields are set depends on the placement;
- the context is a snapshot: it is read once and does not change while the view is open;
- a sidebar gets no selection in its context; the selection arrives only through
selection-changedevents, which the Selection sidebar example shows; - the REST token is a credential and is never displayed.
What each placement receives
The same build runs in three places. viewId tells the code which one it is; the optional fields say what the view is attached to.
| Field | Form extension | Sidebar, Work Items table | Sidebar, Document | Navigation topic |
|---|---|---|---|---|
viewId |
form |
sidebar |
sidebar |
topic |
projectId |
set | set | set | set |
workItemId |
the open item | not set | not set | not set |
spaceId, documentId |
not set | not set | the Document | not set |
selectedWorkItemIds |
the open item, ["drivepilot/DP-477"]; in the multi-item edit form all ticked items |
empty | empty | empty |
All four columns were read on Polarion 2612; the screenshots are on this page. Ids in selectedWorkItemIds include the project, workItemId does not. In the table the sidebar was opened with three rows selected and selectedWorkItemIds stayed empty, also after Read again: a sidebar learns the selection only from selection-changed events. With three rows ticked, the form extension in the multi-item edit form below the table listed all three ids, and workItemId was the current item.



Files
- application-context/
- manifest.json
- package.json
- vite.config.ts
- index.html
- public/
- icon16.png (sidebar menu icon)
- icon30.png (navigation icon)
- icon32.png (sidebar header icon)
- src/
- main.tsx
- App.tsx (reads the context)
- Table.tsx (shows the fields)
- styles.css
- scripts/
- package.mjs
manifest.json
Three views that share one rootDirectory, app. Several views may point to the same folder, so the single dist/ build ends up in the ZIP once and serves all three placements.
{
"manifestVersion": "1.0",
"identifier": "com.example.context",
"title": "Application context",
"description": "One page placed as a form extension, a sidebar and a navigation topic. It shows the context Polarion hands to each placement.",
"publisherName": "Example Publisher",
"applicationVersion": "0.2.0",
"views": {
"formExtensions": [
{
"identifier": "form",
"title": "Application context",
"rootDirectory": "app",
"document": "index.html"
}
],
"sidebars": [
{
"identifier": "sidebar",
"title": "Application context",
"rootDirectory": "app",
"document": "index.html",
"menuIcon": "icon16.png",
"icon": "icon32.png"
}
],
"navigationTopics": [
{
"identifier": "topic",
"title": "Application context",
"icon": "icon30.png",
"rootDirectory": "app",
"document": "index.html"
}
]
}
}
src/App.tsx
import { useEffect, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import Table from "./Table";
/**
* Describes where the view runs. The same build is placed three times; `viewId` (from manifest.json)
* tells which placement this is, and the optional fields say what it is attached to.
*/
function placement(context: PolarionContext): string {
switch (context.viewId) {
case "form":
return `the form of work item ${context.workItemId}`;
case "sidebar":
if (!context.documentId) {
return "a sidebar next to the Work Items table";
}
const documentName = context.spaceId ? `${context.spaceId}/${context.documentId}` : `${context.documentId}`;
return `a sidebar of Document ${documentName}`;
case "topic":
return `a navigation topic of project ${context.projectId}`;
default:
return "an unknown placement";
}
}
export default function App() {
const [context, setContext] = useState<PolarionContext | null>(null);
const [readAt, setReadAt] = useState<Date | null>(null);
const [error, setError] = useState<string | null>(null);
// Used as a refresh trigger for re-fetching the context
const [readCount, setReadCount] = useState(0);
useEffect(() => {
let cancelled = false;
fetchContext()
.then((context) => {
if (cancelled) {
return;
}
setContext(context);
setReadAt(new Date());
})
.catch((error: unknown) => {
if (cancelled) {
return;
}
console.error("Unable to fetch the Polarion context:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to fetch the Polarion context: ${message}`);
});
return () => {
// Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
cancelled = true;
destroy();
};
}, [readCount]);
if (error !== null) {
return (
<div className="card error" role="alert">
<strong>Could not load the Polarion context.</strong>
<p>{error}</p>
</div>
);
}
if (context === null) {
return <p className="muted">Waiting for the Polarion context...</p>;
}
return (
<div className="card">
<h1>Application context</h1>
<p>
View <strong>{context.viewId}</strong> is running in {placement(context)}.
</p>
<Table context={context} />
<p className="footer">
<button type="button" onClick={() => setReadCount((count) => count + 1)}>
Read again
</button>
<span className="muted">Read at {readAt?.toLocaleTimeString() ?? "-"}. The context does not update by itself.</span>
</p>
</div>
);
}
- Three states. Waiting for the context, context received, or failed.
fetchContext()fails after five seconds when the page is not embedded by Polarion, for example when you open the view URL directly. - StrictMode. In development React mounts the component twice. The cleanup sets a
cancelledflag beforedestroy(), so whatever the first mount'sfetchContext()returns, including its rejection, is ignored. - Optional fields.
projectId,workItemId,spaceIdanddocumentIdare optional in the type and absent where they do not apply. The table shows not set instead of failing. - The token.
restTokenis shown as present or not set, never as its value. Not set means that REST token authentication is off on the server; see Enable Applications in Polarion. - Read again. The button increments
readCount, which re-runs the effect: the cleanup destroys the previous SDK instance and the effect fetches a new snapshot. Nothing in the object changes by itself. - Rendering in
Table.tsx.App.tsxreads the context and handles the states;Table.tsxshows one row per field.
src/Table.tsx
One row per context field. Optional fields that do not apply to the placement show not set; the token shows only whether it is present.
import type { PolarionContext } from "polarion-app-sdk";
type TableProps = {
context: PolarionContext;
};
/** Shows an optional value, or that it is not set in this placement. */
function optional(value: string | undefined) {
return value ? value : <span className="muted">not set</span>;
}
export default function Table({ context }: TableProps) {
return (
<table>
<tbody>
<tr>
<th>applicationId</th>
<td>{context.applicationId}</td>
</tr>
<tr>
<th>viewId</th>
<td>{context.viewId}</td>
</tr>
<tr>
<th>projectId</th>
<td>{optional(context.projectId)}</td>
</tr>
<tr>
<th>workItemId</th>
<td>{optional(context.workItemId)}</td>
</tr>
<tr>
<th>spaceId</th>
<td>{optional(context.spaceId)}</td>
</tr>
<tr>
<th>documentId</th>
<td>{optional(context.documentId)}</td>
</tr>
<tr>
<th>selectedWorkItemIds</th>
<td>{context.selectedWorkItemIds.length > 0 ? context.selectedWorkItemIds.join(", ") : <span className="muted">empty</span>}</td>
</tr>
<tr>
<th>restBaseUrl</th>
<td>{context.restBaseUrl}</td>
</tr>
<tr>
<th>appEndpoint</th>
<td>{context.appEndpoint}</td>
</tr>
<tr>
<th>restToken</th>
{/* The token is a credential: show that it is there, never its value. */}
<td>{context.restToken ? "present (hidden)" : <span className="muted">not set: token authentication is off</span>}</td>
</tr>
</tbody>
</table>
);
}
Build and deploy
cd examples/application-context
npm install
npm run package # → com.example.context.zip
Upload the ZIP in Global Administration → Applications. Then place the views:
- Form extension: add
<applicationView id="p-examples-application-context-com.example.context.form" label="Application context" height="460px"/>to a form layout, as in Form extensions. - Navigation topic: add
<applicationView id="p-examples-application-context-com.example.context.topic"/>to the project's Topics, as in Navigation topics. - Sidebar: nothing to configure. Open the Work Items table or a Document, click Show Sidebar and choose Application context.
Things to try
- Open the sidebar in the table, select rows and click Read again:
selectedWorkItemIdsstays empty. Follow the selection with events in the Selection sidebar example. - Open the same sidebar inside a Document and look at
spaceIdanddocumentId. - Open
https://<host>/polarion/apps/com.example.context/views/formdirectly. After five seconds the error state appears.
Examples
Traceability with endpoints

| Aspect | Details |
|---|---|
| Folder | examples/traceability |
| Identifier | com.example.traceability |
| View | form extension tree |
| Endpoints | GET linked-tree, POST add-comment |
| Placement | <applicationView id="p-examples-traceability-com.example.traceability.tree" label="Traceability" height="480px"/> |
| Uses | fetchContext(), context.appEndpoint, GraalVM scripts with the tracker service |
Source: the project is in examples/traceability/ of this kit.
What it does
- The view fetches the context and calls
GET {appEndpoint}/linked-tree?objectId=test/TEST-514&depth=2, optionally withrole=implementsto show only links of one role. linked-tree.jsruns on the server: it loads the work item, walks its direct links (downstream) recursively to the requested depth and its back links (upstream) one level, marks suspect links, and returns a nested tree in one response, together with the link roles it met.- The view renders upstream items, then the root with its downstream tree: role, id, title, status, and a warning chip on suspect links.
- A textarea and Add comment button call
POST {appEndpoint}/add-commentwith{ objectId, text };add-comment.jscreates the comment through the Java API and saves.
Files
- traceability/
- manifest.json
- server-scripts/
- linked-tree.js (GET endpoint)
- add-comment.js (POST endpoint)
- src/
- App.tsx (context, endpoint calls, state)
- LinkTree.tsx (role filter and tree rendering)
- polarion.ts (endpointFetch helper)
- types.ts
- main.tsx
- styles.css
- …
manifest.json
The serverScripts.endpoints section maps paths and methods to the script files.
{
"manifestVersion": "1.0",
"identifier": "com.example.traceability",
"title": "Traceability",
"description": "Shows the link tree of the current work item, computed by a server script, and adds comments through a POST endpoint.",
"publisherName": "Example Publisher",
"applicationVersion": "0.2.2",
"views": {
"formExtensions": [
{
"identifier": "tree",
"title": "Traceability",
"rootDirectory": "tree",
"document": "index.html"
}
]
},
"serverScripts": {
"endpoints": [
{
"urlPath": "linked-tree",
"method": "GET",
"script": "linked-tree.js"
},
{
"urlPath": "add-comment",
"method": "POST",
"script": "add-comment.js"
}
]
}
}
server-scripts/linked-tree.js
// GET /polarion/apps/com.example.traceability/rest/linked-tree?objectId=PROJECT/WI-ID&depth=2[&role=implements]
//
// Runs on the Polarion server (GraalVM JavaScript) as the logged-in user.
// Walks the work item links in both directions and returns a nested tree.
// The optional `role` filter applies to links in both directions.
//
// Globals provided by Polarion:
// context – IScriptContext access: context.scriptContext().services().tracker()
// arguments – IArguments: request parameters (query string for GET, JSON body for POST)
const trackerService = context.scriptContext().services().tracker();
let result = {};
// Polarion's IArguments throws ("Argument <name> is missing in workflow definition")
// when a parameter is absent. Optional parameters are therefore read through a guard.
const scriptArguments = arguments;
function getOptionalParam(name, defaultValue) {
try {
const value = scriptArguments.getAsString(name);
return value === null || value === undefined || String(value) === '' ? defaultValue : String(value);
} catch (e) {
return defaultValue;
}
}
function readParameters() {
const objectId = scriptArguments.getAsString('objectId');
if (!objectId) {
throw new Error('objectId parameter is required (PROJECT/WI-ID)');
}
const depth = Math.min(3, Math.max(1, parseInt(getOptionalParam('depth', '2'), 10) || 2));
const roleParam = getOptionalParam('role', '');
const roleFilter = roleParam ? String(roleParam).trim().toLowerCase() : '';
return { objectId, depth, roleFilter };
}
function findWorkItem(objectId) {
const [projectId, workItemId] = objectId.split('/');
const workItem = trackerService.getWorkItem(projectId, workItemId);
if (workItem.isUnresolvable()) {
throw new Error('Work item not found: ' + objectId);
}
return workItem;
}
/** Suspect flag of a link; defaults to false if the API call is unavailable. */
function isSuspect(link) {
try {
return link.isSuspect() === true;
} catch (e) {
return false;
}
}
/** Id, name and opposite name of a link role, e.g. "verifies", "verifies", "is verified by". */
function roleInfo(link) {
const role = link.getLinkRole();
if (!role) return { id: '', name: '', oppositeName: '' };
let oppositeName = '';
try {
oppositeName = role.getOppositeName() ? String(role.getOppositeName()) : '';
} catch (e) {
// Without an opposite name the filter matches the id and the name only.
}
return { id: String(role.getId()), name: String(role.getName()), oppositeName: oppositeName };
}
// Every role met while walking, so the view can offer them in its filter.
const rolesSeen = new Map();
function remember(info) {
if (info.id && !rolesSeen.has(info.id)) {
rolesSeen.set(info.id, info);
}
}
/**
* True when no role filter is set or the link role matches it (case-insensitive).
* The filter compares the role id, its name and its opposite name, so "verifies" also
* matches a back link that reads "is verified by" from this side.
*/
function roleMatches(info, roleFilter) {
if (!roleFilter) return true;
return [info.id, info.name, info.oppositeName].some((value) => value.toLowerCase() === roleFilter);
}
function toTreeNode(workitem) {
return {
id: workitem.getProjectId() + '/' + workitem.getId(),
title: workitem.getTitle(),
type: workitem.getType() ? workitem.getType().getName() : null,
status: workitem.getStatus() ? workitem.getStatus().getName() : null,
};
}
// Direct links ("this item implements X") become the downstream children.
// `ancestors` holds the items on the path from the root to here. Each branch gets its own
// copy, so a cycle stops the recursion but an item reached on two paths is expanded on both.
function buildDownstreamNodes(workitem, depth, ancestors, roleFilter) {
const workItemId = workitem.getProjectId() + '/' + workitem.getId();
if (depth <= 0 || ancestors.has(workItemId)) {
return [];
}
const path = new Set(ancestors);
path.add(workItemId);
const downstream = [];
// Java collections are easiest to iterate as arrays from GraalVM JavaScript.
const direct = workitem.getLinkedWorkItemsStructsDirect().toArray();
for (let i = 0; i < direct.length; i++) {
const link = direct[i];
const info = roleInfo(link);
remember(info);
if (!roleMatches(info, roleFilter)) {
continue;
}
const linkedWorkItem = link.getLinkedItem();
const node = toTreeNode(linkedWorkItem);
node.role = info.name;
node.suspect = isSuspect(link);
if (depth > 1 && !path.has(node.id)) {
node.downstream = buildDownstreamNodes(linkedWorkItem, depth - 1, path, roleFilter);
}
downstream.push(node);
}
return downstream;
}
function buildUpstreamNodes(workItem, roleFilter) {
const upstream = [];
const back = workItem.getLinkedWorkItemsStructsBack().toArray();
for (let i = 0; i < back.length; i++) {
const link = back[i];
const info = roleInfo(link);
remember(info);
// The role filter applies in both directions: a requirement filtered by "verifies"
// shows the test cases that verify it, which are back links seen from here.
if (!roleMatches(info, roleFilter)) {
continue;
}
const node = toTreeNode(link.getLinkedItem());
// Seen from this item a back link reads in the opposite direction ("is verified by").
node.role = info.oppositeName || info.name;
node.suspect = isSuspect(link);
upstream.push(node);
}
return upstream;
}
try {
const { objectId, depth, roleFilter } = readParameters();
const workItem = findWorkItem(objectId);
const rootWorkItemNode = toTreeNode(workItem);
rootWorkItemNode.downstream = buildDownstreamNodes(workItem, depth, new Set(), roleFilter);
rootWorkItemNode.upstream = buildUpstreamNodes(workItem, roleFilter);
result = { item: rootWorkItemNode, roles: Array.from(rolesSeen.values()) };
} catch (e) {
// An `error` key turns the response into an error response for the caller.
result = { error: 'linked-tree failed: ' + e };
}
result;
server-scripts/add-comment.js
// POST /polarion/apps/com.example.traceability/rest/add-comment
// Body: { "objectId": "PROJECT/WI-ID", "text": "…" }
//
// Adds a plain-text comment to the work item. Runs as the logged-in user, who
// therefore needs permission to comment on the item.
const trackerService = context.scriptContext().services().tracker();
const Text = Java.type('com.polarion.core.util.types.Text');
let result = {};
try {
const fullId = arguments.getAsString('objectId');
const text = arguments.getAsString('text');
if (!fullId) {
throw new Error('objectId parameter is required (PROJECT/WI-ID)');
}
if (!text || text.trim() === '') {
throw new Error('text parameter is required');
}
const [projectId, workitemId] = fullId.split('/');
const workitem = trackerService.getWorkItem(projectId, workitemId);
if (workitem.isUnresolvable()) {
throw new Error('Work item not found: ' + fullId);
}
// createComment(IText text, String title, IComment parent) returns the new
// IComment. Saving the work item alone does not persist it; save the comment.
const comment = workitem.createComment(Text.plain(text), 'Traceability app', null);
comment.save();
// The id may not be assigned yet right after save; report it when available.
const commentId = comment.getId();
result = { ok: true, commentId: commentId ? String(commentId) : null };
} catch (e) {
result = { error: 'add-comment failed: ' + e };
}
result;
Note
Text.plain() comes from com.polarion.core.util.types.Text; createComment(IText, String, IComment) is the IWorkItem method and returns the new IComment, which must be saved with comment.save(). Saving the work item alone does not persist the comment.
src/polarion.ts
The endpoint helper: same token header as for REST, plus unwrapping of the { success, data, error } envelope.
import type { PolarionContext } from "polarion-app-sdk";
/** Envelope that Polarion wraps around every server-script response. */
interface Envelope<T> {
timestamp?: string;
success?: boolean;
error?: string;
data?: T;
}
/**
* Calls one of the application's own endpoints declared in
* manifest.json under `serverScripts.endpoints`.
*
* `context.appEndpoint` is the absolute base URL of those endpoints, for example
* `https://host/polarion/apps/com.example.traceability/rest` (no trailing slash), so `path`
* starts with a slash, as in `restFetch`: `"/validate"`. The same
* `X-Polarion-REST-Token` header as for the REST API authenticates the call.
* The response envelope is unwrapped so callers only see the script's result.
*/
export async function endpointFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
const headers = new Headers(init.headers);
headers.set("X-Polarion-REST-Token", context.restToken ?? "");
headers.set("Accept", "application/json");
if (init.body !== undefined && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
const response = await fetch(`${context.appEndpoint}${path}`, { ...init, headers });
// Script errors come back as HTTP 400 with the envelope, so parse the body
// whenever it is JSON and surface the script's own message.
const text = await response.text();
let envelope: Envelope<T> | undefined;
try {
envelope = JSON.parse(text) as Envelope<T>;
} catch {
envelope = undefined;
}
if (envelope && (envelope.success === false || envelope.error)) {
throw new Error(envelope.error ?? "Server script reported an error.");
}
if (!response.ok || !envelope) {
throw new Error(`Endpoint ${response.status}: ${text}`);
}
return envelope.data as T;
}
src/App.tsx
import { useEffect, useRef, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import { endpointFetch } from "./polarion";
import LinkTree from "./LinkTree";
import type { AddCommentResult, LinkedTreeResult, LinkRole, TreeNode, CommentState } from "./types";
export default function App() {
const [tree, setTree] = useState<TreeNode | null>(null);
const [role, setRole] = useState("");
const [roles, setRoles] = useState<LinkRole[]>([]);
const [comment, setComment] = useState("");
const [commentState, setCommentState] = useState<CommentState>({ kind: "idle" });
const [error, setError] = useState<string | null>(null);
// Keep the fetched context available to filter changes without triggering a render.
const contextRef = useRef<PolarionContext | null>(null);
// Changing the role quickly starts several loads; only the latest request may update the view.
const requestRef = useRef(0);
// Loads the linked workitem tree rooted at the selected work item. The server follows downstream
// links recursively to the requested depth and includes direct upstream links; the role filter
// applies to links in both directions.
const loadTree = async (context: PolarionContext, roleFilter = "") => {
const request = ++requestRef.current;
setError(null);
// Build the query from the current work item and optional role filter selected.
const params = new URLSearchParams({
objectId: `${context.projectId}/${context.workItemId}`,
depth: "2",
});
if (roleFilter.trim() !== "") {
params.set("role", roleFilter.trim());
}
try {
// Fetch the linked tree from the server using the constructed query parameters.
const result = await endpointFetch<LinkedTreeResult>(context, `/linked-tree?${params}`);
// Ignore responses that finished after a more recent load was started.
if (request !== requestRef.current) {
return;
}
setTree(result.item);
// Keep roles from previous responses so filtering does not hide other available options.
setRoles((knownRoles) => {
const byId = new Map(knownRoles.map((knownRole) => [knownRole.id, knownRole]));
const resultRoles = result.roles ?? [];
resultRoles.forEach((resultRole) => byId.set(resultRole.id, resultRole));
return [...byId.values()].sort((a, b) => a.name.localeCompare(b.name));
});
} catch (cause) {
// Only show errors from the latest request; an outdated failure is no longer relevant.
if (request === requestRef.current) {
console.error("Unable to load the linked work items:", cause);
const message = cause instanceof Error ? cause.message : String(cause);
setError(`Unable to load the linked work items: ${message}`);
}
}
};
const addCommentHandler = async () => {
const context = contextRef.current;
if (!context) {
setCommentState({ kind: "error", message: "Work item context is not available." });
return;
}
setCommentState({ kind: "saving" });
try {
const result = await endpointFetch<AddCommentResult>(context, "/add-comment", {
method: "POST",
body: JSON.stringify({
objectId: `${context.projectId}/${context.workItemId}`,
text: comment.trim(),
}),
});
if (!result.ok) {
throw new Error("The server did not confirm that the comment was added.");
}
setComment("");
setCommentState({
kind: "success",
message: `Comment added${result.commentId ? ` (${result.commentId})` : ""}. Reload the page to see it.`,
});
} catch (cause: unknown) {
console.error("Unable to add the comment:", cause);
const message = cause instanceof Error ? cause.message : String(cause);
setCommentState({ kind: "error", message: `Unable to add the comment: ${message}` });
}
};
// Initialize the view by fetching the context and loading the tree.
useEffect(() => {
let cancelled = false;
const initialize = async () => {
try {
const context: PolarionContext = await fetchContext();
if (cancelled) {
return;
}
if (!context.projectId || !context.workItemId) {
setError("This view must be placed on a work item form.");
return;
}
contextRef.current = context;
await loadTree(context);
} catch (cause) {
if (!cancelled) {
console.error("Unable to fetch the Polarion context:", cause);
const message = cause instanceof Error ? cause.message : String(cause);
setError(`Unable to fetch the Polarion context: ${message}`);
}
}
};
initialize();
return () => {
// Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
cancelled = true;
requestRef.current += 1;
destroy();
};
}, []);
const applyRole = (selectedRole: string) => {
setRole(selectedRole);
if (contextRef.current) {
void loadTree(contextRef.current, selectedRole);
}
};
if (error) {
return <div className="card error">{error}</div>;
} else if (!tree) {
return <p className="muted">Computing the link tree on the server…</p>;
}
return (
<div className="card">
<LinkTree tree={tree} roles={roles} role={role} onRoleChange={applyRole} />
<h2>Add a comment</h2>
<textarea rows={3} value={comment} onChange={(event) => setComment(event.target.value)} placeholder="Comment text" />
<div className="row">
<button onClick={addCommentHandler} disabled={commentState.kind === "saving" || comment.trim() === ""}>
{commentState.kind === "saving" ? "Saving…" : "Add comment"}
</button>
{commentState.message && <span className={commentState.kind === "success" ? "ok" : "err"}>{commentState.message}</span>}
</div>
</div>
);
}
Points worth noting:
- One round trip. Fetching a two-level link tree through REST would take one request per node; the endpoint does it server-side and returns the result at once.
- The role filter works in both directions. A link is stored on one side only: a test case verifies a requirement, a task has parent a work package. Seen from the requirement or the work package these are back links, labelled with the role's opposite name (is verified by, is parent of). The script therefore filters upstream and downstream links alike and compares the role id, its name and its opposite name. The view offers the roles found on the item in a dropdown, so nobody has to guess role ids.
- Parameters in the right place. The GET endpoint receives
objectId,depthandrolein the query string; the POST endpoint receivesobjectIdandtextin the JSON body. - Errors are data. A failing script returns
success: falsewith a message; the helper converts that into a thrown error, and the component shows it. - Writes need permission.
add-commentruns as the user; without comment permission the envelope carries the Java exception message. - Only the latest load counts. Changing the role quickly starts several requests; a counter in
requestReflets only the most recent response update the tree, and the cleanup of the mount effect sets acancelledflag beforedestroy().
src/LinkTree.tsx
The role dropdown and the tree. LinkTree receives the tree and the known roles as props and reports a new role through onRoleChange; App.tsx then reloads the tree from the endpoint. A private Node component renders one node and calls itself for the node's downstream children.
import type { LinkRole, TreeNode } from "./types";
type LinkTreeProps = {
tree: TreeNode;
roles: LinkRole[];
role: string;
onRoleChange: (role: string) => void;
};
function itemUrl(fullId: string): string {
const [project, id] = fullId.split("/");
return `${window.location.origin}/polarion/#/project/${project}/workitem?id=${id}`;
}
function Node({ node, level = 0, isRoot = false }: { node: TreeNode; level?: number; isRoot?: boolean }) {
const workitemId = node.id.split("/")[1] ?? node.id;
const className = isRoot ? "node root" : "node";
const style = { paddingLeft: `${level * 20}px` };
return (
<>
<div className={className} style={style}>
{node.role && <span className="role">{node.role}</span>}
<a href={itemUrl(node.id)} target="_top">
{workitemId}
</a>
<span className="title">{node.title}</span>
{node.type && <span className="chip">{node.type}</span>}
{node.status && <span className="chip status">{node.status}</span>}
{node.suspect && (
<span className="chip warn" title="The linked item changed after the link was created">
suspect
</span>
)}
</div>
{node.downstream?.map((child) => (
<Node key={child.id} node={child} level={level + 1} />
))}
</>
);
}
export default function LinkTree({ tree, roles, role, onRoleChange }: LinkTreeProps) {
return (
<>
{/* Optional role filter, passed to the GET endpoint as the `role` parameter. It offers the
roles found on this item's links and applies to upstream and downstream links alike. */}
<div className="row filter">
<label htmlFor="role">Link role</label>
<select id="role" value={role} onChange={(event) => onRoleChange(event.target.value)}>
<option value="">All roles</option>
{roles.map((linkRole) => (
<option key={linkRole.id} value={linkRole.id}>
{linkRole.oppositeName && linkRole.oppositeName !== linkRole.name ? `${linkRole.name} / ${linkRole.oppositeName}` : linkRole.name}
</option>
))}
</select>
</div>
<h2>Upstream (items linking to this one)</h2>
{tree.upstream?.length ? tree.upstream.map((parent) => <Node key={parent.id} node={parent} />) : <p className="muted">No upstream links.</p>}
<h2>This item and its downstream links</h2>
<Node node={tree} isRoot />
{!tree.downstream?.length && <p className="muted">No downstream links.</p>}
</>
);
}
Build and deploy
cd examples/traceability
npm install
npm run package # → com.example.traceability.zip (with server-scripts/)
Upload the ZIP, add the applicationView element to a form layout, and open a work item that has links. To see upstream links, open an item that is the target of a link from another item.
Things to try
- Return the link's own id so that the view can offer Clear suspect through the REST API.
- Add a
maxNodesparameter and stop the walk when it is reached, returningtruncated: true. - Call the endpoint directly in the browser while logged in:
https://<host>/polarion/apps/com.example.traceability/rest/linked-tree?objectId=test/TEST-514shows the raw envelope.
Examples
Work item card

| Aspect | Details |
|---|---|
| Folder | examples/work-item-card |
| Identifier | com.example.workitemcard |
| View | form extension card |
| Placement | <applicationView id="p-examples-work-item-card-com.example.workitemcard.card" label="Work item card" height="640px"/> |
| Uses | fetchContext(), REST GET …/workitems/{id}, GET …/linkedworkitems?include=workItem, PATCH …/workitems/{id} (title), GET …/actions/getWorkflowActions and PATCH …?workflowAction= (status), POST …/workitems/{id}/comments |
Source: the project is in examples/work-item-card/ of this kit.
What it does
- Fetches the context to learn
projectId,workItemId,restBaseUrlandrestToken. - Loads the work item with a sparse field set, then its linked work items with
include=workItemso that the titles arrive in the same response. Suspect links get a warning badge. - Renders a card: title, badges for type, status, priority and severity with their Polarion names and icons, the HTML description, and the links with roles.
- Offers three write operations, each a small component: Rename (
PATCH attributes.title), Status (runs a workflow action, so the workflow's conditions and required fields apply) and Add comment (POST …/comments).
Files
- work-item-card/
- manifest.json
- src/
- App.tsx (loading and rendering)
- components/
- RenameForm.tsx (PATCH title)
- StatusForm.tsx (workflow action)
- RequiredFields.tsx (inputs for required fields)
- CommentForm.tsx (POST comment)
- polarion.ts (restFetch helper)
- types.ts (JSON:API shapes)
- fields.ts (field metadata → inputs and values)
- main.tsx
- styles.css
- scripts/package.mjs
- …
manifest.json
{
"manifestVersion": "1.0",
"identifier": "com.example.workitemcard",
"title": "Work item card",
"description": "Shows the current work item, its linked work items and lets the user rename it through the Polarion REST API.",
"publisherName": "Example Publisher",
"applicationVersion": "0.2.1",
"views": {
"formExtensions": [
{
"identifier": "card",
"title": "Work item card",
"rootDirectory": "card",
"document": "index.html"
}
]
}
}
src/polarion.ts
The REST helper used by all REST examples. It is the only place that knows about the token header.
import type { PolarionContext } from "polarion-app-sdk";
/**
* Calls the Polarion REST API (JSON:API) on behalf of the logged-in user.
*
* `context.restBaseUrl` is the absolute base URL of the REST API, for example
* `https://host/polarion/rest/v1` (no trailing slash). `context.restToken` is a
* short-lived token that Polarion hands to the application view; it must be
* sent in the `X-Polarion-REST-Token` header.
*/
export async function restFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
const headers = new Headers(init.headers);
headers.set("X-Polarion-REST-Token", context.restToken ?? "");
headers.set("Accept", "application/json");
if (init.body !== undefined && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
const response = await fetch(`${context.restBaseUrl}${path}`, { ...init, headers });
if (!response.ok) {
throw new Error(`REST ${response.status}: ${await response.text()}`);
}
if (response.status === 204) {
return null as T;
}
return (await response.json()) as T;
}
src/types.ts
Only the parts of the JSON:API documents the component reads. Typing the full REST schema is unnecessary; keep the types close to what you use.
/** Minimal JSON:API shapes used by this example. */
export interface WorkItemAttributes {
title: string;
status: string;
type: string;
priority?: string;
severity?: string;
description?: { type: string; value: string };
}
export interface WorkItemResource {
/** "PROJECT/WI-ID" */
id: string;
type: "workitems";
attributes: WorkItemAttributes;
}
export interface WorkItemResponse {
data: WorkItemResource;
}
export interface LinkedWorkItemResource {
id: string;
type: "linkedworkitems";
attributes: { role: string; suspect?: boolean };
relationships: { workItem: { data: { id: string; type: "workitems" } } };
}
export interface LinkedWorkItemsResponse {
data: LinkedWorkItemResource[];
included?: WorkItemResource[];
}
/** A linked work item flattened for rendering. */
export interface LinkedItem {
role: string;
suspect: boolean;
id: string;
title: string;
status: string;
}
/** One entry of GET …/workitems/{id}/actions/getWorkflowActions. */
export interface WorkflowAction {
/** Position in the list; the PATCH does not accept it. */
id: string;
/** Action id from the workflow configuration, e.g. "start_progress": the value for `?workflowAction=`. */
nativeActionId: string;
name: string;
targetStatus: string;
available: boolean;
unavailableReason?: string;
requiredFields?: string[];
}
export interface WorkflowActionsResponse {
data?: WorkflowAction[];
}
/** UI state of a save action. */
export type ActionState = { kind: "idle" | "saving" | "ok" | "error"; text?: string };
src/App.tsx
import { useCallback, useEffect, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import DOMPurify from "dompurify";
import { restFetch } from "./polarion";
import type { LinkedItem, LinkedWorkItemsResponse, WorkItemAttributes, WorkItemResponse } from "./types";
import { loadCurrentOption, loadOptionsForType, type EnumOption } from "./fields";
import RenameForm from "./components/RenameForm";
import StatusForm from "./components/StatusForm";
import CommentForm from "./components/CommentForm";
interface Badge {
field: string;
/** Shown before the option name where the name alone is ambiguous ("Medium"). */
label?: string;
option: EnumOption;
}
interface Card {
id: string;
attributes: WorkItemAttributes;
badges: Badge[];
linked: LinkedItem[];
}
/** An enumeration value with Polarion's icon and name, colored like in Polarion. */
function OptionBadge({ badge }: { badge: Badge }) {
const { option } = badge;
return (
<span className={`badge ${badge.field}`} style={option.color ? { borderColor: option.color } : undefined} title={`${badge.field}: ${option.id}`}>
{option.iconURL && <img src={`${window.location.origin}${option.iconURL}`} alt="" />}
{badge.label && <span className="badge-label">{badge.label}</span>}
{option.name}
</span>
);
}
// Enumeration fields shown as badges, with the label for those whose value alone is unclear.
const BADGE_FIELDS: { field: keyof WorkItemAttributes; label?: string }[] = [{ field: "type" }, { field: "status" }, { field: "priority", label: "Priority" }, { field: "severity", label: "Severity" }];
/**
* Loads the work item and its links, plus the display names and icons of its enumeration
* values. The REST API returns enumeration fields as ids ("workpackage", "55.0"); the names
* come from getCurrentOptions, and for linked items from the status options of their type.
*/
async function loadCard(context: PolarionContext): Promise<Card> {
const { projectId, workItemId } = context;
if (!projectId || !workItemId) {
throw new Error("This view must be placed on a work item form (projectId / workItemId missing).");
}
const base = `/projects/${projectId}/workitems/${workItemId}`;
const item = await restFetch<WorkItemResponse>(context, `${base}?fields[workitems]=id,title,status,type,priority,severity,description`);
const links = await restFetch<LinkedWorkItemsResponse>(context, `${base}/linkedworkitems?fields[linkedworkitems]=role,suspect,workItem&include=workItem&fields[workitems]=id,title,status,type`);
// The linked items only carry an id; the full work items travel in `included`.
const byId = new Map((links.included ?? []).map((wi) => [wi.id, wi]));
// Display values: one call per badge field, one per work item type among the links.
const present = BADGE_FIELDS.filter((b) => item.data.attributes[b.field]);
const linkedTypes = [...new Set((links.included ?? []).map((wi) => wi.attributes.type))];
const [options, statusByType] = await Promise.all([Promise.all(present.map((b) => loadCurrentOption(context, b.field).catch(() => null))), Promise.all(linkedTypes.map((t) => loadOptionsForType(context, "status", t).catch(() => new Map<string, EnumOption>()))).then((maps) => new Map(linkedTypes.map((t, i) => [t, maps[i]])))]);
const badges = present.flatMap((b, i) => {
const option = options[i] ?? { id: String(item.data.attributes[b.field]), name: String(item.data.attributes[b.field]) };
return [{ field: b.field, label: b.label, option }];
});
const linked: LinkedItem[] = links.data.map((link) => {
const target = byId.get(link.relationships.workItem.data.id);
const status = target?.attributes.status ?? "";
return {
role: link.attributes.role,
suspect: link.attributes.suspect === true,
id: link.relationships.workItem.data.id,
title: target?.attributes.title ?? "",
status: (target && statusByType.get(target.attributes.type)?.get(status)?.name) ?? status,
};
});
return { id: item.data.id, attributes: item.data.attributes, badges, linked };
}
export default function App() {
const [context, setContext] = useState<PolarionContext | null>(null);
const [card, setCard] = useState<Card | null>(null);
const [error, setError] = useState<string | null>(null);
const reload = useCallback(async (ctx: PolarionContext) => {
try {
setCard(await loadCard(ctx));
setError(null);
} catch (error) {
console.error("Unable to load the work item:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to load the work item: ${message}`);
}
}, []);
useEffect(() => {
let cancelled = false;
fetchContext()
.then((ctx) => {
if (cancelled) {
return;
}
setContext(ctx);
return reload(ctx);
})
.catch((error: unknown) => {
if (cancelled) {
return;
}
console.error("Unable to fetch the Polarion context:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to fetch the Polarion context: ${message}`);
});
return () => {
// Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
cancelled = true;
destroy();
};
}, [reload]);
if (error) {
return <div className="card error">{error}</div>;
}
if (!context || !card) {
return <p className="muted">Loading work item…</p>;
}
const a = card.attributes;
const origin = window.location.origin;
return (
<div className="card">
<h1>{a.title}</h1>
<div className="badges">
{card.badges.map((b) => (
<OptionBadge key={b.field} badge={b} />
))}
</div>
<h2>Description</h2>
{a.description?.value ? (
// The description is HTML written by users. Sanitize it before it enters the DOM:
// the view runs on Polarion's origin with the user's session.
<div className="description" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(a.description.value) }} />
) : (
<p className="muted">No description.</p>
)}
<h2>Linked work items</h2>
{card.linked.length === 0 ? (
<p className="muted">No links.</p>
) : (
<ul className="links">
{card.linked.map((link) => {
const [project, id] = link.id.split("/");
return (
<li key={`${link.role}-${link.id}`}>
<span className="role">{link.role}</span>
<a href={`${origin}/polarion/#/project/${project}/workitem?id=${id}`} target="_top">
{id}
</a>{" "}
{link.title} <span className="muted">({link.status})</span>
{link.suspect && <span className="badge warn">suspect</span>}
</li>
);
})}
</ul>
)}
{/* Three ways of writing through the REST API, each in its own small component. */}
<RenameForm context={context} resourceId={card.id} currentTitle={a.title} onSaved={() => reload(context)} />
<StatusForm context={context} resourceId={card.id} currentStatus={a.status} workItemType={a.type} onSaved={() => reload(context)} />
<CommentForm context={context} />
</div>
);
}
Points worth noting:
- Two requests, joined by id. The linked-work-items response carries the link resources in
dataand the target work items inincluded. ThebyIdmap joins them.workItemmust be listed infields[linkedworkitems], otherwise the relationship is not returned. - The description is HTML written by users. Polarion stores rich text as
{ type: 'text/html', value }. The view runs on Polarion's origin with the user's session, so a script inside a description would run there too. The example passes the value through DOMPurify beforedangerouslySetInnerHTMLrenders it; keep a sanitizer in front of any Polarion rich text you render. - Enumeration values are ids. The REST API returns
type,status,priorityandseverityas ids such asworkpackageor55.0. The card asksGET …/fields/{fieldId}/actions/getCurrentOptionsfor the selected option, which carries the display name, icon and color Polarion uses, and renders the badges from it. Statuses of linked items and of workflow targets come fromGET …/workitems/fields/status/actions/getAvailableOptions?type=<type>, because status names depend on the work item type. - Links open in the top window.
target="_top"makes the whole Polarion UI navigate instead of loading inside the iframe. - Each write is a component with its own state. The rename form is keyed on the current title so that it resets after a reload; the status form keeps its state, so its confirmation stays visible, and reloads the workflow actions when the status changes, dropping the old list first so that a stale transition cannot be chosen.
Writing: status and comments
import { useEffect, useState } from "react";
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "../polarion";
import RequiredFields from "./RequiredFields";
import { inputFor, isEmpty, loadFieldsMetadata, loadOptionsForType, toJsonApi, type EnumOption, type FieldMeta } from "../fields";
import type { ActionState, WorkflowAction, WorkflowActionsResponse } from "../types";
interface CurrentValuesResponse {
data: {
attributes?: Record<string, unknown>;
relationships?: Record<string, { data?: unknown }>;
};
}
interface Props {
context: PolarionContext;
resourceId: string;
currentStatus: string;
/** Work item type id; status names depend on it. */
workItemType: string;
onSaved: () => Promise<void>;
}
/**
* Changes the status by running a workflow action, as the status menu in Polarion does.
*
* Writing `attributes.status` directly would bypass the workflow: conditions, required
* fields and functions of the transition would not run. Instead the component lists the
* actions the workflow offers for the current status and runs the chosen one with
* `PATCH …/workitems/{id}?workflowAction=<nativeActionId>`.
*
* When the action requires fields that are still empty, the form asks for them and sends
* them in the same PATCH, as the transition dialog in Polarion does.
*/
export default function StatusForm({ context, resourceId, currentStatus, workItemType, onSaved }: Props) {
const [actions, setActions] = useState<WorkflowAction[] | null>(null);
const [actionId, setActionId] = useState("");
const [state, setState] = useState<ActionState>({ kind: "idle" });
// Field types of this work item (built-in and custom), loaded once.
const [metadata, setMetadata] = useState<Record<string, FieldMeta> | null>(null);
// Required fields of the chosen action that are empty on the work item, and their new values.
const [missing, setMissing] = useState<FieldMeta[] | null>(null);
const [values, setValues] = useState<Record<string, string>>({});
const path = `/projects/${context.projectId}/workitems/${context.workItemId}`;
useEffect(() => {
loadFieldsMetadata(context)
.then(setMetadata)
.catch(() => setMetadata({}));
}, [context]);
// Display names of the statuses, so actions read "Review → Reviewed" instead of "→ reviewed".
const [statuses, setStatuses] = useState<Map<string, EnumOption>>(new Map());
useEffect(() => {
loadOptionsForType(context, "status", workItemType)
.then(setStatuses)
.catch(() => setStatuses(new Map()));
}, [context, workItemType]);
const statusName = (id: string) => statuses.get(id)?.name ?? id;
// The workflow decides which actions exist for the current status and whether the
// user may run them; unavailable ones carry the reason.
useEffect(() => {
let cancelled = false;
// Drop the previous status's actions at once, so a stale transition cannot be chosen
// while the new list loads.
setActions(null);
setActionId("");
restFetch<WorkflowActionsResponse>(context, `${path}/actions/getWorkflowActions`)
.then((r) => {
if (!cancelled) setActions(r.data ?? []);
})
.catch((e: unknown) => {
if (!cancelled) setState({ kind: "error", text: e instanceof Error ? e.message : String(e) });
});
return () => {
cancelled = true;
};
}, [context, path, currentStatus]);
const selected = actions?.find((a) => a.nativeActionId === actionId);
// Read the current values of the action's required fields; only empty ones need input.
// Each field's metadata says whether it is an attribute or a relationship and how to edit it.
useEffect(() => {
setValues({});
const required = selected?.requiredFields ?? [];
if (required.length === 0) {
setMissing([]);
return;
}
setMissing(null);
if (!metadata) return;
const metas = required.map((id): FieldMeta => metadata[id] ?? { id, label: id, part: "attributes", type: { kind: "unknown" } });
let cancelled = false;
restFetch<CurrentValuesResponse>(context, `${path}?fields[workitems]=${required.join(",")}`)
.then((r) => {
const empty = metas.filter((m) => (m.part === "attributes" ? isEmpty(r.data.attributes?.[m.id]) : isEmpty(r.data.relationships?.[m.id]?.data)));
if (cancelled) return;
setMissing(empty);
// A checkbox has a value even when it is not ticked.
setValues(Object.fromEntries(empty.filter((m) => inputFor(m) === "checkbox").map((m) => [m.id, "false"])));
})
.catch(() => {
if (!cancelled) setMissing(metas);
});
return () => {
cancelled = true;
};
}, [context, path, selected, metadata]);
// Run is possible once every empty required field is editable here and has a value.
const complete = missing !== null && missing.every((m) => inputFor(m) !== null && (values[m.id] ?? "").trim() !== "");
async function run() {
if (!selected) return;
setState({ kind: "saving" });
try {
// The action runs on the server with the workflow's conditions and functions. The
// parameter takes the action id from the workflow configuration (nativeActionId).
// The body carries the required fields, which Polarion sets before the transition;
// the action itself sets the target status. The metadata decides where each value
// goes and in which shape (string, rich text, enumeration list, relationship, …).
const attributes: Record<string, unknown> = {};
const relationships: Record<string, unknown> = {};
for (const field of missing ?? []) {
(field.part === "attributes" ? attributes : relationships)[field.id] = toJsonApi(field, values[field.id].trim());
}
await restFetch(context, `${path}?workflowAction=${encodeURIComponent(selected.nativeActionId)}`, {
method: "PATCH",
body: JSON.stringify({ data: { type: "workitems", id: resourceId, attributes, relationships } }),
});
await onSaved();
// The new status offers different actions; they reload through the effect above.
setState({ kind: "ok", text: `${selected.name}: status is now ${statusName(selected.targetStatus)}.` });
} catch (e) {
// A condition or a required field that blocks the transition comes back as an HTTP error.
setState({ kind: "error", text: e instanceof Error ? e.message : String(e) });
}
}
return (
<>
<h2>Status</h2>
{actions === null && state.kind !== "error" && <p className="muted">Loading workflow actions…</p>}
{actions !== null && actions.length === 0 && <p className="muted">The workflow offers no action from status {statusName(currentStatus)}.</p>}
{actions !== null && actions.length > 0 && (
<div className="row">
<select value={actionId} onChange={(e) => setActionId(e.target.value)}>
<option value="">Choose an action…</option>
{actions.map((a) => (
<option key={a.nativeActionId} value={a.nativeActionId} disabled={!a.available}>
{a.name} → {statusName(a.targetStatus)}
{a.available ? "" : ` (${a.unavailableReason ?? "not available"})`}
</option>
))}
</select>
<button onClick={run} disabled={!selected || !selected.available || !complete || state.kind === "saving"}>
{state.kind === "saving" ? "Saving…" : "Run action"}
</button>
</div>
)}
{selected && missing && missing.length > 0 && (
<>
<p className="muted">{selected.name} requires these fields:</p>
<RequiredFields context={context} fields={missing} values={values} onChange={(field, value) => setValues((v) => ({ ...v, [field]: value }))} />
</>
)}
{state.kind === "ok" && <p className="ok">{state.text}</p>}
{state.kind === "error" && <p className="err">{state.text}</p>}
</>
);
}
Change the status through a workflow action, never by writing attributes.status. A PATCH that sets status directly is accepted, but it bypasses the workflow: the transition's conditions, required fields and functions do not run, and the work item can end up in a state the workflow cannot leave cleanly.
The component does what the status menu in Polarion does:
GET …/workitems/{id}/actions/getWorkflowActionsreturns the actions offered from the current status. Each one carriesname,targetStatus,availablewith anunavailableReason, andrequiredFields. Unavailable actions are shown disabled with the reason.PATCH …/workitems/{id}?workflowAction=<nativeActionId>runs the chosen action. PassnativeActionId, the action id from the workflow configuration (for examplereviewed); the numericidof the list entry is rejected with The workflow action '8' was not found.- Required fields are filled in the same request, as the transition dialog in Polarion does. When an action lists
requiredFields, the component reads their current values and asks only for the empty ones. It sends them inattributes(or, forassignee, inrelationships) of thePATCHthat carries?workflowAction=. Polarion sets the fields first and then runs the transition. Verified on 2612: Reject withresolution: "invalid"in the body moves a work package to rejected in one call. - The workflow checks still apply. Without the resolution, Reject comes back as HTTP 400: The required field 'Resolution' (id: 'resolution') of Work Item … is empty. The component shows that message.
- Fields that the action clears (
clearedFields) are emptied after the transition. A value sent for such a field in the same request does not survive.
Nothing in the form is specific to a field. The required fields differ per transition, and the inputs adapt to whatever the workflow and the work item type define, custom fields included:
- Which fields: the action's
requiredFields, filtered to those that are empty on this work item. - How to edit them:
GET …/workitems/{id}/actions/getFieldsMetadatadescribes every field of the work item: whether it is an attribute or a relationship, itskind(string,text,enumeration,date,date-time,duration,boolean,relationship, …), the target resource type of a relationship, andmultifor multi-value fields.fields.tsmaps the kind to an input and converts the entered value into the JSON:API shape: a string, rich text as{ type, value }, an enumeration list for multi-value fields, or a relationship{ data: … }. - Which values: enumeration options come from
GET …/fields/{fieldId}/actions/getAvailableOptions, and relationship targets from the list of that resource type (users and plans in this example).
Verified on 2612 with a work package: Quickly Accept asked for Initial Estimate (a duration, text input), Reject for Resolution (an enumeration, select). Both moved the work item in one request. Field kinds the example does not edit, such as structures, show a note pointing to the work item form, and Run action stays disabled.
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "./polarion";
/**
* Field types as returned by GET …/workitems/{id}/actions/getFieldsMetadata.
* The same call describes built-in and custom fields of this work item's type.
*/
export interface FieldType {
kind: string; // "string", "text", "enumeration", "date", "date-time", "duration", "boolean", "relationship", …
enumName?: string;
targetResourceTypes?: string[];
multi?: boolean;
}
export interface FieldMeta {
id: string;
label: string;
/** Attributes and relationships travel in different parts of a JSON:API body. */
part: "attributes" | "relationships";
type: FieldType;
}
interface MetadataResponse {
data: {
attributes?: Record<string, { label?: string; type: FieldType }>;
relationships?: Record<string, { label?: string; type: FieldType }>;
};
}
export async function loadFieldsMetadata(context: PolarionContext): Promise<Record<string, FieldMeta>> {
const r = await restFetch<MetadataResponse>(context, `/projects/${context.projectId}/workitems/${context.workItemId}/actions/getFieldsMetadata`);
const fields: Record<string, FieldMeta> = {};
for (const part of ["attributes", "relationships"] as const) {
for (const [id, f] of Object.entries(r.data[part] ?? {})) {
fields[id] = { id, label: f.label ?? id, part, type: f.type };
}
}
return fields;
}
/** Relationship targets the form can offer, with the list request that fills the select. */
export const RELATIONSHIP_SOURCES: Record<string, (context: PolarionContext) => string> = {
users: () => "/users?fields[users]=name&sort=name&page[size]=100",
plans: (context) => `/projects/${context.projectId}/plans?fields[plans]=name&page[size]=100`,
};
/** How the form edits a field of this type, or null when the example does not support it. */
export function inputFor(meta: FieldMeta): "select" | "text" | "textarea" | "date" | "datetime" | "checkbox" | null {
const { kind, targetResourceTypes } = meta.type;
if (kind === "relationship") return targetResourceTypes?.length === 1 && RELATIONSHIP_SOURCES[targetResourceTypes[0]] ? "select" : null;
switch (kind) {
case "enumeration":
return "select";
case "string":
case "duration": // for example "1d 4h"
return "text";
case "text":
return "textarea";
case "date":
return "date";
case "date-time":
return "datetime";
case "boolean":
return "checkbox";
default:
return null; // structures, tables and other kinds: edit them in the form
}
}
/** Converts the form's string value into the JSON:API shape the field expects. */
export function toJsonApi(meta: FieldMeta, value: string): unknown {
const { kind, multi, targetResourceTypes } = meta.type;
if (kind === "relationship") {
const ref = { type: targetResourceTypes![0], id: value };
return { data: multi ? [ref] : ref };
}
switch (kind) {
case "enumeration":
return multi ? [value] : value;
case "text":
return { type: "text/plain", value };
case "date-time":
return new Date(value).toISOString();
case "boolean":
return value === "true";
default:
return value;
}
}
/** True when a value read from the REST API counts as not filled in. */
export function isEmpty(value: unknown): boolean {
if (value === undefined || value === null || value === "") return true;
if (Array.isArray(value)) return value.length === 0;
if (typeof value === "object" && "value" in value) return isEmpty((value as { value: unknown }).value);
return false;
}
/** An enumeration option as Polarion shows it: display name, icon and color. */
export interface EnumOption {
id: string;
name: string;
iconURL?: string;
color?: string;
}
interface OptionsResponse {
data?: EnumOption[];
}
/** The selected option of an enumeration field of the current work item, for example its status. */
export async function loadCurrentOption(context: PolarionContext, fieldId: string): Promise<EnumOption | null> {
const r = await restFetch<OptionsResponse>(context, `/projects/${context.projectId}/workitems/${context.workItemId}/fields/${fieldId}/actions/getCurrentOptions`);
return r.data?.[0] ?? null;
}
/** All options of an enumeration field for one work item type, by id. Status names differ per type. */
export async function loadOptionsForType(context: PolarionContext, fieldId: string, type: string): Promise<Map<string, EnumOption>> {
const r = await restFetch<OptionsResponse>(context, `/projects/${context.projectId}/workitems/fields/${fieldId}/actions/getAvailableOptions?type=${encodeURIComponent(type)}`);
return new Map((r.data ?? []).map((o) => [o.id, o]));
}
import { useEffect, useState } from "react";
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "../polarion";
import { inputFor, RELATIONSHIP_SOURCES, type FieldMeta } from "../fields";
interface Props {
context: PolarionContext;
/** The required fields of the action that are still empty, with their metadata. */
fields: FieldMeta[];
values: Record<string, string>;
onChange: (field: string, value: string) => void;
}
interface Option {
id: string;
name: string;
}
interface ListResponse {
data?: { id: string; name?: string; attributes?: { name?: string } }[];
}
/**
* One input per required field, chosen from the field's metadata, so any built-in or custom
* field works without code changes. Select options come from Polarion as well:
* - enumerations: GET …/workitems/{id}/fields/{fieldId}/actions/getAvailableOptions
* - relationships: the list of the target resources (users, plans; see RELATIONSHIP_SOURCES)
*/
export default function RequiredFields({ context, fields, values, onChange }: Props) {
const [options, setOptions] = useState<Record<string, Option[]>>({});
useEffect(() => {
let cancelled = false;
const base = `/projects/${context.projectId}/workitems/${context.workItemId}`;
for (const field of fields) {
if (inputFor(field) !== "select") continue;
// A real application would search large lists (for example users with `query`) instead of loading 100.
const url = field.type.kind === "relationship" ? RELATIONSHIP_SOURCES[field.type.targetResourceTypes![0]](context) : `${base}/fields/${field.id}/actions/getAvailableOptions`;
restFetch<ListResponse>(context, url)
.then((r) => (r.data ?? []).map((o) => ({ id: o.id, name: o.name ?? o.attributes?.name ?? o.id })))
.catch(() => [] as Option[])
.then((list) => {
if (!cancelled) setOptions((o) => ({ ...o, [field.id]: list }));
});
}
return () => {
cancelled = true;
};
}, [context, fields]);
return (
<div className="required">
{fields.map((field) => {
const value = values[field.id] ?? "";
const set = (v: string) => onChange(field.id, v);
let input;
switch (inputFor(field)) {
case "select":
input = options[field.id] ? (
<select value={value} onChange={(e) => set(e.target.value)}>
<option value="">Choose…</option>
{options[field.id].map((o) => (
<option key={o.id} value={o.id}>
{o.name}
</option>
))}
</select>
) : (
<span className="muted">Loading…</span>
);
break;
case "textarea":
input = <textarea rows={2} value={value} onChange={(e) => set(e.target.value)} />;
break;
case "date":
input = <input type="date" value={value} onChange={(e) => set(e.target.value)} />;
break;
case "datetime":
input = <input type="datetime-local" value={value} onChange={(e) => set(e.target.value)} />;
break;
case "checkbox":
input = <input type="checkbox" checked={value === "true"} onChange={(e) => set(String(e.target.checked))} />;
break;
case "text":
input = <input value={value} onChange={(e) => set(e.target.value)} placeholder={field.type.kind === "duration" ? "for example 1d 4h" : ""} />;
break;
default:
input = <span className="muted">Not editable here ({field.type.kind}); set it in the work item form.</span>;
}
return (
<label key={field.id} className="row">
<span className="field-name">{field.label}</span>
{input}
</label>
);
})}
</div>
);
}
import { useState } from "react";
import type { PolarionContext } from "polarion-app-sdk";
import { restFetch } from "../polarion";
import type { ActionState } from "../types";
interface Props {
context: PolarionContext;
}
function escapeHtml(text: string): string {
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
}
/** Adds a comment through POST …/workitems/{id}/comments. Comment text is HTML. */
export default function CommentForm({ context }: Props) {
const [text, setText] = useState("");
const [state, setState] = useState<ActionState>({ kind: "idle" });
async function add() {
setState({ kind: "saving" });
try {
await restFetch(context, `/projects/${context.projectId}/workitems/${context.workItemId}/comments`, {
method: "POST",
body: JSON.stringify({
data: [
{
type: "workitem_comments",
attributes: { text: { type: "text/html", value: `<p>${escapeHtml(text)}</p>` } },
},
],
}),
});
setText("");
setState({ kind: "ok", text: "Comment added. Reload the page to see it in the Comments section." });
} catch (e) {
setState({ kind: "error", text: e instanceof Error ? e.message : String(e) });
}
}
return (
<>
<h2>Add comment</h2>
<textarea rows={3} value={text} onChange={(e) => setText(e.target.value)} placeholder="Comment text" />
<div className="row">
<button onClick={add} disabled={state.kind === "saving" || text.trim() === ""}>
{state.kind === "saving" ? "Saving…" : "Add comment"}
</button>
</div>
{state.kind === "ok" && <p className="ok">{state.text}</p>}
{state.kind === "error" && <p className="err">{state.text}</p>}
</>
);
}
Comments are a sub-resource of the work item. The text is HTML, so user input is escaped before it is wrapped in a paragraph.
Note
After any write, the Polarion form around the panel still shows the old values until the page is reloaded; the framework has no refresh call yet. The messages say so.
Build and deploy
cd examples/work-item-card
npm install
npm run package # → com.example.workitemcard.zip
Upload the ZIP, then add the applicationView element to a form layout. Open a work item that has links to see the full card.
Things to try
- Ask for
assigneein the field list and render it fromrelationships(see the Cookbook). - Replace the user select in
RequiredFields.tsxwith a search box that callsGET /users?query=name:…. - Add a Create follow-up task button that
POSTs a new work item and links it to the current one.
Examples
Project dashboard

| Aspect | Details |
|---|---|
| Folder | examples/project-dashboard |
| Identifier | com.example.dashboard |
| View | navigation topic dashboard with icon |
| Placement | <applicationView id="p-examples-project-dashboard-com.example.dashboard.dashboard"/> in the project's Topics configuration |
| Uses | fetchContext(), REST GET …/workitems?query=…&fields[workitems]=…,assignee&page[size]=100 |
Source: the project is in examples/project-dashboard/ of this kit.
What it does
- Fetches the context for
projectId. - Loads up to 100 work items with
id,title,status,type,createdand theassigneerelationship, optionally filtered by a Lucene query the user types. - Renders four tiles (items loaded, not resolved, distinct types, unassigned), three bar charts built from plain
<div>s (by status, by type, by assignee), and a table of the ten most recently created items with links. - Apply runs the typed query and Reset goes back to all work items; Refresh repeats the applied query, shows Refreshing… while it runs and the time of the last refresh afterwards.
Files
- project-dashboard/
- manifest.json
- public/
- icon30.png (navigation icon (30 × 30 px))
- src/
- App.tsx
- polarion.ts
- types.ts
- main.tsx
- styles.css
- …
manifest.json
{
"manifestVersion": "1.0",
"identifier": "com.example.dashboard",
"title": "Project dashboard",
"description": "A navigation topic that summarises the work items of the current project.",
"publisherName": "Example Publisher",
"applicationVersion": "0.2.1",
"views": {
"navigationTopics": [
{
"identifier": "dashboard",
"title": "Project dashboard",
"icon": "icon30.png",
"rootDirectory": "dashboard",
"document": "index.html"
}
]
}
}
src/types.ts
The assignee is a relationship, not an attribute. Asking for it in fields[workitems] makes the API include relationships.assignee.data, a list of user references.
/** Minimal JSON:API shapes used by this example. */
export interface WorkItemResource {
/** "PROJECT/WI-ID" */
id: string;
type: "workitems";
attributes: { title: string; status: string; type: string; created?: string };
/** Relationships are only present when requested through `fields[workitems]`. */
relationships?: {
assignee?: { data?: { id: string; type: "users" }[] };
};
}
export interface WorkItemListResponse {
data: WorkItemResource[];
meta?: { totalCount?: number };
}
src/App.tsx
import { useCallback, useEffect, useRef, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import { restFetch } from "./polarion";
import type { WorkItemListResponse, WorkItemResource } from "./types";
const CLOSED_STATUSES = new Set(["resolved", "done", "closed", "verified", "rejected"]);
/** First assignee id, or "unassigned". The relationship is absent when the field was not requested. */
function assigneeOf(item: WorkItemResource): string {
const data = item.relationships?.assignee?.data;
return data && data.length > 0 ? data[0].id : "unassigned";
}
function countBy(items: WorkItemResource[], key: (item: WorkItemResource) => string): [string, number][] {
const counts = new Map<string, number>();
for (const item of items) {
const k = key(item);
counts.set(k, (counts.get(k) ?? 0) + 1);
}
return [...counts.entries()].sort((a, b) => b[1] - a[1]);
}
/** A horizontal bar chart made of plain <div>s. */
function Bars({ title, data }: { title: string; data: [string, number][] }) {
const max = Math.max(1, ...data.map(([, n]) => n));
return (
<div className="panel">
<h2>{title}</h2>
{data.length === 0 && <p className="muted">No data.</p>}
{data.map(([label, n]) => (
<div className="bar-row" key={label}>
<span className="bar-label" title={label}>
{label}
</span>
<div className="bar-track">
<div className="bar" style={{ width: `${(n / max) * 100}%` }} />
</div>
<span className="bar-value">{n}</span>
</div>
))}
</div>
);
}
export default function App() {
const [context, setContext] = useState<PolarionContext | null>(null);
const [items, setItems] = useState<WorkItemResource[] | null>(null);
const [total, setTotal] = useState<number | undefined>(undefined);
const [query, setQuery] = useState("");
const [appliedQuery, setAppliedQuery] = useState("");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [loadedAt, setLoadedAt] = useState<Date | null>(null);
// Apply and Refresh can start a load while another one runs; only the latest may update the page.
const requestRef = useRef(0);
const load = useCallback(async (ctx: PolarionContext, lucene: string) => {
if (!ctx.projectId) {
setError("No project in context. This view is meant to be opened inside a project.");
return;
}
const params = new URLSearchParams({
"fields[workitems]": "id,title,status,type,created,assignee",
"page[size]": "100",
});
if (lucene.trim() !== "") {
params.set("query", lucene.trim());
}
const request = ++requestRef.current;
const isCurrent = () => request === requestRef.current;
setLoading(true);
try {
// `no-store` makes Refresh always reach the server instead of a cached response.
const response = await restFetch<WorkItemListResponse>(ctx, `/projects/${ctx.projectId}/workitems?${params}`, { cache: "no-store" });
if (!isCurrent()) return;
// The query counts as applied only once it has loaded, so a failed Apply never labels old data.
setAppliedQuery(lucene);
setItems(response.data);
setTotal(response.meta?.totalCount);
setLoadedAt(new Date());
setError(null);
} catch (error) {
if (!isCurrent()) return;
console.error("Unable to load the work items:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to load the work items: ${message}`);
} finally {
if (isCurrent()) setLoading(false);
}
}, []);
useEffect(() => {
let cancelled = false;
fetchContext()
.then((ctx) => {
if (cancelled) {
return;
}
setContext(ctx);
return load(ctx, "");
})
.catch((error: unknown) => {
if (cancelled) {
return;
}
console.error("Unable to fetch the Polarion context:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to fetch the Polarion context: ${message}`);
});
return () => {
// Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
cancelled = true;
destroy();
};
}, [load]);
function apply() {
if (!context) return;
void load(context, query);
}
/** Back to the initial state: no query, all work items of the project. */
function reset() {
if (!context) return;
setQuery("");
void load(context, "");
}
if (!context || !context.projectId) {
return error ? <div className="panel error">{error}</div> : <p className="muted">Loading work items…</p>;
}
if (!items && !error) {
return <p className="muted">Loading work items…</p>;
}
// After a failed query or request the dashboard stays mounted, so the user can
// correct the query or press Refresh; the error is shown inline below the query row.
const loaded = items ?? [];
const open = loaded.filter((i) => !CLOSED_STATUSES.has((i.attributes.status ?? "").toLowerCase())).length;
const types = new Set(loaded.map((i) => i.attributes.type)).size;
const unassigned = loaded.filter((i) => assigneeOf(i) === "unassigned").length;
const recent = [...loaded].sort((a, b) => (b.attributes.created ?? "").localeCompare(a.attributes.created ?? "")).slice(0, 10);
const origin = window.location.origin;
return (
<div className="page">
<header>
<h1>Project {context.projectId}</h1>
{/* Refresh repeats the applied query; the time below shows that it ran even when nothing changed. */}
<button onClick={() => load(context, appliedQuery)} disabled={loading}>
{loading ? "Refreshing…" : "Refresh"}
</button>
</header>
{/* Any Lucene query that works in the Work Items table works here too. */}
<div className="query-row">
<input value={query} onChange={(e) => setQuery(e.target.value)} onKeyDown={(e) => e.key === "Enter" && apply()} placeholder="Lucene query, for example: type:task AND NOT status:done" />
<button onClick={apply}>Apply</button>
<button onClick={reset} disabled={query === "" && appliedQuery === ""}>
Reset
</button>
</div>
{error && <div className="panel error">{error}</div>}
<p className="muted small">
{loaded.length} loaded{total !== undefined ? ` of ${total}` : ""}
{appliedQuery ? ` for "${appliedQuery}"` : ""} (first 100 shown)
{loadedAt ? `, refreshed at ${loadedAt.toLocaleTimeString()}` : ""}
</p>
<div className="tiles">
<div className="tile">
<span className="value">{loaded.length}</span>
<span className="label">work items loaded</span>
</div>
<div className="tile">
<span className="value">{open}</span>
<span className="label">not resolved</span>
</div>
<div className="tile">
<span className="value">{unassigned}</span>
<span className="label">unassigned</span>
</div>
<div className="tile">
<span className="value">{types}</span>
<span className="label">distinct types</span>
</div>
</div>
<div className="charts">
<Bars title="By status" data={countBy(loaded, (i) => i.attributes.status)} />
<Bars title="By type" data={countBy(loaded, (i) => i.attributes.type)} />
<Bars title="By assignee" data={countBy(loaded, assigneeOf)} />
</div>
<div className="panel">
<h2>Most recently created</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Type</th>
<th>Status</th>
<th>Assignee</th>
<th>Created</th>
</tr>
</thead>
<tbody>
{recent.map((item) => {
const [project, id] = item.id.split("/");
return (
<tr key={item.id}>
<td>
<a href={`${origin}/polarion/#/project/${project}/workitem?id=${id}`} target="_top">
{id}
</a>
</td>
<td>{item.attributes.title}</td>
<td>{item.attributes.type}</td>
<td>{item.attributes.status}</td>
<td>{assigneeOf(item)}</td>
<td>{item.attributes.created?.slice(0, 10)}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}
Points worth noting:
- The query box passes the Lucene syntax through.
type:requirement AND status:openworks exactly as in the Work Items table. - No chart library. The
Barscomponent scales widths relative to the largest value. For richer charts, bundle a library; do not load it from a CDN (Content Security Policy). - "Not resolved" is a heuristic. The set of closed status ids depends on the project's workflow; adapt
CLOSED_STATUSESor derive it from the status enumeration through REST. - Page size. For projects with more than 100 items, either page through
page[number]or move the aggregation into an endpoint; the dashboard shows "N loaded of total" so the user knows. - Only the latest request counts. Apply and Refresh can start a load while another one runs; a request number makes sure that an older response never overwrites a newer query. The query counts as applied only when it has loaded, so after a failed Apply the page keeps the previous data under its own query.
- Refresh must be visible. When nothing changed, a reload looks exactly like no reload. The button state and the refreshed at time show that the request ran, and
cache: "no-store"makes sure it reaches the server. - Links use
target="_top"so that clicking a row leaves the dashboard and opens the work item in Polarion.
Build and deploy
cd examples/project-dashboard
npm install
npm run package # → com.example.dashboard.zip
Upload the ZIP. In the project, open Administration → Portal → Topics, choose the View (Default), add the applicationView element among the topics, save, and reload the project. Project dashboard appears in the navigation panel.

Things to try
- Move the aggregation into a
statsendpoint that counts across all items on the server, and keep the REST list only for the table. - Resolve assignee ids to names with
include=assignee&fields[users]=name. - Show the data time stamp in the header and auto-refresh every minute.
Examples
Release checklist

| Aspect | Details |
|---|---|
| Folder | examples/release-checklist |
| Identifier | com.example.releasechecklist |
| View | sidebar checklist |
| Endpoints | POST validate, POST assign-to-me |
| Placement | none; choose Release checklist in the Show Sidebar menu |
| Uses | fetchContext(), selection-changed events, your own endpoints with a JSON array in the body, the tracker and security services on the server |
Source: the project is in examples/release-checklist/ of this kit.
This is the most complete example in the guide: a view that follows the user, and server-side capability that the REST API does not offer in one call. It shows the typical shape of a rich application: the sidebar is the experience, the endpoints are the capability.
What it does
- The sidebar fetches the context and subscribes to selection changes, debounced by 200 ms.
- For the selected ids it calls the application's own
validateendpoint with{ "objectId": "test/TEST-514", "objectIds": "[\"test/TEST-514\", …]" }:objectIdis mandatory on every call, and the list is JSON-encoded into a string because Polarion accepts only string values in a POST body. validate.jsruns on the server: it loads each work item, applies five rules (empty description, no assignee, no links, no priority, open for more than 90 days) and returns findings per item plus a summary. Fifty selected items are still one request. The endpoints accept at most 100 ids per call, so the view sends larger selections in chunks of 100 and merges the reports.- The sidebar renders a summary strip with a chip per finding code and one card per item.
- Assign unassigned to me calls the
assign-to-meendpoint with the ids that have theunassignedfinding.assign-to-me.jsadds the calling user as assignee and saves; the sidebar then re-validates.
Files
- release-checklist/
- manifest.json
- server-scripts/
- validate.js (POST validate)
- assign-to-me.js (POST assign-to-me)
- public/
- icon16.png
- icon32.png
- src/
- App.tsx
- polarion.ts (endpointFetch helper)
- types.ts (the endpoint contracts)
- main.tsx
- styles.css
- …
manifest.json
A sidebar view and two POST endpoints:
{
"manifestVersion": "1.0",
"identifier": "com.example.releasechecklist",
"title": "Release checklist",
"description": "A sidebar that checks the selected work items against release rules computed by the application's own server-side endpoints, and can assign items to the current user.",
"publisherName": "Example Publisher",
"applicationVersion": "0.2.2",
"views": {
"sidebars": [
{
"identifier": "checklist",
"title": "Release checklist",
"rootDirectory": "checklist",
"document": "index.html",
"menuIcon": "icon16.png",
"icon": "icon32.png"
}
]
},
"serverScripts": {
"endpoints": [
{
"urlPath": "validate",
"method": "POST",
"script": "validate.js"
},
{
"urlPath": "assign-to-me",
"method": "POST",
"script": "assign-to-me.js"
}
]
}
}
The contract
The request and response shapes are declared once, in TypeScript, and used by the view. Together with the README they are the documentation of the endpoints.
/** Shapes returned by the application's own endpoints (server-scripts/). */
export type FindingCode = "no-description" | "unassigned" | "no-links" | "missing-priority" | "open-too-long" | "not-found";
export interface Finding {
code: FindingCode;
message: string;
}
export interface ItemResult {
/** "PROJECT/WI-ID" */
id: string;
title: string;
status: string | null;
findings: Finding[];
}
/** POST validate */
export interface ValidateResult {
results: ItemResult[];
summary: {
items: number;
withFindings: number;
byCode: Partial<Record<FindingCode, number>>;
};
}
/** POST assign-to-me */
export interface AssignResult {
updated: string[];
failed: { id: string; error: string }[];
}
export const FINDING_LABELS: Record<FindingCode, string> = {
"no-description": "No description",
"unassigned": "Unassigned",
"no-links": "No links",
"missing-priority": "No priority",
"open-too-long": "Open > 90 days",
"not-found": "Not readable",
};
server-scripts/validate.js
// POST /polarion/apps/com.example.releasechecklist/rest/validate
// Body: { "objectId": "PROJECT/WI-ID", "objectIds": "[\"PROJECT/WI-ID\", …]" }
// objectId is mandatory on every endpoint call; the list travels as a JSON string
// because POST bodies accept string values only.
//
// Checks each work item against a few release rules on the server and returns
// the findings in one response. Runs as the logged-in user; items the user may
// not read come back with a `not-found` finding.
//
// Response (inside Polarion's { timestamp, success, data } envelope):
// { results: [ { id, title, status, findings: [ { code, message } ] } ],
// summary: { items, withFindings, byCode: { code: count } } }
const trackerService = context.scriptContext().services().tracker();
let result = {};
// Polarion's IArguments is the script-level `arguments`; inside a function the
// name refers to the function's own arguments, so capture it once at the top.
const scriptArguments = arguments;
const NINETY_DAYS_MS = 90 * 24 * 60 * 60 * 1000;
const RESOLVED_STATUSES = ['resolved', 'done', 'closed', 'verified', 'rejected'];
const MAX_OBJECT_IDS = 100;
const OBJECT_ID = /^[^/\s]+\/[^/\s]+$/;
/**
* Reads `objectIds`: a JSON array of "PROJECT/WI-ID" strings, sent as a string because POST bodies
* accept string values only. Returns [{ id, projectId, workItemId }]; throws on any other input.
*/
function readObjectIds() {
// getAsString throws "Argument objectIds is missing" when the view did not send it.
const raw = scriptArguments.getAsString('objectIds');
let list;
try {
list = JSON.parse(raw);
} catch (e) {
throw new Error('objectIds must be a JSON array of "PROJECT/WI-ID" strings');
}
if (!Array.isArray(list) || list.length === 0) {
throw new Error('objectIds must be a non-empty JSON array of "PROJECT/WI-ID" strings');
}
if (list.length > MAX_OBJECT_IDS) {
throw new Error('objectIds: at most ' + MAX_OBJECT_IDS + ' items per call');
}
return list.map(function (id) {
if (typeof id !== 'string' || !OBJECT_ID.test(id)) {
throw new Error('objectIds: expected "PROJECT/WI-ID", got ' + JSON.stringify(id));
}
const parts = id.split('/');
return { id: id, projectId: parts[0], workItemId: parts[1] };
});
}
function isEmptyText(text) {
if (text === null || text === undefined) return true;
const content = text.getContent ? text.getContent() : String(text);
return content === null || String(content).replace(/<[^>]*>/g, '').trim() === '';
}
function checkItem(wi) {
const findings = [];
const statusId = wi.getStatus() ? String(wi.getStatus().getId()).toLowerCase() : '';
if (isEmptyText(wi.getDescription())) {
findings.push({ code: 'no-description', message: 'The description is empty.' });
}
if (wi.getAssignees().isEmpty()) {
findings.push({ code: 'unassigned', message: 'Nobody is assigned.' });
}
const direct = wi.getLinkedWorkItemsStructsDirect().toArray();
const back = wi.getLinkedWorkItemsStructsBack().toArray();
if (direct.length === 0 && back.length === 0) {
findings.push({ code: 'no-links', message: 'The item has no links in either direction.' });
}
if (wi.getPriority() === null || wi.getPriority() === undefined) {
findings.push({ code: 'missing-priority', message: 'No priority is set.' });
}
const created = wi.getCreated();
if (created && RESOLVED_STATUSES.indexOf(statusId) === -1) {
const createdDate = new Date(created.getTime());
if (Date.now() - createdDate.getTime() > NINETY_DAYS_MS) {
findings.push({ code: 'open-too-long', message: 'Open for more than 90 days.' });
}
}
return findings;
}
try {
const ids = readObjectIds();
const results = [];
const byCode = {};
let withFindings = 0;
for (let i = 0; i < ids.length; i++) {
const entry = { id: ids[i].id, title: '', status: null, findings: [] };
try {
const wi = trackerService.getWorkItem(ids[i].projectId, ids[i].workItemId);
if (wi.isUnresolvable()) {
throw new Error('not found');
}
entry.title = wi.getTitle();
entry.status = wi.getStatus() ? wi.getStatus().getName() : null;
entry.findings = checkItem(wi);
} catch (e) {
entry.findings = [{ code: 'not-found', message: 'Could not read the work item: ' + e }];
}
if (entry.findings.length > 0) withFindings++;
for (let f = 0; f < entry.findings.length; f++) {
const code = entry.findings[f].code;
byCode[code] = (byCode[code] || 0) + 1;
}
results.push(entry);
}
result = {
results: results,
summary: { items: results.length, withFindings: withFindings, byCode: byCode },
};
} catch (e) {
// An `error` key turns the response into an error response for the caller.
result = { error: 'validate failed: ' + e };
}
result;
Points worth noting:
- Reading a list from the body. The view sends the list as a JSON string;
readObjectIds()reads it withscriptArguments.getAsString('objectIds')and accepts exactly one format: a JSON array of"PROJECT/WI-ID"strings, at most 100. Anything else (no array, an empty list, an id without the project) fails the whole call with a message that names the expected format, andreadObjectIds()returns the ids already split intoprojectIdandworkItemId, so the loop does not parse them again.scriptArgumentsis Polarion'sargumentscaptured at the top level, because inside a functionargumentsmeans something else. - Rules are small functions over
IWorkItem. Adding a rule means oneifblock and one finding code; the view only needs a label for the new code. - Per-item error handling. An item the user may not read, or an id that does not exist, becomes a
not-foundfinding instead of failing the whole request. - Summary computed on the server. The view renders
summary.byCodedirectly.
server-scripts/assign-to-me.js
// POST /polarion/apps/com.example.releasechecklist/rest/assign-to-me
// Body: { "objectId": "PROJECT/WI-ID", "objectIds": "[\"PROJECT/WI-ID\", …]" }
// objectId is mandatory on every endpoint call; the list travels as a JSON string
// because POST bodies accept string values only.
//
// Adds the calling user as assignee of every listed work item and saves.
// Runs as the logged-in user, who needs permission to modify the items.
//
// API calls to check against the javadoc of your Polarion version:
// ISecurityService.getCurrentUser() -> user id of the caller
// ITrackerService.getProjectsService() -> IProjectService
// IProjectService.getUser(String) -> IUser
// IWorkItem.getAssignees(), addAssignee(IUser), save()
//
// Response: { updated: [ids], failed: [ { id, error } ] }
const services = context.scriptContext().services();
const trackerService = services.tracker();
const securityService = services.security();
let result = {};
// Polarion's IArguments is the script-level `arguments`; inside a function the
// name refers to the function's own arguments, so capture it once at the top.
const scriptArguments = arguments;
const MAX_OBJECT_IDS = 100;
const OBJECT_ID = /^[^/\s]+\/[^/\s]+$/;
/**
* Reads `objectIds`: a JSON array of "PROJECT/WI-ID" strings, sent as a string because POST bodies
* accept string values only. Returns [{ id, projectId, workItemId }]; throws on any other input.
*/
function readObjectIds() {
// getAsString throws "Argument objectIds is missing" when the view did not send it.
const raw = scriptArguments.getAsString('objectIds');
let list;
try {
list = JSON.parse(raw);
} catch (e) {
throw new Error('objectIds must be a JSON array of "PROJECT/WI-ID" strings');
}
if (!Array.isArray(list) || list.length === 0) {
throw new Error('objectIds must be a non-empty JSON array of "PROJECT/WI-ID" strings');
}
if (list.length > MAX_OBJECT_IDS) {
throw new Error('objectIds: at most ' + MAX_OBJECT_IDS + ' items per call');
}
return list.map(function (id) {
if (typeof id !== 'string' || !OBJECT_ID.test(id)) {
throw new Error('objectIds: expected "PROJECT/WI-ID", got ' + JSON.stringify(id));
}
const parts = id.split('/');
return { id: id, projectId: parts[0], workItemId: parts[1] };
});
}
try {
const ids = readObjectIds();
const userId = securityService.getCurrentUser();
const user = trackerService.getProjectsService().getUser(userId);
if (!user || user.isUnresolvable()) {
throw new Error('Current user not found: ' + userId);
}
const updated = [];
const failed = [];
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
try {
const wi = trackerService.getWorkItem(id.projectId, id.workItemId);
if (wi.isUnresolvable()) throw new Error('not found');
let already = false;
const assignees = wi.getAssignees().toArray();
for (let a = 0; a < assignees.length; a++) {
if (String(assignees[a].getId()) === String(userId)) already = true;
}
if (!already) {
wi.addAssignee(user);
wi.save();
}
updated.push(id.id);
} catch (e) {
failed.push({ id: id.id, error: String(e) });
}
}
result = { updated: updated, failed: failed };
} catch (e) {
result = { error: 'assign-to-me failed: ' + e };
}
result;
The write endpoint resolves the calling user through the security service, loops over the items, saves each, and reports updated and failed lists rather than aborting on the first error.
Note
The comment at the top of the script lists the Java API calls it relies on. All of them were exercised against a Polarion 2612 server; verify them against the javadoc when your version differs.
src/App.tsx
import { useCallback, useEffect, useRef, useState } from "react";
import { destroy, events, EventTypes, fetchContext, type PolarionContext, type SelectionChangedData } from "polarion-app-sdk";
import { endpointFetch } from "./polarion";
import { FINDING_LABELS, type AssignResult, type FindingCode, type ItemResult, type ValidateResult } from "./types";
/** Selection ids may arrive as "WI-1" or "PROJECT/WI-1"; the endpoints expect "PROJECT/WI-1". */
function fullId(projectId: string, id: string): string {
return id.includes("/") ? id : `${projectId}/${id}`;
}
// The endpoints accept at most 100 ids per call (MAX_OBJECT_IDS in the server scripts),
// while the table can select more. Larger selections are sent in chunks of 100.
const MAX_IDS_PER_CALL = 100;
function chunk<T>(list: T[]): T[][] {
const parts: T[][] = [];
for (let i = 0; i < list.length; i += MAX_IDS_PER_CALL) parts.push(list.slice(i, i + MAX_IDS_PER_CALL));
return parts;
}
/** Joins the reports of several validate calls into one. */
function mergeReports(parts: ValidateResult[]): ValidateResult {
const byCode: ValidateResult["summary"]["byCode"] = {};
for (const part of parts) {
for (const [code, n] of Object.entries(part.summary.byCode) as [FindingCode, number][]) {
byCode[code] = (byCode[code] ?? 0) + n;
}
}
return {
results: parts.flatMap((p) => p.results),
summary: {
items: parts.reduce((sum, p) => sum + p.summary.items, 0),
withFindings: parts.reduce((sum, p) => sum + p.summary.withFindings, 0),
byCode,
},
};
}
function itemUrl(id: string): string {
const [project, wi] = id.split("/");
return `${window.location.origin}/polarion/#/project/${project}/workitem?id=${wi}`;
}
function ItemCard({ item }: { item: ItemResult }) {
const wiId = item.id.split("/")[1] ?? item.id;
return (
<div className={`box item${item.findings.length === 0 ? " clean" : ""}`}>
<div className="item-head">
<a href={itemUrl(item.id)} target="_top">
{wiId}
</a>
{item.status && <span className="chip status">{item.status}</span>}
</div>
<div className="item-title">{item.title || <span className="muted">(no title)</span>}</div>
{item.findings.length === 0 ? (
<div className="finding ok">✓ Ready for release</div>
) : (
<ul className="findings">
{item.findings.map((f) => (
<li key={f.code} className={`finding code-${f.code}`}>
<span className="chip warn">{FINDING_LABELS[f.code] ?? f.code}</span> {f.message}
</li>
))}
</ul>
)}
</div>
);
}
export default function App() {
const [context, setContext] = useState<PolarionContext | null>(null);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [report, setReport] = useState<ValidateResult | null>(null);
const [busy, setBusy] = useState<"idle" | "checking" | "assigning">("idle");
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
// 1. Context (initial selection) and 2. selection events.
useEffect(() => {
let cancelled = false;
fetchContext()
.then((ctx) => {
if (cancelled) {
return;
}
setContext(ctx);
setSelectedIds(ctx.selectedWorkItemIds ?? []);
})
.catch((error: unknown) => {
if (cancelled) {
return;
}
console.error("Unable to fetch the Polarion context:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to fetch the Polarion context: ${message}`);
});
const unsubscribe = events.subscribe<SelectionChangedData>(EventTypes.SELECTION_CHANGED, (data) => {
setSelectedIds(data.selectedWorkItemIds ?? []);
});
return () => {
// Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
cancelled = true;
// Remove the subscription and release the message listener.
unsubscribe();
destroy();
};
}, []);
// 3. Ask our own endpoint to validate the selected items.
const validate = useCallback(async (ctx: PolarionContext, ids: string[], isCurrent: () => boolean = () => true) => {
if (!ctx.projectId || ids.length === 0) {
setReport(null);
return;
}
setBusy("checking");
setError(null);
try {
const objectIds = ids.map((id) => fullId(ctx.projectId!, id));
// `objectId` is required by Polarion on every endpoint call; the list travels
// in `objectIds` as a JSON string (POST bodies accept string values only).
const parts = await Promise.all(
chunk(objectIds).map((part) =>
endpointFetch<ValidateResult>(ctx, "/validate", {
method: "POST",
body: JSON.stringify({ objectId: part[0], objectIds: JSON.stringify(part) }),
}),
),
);
if (isCurrent()) setReport(mergeReports(parts));
} catch (error) {
if (!isCurrent()) return;
console.error("Unable to validate the selection:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to validate the selection: ${message}`);
} finally {
if (isCurrent()) setBusy("idle");
}
}, []);
// Debounce: wait until the selection has been stable for 200 ms. A request
// that is still running when the selection changes again is ignored on return.
// The old report is dropped at once, so its "Assign" button cannot act on the
// previous selection while the new one is being validated.
const requestRef = useRef(0);
const recheck = useCallback(
(ctx: PolarionContext, ids: string[]) => {
const request = ++requestRef.current;
return validate(ctx, ids, () => request === requestRef.current);
},
[validate],
);
// Counts selection changes, so work started for one selection can tell that it is outdated.
const selectionRef = useRef(0);
useEffect(() => {
if (!context) return;
++selectionRef.current;
++requestRef.current;
setReport(null);
setNotice(null);
const timer = setTimeout(() => void recheck(context, selectedIds), 200);
return () => clearTimeout(timer);
}, [context, selectedIds, recheck]);
async function assignToMe() {
if (!context || !report) return;
const ids = report.results.filter((r) => r.findings.some((f) => f.code === "unassigned")).map((r) => r.id);
if (ids.length === 0) return;
const selection = selectionRef.current;
setBusy("assigning");
setNotice(null);
setError(null);
try {
const parts = await Promise.all(
chunk(ids).map((part) =>
endpointFetch<AssignResult>(context, "/assign-to-me", {
method: "POST",
body: JSON.stringify({ objectId: part[0], objectIds: JSON.stringify(part) }),
}),
),
);
const updated = parts.flatMap((p) => p.updated);
const failed = parts.flatMap((p) => p.failed);
setNotice(`${updated.length} item(s) assigned to you` + (failed.length ? `, ${failed.length} failed: ${failed[0].error}` : "."));
// Re-validate only if the selection is still the one that was assigned; otherwise the
// new selection's own validation owns the report.
if (selection === selectionRef.current) await recheck(context, selectedIds);
} catch (error) {
console.error("Unable to assign the work items:", error);
const message = error instanceof Error ? error.message : String(error);
setError(`Unable to assign the work items: ${message}`);
} finally {
setBusy("idle");
}
}
if (!context && !error) {
return <p className="muted">Waiting for the Polarion context…</p>;
}
const unassignedCount = report?.summary.byCode.unassigned ?? 0;
const codes = report ? (Object.keys(report.summary.byCode) as FindingCode[]) : [];
return (
<div>
<p className="headline">Release checklist</p>
{error && <div className="box error">{error}</div>}
{selectedIds.length === 0 ? (
<div className="box hint">Select one or more work items in the table to check them.</div>
) : (
<>
<div className="box summary">
<div className="summary-line">{busy === "checking" ? "Checking…" : report ? `${report.summary.items} checked, ${report.summary.withFindings} with findings` : `${selectedIds.length} selected`}</div>
{codes.length > 0 && (
<div className="chips">
{codes.map((code) => (
<span key={code} className="chip warn">
{FINDING_LABELS[code] ?? code}: {report!.summary.byCode[code]}
</span>
))}
</div>
)}
<div className="actions">
<button onClick={() => context && recheck(context, selectedIds)} disabled={busy !== "idle"}>
Re-check
</button>
<button onClick={assignToMe} disabled={busy !== "idle" || unassignedCount === 0}>
{busy === "assigning" ? "Assigning…" : `Assign unassigned to me (${unassignedCount})`}
</button>
</div>
{notice && <div className="muted small">{notice}</div>}
</div>
{report?.results.map((item) => (
<ItemCard key={item.id} item={item} />
))}
</>
)}
</div>
);
}
Points worth noting:
- Same event pattern as the selection sidebar, plus a debounce effect so that keyboard navigation through the table does not fire a request per row.
- The endpoint shapes the UI. No JSON:API assembly in the view;
report.resultsandreport.summaryare rendered as they arrive. - A report belongs to one selection. When the selection changes, the old report is dropped at once and any validation still running is ignored on return, so Assign unassigned to me never acts on items that are no longer selected.
- Writes go through an endpoint too. One request per 100 items assigns all unassigned items and returns a result the view can explain.
Build and deploy
cd examples/release-checklist
npm install
npm run package # → com.example.releasechecklist.zip (with server-scripts/)
Upload the ZIP. Open a project's Work Items table, click Show Sidebar and choose Release checklist. Select a few items; the findings appear after a moment.
Things to try
- Add a rule
no-testsfor requirements without averifiesback link, and a label for it inFINDING_LABELS. - Replace the fixed 90-day threshold with a
maxAgeDaysparameter sent by the view. - Add a Set priority to Medium action with a third endpoint, and compare with doing the same through the REST API (
PATCH attributes.priority) from the view.
Reference
manifest.json
manifest.json sits at the root of the application folder inside the ZIP. Polarion reads it during upload and whenever it needs to serve or place a view.
Complete example
{
"manifestVersion": "1.0",
"identifier": "com.example.inspector",
"title": "Work item inspector",
"description": "Shows details and links of the selected work items.",
"publisherName": "Example Publisher",
"applicationVersion": "1.2.0",
"views": {
"formExtensions": [
{
"identifier": "card",
"title": "Inspector",
"rootDirectory": "card",
"document": "index.html"
}
],
"sidebars": [
{
"identifier": "sidebar",
"title": "Inspector",
"rootDirectory": "sidebar",
"document": "index.html",
"menuIcon": "icon16.png",
"icon": "icon32.png"
}
],
"navigationTopics": [
{
"identifier": "overview",
"title": "Inspector overview",
"icon": "icon30.png",
"rootDirectory": "overview",
"document": "index.html"
}
]
},
"serverScripts": {
"endpoints": [
{ "urlPath": "linked-tree", "method": "GET", "script": "linked-tree.js" },
{ "urlPath": "add-comment", "method": "POST", "script": "add-comment.js" }
]
}
}
Top-level fields
| Field | Type | Required | Description |
|---|---|---|---|
manifestVersion |
string | yes | Version of the manifest format. "1.0" in Polarion 2612. |
identifier |
string | yes | Unique identifier of the application on the server. Must equal the name of the top-level folder in the ZIP. Used in URLs (/polarion/apps/<identifier>/) and as the prefix of every configuration id. Reverse-DNS style recommended. |
title |
string | yes | Human-readable name. Shown on the Applications tile, in the upload dialog and in Properties. |
description |
string | no | Longer text. Shown as the tile tooltip and in Properties. |
publisherName |
string | yes | Organization or team that publishes the application. Shown in the upload dialog and in Properties as Publisher. |
applicationVersion |
string | yes | Free-form version string. Shown in the upload dialog (and compared visually with the installed version on update) and in Properties. Not parsed. |
views |
object | yes | The views of the application. See below. At least one view is expected. |
serverScripts |
object | no | Endpoints backed by server scripts. See below. |
views
views is an object with up to three arrays. Each array may be empty or omitted.
| Key | View type | Placed by |
|---|---|---|
formExtensions |
Panel in the Work Item form | <applicationView> in the form layout |
sidebars |
Sidebar next to the Work Items table and in Documents | Nothing; listed in Show Sidebar automatically |
navigationTopics |
Page in the project navigation | <applicationView> in the Topics configuration |
Common view fields
| Field | Type | Required | Description |
|---|---|---|---|
identifier |
string | yes | Id of the view, unique within the application. Combined with the application identifier into the configuration id <identifier>.<viewId> and the view URL /polarion/apps/<identifier>/views/<viewId>. |
title |
string | yes | Display name. Used as the menu label for sidebars and the navigation label for topics. For form extensions the panel heading comes from the layout's label attribute instead. |
rootDirectory |
string | yes | Folder inside the application folder that holds the view's files. One path segment, no slashes. Several views may share one folder (verified on Polarion 2612); the Application context example serves a form extension, a sidebar and a navigation topic from one. |
document |
string | yes | Entry file inside rootDirectory, usually index.html. |
Additional fields per view type
| Field | Applies to | Description |
|---|---|---|
menuIcon |
sidebars |
16 × 16 px image shown in the Show Sidebar menu. Path relative to rootDirectory. |
icon |
sidebars, navigationTopics |
Image shown in the sidebar header (32 × 32 px) or the navigation panel (30 × 30 px, like Polarion's own topic icons). Path relative to rootDirectory. Accepted on formExtensions but apparently not displayed in 2612. |
serverScripts.endpoints
An array of endpoint definitions. Each endpoint maps an HTTP method and path to a script file.
| Field | Type | Required | Description |
|---|---|---|---|
urlPath |
string | yes | Last path segment of the endpoint URL: /polarion/apps/<identifier>/rest/<urlPath>. Letters, digits and hyphens. Unique per method. |
method |
"GET" | "POST" |
yes | HTTP method the endpoint accepts. GET reads parameters from the query string; POST from a JSON body. |
script |
string | yes | File name inside server-scripts/. |
The runtime available to scripts is described in Server script runtime.
Validation rules
identifier,title,publisherName,applicationVersionand every viewidentifiermust be non-empty.- Every
rootDirectorymust exist in the package and containdocument. - Every
scriptmust exist inserver-scripts/. - The top-level folder name must equal
identifier. - The file must be strict JSON (no comments, no trailing commas).
Violations are reported in the upload dialog as Application validation failed with a message, or as Application's zip structure is incorrect for layout problems.
Minimal manifest
{
"manifestVersion": "1.0",
"identifier": "com.example.hello",
"title": "Hello Polarion",
"publisherName": "Example Publisher",
"applicationVersion": "0.1.0",
"views": {
"formExtensions": [
{ "identifier": "hello", "title": "Hello Polarion", "rootDirectory": "hello", "document": "index.html" }
]
}
}
Reference
SDK API
Package: polarion-app-sdk, version 0.5.2-preview. Entry module HostBridge (ESM and CommonJS). No runtime dependencies. Browser only; it uses window.parent.postMessage.
import {
fetchContext,
events,
destroy,
EventTypes,
type PolarionContext,
type SelectionChangedData,
} from 'polarion-app-sdk';
fetchContext()
function fetchContext(): Promise<PolarionContext>
Requests the current context from the Polarion host page.
- Creates the internal gateway on first use (or after
destroy()). - Resolves with a
PolarionContext. - Rejects with
Error('Timeout waiting for response to get-context')after five seconds without an answer, and withError('Invalid context received')if the answer does not containapplicationIdandviewId. A call made whiledestroy()is tearing down a previous instance is rejected withError('ApplicationGateway is destroyed, pending request cancelled.'). - May be called any number of times; each call is a separate round trip and returns the state at that moment.
events.subscribe()
events.subscribe<T = unknown>(
eventName: EventType,
callback: (data: T) => void,
): () => void
Registers callback for an event emitted by the host and returns a function that removes the registration.
eventName: a value ofEventTypes. In 0.5.2-preview the only value isEventTypes.SELECTION_CHANGED("selection-changed").callbackreceives the event payload. ForSELECTION_CHANGEDthe payload isSelectionChangedData; pass it as the type parameter.- Throws
Error('Already subscribed to event: <name>')when a subscription for that event already exists. Unsubscribe first. - The returned function is idempotent; calling it twice is harmless.
const unsubscribe = events.subscribe<SelectionChangedData>(
EventTypes.SELECTION_CHANGED,
({ selectedWorkItemIds }) => update(selectedWorkItemIds),
);
destroy()
function destroy(): void
Tears down the gateway: removes the message listener, rejects pending fetchContext() promises with Error('ApplicationGateway is destroyed, pending request cancelled.'), sends an unsubscribe for every active subscription, and clears them. Safe to call when nothing was created. The next fetchContext() or events.subscribe() creates a new instance.
Call it from the unmount hook of your framework.
EventTypes
const EventTypes = {
SELECTION_CHANGED: 'selection-changed',
} as const;
type EventType = typeof EventTypes[keyof typeof EventTypes];
Types
PolarionContext
interface PolarionContext {
applicationId: string;
viewId: string;
projectId?: string;
spaceId?: string;
documentId?: string;
workItemId?: string;
selectedWorkItemIds: string[];
appEndpoint: string;
restBaseUrl: string;
restToken?: string;
}
Described field by field in PolarionContext.
SelectionChangedData
interface SelectionChangedData {
selectedWorkItemIds: string[];
}
Work item ids with the project ("test/TEST-514"), observed on Polarion 2612 in the Work Items table and in Documents. Empty array when nothing is selected.
Behavior notes
- Origin check: the SDK posts to and accepts messages only from
window.location.origin. Messages from other origins are ignored with a console warning. - Single instance per page: the module keeps one gateway. Several components in the same view share it; only one of them may subscribe to a given event.
- Console output: the SDK logs warnings for unexpected messages (
Received message from unknown origin…,No pending request found…). They are harmless in Polarion but worth investigating if they appear repeatedly. - Timeouts: fixed at 5 s and not configurable.
Internal modules (not public API)
ApplicationGateway, Constants (Actions, MessageTypes) and the protocol types in types/ApplicationGatewayProtocol describe the postMessage protocol (polarion-view-bridge, polarion-view-bridge-result, polarion-view-bridge-event). They are exported as type declarations for transparency but may change without notice. Do not post these messages yourself.
Reference
PolarionContext
The object returned by fetchContext(), field by field.
interface PolarionContext {
applicationId: string;
viewId: string;
projectId?: string;
spaceId?: string;
documentId?: string;
workItemId?: string;
selectedWorkItemIds: string[];
appEndpoint: string;
restBaseUrl: string;
restToken?: string;
}
Fields
applicationId
The identifier from the manifest of the application that owns the view. Always set.
viewId
The identifier of the view (from views.*[].identifier). Always set. Together with applicationId it tells a shared code base which view is running.
projectId
Id of the project the view is shown in, for example "test". Set for all view types inside a project. Undefined only in places without a project context (none of the three view types in 2612 are placed outside a project).
spaceId, documentId
Space and name of the Document, set (according to the SDK documentation) when the view is shown inside a Document: a sidebar opened in the Document editor, or a form extension in a work item form opened from a Document. Undefined elsewhere. Use them to build the REST URL …/projects/{projectId}/spaces/{spaceId}/documents/{documentId}.
workItemId
Project-local id of the work item whose form contains the view, for example "TEST-514". Set for form extensions. Undefined for sidebars and navigation topics, and in the create form of a work item that is not saved yet.
selectedWorkItemIds
Array of work item ids with the project, for example "test/TEST-514". Always present, possibly empty.
| View type | Content |
|---|---|
| Form extension | The open work item, ["<projectId>/<workItemId>"]. In the multi-item edit form below the Work Items table: all ticked items, while workItemId is the current one. |
| Sidebar | Empty on Polarion 2612, even when rows are selected. The selection arrives through selection-changed events. |
| Navigation topic | Empty. |
appEndpoint
Absolute base URL of the application's server-script endpoints, without trailing slash:
https://<host>/polarion/apps/<applicationId>/rest
Append /<urlPath> for each endpoint declared in the manifest. Set even when the application declares no endpoints.
restBaseUrl
Absolute base URL of the Polarion REST API, without trailing slash:
https://<host>/polarion/rest/v1
restToken
Token that authenticates REST and endpoint calls as the current user. Send it in the required X-Polarion-REST-Token header on every REST and endpoint call. Application endpoints cannot authenticate through the browser session or cookies. Undefined or empty when the server has not enabled REST token authentication (com.siemens.polarion.rest.security.restApiToken.enabled). Treat it as a credential: memory only, same origin only.
Example values
Form extension on a Task:
{
"applicationId": "com.example.context",
"viewId": "form",
"projectId": "test",
"workItemId": "TEST-514",
"selectedWorkItemIds": ["test/TEST-514"],
"appEndpoint": "https://polarion.example.com/polarion/apps/com.example.context/rest",
"restBaseUrl": "https://polarion.example.com/polarion/rest/v1",
"restToken": "UE9M…"
}
Sidebar in the Work Items table with two rows selected (the selection comes through events, not here):
{
"applicationId": "com.example.selectionsidebar",
"viewId": "selection",
"projectId": "test",
"selectedWorkItemIds": [],
"appEndpoint": "https://polarion.example.com/polarion/apps/com.example.selectionsidebar/rest",
"restBaseUrl": "https://polarion.example.com/polarion/rest/v1",
"restToken": "UE9M…"
}
Navigation topic:
{
"applicationId": "com.example.dashboard",
"viewId": "dashboard",
"projectId": "test",
"selectedWorkItemIds": [],
"appEndpoint": "https://polarion.example.com/polarion/apps/com.example.dashboard/rest",
"restBaseUrl": "https://polarion.example.com/polarion/rest/v1",
"restToken": "UE9M…"
}
Validation performed by the SDK
fetchContext() only checks that applicationId and viewId are strings. All other fields are passed through as delivered by the host. Code defensively against undefined optional fields.
Reference
Endpoint runtime
This page describes the environment a server script runs in. Observed behavior on Polarion 2612 is stated as fact; details marked as expected should be checked against your server.
Request mapping
| GET endpoint | POST endpoint | |
|---|---|---|
| URL | /polarion/apps/<identifier>/rest/<urlPath>?a=1&b=2 |
/polarion/apps/<identifier>/rest/<urlPath> |
| Parameters | Query string | Flat JSON object with string values in the request body; Content-Type: application/json required. Arrays or objects as values are rejected with HTTP 500 (Expected a string but was BEGIN_ARRAY). |
| Reading a parameter | arguments.getAsString('a') |
arguments.getAsString('a') |
| Authentication | Valid X-Polarion-REST-Token header required; sessions and cookies do not authenticate endpoint calls |
Same requirement |
| Intended for | Reads | Writes and anything with side effects |
A POST without a JSON content type or without a parseable body is expected to be rejected with HTTP 400 before the script runs. Parameters sent in the query string of a POST are not visible to the script.
objectId is mandatory on every call (GET or POST). Without it Polarion answers HTTP 400 Argument objectId is missing in workflow definition before the script runs. Use PROJECT/WI-ID of the object the call concerns, or a project id.
Globals
context
Entry point to the Polarion scripting API.
| Expression | Returns |
|---|---|
context.scriptContext() |
IScriptContext |
context.scriptContext().services() |
IScriptServices: tracker(), security(), project(), … |
context.scriptContext().utils() |
IScriptUtils: httpClient(), … |
services().tracker() is ITrackerService, the usual way to reach work items:
const trackerService = context.scriptContext().services().tracker();
const wi = trackerService.getWorkItem(projectId, workItemId); // IWorkItem
const project = trackerService.getTrackerProject(projectId); // ITrackerProject
services().security() is ISecurityService; see the javadoc for the accessor of the current user.
arguments
Polarion's IArguments object with the request parameters, available under the name arguments at the top level of the script. Inside a function the name refers to the function's own arguments object, so capture it first: const scriptArguments = arguments;.
| Method | Description |
|---|---|
getAsString(name) |
The parameter as a string. Throws Argument name is missing in workflow definition when the parameter was not sent; the call then fails with HTTP 400. Wrap reads of optional parameters in try/catch. |
getAsString(name, default) |
Variant with a default value, as listed for IArguments in the scripting API; check the javadoc of your version. The examples use a guarded helper instead. |
getAsInt(name), getAsBoolean(name), … |
Typed variants as documented for IArguments in the scripting API. |
Structured input must be sent as a JSON-encoded string and parsed with JSON.parse.
Java
GraalVM's interop object. Java.type('fully.qualified.Name') loads a Polarion or JDK class:
const Text = Java.type('com.polarion.core.util.types.Text');
const comment = wi.createComment(Text.plain('Reviewed.'), 'My app', null);
Working with Java objects
- Java collections (
Collection,List) are easiest to iterate after.toArray(); the resulting Java array is indexable with[i]and has.length. - Java strings behave like JavaScript strings for comparison and concatenation.
nullfrom Java isnullin JavaScript; check for it before calling methods (wi.getType() ? wi.getType().getName() : null).- Unresolvable objects (for example a work item id that does not exist) are returned as placeholder objects; check
isUnresolvable().
Result and envelope
The script's last expression is the result. It must be a plain JavaScript object, array or primitive that can be serialized to JSON. Polarion wraps it:
{ "timestamp": "2026-10-05T10:15:42.945Z", "success": true, "data": <result> }
If the result object contains a non-empty error property, or the script throws, the envelope becomes:
{ "timestamp": "…", "success": false, "error": "<message>" }
A successful script returns HTTP 200. A script that returned { error }, threw, or read a missing parameter returns HTTP 400 with the envelope; a body with non-string values returns HTTP 500. The table below summarizes what was observed on Polarion 2612.
| HTTP status | Body | Cause |
|---|---|---|
| 200 | { timestamp, success: true, data } |
Script completed |
| 400 | { timestamp, success: false, error } |
Script returned an error key or threw |
| 400 | { error: "Argument objectId is missing in workflow definition." } |
objectId not sent, or arguments.getAsString() on an absent parameter |
| 500 | { error: "… Expected a string but was BEGIN_ARRAY …" } |
POST body contains an array or object value |
| 401 | REST error document | Missing, invalid or expired X-Polarion-REST-Token, even if a Polarion session exists |
| 404 | HTML or error document | Unknown urlPath, wrong method, application not installed |
Permissions and transactions
- The script runs as the user identified by the required REST token. All Polarion permission checks apply.
- Writes must call
save()on the modified or created object:wi.save()for field and assignee changes,comment.save()for a new comment. Several objects can be saved in one script; there is no explicit transaction API. - Fields are changed with the setters of
IWorkItem, for examplewi.setTitle('New title')orwi.setDescription(Text.html('<p>New text</p>'));Text.plain(…)creates plain text. Rich text is not escaped for you. Verified on Polarion 2612 with an endpoint that writes the description. - The open work item form does not show a change made by an endpoint until the page is reloaded; a view cannot trigger that reload.
- Treat GET endpoints as read-only and keep saves in POST endpoints; whether a save in a GET script is rejected was not verified for 2612.
Logging
console.log() output is expected in the Polarion server log. Keep it sparse; the log is shared by the whole server.
Limits
- A script runs for the duration of the request; long-running scripts keep the caller waiting. Keep work per call small or paginate.
- There is no state between calls. Cache in the view, or persist in Polarion objects.
- The script file is read from the uploaded package; re-upload to change it.
Further reading
- Polarion Scripting Guide in your server's Help (Administrator and User Help → Polarion Scripting Guide).
https://<polarion-host>/polarion/sdk/doc/scripting-api/forIScriptContext,IScriptServices,IArguments.https://<polarion-host>/polarion/sdk/doc/javadoc/for the Java API (com.polarion.alm.tracker.model.IWorkItemand friends).
Reference
View configuration XML
Form extensions and navigation topics are placed with the applicationView element in Polarion's configuration XML. Sidebars need no XML.
Form layout (formLayout)
Location: Project Administration → Work Items → Form Configuration → Form Layouts → Edit (per work item type and Polarion View). Repository-level defaults: Global Administration → Work Items → Form Configuration.
<applicationView id="com.example.workitemcard.card" label="Work item card" height="640px"/>
| Attribute | Required | Description |
|---|---|---|
id |
yes | <application identifier>.<view identifier> of a formExtensions view |
label |
no | Heading of the panel. Default Polarion Application. |
height |
no | CSS height of the iframe (320px, 50vh). |
Placement: a direct child of <formLayout>, in document order with <field>, <horizontal>, <vertical> and <extension> elements. Not allowed inside <section> or <panel>.
Full example:
<?xml version="1.0" encoding="UTF-8"?>
<formLayout xmlns="http://polarion.com/schema/WorkItems/FormLayout"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://polarion.com/schema/WorkItems/FormLayout">
<horizontal>
<vertical>
<section>
<field id="type"/>
<field id="severity"/>
<field id="author"/>
</section>
</vertical>
<vertical>
<section>
<field id="assignee"/>
<field id="priority"/>
<field id="status"/>
</section>
</vertical>
</horizontal>
<applicationView id="com.example.workitemcard.card" label="Work item card" height="640px"/>
<field id="description"/>
<applicationView id="com.example.traceability.tree" label="Traceability" height="480px"/>
<field id="comments"/>
<field id="linkedWorkItems"/>
<field id="attachments"/>
</formLayout>
Topics configuration (topics)
Location: Project Administration → Portal → Topics → (View). Repository-level defaults: Global Administration → Portal → Topics.
<applicationView id="com.example.dashboard.dashboard"/>
| Attribute | Required | Description |
|---|---|---|
id |
yes | <application identifier>.<view identifier> of a navigationTopics view |
Placement: a direct child of <topics>, among <topic> elements. Order determines the position in the navigation panel.
<?xml version="1.0" encoding="UTF-8"?>
<topics xmlns="http://polarion.com/schema/Portal/Topics"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://polarion.com/schema/Portal/Topics">
<topic id="workitems"/>
<topic id="wiki"/>
<topic id="plans"/>
<topic id="testruns"/>
<topic id="collections"/>
<topic id="baselines"/>
<topic id="builds"/>
<topic id="reports"/>
<topic id="monitor"/>
<applicationView id="com.example.dashboard.dashboard"/>
<topic id="global_shortcuts"/>
<topic id="project_shortcuts"/>
<topic id="user_shortcuts"/>
</topics>
Sidebars
No XML. The sidebar is opened from the Show Sidebar menu and remembered in the page URL:
?sidebar=polarion-application.<application identifier>.<view identifier>
Example: /polarion/#/project/test/workitems?sidebar=polarion-application.com.example.selectionsidebar.selection
Validation
Polarion does not appear to validate the referenced application or view when saving the XML; a wrong id results in an empty or failing panel. Check Global Administration → Applications → Properties for the installed identifier and the manifest for the view identifier when a panel does not appear.
Reference
Configuration properties
The properties below control the Applications feature and the REST authentication that views depend on.
| Property | Where | Restart | Effect |
|---|---|---|---|
polarionapp.enabled |
Global Administration → Configuration Properties (global configuration property, not a polarion.properties entry) |
no | true enables the Applications feature: the Applications topic in Global Administration, serving of /polarion/apps/…, and the host bridge in the UI. Default false. |
com.siemens.polarion.rest.enabled |
polarion.properties |
yes | Enables the REST API. Required for views that call restBaseUrl and for server script endpoints. |
com.siemens.polarion.rest.security.restApiToken.enabled |
polarion.properties |
yes | Enables the REST token mechanism used by application views (context.restToken, header X-Polarion-REST-Token). Without it the token is empty and REST API and application endpoint calls fail with 401. Application endpoints require the token header even if a browser session exists. |
Related settings
- Content Security Policy headers configured on the Polarion web server apply to application views. A policy that forbids external scripts blocks CDN-loaded libraries in views; bundle dependencies instead.
- Personal access tokens (user level, My Account → Personal Access Tokens) are not used by views, but are convenient for local development against a real server (see Develop locally).
Where the files live
Uploaded applications are stored by Polarion on the server and served at /polarion/apps/<identifier>/. They are not placed in the extensions/ folder and do not require a restart.
Reference
Limitations and known issues
This page lists what the 2612 preview does not do yet and the issues to be aware of when planning an application.
Preview scope
Polarion Applications and the SDK are a preview in 2612. The feature is usable for internal applications and pilots; expect changes in later releases, in particular to the manifest format, the SDK API and the configuration elements.
SDK
- One event type. Only
selection-changedis delivered. There are no events for work item saves, navigation, form field changes or document edits. - One subscription per event type per view. A second
subscribe()throws. - No calls into the host. A view cannot ask Polarion to refresh the form, navigate, open a dialog, show a notification or resize the panel. Use
target="_top"links for navigation and set the panelheightin the layout. - Fixed 5 s timeout for
fetchContext(). - No selection in the sidebar context.
selectedWorkItemIdsis empty in a sidebar's context, even when rows are selected. The selection arrives only withselection-changed, so a sidebar in the Work Items table shows nothing until the user changes the selection once. - Not published on npm. Install from the server or a local file.
Views
- Iframe height is static. The panel does not grow with the content; choose a
heightin the form layout and scroll inside the view. - No styling inheritance. Views do not receive Polarion's fonts, colors or the user's theme.
- Form extension
titleandiconin the manifest are accepted but appear not to be displayed; the panel heading comes from the layout'slabel. - Create form. In the form of a not-yet-saved work item there is no
workItemId. - Views are reloaded on every navigation. No state survives switching work items.
Server scripts
- Only
GETandPOSTmethods. - No streaming or binary responses; results are JSON only.
- Synchronous execution; no background jobs.
Administration
- Upload is interactive in the UI. Automation through the REST API should be validated against your server version.
- Deleting an application does not clean up
applicationViewreferences in form layouts and Topics configurations. - Application identifiers are global per server; there is no namespace per project.
Browser support
Views run in the browsers Polarion supports. Vite's default target (modern evergreen browsers) is appropriate; no transpilation for legacy browsers is needed.
Reporting issues
Report problems with the Applications feature or the SDK through your usual Polarion support channel, quoting the Polarion build (shown on the login page), the SDK version from node_modules/polarion-app-sdk/package.json, and the manifest of the application.
Reference
Glossary
The vocabulary of Polarion Applications, in alphabetical order. Each entry links to the page where the concept is explained.
A
Application : A package (ZIP) with a manifest, one or more views and optional endpoints, uploaded to Polarion through Global Administration. The extensibility framework
Application identifier
: The identifier field of the manifest; globally unique on a server and the name of the top-level folder in the ZIP. Reverse-DNS style, for example com.example.inspector. Application package
applicationView
: The XML element that places a form extension in a form layout or a navigation topic in a Topics configuration. Its id is <identifier>.<viewId>. View configuration XML
appEndpoint
: Context field with the base URL of the application's own endpoints: https://<host>/polarion/apps/<identifier>/rest. PolarionContext
arguments
: Polarion's IArguments object inside a server script, holding the request parameters. Inside a JavaScript function the name refers to the function's own arguments, so capture it at the top level. Write the server script
C
Context
: The PolarionContext object a view receives from fetchContext(): identifiers of the surrounding project, work item or document, the selection, and the URLs and token for HTTP calls. Application context
E
Endpoint
: An HTTP path under /polarion/apps/<identifier>/rest/ implemented by a server script and declared in serverScripts.endpoints. Your own REST API inside Polarion. Your own REST endpoints
Envelope
: The JSON wrapper { timestamp, success, data } or { timestamp, success: false, error } around every endpoint response. Results and the envelope
Event
: A notification pushed by the Polarion host to a view through the SDK. Polarion 2612 emits selection-changed. React to selection changes
F
Form extension : A view type rendered as a collapsible panel inside the Work Item form; knows the open work item. Form extension
Form layout : Polarion's XML configuration of the Work Item form per work item type and Polarion View. Where form extensions are placed. Place it in a form layout
H
Host bridge
: The part of the Polarion page that answers SDK requests and emits events to application iframes over postMessage. How an application works
M
manifestVersion
: Manifest field with the version of the manifest format; "1.0" in Polarion 2612. manifest.json
Manifest
: manifest.json, the descriptor of an application: identity, views and endpoints. manifest.json
N
Navigation topic : A view type rendered as a full page with an entry in the project navigation panel. Navigation topic
O
objectId
: The parameter every endpoint call must carry, usually PROJECT/WI-ID of the object the call is about. The objectId parameter
P
Polarion View (hat) : Polarion's named sets of navigation topics and form layouts (Default and any custom ones). Not to be confused with an application view.
Polarion Application SDK
: The npm package polarion-app-sdk providing fetchContext, events, destroy and EventTypes. SDK API
publisherName
: Manifest field naming the organization that publishes the application; shown in the upload dialog and in Properties. manifest.json
R
REST API
: Polarion's documented REST API under /polarion/rest/v1, callable from a view with the token from the context. Calling the REST API from a view
REST token
: The value of context.restToken, sent as the X-Polarion-REST-Token header to authenticate REST and endpoint calls as the current user. Requires token authentication on the server. Enable Applications in Polarion
Root directory
: The folder of a view inside the application package (rootDirectory in the manifest). Application package
S
Selection
: The work items currently selected in a Work Items table or Document. Sidebars receive it only through the selection-changed event; their context.selectedWorkItemIds is empty. A form extension gets the open item, or all ticked items in the multi-item edit form, in context.selectedWorkItemIds. React to selection changes
Server script
: A JavaScript file in server-scripts/ executed on the Polarion server by GraalVM when its endpoint is called; has access to the Polarion Java API. Write the server script
Sidebar : A view type shown in the sidebar area next to the Work Items table and in Documents, selectable from the Show Sidebar menu. Sidebar
T
Topics configuration : Polarion's XML configuration of the navigation panel per Polarion View. Where navigation topics are placed. Add it to the navigation
V
View
: One web page of an application placed at one kind of location in Polarion: form extension, sidebar or navigation topic. Declared under views in the manifest. Views
View identifier
: The identifier of a view, unique within its application. Combined with the application identifier into <identifier>.<viewId>. manifest.json
Reference
Cheat sheet
Everything on this page was verified on Polarion 2612. Follow the links for the details.
URLs
| What | URL |
|---|---|
| Static files of an application | https://<host>/polarion/apps/<identifier>/<rootDirectory>/<file> |
| View entry (redirects to the view's document) | https://<host>/polarion/apps/<identifier>/views/<viewId> |
| Application endpoint | https://<host>/polarion/apps/<identifier>/rest/<urlPath> |
| REST API | https://<host>/polarion/rest/v1/… |
| Navigation topic page | https://<host>/polarion/#/project/<projectId>/<identifier>.<viewId> |
| Work Items table with a sidebar open | …/#/project/<projectId>/workitems?sidebar=polarion-application.<identifier>.<viewId> |
| SDK download | https://<host>/polarion/sdk/applications/polarion-app-sdk-0.5.2-preview.tgz |
Configuration XML
<!-- Form layout: Project Administration → Work Items → Form Configuration → Form Layouts -->
<applicationView id="<identifier>.<viewId>" label="Panel heading" height="480px"/>
<!-- Topics: Project Administration → Portal → Topics → <View> -->
<applicationView id="<identifier>.<viewId>"/>
<!-- Sidebars: no XML; listed in Show Sidebar automatically -->
Package layout
.zip / (one top-level folder, named after the identifier) - manifest.json
/ (per view, or shared by several views: index.html + assets (relative URLs)) - server-scripts/ (only with serverScripts.endpoints)
Server settings
# Global Administration → Configuration Properties (global configuration property)
polarionapp.enabled=true # Applications feature
# polarion.properties (restart required)
com.siemens.polarion.rest.enabled=true # REST API (else 503)
com.siemens.polarion.rest.security.restApiToken.enabled=true # token for views (else warning dialog, 401)
SDK
import { fetchContext, events, EventTypes, destroy } from 'polarion-app-sdk';
const context = await fetchContext(); // 5 s timeout outside Polarion
const stop = events.subscribe(EventTypes.SELECTION_CHANGED, ({ selectedWorkItemIds }) => {});
stop(); destroy(); // on unmount
context.restBaseUrl and context.appEndpoint have no trailing slash. workItemId is project-local (DP-477); selectedWorkItemIds and selection events carry the project (drivepilot/DP-477).
REST call
fetch(`${context.restBaseUrl}/projects/${p}/workitems/${id}?fields[workitems]=id,title,status`, {
headers: { 'X-Polarion-REST-Token': context.restToken!, Accept: 'application/json' },
});
Sparse field sets also filter relationships: fields[linkedworkitems]=role,suspect,workItem.
Endpoint rules
- Every call carries
objectId(PROJECT/WI-ID), in the query string (GET) or the body (POST). - POST bodies are flat objects with string values; encode lists as JSON strings.
arguments.getAsString('x')throws for an absent parameter; guard optional ones.- Inside a function,
argumentsis JavaScript's own; captureconst scriptArguments = arguments;at the top. - Save what you change:
wi.save()for fields,comment.save()for a new comment. - The last expression is the response; an
errorkey makes it an error (HTTP 400 with the envelope).
const trackerService = context.scriptContext().services().tracker();
const scriptArguments = arguments;
let result = {};
try {
const [projectId, wiId] = scriptArguments.getAsString('objectId').split('/');
const wi = trackerService.getWorkItem(projectId, wiId);
result = { id: wi.getId(), title: wi.getTitle() };
} catch (e) {
result = { error: 'my-endpoint failed: ' + e };
}
result;
Upload dialog
Install: identity + SHA-2 hash (128 hex digits). Update: New Version next to Current Version. Delete: immediate, no visible confirmation.

