Portal library

Contents

API to access functions related to rendering.

Install

Add the library to your build.gradle file:

dependencies {
  include xplibs.portal
}

TypeScript types come from the @enonic-types/lib-portal package, installed at the version of XP your project builds against — see TypeScript.

Base URLs

A generated URL is anchored to the mount the call was made from — a site, a webapp, an admin tool — and falls back to the installation’s /api/ space when there is no request to anchor to, as in a task. Content URLs use the site’s configured Base URL where there is one.

XPXP8.1.08.1.0 A configured Base URL is used verbatim and decides on its own whether the URL is absolute, so type applies only to request-anchored URLs.

To serve media from another host, configure media.defaultBaseUrl — see the portal configuration.

URL parts

XPXP8.1.08.1.0 The URL functions follow the request: they generate the URL the current request leads to, through its virtual host. A frontend serving content from a host of its own, such as a headless one, needs URLs resolved from configuration alone instead. Each request-following function has a counterpart that returns such a URL as parts to assemble:

Follows the request From configuration alone

pageUrl()

pageUrlParts()

imageUrl()

imageUrlParts()

attachmentUrl()

attachmentUrlParts()

processHtml()

processHtmlParts()

baseUrl()

portalScope()

Page URLs and rich text belong to a site, or to a project. The request-following functions take it from the request: its project, branch, site and the site’s configuration. portalScope() resolves the same from configuration alone, as a stand-in for a site request. Its key names the content that page paths are relative to, as they are to the content a virtual host mounts, and its result is passed as scope to every pageUrlParts() and processHtmlParts() call below that content. Its baseUrl is the Base URL configured for the site or project, followed by the path of that content there, or null. A page URL is baseUrl + path + queryString, where the caller supplies the origin the site is served from when baseUrl is null.

imageUrlParts() and attachmentUrlParts() take a project and branch. A media URL is mediaBaseUrl + path + queryString, where the caller supplies the root of the media APIs as it serves them; media.defaultBaseUrl and the mounts of the media APIs do not apply.

Parts are URL-escaped as they appear in the URL: assemble them without encoding them again.

Use each image URL as it is returned, and don’t make other sizes by editing its scale segment. The fingerprint of an image URL can depend on its whole transformation, so an edited URL may no longer be served. The image’s style also contributes to the scale. Ask XP for each size instead, with scale of imageUrlParts(), or imageSrcWidth and imageWidths of processHtmlParts().

URLs that do not resolve

XPXP8.1.08.1.0 When the content a URL names does not resolve - a missing content, a content that is not an image, an unknown attachment, or a deleted project or branch - pageUrl(), imageUrl(), attachmentUrl() and processHtml() generate a URL answered with 404 Not Found, and log a warning. A broken link in rich text therefore leaves the rest of the text intact. In processHtmlParts(), the element of a link or image that does not resolve holds such a URL, and its entry has no parts.

Functions

apiUrl

Generates a URL pointing to a Universal API. Picks the right URL form based on the calling context — a contextual URL under the active service when called from a site, webapp, or admin tool, and /api/ otherwise.

Parameters

apiUrl() takes a single ApiUrlParams object with these properties:

Name Type Description

api

string

Descriptor key in <app>:<api> form.

type

string

Optional. URL type. Either server (server-relative), absolute, or websocket. Defaults to server. Ignored when a base URL applies — see Base URLs.

path

string | string[]

Optional. Path appended after the API segment. Accepts a string or a string array.

params

object

Optional. Custom query parameters to append to the URL.

baseUrl

string

Deprecated. Expose the API location as a vhost mapping instead.

Returns

string : The generated URL.

Example

import {apiUrl} from '/lib/xp/portal';

const url = apiUrl({
  api: 'com.example.myapp:myapi',
  path: '/items',
  params: {
    id: '42'
  }
});

assetUrl

assetUrl is deprecated and will be removed in future versions. lib-asset and lib-static are introduced as a replacement.

Generates URL to a static file.

Parameters

assetUrl() takes a single AssetUrlParams object with these properties:

Name Type Description

path

string

Path to the asset.

application

string

Optional. Other application to reference to. Defaults to current application.

type

string

Optional. URL type. Either server (server-relative URL) or absolute. Default is server.

params

object

Optional. Custom query parameters to append to the URL.

Returns

string : The generated URL.

Example

import {assetUrl} from '/lib/xp/portal';

const url = assetUrl({
  path: 'styles/main.css'
});

attachmentUrl

Generates URL to an attachment.

If name is provided, the URL points to the attachment with that unique name. If name is empty but label is provided, it points to the first attachment with that label. If both name and label are empty, it points to the attachment of a binary content. When no attachment matches, the URL is answered with 404 — see URLs that do not resolve.

Parameters

attachmentUrl() takes a single AttachmentUrlParams object with these properties:

Name Type Description

id

string

Optional. Id of the content with the attachment.

path

string

Optional. Path to the content with the attachment.

name

string

Optional. Unique name of the attachment.

label

string

Optional. Label of the attachment. Default is source.

download

boolean

Optional. Set to true if the disposition header should be set to attachment. Default is false.

type

string

Optional. URL type. Either server (server-relative URL) or absolute. Default is server. Ignored when a base URL applies — see Base URLs.

project

string

Optional. Name of the project.

branch

string

Optional. Name of the branch.

baseUrl

string

Deprecated. Configure media.defaultBaseUrl, or a Base URL on the site, instead.

params

object

Optional. Deprecated. Custom query parameters to append to the URL. The attachment API reads none but download, which the download parameter sets.

Returns

string : The generated URL; one answered with 404 when the attachment does not resolve — see URLs that do not resolve.

Example

import {attachmentUrl} from '/lib/xp/portal';

const url = attachmentUrl({
  id: '1234',
  download: true
});

attachmentUrlParts

XPXP8.1.08.1.0 Resolves the parts of an attachment URL from configuration alone: mediaBaseUrl + path + queryString, where mediaBaseUrl is the root of the media APIs as the caller serves them. See URL parts.

The parts also hold the segments of the path - context, id, fingerprint and name - for a host that serves the media API with leading segments hidden by a virtual host mapping, such as https://cdn.example.com/<context>/<id>:<fingerprint>/<name>. The attachment is picked as in attachmentUrl().

Parameters

attachmentUrlParts() takes a single AttachmentUrlPartsParams object with these properties:

Name Type Description

id

string

Optional. Id of the content holding the attachment. Either id or path is required.

path

string

Optional. Path of the content holding the attachment, within the project.

name

string

Optional. Name of the attachment. Picks the attachment by name, before label.

label

string

Optional. Label of the attachment, used when name is absent. Defaults to source.

download

boolean

Optional. Set to true to ask for the attachment to be downloaded. Defaults to false.

project

string

Optional. Name of the project. Defaults to the project of the current context.

branch

string

Optional. Name of the branch. Defaults to the branch of the current context.

Returns

object : (AttachmentUrlParts) The parts of the URL.

Example

import {attachmentUrlParts} from '/lib/xp/portal';

// Parts of the URL of an attachment, to be downloaded
const parts = attachmentUrlParts({
  path: '/my-site/documents/report',
  download: true,
  project: 'myproject',
  branch: 'draft'
});

// The root of the media APIs as the frontend serves them
const url = 'https://cdn.example.com/api' + parts.path + parts.queryString;

baseUrl

Generates the base URL of the current site request: the address of the site - or project - the matched virtual host mapping points at, rewritten for that host. Page URLs following the request are relative to it, and so are routes the site serves outside the content tree, such as mappings. Without a site request, it is the Base URL configured for the project of the current context, or else the address the site engine serves the project at.

For the Base URL configured for a site or project, independent of the request, use portalScope().

Parameters

baseUrl() takes a single, optional BaseUrlParams object with these properties:

Name Type Description

type

string

Optional. URL type. Either server (server-relative URL) or absolute or websocket. Default is server. Ignored when the site has a configured Base URL — see Base URLs.

id

string

Deprecated. Use portalScope() with key instead.

path

string

Deprecated. Use portalScope() with key instead.

project

string

Deprecated. Use portalScope() with project instead.

branch

string

Deprecated. Use portalScope() with branch instead.

Returns

string : The generated URL.

Example

import {baseUrl} from '/lib/xp/portal';

// The address the current site request is served from: routes of the site are relative to it
const base = baseUrl();
const searchUrl = base + '/search';

// The same, as an absolute URL, for a canonical link
const absoluteBase = baseUrl({
  type: 'absolute'
});

componentUrl

Generates URL to a page component.

Parameters

componentUrl() takes a single ComponentUrlParams object with these properties:

Name Type Description

id

string

Optional. Id to the page.

path

string

Optional. Path to the page.

component

string

Optional. Path to the component. If not set, the current path is set.

type

string

Optional. URL type. Either server (server-relative URL) or absolute. Default is server.

params

object

Optional. Custom query parameters to append to the URL.

Returns

string : The generated URL.

Example

import {componentUrl} from '/lib/xp/portal';

const url = componentUrl({
  component: 'main/0'
});

csp

XPXP8.1.08.1.0 Returns the request-scoped enforced Content Security Policy builder for the current portal request. A portal request exists in site pages and components, webapps, admin tools and APIs alike, so the policy can be declared from any of them, and a Java extension response processor contributes to the same policy. Its directives are composed into the Content-Security-Policy header emitted on the response. For the report-only companion, use cspReportOnly(). Takes no arguments.

One policy is shared for the whole request, so a page with its layouts, parts and any response processors all contribute to the same header. It is composed and emitted automatically when the response is flushed, so late contributions still land — you never set the header yourself.

A Content-Security-Policy header set directly on the response is folded into the policy (as if passed to resetTo()) rather than sent verbatim, so later contributions still apply on top; a Content-Security-Policy-Report-Only header is folded into the report-only policy the same way.

Setting the Content-Security-Policy header directly is a legacy path, kept only for compatibility with existing apps. New code should declare the policy through csp() (and cspReportOnly() for report-only) instead.

Returns

object : (Csp) The request-scoped Content Security Policy; its directives are emitted as the response’s Content-Security-Policy header.

Example

Seed a deny-all baseline, then open up only what the page needs:
import {csp, CspSource} from '/lib/xp/portal';

const policy = csp();

// Deny-all baseline: default-src, base-uri and frame-ancestors all 'none'
policy.strict();

// Open up only the directives this page needs (calls chain)
policy
  .scriptSrc(CspSource.SELF, 'https://cdn.example.com')
  .styleSrc(CspSource.SELF)
  .imgSrc(CspSource.SELF, CspSource.DATA);
Allow one inline script with a per-request nonce:
import {csp} from '/lib/xp/portal';

// Wires 'nonce-<value>' into script-src and returns the value to stamp on the tag
const nonce = csp().nonceScriptSrc();

const view = `<script nonce="${nonce}">window.app = {};</script>`;

cspReportOnly

XPXP8.1.08.1.0 Returns the request-scoped report-only Content Security Policy builder, emitted as the Content-Security-Policy-Report-Only header. Takes no arguments.

It is an independent companion to the enforced policy from csp() — the same Csp API, sharing the request nonce — and the two headers can coexist on one response, so you can enforce a settled policy while trialling a stricter one. While the report-only policy is left empty, no header is emitted.

Returns

object : (Csp) The request-scoped report-only Content Security Policy; its directives are emitted as the response’s Content-Security-Policy-Report-Only header.

Example

Enforce one policy while trialling a stricter one in report-only mode:
import {csp, cspReportOnly, CspSource} from '/lib/xp/portal';

// Enforced: still allow inline scripts for now
csp().scriptSrc(CspSource.SELF, CspSource.UNSAFE_INLINE);

// Report-only: trial a strict policy — violations are reported, not blocked
cspReportOnly().scriptSrc(CspSource.SELF);

getComponent

Returns the component in the current execution context. Meant to be called from a layout or part. Takes no arguments.

Returns

*object* : (<<../libraries/types#component, `Component`>>) The current component, or `null` if there is no component in the current context.

Example

Returns component in the current context:
import {getComponent} from '/lib/xp/portal';

const result = getComponent();
log.info('Current component name = %s', result.name);
Return value:
const expected = {
  path: "/main/0",
  type: "layout",
  descriptor: "myapplication:mylayout",
  config: {
    a: "1"
  },
  regions: {
    bottom: {
      components: [
        {
          path: "/main/0/bottom/0",
          type: "part",
          descriptor: "myapplication:mypart",
          config: {
            a: "1"
          }
        }
      ],
      name: "bottom"
    }
  }
};

getContent

Returns the content in the current execution context. Meant to be called from a page, layout, or part. Takes no arguments.

The content’s page is the page as rendered: where the content uses a page template, the template’s components are in place. For the page as stored, and for how the tree relates to the flat components list XP persists, see Pages and components.

The content follows the request’s contentPath, so when a site mapping filter has re-routed rendering, this returns the content the request was re-routed to.

Returns

*object* : (<<../libraries/types#content, `Content`>>) The current content, or `null` if there is no content in the current context.

Example

Get content and log the result:
import {getContent} from '/lib/xp/portal';

const result = getContent();
log.info('Current content path = %s', result._path);
Return value:
const expected = {
  _id: "123456",
  _name: "mycontent",
  _path: "/a/b/mycontent",
  creator: "user:system:admin",
  modifier: "user:system:admin",
  createdTime: "1970-01-01T00:00:00Z",
  modifiedTime: "1970-01-01T00:00:00Z",
  type: "base:unstructured",
  displayName: "My Content",
  hasChildren: false,
  language: "en",
  valid: false,
  data: {
    a: "1"
  },
  x: {},
  page: {},
  attachments: {},
  publish: {}
};

getIdProviderKey

Returns the key of ID provider in the current execution context. Takes no arguments.

Returns

string|null : The current ID provider key, or null if no ID provider is bound to the current context.

Example

Returns the current ID provider:
import {getIdProviderKey} from '/lib/xp/portal';

const idProviderKey = getIdProviderKey();

if (idProviderKey) {
    log.info('Id provider key: %s', idProviderKey);
}
Return value:
const expected = "myidprovider";

getMultipartForm

Returns a JSON containing multipart items. If the request is not multipart, an empty object is returned. Takes no arguments.

Returns

*object* : (<<multipart-form, `MultipartForm`>>) The multipart form items.

Example

Get the form and log the result:
import {getMultipartForm} from '/lib/xp/portal';

const result = getMultipartForm();
log.info('Multipart form %s', result);
Return value:
const expected = {
  item1: {
    name: "item1",
    fileName: "item1.jpg",
    contentType: "image/png",
    size: 10
  },
  item2: [
    {
      name: "item2",
      fileName: "image1.png",
      contentType: "image/png",
      size: 123
    },
    {
      name: "item2",
      fileName: "image2.jpg",
      contentType: "image/jpeg",
      size: 456
    }
  ]
};

getMultipartItem

Returns a JSON containing a named multipart item. If the item does not exist, it returns null.

Parameters

getMultipartItem() takes the name of the multipart item (string) and an optional zero-based index (number) — specify the index when several items share the same name.

Returns

*object* : (<<multipart-item, `MultipartItem`>>) The named multipart form item, or `null` if it does not exist.

Example

Get item and log the result:
import {getMultipartItem} from '/lib/xp/portal';

const result = getMultipartItem('item1');
log.info('Multipart item %s', result);
Return value:
const expected = {
  name: "item1",
  fileName: "item1.jpg",
  contentType: "image/png",
  size: 10
};

getMultipartStream

Returns a data stream for a named multipart item. If the item does not exist, it returns null.

Parameters

getMultipartStream() takes the name of the multipart item (string) and an optional zero-based index (number) — specify the index when several items share the same name.

Returns

*object* : (<<../libraries/types#byte-source, `ByteSource`>>) Stream of multipart item data, or `null` if the item does not exist.

Example

import {getMultipartStream} from '/lib/xp/portal';

const stream1 = getMultipartStream('item2');
const stream2 = getMultipartStream('item2', 1);

getMultipartText

Returns the multipart item data as text. If the item does not exist, it returns null.

Parameters

getMultipartText() takes the name of the multipart item (string) and an optional zero-based index (number) — specify the index when several items share the same name.

Returns

string|null : Text for multipart item data, or null if the item does not exist.

Example

import {getMultipartText} from '/lib/xp/portal';

const text = getMultipartText('item1');

getSite

Returns the parent site of the content in the current execution context. Meant to be called from a page, layout, or part. Takes no arguments.

Returns

*object* : (<<site, `Site`>>) The current site, or `null` if the content has no parent site.

Example

Get site and log the result:
import {getSite} from '/lib/xp/portal';

const result = getSite();
log.info('Current site name = %s', result._name);
Return value:
const expected = {
  _id: "100123",
  _name: "my-content",
  _path: "/my-content",
  type: "base:unstructured",
  hasChildren: false,
  valid: false,
  data: {
    siteConfig: {
      applicationKey: "myapplication",
      config: {
        Field: 42
      }
    }
  },
  x: {},
  page: {},
  attachments: {},
  publish: {}
};

getSiteConfig

Returns the configuration of the parent site for the content in the current execution context. Meant to be called from a page, layout, or part. Takes no arguments.

Returns

object|null : The site configuration for the current application, or null if the content has no parent site.

Example

Get site and log the result:
import {getSiteConfig} from '/lib/xp/portal';

const result = getSiteConfig();
log.info('Field value for the current site config = %s', result.Field);
Return value:
const expected = {
  Field: 42
};

idProviderUrl

Generates URL to an ID provider.

Parameters

idProviderUrl() takes a single, optional IdProviderUrlParams object with these properties:

Name Type Description

idProvider

string

Optional. Key of an ID provider. If idProvider is not set, then the id provider corresponding to the current execution context will be used.

type

string

Optional. URL type. Either server (server-relative URL) or absolute. Default is server.

params

object

Optional. Custom query parameters to append to the URL.

Returns

string : The generated URL.

imagePlaceholder

Generates URL of an image placeholder with a specified size.

Parameters

imagePlaceholder() takes a single ImagePlaceholderParams object with these properties:

Name Type Description

width

number

Optional. Width of the image in pixels.

height

number

Optional. Height of the image in pixels.

Returns

string : Placeholder image URL.

Example

Obtains image encoded to base64:
import {imagePlaceholder} from '/lib/xp/portal';

const url = imagePlaceholder({
  width: 32,
  height: 24
});
Return value:
const expected = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAYAAACbU/80AAAAGUlEQVR42u3BAQEAAACCIP+vbkhAAQAA7wYMGAAB93LuRQAAAABJRU5ErkJggg==';

imageUrl

Generates URL to an image: an image or a vector image.

Parameters

imageUrl() takes a single ImageUrlParams object with these properties:

Name Type Description

id

string

Optional. ID of the image content. Either id or path is required.

path

string

Optional. Path to the image. If id is specified, this parameter is not used.

scale

string

Options are width(px), height(px), block(width,height), square(px), max(px), wide(width,height) and full.

quality

number

Optional. Quality for JPEG images, ranges from 0 (max compression) to 100 (min compression). Default is 85.

background

string

Optional. Background color.

format

string

Optional. Format of the image.

filter

string

Optional. A number of filters are available to alter the image appearance, for example, blur(3), grayscale(), rounded(5), etc.

type

string

Optional. URL type. Either server (server-relative URL) or absolute. Default is server. Ignored when a base URL applies — see Base URLs.

project

string

Optional. Name of the project.

branch

string

Optional. Name of the branch.

baseUrl

string

Deprecated. Configure media.defaultBaseUrl, or a Base URL on the site, instead.

params

object

Optional. Deprecated. Custom query parameters to append to the URL. The image API reads none but quality, background and filter, which have their own parameters.

Returns

string : The generated URL; one answered with 404 when the image does not resolve — see URLs that do not resolve.

Example

Obtains image url:
import {imageUrl} from '/lib/xp/portal';

const url = imageUrl({
  id: '1234',
  scale: 'block(1024,768)',
  filter: 'rounded(5);sharpen()'
});

imageUrlParts

XPXP8.1.08.1.0 Resolves the parts of an image URL from configuration alone: mediaBaseUrl + path + queryString, where mediaBaseUrl is the root of the media APIs as the caller serves them. See URL parts.

The parts also hold the segments of the path - context, id, fingerprint, scale and name - for a host that serves the media API with leading segments hidden by a virtual host mapping, such as https://img.example.com/<context>/<id>:<fingerprint>/<scale>/<name>.

The content has to be an image or a vector image; for other content an error is raised. An image the image API serves as stored, such as a vector image, has a single URL, with the full scale and none of the processing parameters.

Parameters

imageUrlParts() takes a single ImageUrlPartsParams object with these properties:

Name Type Description

id

string

Optional. ID of the image content. Either id or path is required.

path

string

Optional. Path of the image content within the project.

scale

string

Optional. Options are width(px), height(px), block(width,height), square(px), max(px), wide(width,height) and full. Defaults to full, the image as stored.

quality

number

Optional. Quality for JPEG images, ranges from 0 (max compression) to 100 (min compression). Defaults to 85.

background

string

Optional. Background color.

format

string

Optional. Format of the image.

filter

string

Optional. Filters to alter the image appearance, for example, blur(3), grayscale(), rounded(5).

project

string

Optional. Name of the project. Defaults to the project of the current context.

branch

string

Optional. Name of the branch. Defaults to the branch of the current context.

Returns

object : (ImageUrlParts) The parts of the URL.

Example

import {imageUrlParts} from '/lib/xp/portal';

// Parts of the URL of a scaled image
const parts = imageUrlParts({
  id: '11cc4e09-0d9d-4a4d-9a4b-1a3a8c2b6f3e',
  scale: 'block(1024,768)',
  quality: 85,
  project: 'myproject',
  branch: 'master'
});

// The root of the media APIs as the frontend serves them
const url = 'https://cdn.example.com/api' + parts.path + parts.queryString;

loginUrl

Generates URL to the login endpoint of an ID provider.

Parameters

loginUrl() takes a single, optional LoginUrlParams object with these properties:

Name Type Description

idProvider

string

Optional. Id provider key. If idProvider is not set, then the id provider corresponding to the current execution context will be used.

redirect

string

Optional. The URL to redirect to after the login.

type

string

Optional. URL type. Either server (server-relative URL) or absolute. Default is server.

params

object

Optional. Custom query parameters to append to the URL.

Returns

string : The generated URL.

logoutUrl

Generates URL to the logout endpoint of ID provider in the current context.

Parameters

logoutUrl() takes a single, optional LogoutUrlParams object with these properties:

Name Type Description

redirect

string

Optional. The URL to redirect to after the logout.

type

string

Optional. URL type. Either server (server-relative URL) or absolute. Default is server.

params

object

Optional. Custom query parameters to append to the URL.

Returns

string : The generated URL.

pageUrl

Generates URL to a content page.

Parameters

pageUrl() takes a single PageUrlParams object with these properties:

Name Type Description

id

string

Optional. Id of a content. If id is set, then path is not used.

path

string

Optional. Path of a content. Relative paths are resolved based on the current context.

type

string

Optional. URL type. Either server (server-relative URL) or absolute or websocket. Default is server. Ignored when the site has a configured Base URL — see Base URLs.

project

string

Deprecated. Use pageUrlParts() with a scope from portalScope() with project instead.

branch

string

Deprecated. Use pageUrlParts() with a scope from portalScope() with branch instead.

params

object

Optional. Custom query parameters to append to the URL.

Returns

string : The generated URL; one answered with 404 when the page does not resolve — see URLs that do not resolve.

Example

Obtains page url:
import {pageUrl} from '/lib/xp/portal';

const url = pageUrl({
  path: '/my/page',
  params: {
    a: 1,
    b: [1, 2]
  }
});

pageUrlParts

XPXP8.1.08.1.0 Resolves the parts of a page URL from configuration alone, for the scope: baseUrl + path + queryString. See URL parts.

The page has to be inside the content of the scope, or be it; for a page elsewhere an error is raised.

Parameters

pageUrlParts() takes a single PageUrlPartsParams object with these properties:

Name Type Description

id

string

Optional. Id of the page. Either id or path is required.

path

string

Optional. Path of the page within the project.

scope

PortalScope

Optional. The scope the URL belongs to, resolved by portalScope(); the page is looked up in its project and branch. Defaults to the project of the current context.

params

object

Optional. Custom query parameters of the URL.

Returns

object : (PageUrlParts) The parts of the URL.

Example

import {pageUrlParts, portalScope} from '/lib/xp/portal';

// The site the URLs belong to, in place of a site request: resolve it once, and pass it to every call for that site
const scope = portalScope({
  key: '/my-site',
  project: 'myproject',
  branch: 'master'
});

// Parts of the URL of a page, relative to the site it belongs to
const parts = pageUrlParts({
  path: '/my-site/posts/first-post',
  scope,
  params: {
    a: 1
  }
});

// The site's configured Base URL, or the origin the frontend serves the site from
const url = (parts.baseUrl ?? 'https://www.example.com') + parts.path + parts.queryString;

portalScope

XPXP8.1.08.1.0 Resolves a portal scope: an immutable, request-independent context for resolving page URLs and processing rich text below a selected content or project, from configuration alone. It provides pageUrlParts() and processHtmlParts() what a site request would - the project, the branch, the site and its configuration - without one. Resolve it once and pass it as scope to every call below the content key names. See URL parts.

Page paths are relative to the content key names, as they are to the content a virtual host mounts. The configuration - the applications and the Base URL - is that of the nearest site at or above that content, or of the project outside any site.

Parameters

portalScope() takes a single, optional PortalScopeParams object with these properties:

Name Type Description

key

string

Optional. Id or path of the content that page paths are relative to: a site, or any other content. A key starting with / is a path. Defaults to /, which selects the project.

project

string

Optional. Name of the project. Defaults to the project of the current context.

branch

string

Optional. Name of the branch. Defaults to the branch of the current context.

Returns

object : (PortalScope) The resolved scope.

Example

import {pageUrlParts, portalScope} from '/lib/xp/portal';

// The site URLs belong to, in place of a site request: resolved once for every URL of that site
const scope = portalScope({
  key: '/my-site',
  project: 'myproject',
  branch: 'master'
});

// The site's configured Base URL, or the origin the frontend serves the site from
const origin = scope.baseUrl ?? 'https://www.example.com';

const post = pageUrlParts({path: '/my-site/posts/first-post', scope});
const url = origin + post.path + post.queryString;

processHtml

Resolves internal links to images and internal content items contained in an HTML text and replaces them with correct URLs. It will also process embedded macros.

XPXP8.1.08.1.0 An image names its style in the style parameter of its image:// link: <application>:<name> for the style of that application, or a name alone for the first style of that name. Styles come from the system application and the applications configured on the site.

XPXP8.1.08.1.0 A macro is resolved when the HTML is processed, among the applications configured on the site - by its name, then ignoring case - and then among the built-in macros; a macro no application provides stays as written. HTML comments in the text stay plain comments: they are never run as macros.

A link or image that does not resolve gets a URL answered with 404 — see URLs that do not resolve.

When outputting processed HTML in Thymeleaf, use attribute data-th-utext="${processedHtml}".

Parameters

processHtml() takes a single ProcessHtmlParams object with these properties:

Name Type Description

value

string

HTML to process.

type

string

Optional. URL type. Either server (server-relative URL) or absolute. Default is server.

imageSrcWidth

number

XPXP8.1.08.1.0 Optional. Width of the src of <img> tags, for images the image API scales. The height follows the aspect ratio of the image’s style or scale. Default is 768.

imageWidths

number[]

Optional. Image widths, such as [400, 800]. If provided, the <img> tags of images the image API scales get a srcset attribute with an image URL for each width.

imageSizes

string

Optional. Specifies the width for an image depending on browser dimensions. The value has the following format: (media-condition) width. Multiple sizes are comma-separated. Written only along with the srcset that imageWidths adds.

Returns

string : The processed HTML.

Example

Process HTML:
import {processHtml} from '/lib/xp/portal';

const html = processHtml({
  value: '<a href="content://123" target="">Content</a>' +
         '<a href="media://inline/123" target="">Inline</a>' +
         '<a href="media://download/123" target="">Download</a>' +
         '<img src="image://123"/>',
  imageSrcWidth: 800,
  imageWidths: [480, 800, 1200],
  imageSizes: '(max-width: 800px) 100vw, 800px'
});

processHtmlParts

XPXP8.1.08.1.0 Processes an HTML text like processHtml(), from configuration alone, for the scope, and returns the parts of every internal link, image and macro in it. See URL parts.

Everything is resolved for the scope: the Base URL, the path each content link is relative to, the project and branch contents and media are looked up in, and the applications image styles and macros come from.

Internal links, images and macros in the returned HTML are placeholders, which the caller renders from their entries:

  • a link carries a data-link-ref attribute, and an image a data-image-ref attribute, naming its entry in links or images;

  • a macro an application of the scope provides becomes an editor-macro element holding its body, with a data-macro-name attribute holding the name of its descriptor and a data-macro-ref attribute naming its entry in macros. Other macros stay as written.

A link or image that does not resolve keeps its ref, and its entry has no parts, so the caller decides how to render it.

Parameters

processHtmlParts() takes a single ProcessHtmlPartsParams object with these properties:

Name Type Description

value

string

HTML to process.

scope

PortalScope

Optional. The scope the HTML belongs to, resolved by portalScope(). Defaults to the project of the current context.

imageSrcWidth

number

Optional. Width of the src of <img> tags, for images the image API scales. The height follows the aspect ratio of the image’s style or scale. Default is 768.

imageWidths

number[]

Optional. Image widths for the srcset attribute of <img> tags, for images the image API scales.

imageSizes

string

Optional. Value of the sizes attribute of <img> tags. Written only along with the srcset that imageWidths adds.

Returns

object : (ProcessedHtml) The processed HTML, with the parts of its links and images, and its macros.

Example

import {processHtmlParts, portalScope} from '/lib/xp/portal';

const scope = portalScope({
  key: '/my-site',
  project: 'myproject',
  branch: 'master'
});

const result = processHtmlParts({
  value: '<a href="content://123456">Post</a>[youtube videoid="abc"/]',
  scope
});

// The site's configured Base URL, or the origin the frontend serves the site from
const origin = result.baseUrl ?? 'https://www.example.com';

for (const link of result.links) {
  // a link that does not resolve has no parts
  if (link.type === 'content' && link.page) {
    const href = origin + link.page.path + link.page.queryString + link.fragment;
    // set href on the element whose data-link-ref is link.ref
  }
}

for (const macro of result.macros) {
  if (macro.descriptor === 'com.example.myapp:youtube') {
    const embedUrl = 'https://www.youtube.com/embed/' + macro.config.videoId;
    // render the editor-macro element whose data-macro-ref is macro.ref
  }
}

sanitizeHtml

Sanitizes an HTML string by stripping all potentially unsafe tags and attributes.

HTML sanitization can be used to protect against cross-site scripting (XSS) attacks by sanitizing any HTML code submitted by a user.

Parameters

sanitizeHtml() takes the html string value to process.

Returns

string : The sanitized HTML.

Example

Sanitizes unsafe HTML:
import {sanitizeHtml} from '/lib/xp/portal';

const unsafeHtml = '<p><a href="https://example.com/" onclick="stealCookies()">Link</a></p>' +
                 '<iframe src="javascript:alert(\'XSS\');"></iframe>';
const sanitizedHtml = sanitizeHtml(unsafeHtml);
Return value:
const expected = '<p><a href="https://example.com/">Link</a></p>';

serviceUrl

HTTP services are deprecated in XP 8 in favor of Universal APIs. Use apiUrl for new code; serviceUrl() is retained for backward compatibility with legacy services in src/main/resources/services/.

Generates URL to a service.

Parameters

serviceUrl() takes a single ServiceUrlParams object with these properties:

Name Type Description

service

string

Name of the service.

application

string

Optional. Other application to reference to. Default is current application.

type

string

Optional. URL type. Either server (server-relative URL) or absolute or websocket. Default is server.

params

object

Optional. Custom query parameters to append to the URL.

Returns

string : The generated URL.

Example

import {serviceUrl} from '/lib/xp/portal';

const url = serviceUrl({
  service: 'myservice',
  params: {
    a: 1,
    b: 2
  }
});

url

Generates URL to a resource.

Parameters

url() takes a single UrlParams object with these properties:

Name Type Description

path

string | string[]

Path to the resource. If a string is provided, it is treated as a full path. If an array of strings is provided, each element is treated as a path segment and will be joined using /.

type

string

Optional. URL type. Either server (server-relative URL) or absolute or websocket. Default is server.

params

object

Optional. Custom query parameters to append to the URL.

Returns

string : The generated URL.

Example

import {url as buildUrl} from '/lib/xp/portal';

const url = buildUrl({
  path: '/site/master/mysite',
  params: {
    a: 1,
    b: 2
  }
});

Type Definitions

PortalScope

XPXP8.1.08.1.0 An immutable, request-independent context for resolving page URLs and processing rich text below a selected content or project, resolved by portalScope(). It stands in for a site request: what request-following URLs take from the request, the URL parts take from the scope. Pass it as is to pageUrlParts() and processHtmlParts(); a scope that portalScope() did not return raises an error.

Name Type Description

baseUrl

string | null

Base URL configured for the site or project, followed by the path of the scope’s content there, without a trailing slash; null when none is configured.

PageUrlParts

XPXP8.1.08.1.0 Parts of a page URL: baseUrl + path + queryString.

Name Type Description

baseUrl

string | null

Base URL of the scope the URL belongs to, without a trailing slash; null when none is configured.

path

string

URL-escaped content path relative to the scope’s content, with a leading slash; empty for that content itself, so that baseUrl + path is the Base URL.

queryString

string

URL-escaped query string prefixed with ?; empty when there are no parameters.

ImageUrlParts

XPXP8.1.08.1.0 Parts of an image URL: mediaBaseUrl + path + queryString, with the media base supplied by the caller. All values are URL-escaped as they appear in the URL.

Name Type Description

path

string

The media API path with a leading slash: /media:image/<context>/<id>:<fingerprint>/<scale>/<name>.

queryString

string

Query string prefixed with ?; empty when there are no parameters.

context

string

Project context segment: <project> on the master branch, <project>:<branch> otherwise.

id

string

Content id.

fingerprint

string | null

Media fingerprint, joined with the id as <id>:<fingerprint> in the path.

scale

string

Scale segment, for example max-300.

name

string

File name segment, with the requested format extension applied.

AttachmentUrlParts

XPXP8.1.08.1.0 Parts of an attachment URL: mediaBaseUrl + path + queryString, with the media base supplied by the caller. All values are URL-escaped as they appear in the URL.

Name Type Description

path

string

The media API path with a leading slash: /media:attachment/<context>/<id>:<fingerprint>/<name>.

queryString

string

Query string prefixed with ?, holding download when requested; empty when there are no parameters.

context

string

Project context segment: <project> on the master branch, <project>:<branch> otherwise.

id

string

Content id.

fingerprint

string | null

Media fingerprint, joined with the id as <id>:<fingerprint> in the path.

name

string

Attachment file name segment.

ProcessedHtml

XPXP8.1.08.1.0 Result of processHtmlParts().

Name Type Description

html

string

The processed HTML, with placeholders for its internal links, images and macros.

baseUrl

string | null

Base URL of the scope the HTML belongs to, without a trailing slash; null when none is configured. It is the baseUrl of the page parts of every content link.

links

(ProcessedHtmlContentLink | ProcessedHtmlAttachmentLink)[]

Internal links to contents and attachments, in document order, told apart by their type.

images

ProcessedHtmlImage[]

Internal images, in document order.

macros

ProcessedHtmlMacro[]

Macros, in document order.

XPXP8.1.08.1.0 A link to a content page, written as content://<id>.

Name Type Description

type

string

content.

ref

string

Value of the data-link-ref attribute of the element.

uri

string

The link as written in the HTML.

contentId

string

Id of the linked content.

page

PageUrlParts | null

Parts of the page URL, with the query string the link carries; null when the link does not resolve.

fragment

string

Fragment of the link, with its leading #; empty when it has none. The href of the link is baseUrl + path + queryString + fragment.

XPXP8.1.08.1.0 A link to the attachment of a media content, written as media://<mode>/<id>.

Name Type Description

type

string

attachment.

ref

string

Value of the data-link-ref attribute of the element.

uri

string

The link as written in the HTML.

contentId

string

Id of the media content.

attachment

AttachmentUrlParts | null

Parts of the attachment URL; null when the link does not resolve.

download

boolean

Whether the link asks for the attachment to be downloaded.

ProcessedHtmlImage

XPXP8.1.08.1.0 An internal image.

Name Type Description

ref

string

Value of the data-image-ref attribute of the element.

contentId

string

Id of the image content.

style

ProcessedHtmlImageStyle | null

The image style applied; null for none.

src

ImageUrlParts | null

Parts of the URL in src; null when the image does not resolve.

srcset

ProcessedHtmlImageSource[]

Parts of the URLs in srcset, one for each image width; empty for an image the image API serves as stored.

ProcessedHtmlImageStyle

XPXP8.1.08.1.0 The style applied to an image.

Name Type Description

application

string

Key of the application whose style descriptor holds the style.

name

string

Name of the style in that style descriptor.

aspectRatio

string | null

Aspect ratio the image is cropped to, such as 16:9; null for none.

filter

string | null

Image filter; null for none.

ProcessedHtmlImageSource

XPXP8.1.08.1.0 A srcset candidate of an image.

Name Type Description

width

number

Width in pixels, the w descriptor of the candidate.

url

ImageUrlParts

Parts of the URL of the image at that width.

ProcessedHtmlMacro

XPXP8.1.08.1.0 A macro, resolved among the applications of the site or project the HTML belongs to.

Name Type Description

ref

string

Value of the data-macro-ref attribute of the editor-macro element.

descriptor

string

Key of the macro descriptor, such as system:embed.

config

object

Parameters of the macro. A parameter matching an input of the descriptor’s form, ignoring case, is named as that input. An input taking several values holds a list of them in the order written; any other parameter holds its first value.

body

string

Body of the macro as written; empty for a macro without one.

Site

A site is a specialized Content of type portal:site. In addition to the standard content properties, its data carries the site’s app configurations.

Name Type Description

description

string

Optional. Site description.

siteConfig

SiteConfig | SiteConfig[]

Configuration for one or more applications enabled on the site. A single object when one application is configured, otherwise an array.

SiteConfig

Configuration entry for a single application enabled on a site.

Name Type Description

applicationKey

string

Key of the application this configuration applies to.

config

object

The application’s site configuration, shaped by its site descriptor form.

MultipartForm

A JSON object keyed by item name, where each value is a MultipartItem or an array of them when several items share the same name.

MultipartItem

Name Type Description

name

string

Name of the multipart item.

fileName

string

Original file name of the uploaded item.

contentType

string

MIME content type of the item.

size

number

Size of the item in bytes.

Csp

A request-scoped Content Security Policy builder, obtained from csp() (enforced) or cspReportOnly() (report-only). Within each, repeated calls to the accessor hand back a fresh handle onto the same underlying policy, so every page, layout, part and processor contributes to the one emitted header. Method calls on a handle, by contrast, all return the same Csp instance (except the nonce getters and directive()), so calls chain.

Contributions merge by union: a directive’s source list is the union of every contributor’s sources, deduped and emitted in the order added. The builder does not arbitrate between sources that interact in the browser — for example 'unsafe-inline' alongside a 'nonce-…', a hash, or 'strict-dynamic', which the browser then ignores. It emits exactly what you declare.

Sources are validated: a value containing ; or whitespace (a policy-injection attempt) throws, and a hand-supplied 'nonce-…' source is rejected — only the nonce* methods generate the request nonce.

Source-list directives

Each unions the given sources — CspSource values or raw strings (hosts, schemes, paths, URLs) — into the named directive.

Method Returns Description

defaultSrc(…​sources)

Csp

Unions sources into default-src — the fetch directive the others fall back to when omitted.

scriptSrc(…​sources)

Csp

Unions sources into script-src (JavaScript and WebAssembly); the fallback for script-src-elem and script-src-attr.

styleSrc(…​sources)

Csp

Unions sources into style-src (stylesheets); the fallback for style-src-elem and style-src-attr.

imgSrc(…​sources)

Csp

Unions sources into img-src (images and favicons).

fontSrc(…​sources)

Csp

Unions sources into font-src (fonts loaded with @font-face).

connectSrc(…​sources)

Csp

Unions sources into connect-src (fetch, XMLHttpRequest, WebSocket, EventSource).

mediaSrc(…​sources)

Csp

Unions sources into media-src (<audio>, <video>, <track>).

objectSrc(…​sources)

Csp

Unions sources into object-src (<object> and <embed>).

frameSrc(…​sources)

Csp

Unions sources into frame-src (<frame>, <iframe>); falls back to child-src.

workerSrc(…​sources)

Csp

Unions sources into worker-src (Worker, SharedWorker, ServiceWorker); falls back to child-src.

manifestSrc(…​sources)

Csp

Unions sources into manifest-src (application manifest files).

childSrc(…​sources)

Csp

Unions sources into child-src — the fallback for frame-src and worker-src.

scriptSrcElem(…​sources)

Csp

Unions sources into script-src-elem (governs <script> elements); falls back to script-src.

scriptSrcAttr(…​sources)

Csp

Unions sources into script-src-attr (governs inline event handlers such as onclick); falls back to script-src.

styleSrcElem(…​sources)

Csp

Unions sources into style-src-elem (governs <style> and <link rel=stylesheet>); falls back to style-src.

styleSrcAttr(…​sources)

Csp

Unions sources into style-src-attr (governs inline style attributes); falls back to style-src.

Document and navigation directives

Method Returns Description

frameAncestors(…​sources)

Csp

Unions sources into frame-ancestors — which parents may embed this page via <frame>/<iframe>/<object>/<embed>. Does not fall back to default-src.

baseUri(…​sources)

Csp

Unions sources into base-uri — the URLs allowed in a <base> element. Does not fall back to default-src.

formAction(…​sources)

Csp

Unions sources into form-action — where forms may submit.

Baseline and low-level building blocks

Prefer the typed methods above; reach for these for directives the typed API does not cover, to inspect the policy, or for whole-policy operations.

Method Returns Description

strict()

Csp

Seeds a deny-all baseline — default-src, base-uri and frame-ancestors all set to 'none'. Call it first, then open up only the directives you need.

add(directive, …​sources)

Csp

Unions sources into any directive by name (deduped). With no sources, registers a valueless directive such as upgrade-insecure-requests. A 'nonce-…' source is rejected.

merge(headerValue)

Csp

Parses a Content-Security-Policy header value and unions each directive’s sources onto the policy — existing directives are extended and absent ones added, so you can grant extra permissions on top of a policy built elsewhere without restating it. A wired nonce is kept; 'nonce-…' sources in the value are dropped. Lenient (invalid tokens skipped); an empty or blank value adds nothing.

directive(name)

string[] | null

The sources currently declared for name (deduped, in serialized order), or null if no contributor has declared it. A declared valueless directive returns an empty array. Reads this policy only.

override(directive, …​sources)

Csp

Replaces a directive’s source list with exactly these sources, overriding what other contributors set. Not frozen — a later add() still extends it. To remove a directive entirely, use reset().

reset(…​directives)

Csp

Removes the named directives (for example to unset a valueless directive). With no argument, removes nothing.

resetTo(headerValue)

Csp

Replaces the whole policy with the directives parsed from a raw header string; later contributions still apply on top. Parsing is lenient, mirroring the browser — invalid tokens are skipped, 'nonce-…' sources are dropped, and of repeated directives only the first counts. A comma (which would begin a further policy) and everything after it is ignored — only the first policy is applied. An empty or blank value clears the policy.

Nonces and hashes

Method Returns Description

nonceScriptSrc()

string

Wires the request nonce into script-src and returns its value, to stamp on inline <script nonce="..."> tags. Stable for the whole request — every nonce* method returns this same value.

nonceScriptSrcElem()

string

Wires the same nonce into script-src-elem (governs <script> elements). Use it when that directive is set with 'strict-dynamic'.

nonceStyleSrc()

string

Wires the same nonce into style-src, to stamp on inline <style nonce="..."> tags.

nonceStyleSrcElem()

string

Wires the same nonce into style-src-elem (governs <style> and <link rel=stylesheet>).

shaScriptSrc(source)

Csp

Unions a hash source into script-src. Takes a CspHashSource.

shaStyleSrc(source)

Csp

Unions a hash source into style-src. Takes a CspHashSource.

Sandbox and Trusted Types

Method Returns Description

sandbox(…​flags)

Csp

Unions SandboxFlag values into the sandbox directive. With no flags, registers an empty sandbox (every restriction applied).

requireTrustedTypesForScript()

Csp

Registers require-trusted-types-for 'script'.

trustedTypes(…​values)

Csp

Adds policy names and/or TrustedTypesKeyword keywords to the trusted-types directive.

Reporting

Method Returns Description

reportTo(group)

Csp

Adds the report-to directive naming a reporting group. Define the group with a companion Reporting-Endpoints response header (the caller’s responsibility). The older report-uri is deprecated; use add('report-uri', …​) if still needed.

CspSource

Common source-list keywords and schemes for a CSP source expression, per W3C CSP3. Keyword values are single-quoted; scheme values end in a colon. Pass these to any source-list directive method, alongside raw strings for hosts, paths and URLs.

Name Value Description

SELF

'self'

The page’s own origin.

NONE

'none'

The empty set — matches nothing.

UNSAFE_INLINE

'unsafe-inline'

Allows inline scripts and styles. The browser ignores it when a nonce or hash is also present.

UNSAFE_EVAL

'unsafe-eval'

Allows eval() and similar string-to-code APIs.

STRICT_DYNAMIC

'strict-dynamic'

Propagates trust from a nonced/hashed script to the scripts it loads.

UNSAFE_HASHES

'unsafe-hashes'

Allows specific inline event handlers and style attributes matched by hash.

WASM_UNSAFE_EVAL

'wasm-unsafe-eval'

Allows WebAssembly compilation without allowing eval().

REPORT_SAMPLE

'report-sample'

Asks the browser to include a sample of the offending content in violation reports.

DATA

data:

The data: scheme.

BLOB

blob:

The blob: scheme.

WILDCARD

*

Matches any URL, except the data:, blob: and filesystem: schemes.

SandboxFlag

Flags for the sandbox directive, passed to sandbox(). Tokens are emitted unquoted, as the CSP spec defines them. Each flag lifts one of the sandbox’s default restrictions.

Name Value Description

ALLOW_SCRIPTS

allow-scripts

Lets the content run scripts.

ALLOW_SAME_ORIGIN

allow-same-origin

Lets the content keep its origin instead of being forced into an opaque one.

ALLOW_FORMS

allow-forms

Lets the content submit forms.

ALLOW_POPUPS

allow-popups

Lets the content open popups.

ALLOW_MODALS

allow-modals

Lets the content open modal dialogs.

ALLOW_TOP_NAVIGATION

allow-top-navigation

Lets the content navigate the top-level browsing context.

ALLOW_DOWNLOADS

allow-downloads

Lets the content start downloads.

ALLOW_POINTER_LOCK

allow-pointer-lock

Lets the content use the Pointer Lock API.

ALLOW_PRESENTATION

allow-presentation

Lets the content start a presentation session.

ALLOW_ORIENTATION_LOCK

allow-orientation-lock

Lets the content lock the screen orientation.

TrustedTypesKeyword

Special keywords for the trusted-types directive, passed to trustedTypes() alongside user-defined policy names.

Name Value Description

ALLOW_DUPLICATES

'allow-duplicates'

Allows creating more than one Trusted Types policy with the same name.

NONE

'none'

Disallows creating any Trusted Types policy.

WILDCARD

*

Allows any policy name.

CspHashSource

A hash source passed to shaScriptSrc() / shaStyleSrc(). Provide either inline content to digest, or a precomputed hash — the two are mutually exclusive.

Name Type Description

content

string

Optional. Inline script or style text to digest. The computed '<algo>-<base64>' source is added to the directive. Provide either content or hash.

hash

string

Optional. Precomputed base64 digest, emitted verbatim as '<algo>-<hash>'. Provide either content or hash; when used, algo is required.

algo

string

Optional. Hash algorithm — one of sha256, sha384 or sha512. Defaults to sha256 when digesting content; required with hash. Any other value throws.


Contents

Contents