@apify/utilities 2.35.10 → 3.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/code_hash_manager.d.ts +34 -0
  2. package/code_hash_manager.js +66 -0
  3. package/code_hash_manager.js.map +1 -0
  4. package/crypto.d.ts +35 -0
  5. package/crypto.js +58 -0
  6. package/crypto.js.map +1 -0
  7. package/exponential_backoff.d.ts +9 -0
  8. package/exponential_backoff.js +47 -0
  9. package/exponential_backoff.js.map +1 -0
  10. package/health_checker.d.ts +61 -0
  11. package/health_checker.js +132 -0
  12. package/health_checker.js.map +1 -0
  13. package/hmac.d.ts +20 -0
  14. package/hmac.js +59 -0
  15. package/hmac.js.map +1 -0
  16. package/index.d.ts +14 -0
  17. package/index.js +15 -0
  18. package/index.js.map +1 -0
  19. package/package.json +16 -21
  20. package/parse_boolean.d.ts +10 -0
  21. package/parse_boolean.js +25 -0
  22. package/parse_boolean.js.map +1 -0
  23. package/parse_jsonl_stream.d.ts +25 -0
  24. package/parse_jsonl_stream.js +79 -0
  25. package/parse_jsonl_stream.js.map +1 -0
  26. package/storages.d.ts +29 -0
  27. package/storages.js +37 -0
  28. package/storages.js.map +1 -0
  29. package/streams_utilities.d.ts +10 -0
  30. package/streams_utilities.js +26 -0
  31. package/streams_utilities.js.map +1 -0
  32. package/url_params_utils.d.ts +7 -0
  33. package/url_params_utils.js +11 -0
  34. package/url_params_utils.js.map +1 -0
  35. package/usernames.d.ts +10 -0
  36. package/usernames.js +1137 -0
  37. package/usernames.js.map +1 -0
  38. package/utilities.client.d.ts +125 -0
  39. package/utilities.client.js +408 -0
  40. package/utilities.client.js.map +1 -0
  41. package/utilities.d.ts +111 -0
  42. package/utilities.js +263 -0
  43. package/utilities.js.map +1 -0
  44. package/webhook_payload_template.d.ts +114 -0
  45. package/webhook_payload_template.js +245 -0
  46. package/webhook_payload_template.js.map +1 -0
  47. package/cjs/index.cjs +0 -2402
  48. package/cjs/index.cjs.map +0 -1
  49. package/cjs/index.d.ts +0 -609
  50. package/esm/index.d.mts +0 -609
  51. package/esm/index.mjs +0 -2314
  52. package/esm/index.mjs.map +0 -1
@@ -0,0 +1,245 @@
1
+ import { jsonStringifyExtended, JsonVariable } from './utilities.client.js';
2
+ class WebhookPayloadTemplateError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = this.constructor.name;
6
+ if (typeof Error.captureStackTrace === 'function') {
7
+ Error.captureStackTrace(this, this.constructor);
8
+ }
9
+ }
10
+ }
11
+ export class InvalidJsonError extends WebhookPayloadTemplateError {
12
+ constructor(originalError) {
13
+ super(originalError.message);
14
+ }
15
+ }
16
+ export class InvalidVariableError extends Error {
17
+ constructor(variable) {
18
+ super(`Invalid payload template variable: ${variable}`);
19
+ }
20
+ }
21
+ /**
22
+ * WebhookPayloadTemplate enables creation and parsing of webhook payload template strings.
23
+ * Template strings are JSON that may include template variables enclosed in double
24
+ * curly brackets: `{{variable}}`. When the template is parsed, variables are replaced
25
+ * with values from a provided context.
26
+ *
27
+ * This is useful to create dynamic webhook payloads where a template is saved on webhook
28
+ * creation and then variables are dynamically added on webhook dispatch.
29
+ *
30
+ * **Example:**
31
+ * ```js
32
+ * const payloadTemplate = `{
33
+ * "id": "some-id",
34
+ * "createdAt": "2019-05-08T15:22:21.095Z",
35
+ * "dataToSend": {{data}}
36
+ * }`
37
+ *
38
+ * const data = {
39
+ * status: 200,
40
+ * body: 'hello world'
41
+ * }
42
+ *
43
+ * const payloadObject = WebhookPayloadTemplate.parse(payloadTemplate, null, { data })
44
+ * ```
45
+ *
46
+ * **Produces:**
47
+ * ```js
48
+ * {
49
+ * id: "some-id",
50
+ * createdAt: '2019-05-08T15:22:21.095Z',
51
+ * dataToSend: {
52
+ * status: 200,
53
+ * body: 'hello world'
54
+ * }
55
+ * }
56
+ * ```
57
+ * @hideconstructor
58
+ */
59
+ export class WebhookPayloadTemplate {
60
+ template;
61
+ allowedVariables;
62
+ context;
63
+ payload;
64
+ replacedVariables = [];
65
+ constructor(template, allowedVariables = null, context = {}) {
66
+ this.template = template;
67
+ this.allowedVariables = allowedVariables;
68
+ this.context = context;
69
+ this.payload = template;
70
+ }
71
+ /**
72
+ * Parse existing webhook payload template string into an object, replacing
73
+ * template variables using the provided context.
74
+ *
75
+ * Parse also validates the template structure, so it can be used
76
+ * to check validity of the template JSON and usage of allowedVariables.
77
+ */
78
+ static parse(payloadTemplate, allowedVariables = null, context = {}, options = {}) {
79
+ const type = typeof payloadTemplate;
80
+ if (type !== 'string')
81
+ throw new Error(`Cannot parse a ${type} payload template.`);
82
+ const template = new WebhookPayloadTemplate(payloadTemplate, allowedVariables, context);
83
+ const data = template._parse(); // eslint-disable-line no-underscore-dangle
84
+ if (options.interpolateStrings) {
85
+ return template._interpolate(data); // eslint-disable-line no-underscore-dangle
86
+ }
87
+ return data;
88
+ }
89
+ /**
90
+ * Stringify an object into a webhook payload template.
91
+ * Values created using `getTemplateVariable('foo.bar')`
92
+ * will be stringified to `{{foo.bar}}` template variable.
93
+ */
94
+ static stringify(objectTemplate, replacer, indent = 2) {
95
+ const type = typeof objectTemplate;
96
+ if (!objectTemplate || type !== 'object')
97
+ throw new Error(`Cannot stringify a ${type} payload template.`);
98
+ return jsonStringifyExtended(objectTemplate, replacer, indent);
99
+ }
100
+ /**
101
+ * Produces an instance of a template variable that can be used
102
+ * in objects and will be stringified into `{{variableName}}` syntax.
103
+ *
104
+ * **Example:**
105
+ * ```js
106
+ * const resourceVariable = WebhookPayloadTemplate.getVariable('resource');
107
+ * const objectTemplate = {
108
+ * foo: 'foo',
109
+ * bar: ['bar'],
110
+ * res: resourceVariable,
111
+ * }
112
+ *
113
+ * const payloadTemplate = WebhookPayloadTemplate.stringify(objectTemplate);
114
+ * ```
115
+ *
116
+ * **Produces:**
117
+ * ```json
118
+ * {
119
+ * "foo": "foo",
120
+ * "bar": ["bar"],
121
+ * "res": {{resource}},
122
+ * }
123
+ * ```
124
+ */
125
+ static getVariable(variableName) {
126
+ return new JsonVariable(variableName);
127
+ }
128
+ _parse() {
129
+ let currentIndex = 0;
130
+ while (true) {
131
+ try {
132
+ return JSON.parse(this.payload);
133
+ }
134
+ catch (err) {
135
+ const position = this._findPositionOfNextVariable(currentIndex);
136
+ // When we catch an error from JSON.parse, but there's no remaining variable, we must have an invalid JSON.
137
+ if (!position) {
138
+ throw new InvalidJsonError(err);
139
+ }
140
+ if (!position.isInsideString) {
141
+ this._replaceVariable(position);
142
+ }
143
+ currentIndex = position.openBraceIndex + 1;
144
+ }
145
+ }
146
+ }
147
+ _interpolate(value) {
148
+ if (typeof value === 'string') {
149
+ return this._interpolateString(value);
150
+ }
151
+ // Array needs to go before object!
152
+ if (Array.isArray(value)) {
153
+ return this._interpolateArray(value);
154
+ }
155
+ if (typeof value === 'object' && value !== null) {
156
+ return this._interpolateObject(value);
157
+ }
158
+ // We can't interpolate anything else
159
+ return value;
160
+ }
161
+ _interpolateString(value) {
162
+ // If the string matches exactly, we return the variable value including the type
163
+ if (value.match(/^\{\{([a-zA-Z0-9.]+)\}\}$/)) {
164
+ // This just strips the {{ and }}
165
+ const variableName = value.substring(2, value.length - 2);
166
+ this._validateVariableName(variableName);
167
+ return this._getVariableValue(variableName);
168
+ }
169
+ // If it's just a part of substring, we replace the respective variables with their string variants
170
+ return value.replace(/\{\{([a-zA-Z0-9.]+)\}\}/g, (match, variableName) => {
171
+ this._validateVariableName(variableName);
172
+ const variableValue = this._getVariableValue(variableName);
173
+ return `${variableValue}`;
174
+ });
175
+ }
176
+ _interpolateObject(value) {
177
+ const result = {};
178
+ Object.entries(value).forEach(([key, v]) => {
179
+ result[key] = this._interpolate(v);
180
+ });
181
+ return result;
182
+ }
183
+ _interpolateArray(value) {
184
+ return value.map(this._interpolate.bind(this));
185
+ }
186
+ _findPositionOfNextVariable(startIndex = 0) {
187
+ const openBraceIndex = this.payload.indexOf('{{', startIndex);
188
+ const closeBraceIndex = this.payload.indexOf('}}', openBraceIndex) + 1;
189
+ const someVariableMaybeExists = openBraceIndex > -1 && closeBraceIndex > -1;
190
+ if (!someVariableMaybeExists)
191
+ return null;
192
+ const isInsideString = this._isVariableInsideString(openBraceIndex);
193
+ return { isInsideString, openBraceIndex, closeBraceIndex };
194
+ }
195
+ _isVariableInsideString(openBraceIndex) {
196
+ const unescapedQuoteCount = this._countUnescapedDoubleQuotesUpToIndex(openBraceIndex);
197
+ return unescapedQuoteCount % 2 === 1;
198
+ }
199
+ _countUnescapedDoubleQuotesUpToIndex(index) {
200
+ const payloadSection = this.payload.substring(0, index);
201
+ let unescapedQuoteCount = 0;
202
+ for (let i = 0; i < payloadSection.length; i++) {
203
+ const char = payloadSection[i];
204
+ const prevChar = payloadSection[i - 1];
205
+ if (char === '"' && prevChar !== '\\') {
206
+ unescapedQuoteCount++;
207
+ }
208
+ }
209
+ return unescapedQuoteCount;
210
+ }
211
+ _replaceVariable({ openBraceIndex, closeBraceIndex }) {
212
+ const variableName = this.payload.substring(openBraceIndex + 2, closeBraceIndex - 1);
213
+ this._validateVariableName(variableName);
214
+ const replacement = this._getVariableReplacement(variableName);
215
+ this.replacedVariables.push({ variableName, replacement });
216
+ this.payload =
217
+ this.payload.substring(0, openBraceIndex) + replacement + this.payload.substring(closeBraceIndex + 1);
218
+ }
219
+ _validateVariableName(variableName) {
220
+ if (this.allowedVariables === null)
221
+ return;
222
+ const [variable] = variableName.split('.');
223
+ // Properties of the variable are not validated on purpose
224
+ // as they will later be set to null if not found.
225
+ // This serves to enable dynamic variable structures.
226
+ const isVariableValid = this.allowedVariables.has(variable);
227
+ if (!isVariableValid)
228
+ throw new InvalidVariableError(variableName);
229
+ }
230
+ _getVariableValue(variableName) {
231
+ const [variable, ...properties] = variableName.split('.');
232
+ const context = this.context[variable];
233
+ const value = properties.reduce((ctx, prop) => {
234
+ if (!ctx || typeof ctx !== 'object')
235
+ return null;
236
+ return ctx[prop];
237
+ }, context);
238
+ return value;
239
+ }
240
+ _getVariableReplacement(variableName) {
241
+ const value = this._getVariableValue(variableName);
242
+ return value ? JSON.stringify(value) : null;
243
+ }
244
+ }
245
+ //# sourceMappingURL=webhook_payload_template.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook_payload_template.js","sourceRoot":"","sources":["../src/webhook_payload_template.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE5E,MAAM,2BAA4B,SAAQ,KAAK;IAC3C,YAAY,OAAgB;QACxB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;QAClC,IAAI,OAAO,KAAK,CAAC,iBAAiB,KAAK,UAAU,EAAE,CAAC;YAChD,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;QACpD,CAAC;IACL,CAAC;CACJ;AAED,MAAM,OAAO,gBAAiB,SAAQ,2BAA2B;IAC7D,YAAY,aAAoB;QAC5B,KAAK,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IACjC,CAAC;CACJ;AACD,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAC3C,YAAY,QAAiB;QACzB,KAAK,CAAC,sCAAsC,QAAQ,EAAE,CAAC,CAAC;IAC5D,CAAC;CACJ;AAQD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,MAAM,OAAO,sBAAsB;IAMV;IACA;IACA;IAPb,OAAO,CAAS;IAEf,iBAAiB,GAAoD,EAAE,CAAC;IAEjF,YACqB,QAAgB,EAChB,mBAAuC,IAAI,EAC3C,UAA+B,EAAE;QAFjC,aAAQ,GAAR,QAAQ,CAAQ;QAChB,qBAAgB,GAAhB,gBAAgB,CAA2B;QAC3C,YAAO,GAAP,OAAO,CAA0B;QAElD,IAAI,CAAC,OAAO,GAAG,QAAQ,CAAC;IAC5B,CAAC;IAED;;;;;;OAMG;IACH,M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AAC,CAAC;IAC9G,CAAC;IAEO,qBAAqB,CAAC,YAAoB;QAC9C,IAAI,IAAI,CAAC,gBAAgB,KAAK,IAAI;YAAE,OAAO;QAC3C,MAAM,CAAC,QAAQ,CAAC,GAAG,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAE3C,0DAA0D;QAC1D,kDAAkD;QAClD,qDAAqD;QACrD,MAAM,eAAe,GAAG,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAE5D,IAAI,CAAC,eAAe;YAAE,MAAM,IAAI,oBAAoB,CAAC,YAAY,CAAC,CAAC;IACvE,CAAC;IAEO,iBAAiB,CAAC,YAAoB;QAC1C,MAAM,CAAC,QAAQ,EAAE,GAAG,UAAU,CAAC,GAAG,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC1D,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACvC,MAAM,KAAK,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;YAC1C,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ;gBAAE,OAAO,IAAI,CAAC;YACjD,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC;QACrB,CAAC,EAAE,OAAO,CAAC,CAAC;QACZ,OAAO,KAAK,CAAC;IACjB,CAAC;IAEO,uBAAuB,CAAC,YAAoB;QAChD,MAAM,KAAK,GAAG,IAAI,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;QACnD,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAChD,CAAC;CACJ","sourcesContent":["import { jsonStringifyExtended, JsonVariable } from './utilities.client.js';\n\nclass WebhookPayloadTemplateError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\nexport class InvalidJsonError extends WebhookPayloadTemplateError {\n constructor(originalError: Error) {\n super(originalError.message);\n }\n}\nexport class InvalidVariableError extends Error {\n constructor(variable?: string) {\n super(`Invalid payload template variable: ${variable}`);\n }\n}\n\ninterface ParsePosition {\n isInsideString: boolean;\n openBraceIndex: number;\n closeBraceIndex: number;\n}\n\n/**\n * WebhookPayloadTemplate enables creation and parsing of webhook payload template strings.\n * Template strings are JSON that may include template variables enclosed in double\n * curly brackets: `{{variable}}`. When the template is parsed, variables are replaced\n * with values from a provided context.\n *\n * This is useful to create dynamic webhook payloads where a template is saved on webhook\n * creation and then variables are dynamically added on webhook dispatch.\n *\n * **Example:**\n * ```js\n * const payloadTemplate = `{\n * \"id\": \"some-id\",\n * \"createdAt\": \"2019-05-08T15:22:21.095Z\",\n * \"dataToSend\": {{data}}\n * }`\n *\n * const data = {\n * status: 200,\n * body: 'hello world'\n * }\n *\n * const payloadObject = WebhookPayloadTemplate.parse(payloadTemplate, null, { data })\n * ```\n *\n * **Produces:**\n * ```js\n * {\n * id: \"some-id\",\n * createdAt: '2019-05-08T15:22:21.095Z',\n * dataToSend: {\n * status: 200,\n * body: 'hello world'\n * }\n * }\n * ```\n * @hideconstructor\n */\nexport class WebhookPayloadTemplate {\n private payload: string;\n\n readonly replacedVariables: { variableName: string; replacement: string }[] = [];\n\n constructor(\n private readonly template: string,\n private readonly allowedVariables: Set<string> | null = null,\n private readonly context: Record<string, any> = {},\n ) {\n this.payload = template;\n }\n\n /**\n * Parse existing webhook payload template string into an object, replacing\n * template variables using the provided context.\n *\n * Parse also validates the template structure, so it can be used\n * to check validity of the template JSON and usage of allowedVariables.\n */\n static parse(\n payloadTemplate: string,\n allowedVariables: Set<string> | null = null,\n context: Record<string, any> = {},\n options: { interpolateStrings?: boolean } = {},\n ): Record<string, any> {\n const type = typeof payloadTemplate;\n if (type !== 'string') throw new Error(`Cannot parse a ${type} payload template.`);\n const template = new WebhookPayloadTemplate(payloadTemplate, allowedVariables, context);\n const data = template._parse(); // eslint-disable-line no-underscore-dangle\n if (options.interpolateStrings) {\n return template._interpolate(data); // eslint-disable-line no-underscore-dangle\n }\n return data;\n }\n\n /**\n * Stringify an object into a webhook payload template.\n * Values created using `getTemplateVariable('foo.bar')`\n * will be stringified to `{{foo.bar}}` template variable.\n */\n static stringify(objectTemplate: Record<string, any>, replacer?: ((_: any) => string) | null, indent = 2): string {\n const type = typeof objectTemplate;\n if (!objectTemplate || type !== 'object') throw new Error(`Cannot stringify a ${type} payload template.`);\n return jsonStringifyExtended(objectTemplate, replacer, indent);\n }\n\n /**\n * Produces an instance of a template variable that can be used\n * in objects and will be stringified into `{{variableName}}` syntax.\n *\n * **Example:**\n * ```js\n * const resourceVariable = WebhookPayloadTemplate.getVariable('resource');\n * const objectTemplate = {\n * foo: 'foo',\n * bar: ['bar'],\n * res: resourceVariable,\n * }\n *\n * const payloadTemplate = WebhookPayloadTemplate.stringify(objectTemplate);\n * ```\n *\n * **Produces:**\n * ```json\n * {\n * \"foo\": \"foo\",\n * \"bar\": [\"bar\"],\n * \"res\": {{resource}},\n * }\n * ```\n */\n static getVariable(variableName: string): JsonVariable {\n return new JsonVariable(variableName);\n }\n\n private _parse() {\n let currentIndex = 0;\n\n while (true) {\n try {\n return JSON.parse(this.payload);\n } catch (err) {\n const position = this._findPositionOfNextVariable(currentIndex);\n // When we catch an error from JSON.parse, but there's no remaining variable, we must have an invalid JSON.\n if (!position) {\n throw new InvalidJsonError(err as Error);\n }\n if (!position.isInsideString) {\n this._replaceVariable(position);\n }\n currentIndex = position.openBraceIndex + 1;\n }\n }\n }\n\n private _interpolate(value: any): any {\n if (typeof value === 'string') {\n return this._interpolateString(value);\n }\n // Array needs to go before object!\n if (Array.isArray(value)) {\n return this._interpolateArray(value);\n }\n if (typeof value === 'object' && value !== null) {\n return this._interpolateObject(value);\n }\n // We can't interpolate anything else\n return value;\n }\n\n private _interpolateString(value: string): string {\n // If the string matches exactly, we return the variable value including the type\n if (value.match(/^\\{\\{([a-zA-Z0-9.]+)\\}\\}$/)) {\n // This just strips the {{ and }}\n const variableName = value.substring(2, value.length - 2);\n this._validateVariableName(variableName);\n return this._getVariableValue(variableName);\n }\n // If it's just a part of substring, we replace the respective variables with their string variants\n return value.replace(/\\{\\{([a-zA-Z0-9.]+)\\}\\}/g, (match, variableName) => {\n this._validateVariableName(variableName);\n const variableValue = this._getVariableValue(variableName);\n return `${variableValue}`;\n });\n }\n\n private _interpolateObject(value: Record<string, any>): Record<string, any> {\n const result = {} as Record<string, any>;\n Object.entries(value).forEach(([key, v]) => {\n result[key] = this._interpolate(v);\n });\n return result;\n }\n\n private _interpolateArray(value: any[]): any[] {\n return value.map(this._interpolate.bind(this));\n }\n\n private _findPositionOfNextVariable(startIndex = 0): ParsePosition | null {\n const openBraceIndex = this.payload.indexOf('{{', startIndex);\n const closeBraceIndex = this.payload.indexOf('}}', openBraceIndex) + 1;\n const someVariableMaybeExists = openBraceIndex > -1 && closeBraceIndex > -1;\n if (!someVariableMaybeExists) return null;\n const isInsideString = this._isVariableInsideString(openBraceIndex);\n return { isInsideString, openBraceIndex, closeBraceIndex };\n }\n\n private _isVariableInsideString(openBraceIndex: number): boolean {\n const unescapedQuoteCount = this._countUnescapedDoubleQuotesUpToIndex(openBraceIndex);\n return unescapedQuoteCount % 2 === 1;\n }\n\n private _countUnescapedDoubleQuotesUpToIndex(index: number): number {\n const payloadSection = this.payload.substring(0, index);\n let unescapedQuoteCount = 0;\n for (let i = 0; i < payloadSection.length; i++) {\n const char = payloadSection[i];\n const prevChar = payloadSection[i - 1];\n if (char === '\"' && prevChar !== '\\\\') {\n unescapedQuoteCount++;\n }\n }\n return unescapedQuoteCount;\n }\n\n private _replaceVariable({ openBraceIndex, closeBraceIndex }: ParsePosition): void {\n const variableName = this.payload.substring(openBraceIndex + 2, closeBraceIndex - 1);\n this._validateVariableName(variableName);\n const replacement = this._getVariableReplacement(variableName)!;\n this.replacedVariables.push({ variableName, replacement });\n this.payload =\n this.payload.substring(0, openBraceIndex) + replacement + this.payload.substring(closeBraceIndex + 1);\n }\n\n private _validateVariableName(variableName: string): void {\n if (this.allowedVariables === null) return;\n const [variable] = variableName.split('.');\n\n // Properties of the variable are not validated on purpose\n // as they will later be set to null if not found.\n // This serves to enable dynamic variable structures.\n const isVariableValid = this.allowedVariables.has(variable);\n\n if (!isVariableValid) throw new InvalidVariableError(variableName);\n }\n\n private _getVariableValue(variableName: string): any {\n const [variable, ...properties] = variableName.split('.');\n const context = this.context[variable];\n const value = properties.reduce((ctx, prop) => {\n if (!ctx || typeof ctx !== 'object') return null;\n return ctx[prop];\n }, context);\n return value;\n }\n\n private _getVariableReplacement(variableName: string): string | null {\n const value = this._getVariableValue(variableName);\n return value ? JSON.stringify(value) : null;\n }\n}\n"]}