Built-in object types
AutomatorScript supports a number of built-in object types that follow the behavior of their JavaScript original.
Array
Documentation about arrays and their methods can be found in the MDN Array reference.
Note: sparse arrays are not supported.
Usage example
let list = [1, 2, 3, 4];
let task_list = workflow.tasks;
Allowed static methods
Allowed instance methods
- at
- concat
- copyWithin
- entries
- every
- fill
- filter
- find
- findIndex
- first
- flat
- flatMap
- forEach
- groupBy
- includes
- indexBy
- indexOf
- inSlicesOf
- join
- keys
- last
- lastIndexOf
- map
- pop
- push
- reduce
- reverse
- shift
- slice
- some
- sort
- splice
- toString
- uniq
- unshift
Array extension methods
Some of the methods listed above are not native to JavaScript and have been added in AutomatorScript to make working with lists of items easier. These methods are described below.
first
Returns the first element of the array.
let array = [1, 2, 3];
let first = array.first();
// first = 1
groupBy
Returns an object where the keys are the values of the specified property and the values are arrays of elements with that property.
let people = [
{ name: "John", age: 30 },
{ name: "Peter", age: 25 },
{ name: "Mary", age: 25 },
];
let groupedByAge = people.groupBy("age");
// groupedByAge = {
// 25: [{ name: "Peter", age: 25 }, { name: "Mary", age: 25 }],
// 30: [{ name: "John", age: 30 }]
// }
Once you have created the groups, you can use Object.entries() to iterate over them, for example:
for (const [age, group] of Object.entries(groupedByAge)) {
log(age, group); // Log the people in each age group
}
indexBy
Returns an object where the keys are the values of the specified property and the values are the elements themselves. If there are multiple elements with the same value of the specified property, only the last one is returned.
let people = [
{ name: "John", age: 30 },
{ name: "Peter", age: 25 },
{ name: "Mary", age: 25 },
];
let indexedByName = people.indexBy("name");
// indexedByName = {
// John: { name: "John", age: 30 },
// Peter: { name: "Peter", age: 25 },
// Mary: { name: "Mary", age: 25 }
// }
let indexedByAge = people.indexBy("age");
// indexedByAge = {
// 25: { name: "Mary", age: 25 },
// 30: { name: "John", age: 30 }
// }
inSlicesOf
Splits the array into smaller arrays (slices) of the specified size. The last slice may contain fewer elements if the array length is not evenly divisible by the slice size.
let people = [
{ name: "John", age: 30 },
{ name: "Peter", age: 25 },
{ name: "Mary", age: 25 },
];
let slices = people.inSlicesOf(2);
// slices = [
// [{ name: "John", age: 30 }, { name: "Peter", age: 25 }],
// [{ name: "Mary", age: 25 }]
// ]
last
Same as array.at(-1).
let array = [1, 2, 3];
let last = array.last();
// last = 3
renameKeys
Renames the keys of each object in the array according to the given mapping. Keys not present in the mapping are kept as-is. The mapping can be specified as object or Map.
Returns a new array with the renamed objects.
let people = [{ name: "John", age: 30 }, { name: "Peter", age: 25 }];
let renamed1 = people.renameKeys({ name: "full_name" });
// [{ full_name: "John", age: 30 }, { full_name: "Peter", age: 25 }]
let mapping = new Map();
mapping.set("age", "years");
let renamed2 = people.renameKeys(mapping);
// [{ name: "John", years: 30 }, { name: "Peter", years: 25 }]
pick
Projects each object in the array to only the specified keys.
Returns a new array with objects containing only the specified keys.
let people = [{ name: "John", age: 30, city: "NY" }, { name: "Peter", age: 25, city: "LA" }];
let names = people.pick(["name", "city"]);
// [{ name: "John", city: "NY" }, { name: "Peter", city: "LA" }]
The pick method does not auto fetch lazily loaded Xurrent objects.
For example, this will not work:
let requests = fetchFilter("requests", "category=rfc");
let members = requests.map(request => request.member);
// At this point, `members` is an array of references to Person records (containing only ID and name),
// and their details have not yet been auto fetched.
let jobTitles = members.pick(["job_title"]); // Does NOT work! `pick` does not auto fetch
uniq
Returns a new array with only the unique values of the original array.
let array = [1, 3, 2, 2, 3, 3, 1];
let uniq = array.uniq();
// uniq = [1, 3, 2]
wrap
If the given value is an array, returns the value as-is, otherwise wraps it in an array.
This can be very useful, for example, when dealing with Xurrent custom fields, which value can sometimes be a single
element and sometimes be an array, depending on whether the field was marked as "Multiple". By wrapping the value in an
array, you can further process it in an uniform way, using functions such as map.
let val1 = Array.wrap(42); // => [42]
let val2 = Array.wrap([42]); // => [42]
let val3 = Array.wrap([42, 43]); // => [42, 43]
Iterator
Documentation about iterators can be found in the MDN Iterator reference.
Usage example
let list = [1, 2, 3, 4];
let list_iterator = list.entries();
let value_1 = list_iterator.next();
log("value_1", value_1.value);
let value_2 = list_iterator.next();
log("value_2", value_2.value);
Allowed members
Boolean
Documentation about booleans can be found in the MDN Boolean reference.
Allowed members
Date
Documentation about dates can be found in the MDN Date reference.
New date objects can be created with the Date() constructor.
Usage example
let date_1 = new Date(); //current date
let date_2 = new Date(2010, 12, 24); // Christmas 2010
Allowed members
- getDate
- getDay
- getFullYear
- getHours
- getMilliseconds
- getMinutes
- getMonth
- getSeconds
- getTime
- getTimezoneOffset
- getYear
- getUTCDate
- getUTCFullYear
- getUTCHours
- getUTCMilliseconds
- getUTCMinutes
- getUTCMonth
- getUTCSeconds
- setDate
- setFullYear
- setYear
- setHours
- setMilliseconds
- setMinutes
- setMonth
- setSeconds
- setTime
- setUTCDate
- setUTCFullYear
- setUTCHours
- setUTCMilliseconds
- setUTCMinutes
- setUTCMonth
- setUTCSeconds
- toDateString
- toGMTString
- toISOString
- toJSON
- toLocaleDateString
- toLocaleTimeString
- toTimeString
- toUTCString
Error
Documentation about the Error object can be found in the MDN Error reference.
New error objects can be created with the Error() constructor.
The following constructor variants are supported:
new Error();
new Error(message);
new Error(message, { cause });
The optional second parameter is an object with a cause attribute.
When you catch an error, the following properties can be accessed:
For backward compatibility with existing packages, you can also access the cause via the exception property.
This property is deprecated, however, and should be avoided in new packages.
When you log an error, the following properties will be included in the log:
- name
- message
- cause
- stack
Usage example
function checkLimit() {
if (nrOfRequests > limit) {
throw new Error(`The number of requests cannot exceed ${limit}`);
}
}
try {
checkLimit();
} catch (e) {
const { name, message, cause } = e;
logError(`Unexpected ${name}: ${message}`, cause);
throw new Error("Something went wrong", { cause: e });
// You can also re-raise caught errors directly, for example:
// throw e;
}
Global
Allowed members
JavaScript has a small number of global utility functions that are not part of any object type. AutomatorScript supports the following:
Math
Documentation about math functions can be found in the MDN Math reference.
Usage example
let pi = Math.PI;
Allowed members
- E
- LN10
- LN2
- LOG10E
- PI
- SQRT1_2
- SQRT2
- abs
- acos
- acosh
- asin
- asinh
- atan
- atan2
- atanh
- cbrt
- ceil
- clz32
- cos
- cosh
- exp
- expm1
- floor
- fround
- hypot
- imul
- log
- log10
- log1p
- log2
- max
- min
- pow
- random
- round
- sign
- sin
- sinh
- sqrt
- tan
- tanh
- trunc
Number
Documentation about numbers can be found in the MDN Number reference.
Usage example
let x = 5;
let check = Number.isInteger(x);
log("check", check ? "It is" : "It is not");
Allowed members
- EPSILON
- MAX_SAFE_INTEGER
- MAX_VALUE
- MIN_SAFE_INTEGER
- MIN_VALUE
- NEGATIVE_INFINITY
- NaN
- POSITIVE_INFINITY
- isFinite
- isInteger
- isNaN
- isSafeInteger
- parseFloat
- toExponential
- toPrecision
- toString
Object
Documentation about the Object type can be found in the MDN Object reference.
Usage example
let obj = { a: 1, b: 2 };
let keys = Object.keys(obj); // ['a', 'b']
let values = Object.values(obj); // [1, 2]
Allowed members
RegExp
Documentation about regular expressions can be found in the MDN RegExp reference.
To create a regular expression, either use
the RegExp() constructor
or the literal syntax /pattern/flags.
Allowed members
Map
Documentation about maps can be found in the MDN Map reference.
Maps are similar to plain JavaScript objects in many ways, but there are some interesting differences. The section on objects vs. maps provides a good overview of the differences and similarities between the two.
New maps can be constructed with the Map() constructor.
Usage example
let map = new Map();
Allowed members
Set
Documentation about sets can be found in the MDN Set reference.
New sets can be constructed with the Set() constructor.
Usage example
let set = new Set();
Allowed members
- add
- clear
- delete
- difference
- entries
- has
- keys
- intersection
- isDisjointFrom
- isSubsetOf
- isSupersetOf
- symmetricDifference
- union
- values
String
Documentation about strings can be found in the MDN String reference.
Usage example
let str = "Hello!";
Allowed members
- anchor
- at
- charAt
- charCodeAt
- codePointAt
- concat
- endsWith
- fromCharCode
- fromCodePoint
- includes
- indexOf
- lastIndexOf
- link
- localeCompare
- match
- normalize
- padEnd
- padStart
- repeat
- replace
- replaceAll
- search
- slice
- split
- startsWith
- substr
- substring
- toLocaleLowerCase
- toLocaleUpperCase
- toLowerCase
- toUpperCase
- trim
- trimEnd
- trimLeft
- trimRight
- trimStart
Buffer
Buffers are used to represent a sequence of bytes (i.e. binary data).
Some functions, such as crypto_randomBytes, return a buffer.
Also, the content attribute of inbound email attachments is a buffer.
Documentation about buffers can be found on the Node.js Buffer page.
Usage example
let buffer = crypto_randomBytes(10);
let string = buffer.toString("hex");
// Assume that `mail` has a text attachment containing a CSV file.
let csv = mail.attachments[0].content.toString("utf8");
Allowed members
Moment - Timezone
Moment.js is a library for parsing, validating, manipulating, and formatting dates.
To create a moment object, use the moment() function.
Usage example
let dt = new Date();
let m = moment(dt);
Allowed members
- add
- calendar
- date
- dates
- day
- dayOfYear
- days
- daysInMonth
- diff
- endOf
- format
- from
- fromNow
- get
- hour
- hours
- invalidAt
- isAfter
- isBefore
- isBetween
- isDST
- isDSTShifted
- isLeapYear
- isoWeek
- isoWeekday
- isoWeeks
- isoWeeksInYear
- isoWeekYear
- isSame
- isSameOrAfter
- isSameOrBefore
- isValid
- local
- locale
- millisecond
- milliseconds
- minute
- minutes
- month
- months
- quarter
- quarters
- second
- seconds
- set
- startOf
- subtract
- to
- toDate
- toISOString
- toJSON
- toNow
- toString
- tz
- utc
- utcOffset
- valueOf
- week
- weekday
- weeks
- weekYear
- year
- years