import { Plugin, CallExpressionShape, type RecordId } from '@servicenow/sdk-build-core' import { NowIdShape } from './now-id-plugin' export const ApplicabilityPlugin = Plugin.create({ name: 'ApplicabilityPlugin', records: { // TODO Add relationship support for role_names? sys_ux_applicability: { async toShape(record, { factory }) { const roles = record.get('roles') const roleIds = roles.ifString()?.ifNotEmpty()?.split(',') ?? [] const roleRefs: RecordId[] = [] for (const roleId of roleIds) { roleRefs.push( await factory.createReference({ source: record, table: 'sys_user_role', guid: roleId, }) ) } return { success: true, value: new CallExpressionShape({ source: record, callee: 'Applicability', args: [ record.transform(({ $ }) => { return { $id: $.val(NowIdShape.from(record)), name: $.def(''), description: $.def(''), active: $.toBoolean().def(true), roles: $.val(roleRefs).def([]), roleNames: $.from('role_names').def(''), // TODO Better support of this with references } }), ], }), } }, }, }, shapes: [ { shape: CallExpressionShape, fileTypes: ['fluent'], async toRecord(source, { factory }) { if (source.getCallee() !== 'Applicability') { return { success: false } } const arg = source.getArgument(0).asObject() const applicability = await factory.createRecord({ source: source, table: 'sys_ux_applicability', explicitId: arg.get('$id'), properties: arg.transform(({ $ }) => ({ name: $, description: $.def(''), active: $.toBoolean().def(true), roles: $.def([]).map((v) => v .ifArray() ?.pipe((r) => Array.from( new Set( r.getElements().map((r) => r.ifRecord()?.getId().getValue() ?? r.getValue()) ) ).join(',') ) ), role_names: $.from('roleNames').def(''), // TODO Better support of this with references })), }) return { success: true, value: applicability } }, }, ], })