Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(message): unify bulk template variables onto the shared {{name}} renderer (#69) (#411)
Yudhi Armyndharis982575ea5761
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ff4b01815..2161f9ac3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Changed++- **Bulk-message variable substitution now uses the same `{{name}}` syntax as message templates.**+ `POST /sessions/:id/messages/send-bulk` previously substituted `messages[].variables` with a+ single-brace `{name}` convention, inconsistent with the double-brace `{{name}}` used everywhere+ else in the gateway. Bulk content is now rendered by the shared template helper, so the canonical+ `{{name}}` placeholders work in bulk content. Existing single-brace `{name}` content keeps working+ unchanged. (#69, #411)++### Deprecated++- **Single-brace `{name}` placeholders in bulk-message content.** Prefer `{{name}}`; the legacy+ `{name}` form is still substituted for backward compatibility but may be removed in a future major+ version. (#69, #411)+### Fixed- **A session is no longer mutated by callbacks from an engine it has already replaced or torndiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 42f2c52d9..50581f843 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -752,7 +752,7 @@ POST /api/sessions/:sessionId/messages/send-bulk"chatId": "[email protected]","type": "text","content": {- "text": "Hello {name}!"+ "text": "Hello {{name}}!"},"variables": {"name": "John"@@ -763,7 +763,7 @@ POST /api/sessions/:sessionId/messages/send-bulk"type": "image","content": {"image": { "url": "https://example.com/promo.jpg" },- "caption": "Special offer for {name}!"+ "caption": "Special offer for {{name}}!"},"variables": {"name": "Jane"@@ -787,7 +787,7 @@ POST /api/sessions/:sessionId/messages/send-bulk| `messages[].chatId` | string | Yes | Recipient chat ID || `messages[].type` | string | Yes | Message type: `text`, `image`, `video`, `audio`, `document` || `messages[].content` | object | Yes | Message content based on type |-| `messages[].variables` | object | No | Variables for template substitution |+| `messages[].variables` | object | No | Variables substituted into `content` strings. Use canonical `{{name}}` placeholders (consistent with message templates); the legacy single-brace `{name}` is deprecated but still honored. Unknown placeholders are left literal. || `options.delayBetweenMessages` | number | No | Delay in ms (default: 3000, min: 1000) || `options.randomizeDelay` | boolean | No | Add random 0-2s to delay (default: true) || `options.stopOnError` | boolean | No | Stop batch on first error (default: false) |diff --git a/src/common/utils/template-render.spec.ts b/src/common/utils/template-render.spec.tsnew file mode 100644index 000000000..9ce50cf83--- /dev/null+++ b/src/common/utils/template-render.spec.ts@@ -0,0 +1,56 @@+import { renderTemplate } from './template-render';++describe('renderTemplate', () => {+ describe('canonical double-brace {{name}}', () => {+ it('substitutes a known placeholder', () => {+ expect(renderTemplate('Hi {{name}}', { name: 'Sam' })).toBe('Hi Sam');+ });++ it('tolerates surrounding whitespace', () => {+ expect(renderTemplate('Hi {{ name }}', { name: 'Sam' })).toBe('Hi Sam');+ });++ it('supports dotted/dashed keys', () => {+ expect(renderTemplate('{{first.name}}-{{order-id}}', { 'first.name': 'A', 'order-id': '7' })).toBe('A-7');+ });++ it('leaves an unknown placeholder literal', () => {+ expect(renderTemplate('Hi {{name}}', {})).toBe('Hi {{name}}');+ });+ });++ describe('legacy single-brace {name} (deprecated, still supported)', () => {+ it('substitutes a known placeholder', () => {+ expect(renderTemplate('Hi {name}', { name: 'Sam' })).toBe('Hi Sam');+ });++ it('leaves an unknown placeholder literal', () => {+ expect(renderTemplate('Hi {name}', {})).toBe('Hi {name}');+ });+ });++ describe('mixed + disambiguation', () => {+ it('substitutes both conventions in one string', () => {+ expect(renderTemplate('{greeting}, {{name}}!', { greeting: 'Hello', name: 'Sam' })).toBe('Hello, Sam!');+ });++ it('does NOT mangle {{name}} into {value} (double-brace consumed as a unit)', () => {+ expect(renderTemplate('{{name}}', { name: 'X' })).toBe('X');+ });+ });++ describe('edge cases', () => {+ it('returns an empty body unchanged', () => {+ expect(renderTemplate('', { name: 'Sam' })).toBe('');+ });++ it('leaves non-placeholder braces untouched', () => {+ expect(renderTemplate('a { b } c', { b: 'X' })).toBe('a { b } c'); // spaces => not a legacy placeholder+ });++ it('substitutes an explicitly-provided empty-string value', () => {+ // hasOwnProperty semantics: an explicit '' substitutes to '' (the legacy `||` renderer left it literal).+ expect(renderTemplate('[{name}]', { name: '' })).toBe('[]');+ });+ });+});diff --git a/src/common/utils/template-render.ts b/src/common/utils/template-render.tsindex fee7a46bc..e7b2effae 100644--- a/src/common/utils/template-render.ts+++ b/src/common/utils/template-render.ts@@ -1,35 +1,37 @@/**- * Shared server-side text template renderer.+ * Shared server-side text template renderer — the single templating helper for the gateway.*- * Substitutes Handlebars-style `{{name}}` placeholders with values from the- * provided `vars` map. Placeholders whose key is absent from `vars` are left- * untouched (the literal `{{key}}` is preserved) so that missing variables are- * visible rather than silently blanked.+ * Substitutes `{{name}}` placeholders (the canonical, Handlebars-style convention) with values from+ * the provided `vars` map. Placeholders whose key is absent from `vars` are left untouched (the+ * literal placeholder is preserved) so missing variables stay visible rather than silently blanked.*- * NOTE: bulk-message.service.ts ships an independent single-brace `{name}`- * renderer (see `applyVariables`). The two placeholder conventions- * (`{{name}}` here vs `{name}` there) should be reconciled into this shared- * helper in a follow-up so the gateway exposes one consistent templating- * syntax. See issue #69.+ * Legacy single-brace `{name}` placeholders are ALSO substituted, for backward compatibility with+ * the bulk-message API that historically used them. Single-brace is deprecated — prefer `{{name}}`.*/-const PLACEHOLDER_PATTERN = /\{\{\s*([\w.-]+)\s*\}\}/g;+// Ordered alternation: the double-brace branch is tried first at each position, so `{{name}}` is+// consumed as a unit and the single-brace branch never sees its interior (no `{{name}}` -> `{value}`+// mangling). The legacy branch keeps the historical shape exactly: `{name}`, word chars only, no+// surrounding whitespace — so existing single-brace bulk content renders bit-for-bit as before.+const PLACEHOLDER_PATTERN = /\{\{\s*([\w.-]+)\s*\}\}|\{(\w+)\}/g;/**- * Render a template body by replacing `{{key}}` placeholders with `vars[key]`.+ * Render a template body by replacing `{{key}}` (canonical) or `{key}` (legacy) placeholders with+ * `vars[key]`.*- * @param body Template text containing `{{key}}` placeholders.+ * @param body Template text containing `{{key}}` and/or `{key}` placeholders.* @param vars Map of placeholder keys to substitution values.- * @returns The rendered text with known placeholders substituted and unknown- * placeholders left as literal `{{key}}`.+ * @returns The rendered text with known placeholders substituted and unknown placeholders left+ * literal.*/export function renderTemplate(body: string, vars: Record<string, string> = {}): string {if (!body) {return body;}- return body.replace(PLACEHOLDER_PATTERN, (match, key: string) => {- if (Object.prototype.hasOwnProperty.call(vars, key) && vars[key] != null) {+ return body.replace(PLACEHOLDER_PATTERN, (match, doubleKey: string | undefined, singleKey: string | undefined) => {+ const key = doubleKey ?? singleKey;+ if (key !== undefined && Object.prototype.hasOwnProperty.call(vars, key) && vars[key] != null) {return String(vars[key]);}// Leave unmatched placeholders literal so missing variables stay visible.diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex f5c1afb7e..8fe027ff5 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -172,6 +172,28 @@ describe('BulkMessageService.processBatch', () => {const savedStatuses = (repo.save.mock.calls as [MessageBatch][]).map(c => c[0].status);expect(savedStatuses[savedStatuses.length - 1]).toBe(BatchStatus.CANCELLED);});++ it('substitutes canonical {{name}} placeholders in bulk content', async () => {+ const batch = makeBatch(1);+ batch.messages[0].content = { text: 'Hi {{name}}' };+ batch.messages[0].variables = { name: 'Sam' };+ repo.findOne.mockResolvedValue(batch);++ await runProcessBatch();++ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi Sam');+ });++ it('still substitutes legacy single-brace {name} placeholders (backward compatible)', async () => {+ const batch = makeBatch(1);+ batch.messages[0].content = { text: 'Hi {name}' };+ batch.messages[0].variables = { name: 'Sam' };+ repo.findOne.mockResolvedValue(batch);++ await runProcessBatch();++ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi Sam');+ });});describe('BulkMessageService.createBatch base64 media cap', () => {diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex bef47fffe..76a98423b 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -15,6 +15,7 @@ import { SessionService } from '../session/session.service';import { MessageService } from './message.service';import { assertBase64WithinMediaCap } from './media-cap.util';import { SsrfBlockedError } from '../../common/security/ssrf-guard';+import { renderTemplate } from '../../common/utils/template-render';import { IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';// Type definitions for bulk message content@@ -315,15 +316,10 @@ export class BulkMessageService implements OnApplicationBootstrap {private applyVariables(content: BulkMessageContent, variables?: Record<string, string>): BulkMessageContent {if (!variables) return content;- // NOTE: This single-brace `{name}` convention differs from the shared- // server-side template renderer (`renderTemplate` in- // common/utils/template-render.ts) which uses double-brace `{{name}}`- // placeholders. The two conventions should be reconciled onto the shared- // helper in a follow-up so the gateway exposes one consistent templating- // syntax. See issue #69.- const replaceVars = (str: string): string => {- return str.replace(/\{(\w+)\}/g, (_, key: string) => variables[key] || `{${key}}`);- };+ // Delegate to the shared renderer so the gateway exposes one templating syntax (#69). It+ // substitutes canonical `{{name}}` placeholders and still honors the legacy single-brace+ // `{name}` this endpoint historically used (deprecated — prefer `{{name}}`).+ const replaceVars = (str: string): string => renderTemplate(str, variables);const processValue = (value: unknown): unknown => {if (typeof value === 'string') {