Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## 0.3.0 — 2026-11-16

Render Template can load the chosen template's merge fields.

### Added

- **Merge Fields Source → From Template** on **Render → Render Template**.
Picking a template lists its merge fields, one input each, so nobody types
placeholder names. A field left empty keeps the template's own value, and so
does a field added to the template after the step was set up, so neither
renders as a raw placeholder. Each value takes the type of the template's
own value, so a "5" from a sheet fills a number placeholder as a number.
**Map Automatically** fills the fields from input columns with the same
names.
- Node version 2, where **From Template** is the default, so new Shotstack
steps show a template's fields as soon as it is picked. Saved workflows stay
on version 1, where **Fields** is still the default, so they are unchanged.

## 0.2.2 — 2026-10-30

Fixes the Shotstack credential in n8n's HTTP Request node. With the credential
Expand Down
21 changes: 14 additions & 7 deletions MAINTAINING.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,13 @@ only eight.
| --- | --- |
| `package.json` | the package name `@shotstack/n8n-nodes-shotstack`, and the built paths `dist/nodes/Shotstack/Shotstack.node.js` and `dist/credentials/ShotstackApi.credentials.js` |
| `credentials/ShotstackApi.credentials.ts` | the credential type `shotstackApi`; the fields `environment` and `apiKey`; the values `sandbox` and `production` |
| `nodes/Shotstack/Shotstack.node.ts` | the node type `shotstack`; the behaviour of version 1, which n8n stamps on every saved node as typeVersion; the field `resource`; the values `render`, `asset` and `generation` |
| `nodes/Shotstack/Shotstack.node.ts` | the node type `shotstack`; the behaviour of versions 1 and 2, which n8n stamps on every saved node as typeVersion; the field `resource`; the values `render`, `asset` and `generation` |
| `nodes/Shotstack/resources/render/index.ts` | the field `operation`; the values `postRender`, `postTemplateRender` and `getRender` |
| `nodes/Shotstack/resources/asset/index.ts` | the field `operation`; the value `getAssetByRenderId` |
| `nodes/Shotstack/resources/generation/index.ts` | the field `operation`; the values `postGenerate`, `getGenerate`, `getModels` and `postGenerateQuote` |
| `nodes/Shotstack/Shotstack.node.json` | the codex key `@shotstack/n8n-nodes-shotstack.shotstack`. n8n matches the codex to the node on that exact string, which joins the package name to the node type, so it is a third place either can break |
| `nodes/Shotstack/resources/render/postRender.ts` | the fields `edit` and `callback` |
| `nodes/Shotstack/resources/render/postTemplateRender.ts` | the fields `templateId`, `mergeSource`, `mergeJson` and `merge`; the picker modes `list` and `id`; the collection key `mergeFields` and its fields `find` and `replace`; the values `fields` and `json` |
| `nodes/Shotstack/resources/render/postTemplateRender.ts` | the fields `templateId`, `mergeSource`, `mergeJson`, `merge` and `templateFields`; the picker modes `list` and `id`; the collection key `mergeFields` and its fields `find` and `replace`; the values `fields`, `json` and `template` |
| `nodes/Shotstack/resources/render/getRender.ts` | the fields `renderId`, `waitForCompletion`, `giveUpAfter`, `includeData` and `simple`; the Simplify keys `id`, `status`, `url`, `poster`, `thumbnail`, `duration`, `renderTime`, `error` and `data` |
| `nodes/Shotstack/resources/asset/getAssetByRenderId.ts` | the fields `renderId`, `mainFileOnly` and `simple`; the Simplify keys `assetId`, `renderId`, `url`, `filename` and `status`. `assetId` departs from the spec on purpose: the spec calls it `id`, but only inside an asset object, and Simplify flattens that object away. Do not correct it back |
| `nodes/Shotstack/resources/generation/postGenerate.ts` | the fields `assetType`, `prompt`, `model`, `modelOptions`, `length`, `waitForAsset` and `giveUpAfter`; the asset type values `image`, `video` and `audio`. These build the request body in code, so a rename here changes what a saved workflow sends, not just what it shows |
Expand All @@ -148,11 +148,12 @@ The check leaves one thing alone: the node version number. Raising it is how
you change a frozen name safely, so a check on it would fire on every release.
See the versioning rule under Rules.

One name is not frozen and still breaks in silence, because two files have to
agree on it. `nodes/Shotstack/Shotstack.node.ts` exports the list method as
`getTemplates`, and `nodes/Shotstack/resources/render/postTemplateRender.ts`
asks for it by that name. Rename one end only and the template picker returns
nothing, with no error. Change both ends together.
Two names are not frozen and still break in silence, because two files have to
agree on each. `nodes/Shotstack/Shotstack.node.ts` exports the list method as
`getTemplates` and the resource mapper method as `getTemplateFields`, and
`nodes/Shotstack/resources/render/postTemplateRender.ts` asks for each by that
name. Rename one end only and the template picker, or the template's merge
fields, come back empty, with no error. Change both ends together.

One more, and it is the filename rather than the contents:
`.github/workflows/publish.yml`. npm's trusted publisher entry names that file,
Expand Down Expand Up @@ -181,6 +182,12 @@ Break one of these and something fails quietly.
`typeVersion` on every node, so an existing workflow keeps running the old
version and a new node gets the new one. Editing a name in place instead
empties that field in every saved workflow, with no error.
- **A new default needs a version too.** n8n leaves a value that equals its
default out of a saved workflow, so changing a default changes every saved
step that relied on the old one. Raise `version` and give the property one
copy per version, told apart by `'@version'` in its displayOptions, as
`mergeSource` does in `postTemplateRender.ts`. An addition that no saved
workflow can be using, such as a new option, may go into version 1 too.
- **Never use `setTimeout`.** Use `sleep` from `n8n-workflow`. The lint blocks
`setTimeout` and n8n Cloud verification rejects it.
- **Never throw from inside a routing expression.** n8n evaluates those in a
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ Renders a template saved in your Shotstack account, filling in its placeholders.
| Field | Notes |
| --- | --- |
| **Template** | Pick one from the list, or paste an ID. Templates are made in [Shotstack Studio](https://shotstack.io/studio/). |
| **Merge Fields Source** | **Fields** for find/replace pairs, or **JSON** to supply the whole list at once. |
| **Merge Fields** | The find value is the placeholder name without braces. See [Merging data](https://shotstack.io/docs/guide/architecting-an-application/merging-data/). |
| **Merge Fields Source** | **From Template**, the default for new steps, loads the chosen template's merge fields, one input each. **Fields** for find/replace pairs, or **JSON** to supply the whole list at once. Steps saved before 0.3.0 keep **Fields** as their default. |
| **Merge Fields** | With **From Template**, a field left empty keeps the template's own value, and so does a field added to the template later. Each value takes the type of the template's own value, so a `5` from a sheet fills a number placeholder as a number. **Map Automatically** fills fields from input columns with the same names. With **Fields**, the find value is the placeholder name without braces. See [Merging data](https://shotstack.io/docs/guide/architecting-an-application/merging-data/). |

Returns the render `id`. This operation takes no Callback URL: the Edit API
accepts one on `POST /templates/render` and does not act on it. Use
Expand Down
8 changes: 7 additions & 1 deletion nodes/Shotstack/Shotstack.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { TELEMETRY_HEADERS } from './telemetry';
import { EDIT_BASE_URL } from './environment';
import { getTemplates } from './listSearch/getTemplates';
import { getModels } from './loadOptions/getModels';
import { getTemplateFields } from './resourceMapping/getTemplateFields';
import codexFile from './Shotstack.node.json';

export class Shotstack implements INodeType {
Expand All @@ -17,7 +18,9 @@ export class Shotstack implements INodeType {
dark: 'file:../../icons/shotstack.dark.svg',
},
group: ['transform'],
version: 1,
// Version 2 starts Render Template on the template's own merge fields. Saved
// workflows keep version 1, which defaults to Fields.
version: [1, 2],
// The operation values are OpenAPI operationIds, so the resource tells
// the reader which of the three a bare id belongs to.
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
Expand Down Expand Up @@ -87,5 +90,8 @@ export class Shotstack implements INodeType {
loadOptions: {
getModels,
},
resourceMapping: {
getTemplateFields,
},
};
}
84 changes: 84 additions & 0 deletions nodes/Shotstack/resourceMapping/getTemplateFields.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { NodeOperationError } from 'n8n-workflow';
import type {
IDataObject,
IExecuteSingleFunctions,
ILoadOptionsFunctions,
ResourceMapperFields,
} from 'n8n-workflow';
import { apiPathFor } from '../environment';
import { TELEMETRY_HEADERS } from '../telemetry';

export type MergeField = { find: string; replace: unknown };

// n8n starts every item of a run at once, so the items share one lookup instead of
// making one each. Keyed by run, so a template edited in Studio between runs is read fresh.
const lookups = new Map<string, Promise<MergeField[]>>();

/** The template's merge fields as saved in Shotstack, each with the template's own value. */
export async function templateMerge(
this: IExecuteSingleFunctions | ILoadOptionsFunctions,
id: string,
): Promise<MergeField[]> {
const credentials = await this.getCredentials('shotstackApi');
const path = apiPathFor(credentials?.environment);
const run = this.getExecutionId();
const key = `${run}:${path}:${id}`;
let lookup = run ? lookups.get(key) : undefined;
if (!lookup) {
lookup = (async () => {
const response = (await this.helpers.httpRequestWithAuthentication.call(this, 'shotstackApi', {
method: 'GET',
url: `https://api.shotstack.io/edit/${path}/templates/${encodeURIComponent(id)}`,
json: true,
timeout: 30000,
headers: { ...TELEMETRY_HEADERS },
})) as IDataObject;
const template = ((response?.response as IDataObject | undefined)?.template ?? {}) as IDataObject;
const merge = Array.isArray(template.merge) ? (template.merge as MergeField[]) : [];
return merge.filter((field) => typeof field?.find === 'string' && field.find !== '');
})();
if (run) {
if (lookups.size >= 100) lookups.clear();
lookups.set(key, lookup);
// Retry On Fail runs the step again inside the same run, so a failed lookup is dropped.
lookup.catch(() => lookups.delete(key));
}
}

try {
return await lookup;
} catch (error) {
// A new error for each caller, since n8n writes the item index onto the error it gets.
const status = String((error as { httpCode?: unknown }).httpCode ?? '');
const refused = status === '401' || status === '403';
throw new NodeOperationError(
this.getNode(),
refused ? 'Shotstack refused the API key' : "Couldn't read the template's merge fields",
{
description: refused
? 'Check the key, and check that the credential environment matches it. Sandbox and Production keep separate templates.'
: `${(error as Error).message}. Check that the template exists in the credential's environment.`,
...('getItemIndex' in this ? { itemIndex: (this as IExecuteSingleFunctions).getItemIndex() } : {}),
},
);
}
}

/** Lists the chosen template's merge fields, one input each, so nobody types placeholder names. */
export async function getTemplateFields(this: ILoadOptionsFunctions): Promise<ResourceMapperFields> {
const id = this.getNodeParameter('templateId', '', { extractValue: true }) as string;
if (!id) return { fields: [] };
return {
fields: (await templateMerge.call(this, id)).map(({ find }) => ({
id: find,
displayName: find,
required: false,
defaultMatch: false,
canBeUsedToMatch: false,
display: true,
// Text inputs throughout. The render step gives each value the type of the
// template's own value, which n8n's type check would refuse before it could.
type: 'string',
})),
};
}
99 changes: 81 additions & 18 deletions nodes/Shotstack/resources/render/postTemplateRender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,28 @@ import type {
INodeProperties,
PreSendAction,
} from 'n8n-workflow';
import { templateMerge } from '../../resourceMapping/getTemplateFields';

const showOnly = {
resource: ['render'],
operation: ['postTemplateRender'],
};

/**
* A value in the JSON type of the template's own value. Shotstack keeps each
* value's type, so a sheet's "5" fills a number placeholder as 5, and a number
* fills a text placeholder as text.
*/
const likeTemplate = (value: unknown, templateValue: unknown): unknown => {
if (typeof templateValue === 'number' && typeof value === 'string' && Number.isFinite(Number(value))) {
return Number(value);
}
if (typeof templateValue === 'string' && (typeof value === 'number' || typeof value === 'boolean')) {
return String(value);
}
return value;
};

/**
* Puts the merge list on the body, from whichever source the user chose.
*
Expand All @@ -29,7 +45,22 @@ const buildMerge: PreSendAction = async function (
const body = (requestOptions.body ?? {}) as IDataObject;
let merge: unknown;

if (source === 'json') {
if (source === 'template') {
// Built from the template as it is now. Shotstack does not fill gaps, so a
// field left empty, or added in Studio after this step was set up, goes out
// with the template's own value instead of as a raw placeholder.
// skipValidation: n8n would otherwise refuse "9" for a number, or an emptied
// field, before likeTemplate gets to convert it.
const id = this.getNodeParameter('templateId', '', { extractValue: true }) as string;
const given = ((this.getNodeParameter('templateFields.mappingMode', 'defineBelow') === 'autoMapInputData'
? this.getInputData().json
: this.getNodeParameter('templateFields.value', {}, { skipValidation: true })) ?? {}) as IDataObject;
merge = (id ? await templateMerge.call(this, id) : []).map(({ find, replace }) => {
const value = given[find];
const empty = value === undefined || value === null || (typeof value === 'string' && value.trim() === '');
return { find, replace: empty ? replace : likeTemplate(value, replace) };
});
} else if (source === 'json') {
const raw = this.getNodeParameter('mergeJson', '') as string | unknown[];
if (typeof raw === 'string') {
const text = raw.trim();
Expand Down Expand Up @@ -97,6 +128,34 @@ const buildMerge: PreSendAction = async function (
return requestOptions;
};

const mergeSourceV1: INodeProperties = {
displayName: 'Merge Fields Source',
name: 'mergeSource',
type: 'options',
noDataExpression: true,
default: 'fields',
displayOptions: { show: { ...showOnly, '@version': [1] } },
description:
"Whether to fill in the chosen template's own fields, type each placeholder yourself, or hand over a ready-made list. Choose JSON when an earlier step or an AI agent builds the list.",
options: [
{
name: 'From Template',
value: 'template',
description: "Load the chosen template's merge fields and fill in each one",
},
{
name: 'Fields',
value: 'fields',
description: 'Type each placeholder and its value',
},
{
name: 'JSON',
value: 'json',
description: 'Supply the whole list as [{"find":"NAME","replace":"value"}]',
},
],
};

export const postTemplateRenderDescription: INodeProperties[] = [
{
displayName: 'Template',
Expand Down Expand Up @@ -144,27 +203,31 @@ export const postTemplateRenderDescription: INodeProperties[] = [
},
},
},
mergeSourceV1,
// A new default needs a new version: n8n leaves a default value out of a saved workflow,
// so changing version 1's default would switch every saved step to the new source.
{ ...mergeSourceV1, default: 'template', displayOptions: { show: { ...showOnly, '@version': [2] } } },
{
displayName: 'Merge Fields Source',
name: 'mergeSource',
type: 'options',
displayName: 'Merge Fields',
name: 'templateFields',
type: 'resourceMapper',
noDataExpression: true,
default: 'fields',
displayOptions: { show: showOnly },
default: { mappingMode: 'defineBelow', value: null },
displayOptions: { show: { ...showOnly, mergeSource: ['template'] } },
description:
'Whether to fill the placeholders one at a time, or hand over a ready-made list. Choose JSON when an earlier step or an AI agent builds the list.',
options: [
{
name: 'Fields',
value: 'fields',
description: 'Type each placeholder and its value',
},
{
name: 'JSON',
value: 'json',
description: 'Supply the whole list as [{"find":"NAME","replace":"value"}]',
"The chosen template's merge fields. Leave one empty to keep the template's own value.",
typeOptions: {
loadOptionsDependsOn: ['templateId.value'],
resourceMapper: {
resourceMapperMethod: 'getTemplateFields',
mode: 'add',
fieldWords: { singular: 'merge field', plural: 'merge fields' },
addAllFields: true,
multiKeyMatch: false,
supportAutoMap: true,
noFieldsError: 'No merge fields yet. Pick a template above, or add placeholders to it in Shotstack Studio.',
},
],
},
},
{
displayName: 'Merge Fields (JSON)',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"lint:fix": "npm run gen && n8n-node lint --fix",
"release": "n8n-node release",
"prepublishOnly": "n8n-node prerelease",
"test": "npm run build && node test/package-loads.mjs && node test/credential-host-scope.mjs && node test/docs-match-ui.mjs && node test/environment-mapping.mjs && node test/wait-and-backoff.mjs && node test/submit-guards.mjs && node test/generation-guards.mjs",
"test": "npm run build && node test/package-loads.mjs && node test/credential-host-scope.mjs && node test/docs-match-ui.mjs && node test/environment-mapping.mjs && node test/wait-and-backoff.mjs && node test/submit-guards.mjs && node test/generation-guards.mjs && node test/template-fields.mjs",
"gen": "node scripts/build-user-agent.mjs"
},
"files": [
Expand Down
8 changes: 6 additions & 2 deletions scripts/review-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,8 @@ const UNWALKABLE = [
/**
* Every name a rename can reach a user through, read from the built node.
*
* Mostly what n8n stores in a saved workflow. Also the list method key, which
* two files must agree on, so both ends are collected here.
* Mostly what n8n stores in a saved workflow. Also the list and resource mapper
* method keys, which two files must agree on, so both ends are collected here.
*/
const frozenNames = () => {
const names = new Set();
Expand All @@ -366,6 +366,9 @@ const frozenNames = () => {
names.add(mode.name);
if (mode.typeOptions?.searchListMethod) names.add(mode.typeOptions.searchListMethod);
}
// A resource mapper names the method that lists its fields, just the same.
const mapper = property.typeOptions?.resourceMapper?.resourceMapperMethod;
if (mapper) names.add(mapper);
for (const step of property.routing?.output?.postReceive ?? []) fromPostReceive(step);
for (const option of property.options ?? []) {
if (option.value !== undefined) names.add(String(option.value));
Expand All @@ -382,6 +385,7 @@ const frozenNames = () => {
walk(shotstack.description.properties);
names.add(shotstack.description.name);
for (const method of Object.keys(shotstack.methods?.listSearch ?? {})) names.add(method);
for (const method of Object.keys(shotstack.methods?.resourceMapping ?? {})) names.add(method);
// The product token only. Shotstack's render log keeps it, and nothing joins
// an old token to a new one. The version after the slash is meant to move.
names.add(String(req(resolve(process.cwd(), 'dist/nodes/Shotstack/userAgent.js')).USER_AGENT).split('/')[0]);
Expand Down
Loading
Loading