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.