Skip to content

Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.

fix(amplitude): validate ingestion JSON container shapes

Rudy Celekli8b5e189ee896
diff --git a/tests/clis/amplitude-json-shapes.test.cjs b/tests/clis/amplitude-json-shapes.test.cjs
new file mode 100644
index 0000000..2619dd5
--- /dev/null
+++ b/tests/clis/amplitude-json-shapes.test.cjs
@@ -0,0 +1,73 @@
+const { test } = require('node:test')
+const assert = require('node:assert/strict')
+const { spawnSync } = require('node:child_process')
+const path = require('node:path')
+
+const cli = path.resolve(__dirname, '../../tools/clis/amplitude.js')
+function run(argv) {
+ const code = `let calls=0;global.fetch=async(url,options)=>{calls++;return {status:200,text:async()=>JSON.stringify({calls,url,body:JSON.parse(options.body)})}};process.argv=['node',${JSON.stringify(cli)},...${JSON.stringify(argv)}];require(${JSON.stringify(cli)});process.on('exit',()=>console.error(JSON.stringify({calls})));`
+ const child = spawnSync(process.execPath, ['-e', code], {
+ encoding: 'utf8', env: { ...process.env, AMPLITUDE_API_KEY: 'fixture-only' }, timeout: 5000,
+ })
+ assert.ifError(child.error)
+ const errors = child.stderr.trim().split('\n').map(line => JSON.parse(line))
+ return { status: child.status, calls: errors.at(-1).calls, error: errors[0].error, stdout: child.stdout }
+}
+const single = ['track', 'event', '--user-id', 'customer-123', '--event-type', 'Purchase']
+const event = { user_id: 'customer-123', event_type: 'Purchase' }
+const invalidObjects = ['null', '[]', 'true', '1', '"text"']
+for (const preview of [false, true]) {
+ for (const value of [...invalidObjects, '']) {
+ test(`single-event properties reject ${JSON.stringify(value)} (${preview ? 'preview' : 'request'})`, () => {
+ const r = run([...single, '--properties', value, ...(preview ? ['--dry-run'] : [])])
+ assert.equal(r.status, 1)
+ assert.equal(r.calls, 0)
+ assert.match(r.error, /--properties must be a JSON object/)
+ })
+ }
+ for (const value of [...invalidObjects.filter(v => v !== '[]'), '[null]', '[1]', '[[]]', '[true]', '["text"]']) {
+ test(`batch rejects ${value} (${preview ? 'preview' : 'request'})`, () => {
+ const r = run(['track', 'batch', '--events', value, ...(preview ? ['--dry-run'] : [])])
+ assert.equal(r.status, 1)
+ assert.equal(r.calls, 0)
+ assert.match(r.error, /--events must be a JSON array of event objects/)
+ })
+ }
+ for (const value of [null, [], true, 1, 'text']) {
+ test(`batch event properties reject ${JSON.stringify(value)} (${preview ? 'preview' : 'request'})`, () => {
+ const r = run(['track', 'batch', '--events', JSON.stringify([{ ...event, event_properties: value }]), ...(preview ? ['--dry-run'] : [])])
+ assert.equal(r.status, 1)
+ assert.equal(r.calls, 0)
+ assert.match(r.error, /event_properties must be a JSON object/)
+ })
+ }
+}
+for (const properties of [{}, { items: [1, 'two', null], order: { amount: 0, paid: false }, note: '' }]) {
+ test(`single-event properties preserve ${JSON.stringify(properties)}`, () => {
+ const r = run([...single, '--properties', JSON.stringify(properties)])
+ assert.equal(r.status, 0)
+ assert.equal(r.calls, 1)
+ assert.deepEqual(JSON.parse(r.stdout).body.events[0], { ...event, event_properties: properties })
+ })
+}
+test('single-event properties remain optional', () => {
+ const r = run(single)
+ assert.equal(r.status, 0)
+ assert.deepEqual(JSON.parse(r.stdout).body.events, [event])
+})
+test('valid batch preserves nested properties and unrelated event fields', () => {
+ const events = [event, { device_id: 'visitor-device-123', event_type: 'Viewed Pricing', time: 123456789, insert_id: 'retry-key', event_properties: { items: ['a', 'b'], paid: false } }]
+ const r = run(['track', 'batch', '--events', JSON.stringify(events)])
+ assert.equal(r.status, 0)
+ assert.equal(r.calls, 1)
+ assert.equal(JSON.parse(r.stdout).url, 'https://api2.amplitude.com/batch')
+ assert.deepEqual(JSON.parse(r.stdout).body.events, events)
+})
+test('valid batch preview preserves data and masks the fixture key', () => {
+ const r = run(['track', 'batch', '--events', JSON.stringify([event]), '--dry-run'])
+ assert.equal(r.status, 0)
+ assert.equal(r.calls, 0)
+ const output = JSON.parse(r.stdout)
+ assert.equal(output.body.api_key, '***')
+ assert.deepEqual(output.body.events, [event])
+})
diff --git a/tools/clis/amplitude.js b/tools/clis/amplitude.js
index 7ab0806..1302983 100755
--- a/tools/clis/amplitude.js
+++ b/tools/clis/amplitude.js
@@ -87,6 +87,19 @@ function parseArgs(args) {
const args = parseArgs(rawArgs)
const [cmd, sub, ...rest] = args._
+function isObject(value) {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+function jsonArg(name, description) {
+ if (typeof args[name] !== 'string') throw new Error(`--${name} must be ${description}`)
+ try {
+ return JSON.parse(args[name])
+ } catch {
+ throw new Error(`--${name} must be ${description}`)
+ }
+}
+
async function main() {
let result
@@ -104,8 +117,9 @@ async function main() {
...(args['device-id'] !== undefined ? { device_id: args['device-id'] } : {}),
event_type: args['event-type'],
}
- if (args.properties) {
- event.event_properties = JSON.parse(args.properties)
+ if (args.properties !== undefined) {
+ event.event_properties = jsonArg('properties', 'a JSON object')
+ if (!isObject(event.event_properties)) throw new Error('--properties must be a JSON object')
}
result = await ingestApi('POST', '/2/httpapi', {
api_key: API_KEY,
@@ -115,7 +129,13 @@ async function main() {
}
case 'batch': {
if (!args.events) { result = { error: '--events required (JSON array)' }; break }
- const events = JSON.parse(args.events)
+ const events = jsonArg('events', 'a JSON array of event objects')
+ if (!Array.isArray(events) || events.some(event => !isObject(event))) {
+ throw new Error('--events must be a JSON array of event objects')
+ }
+ if (events.some(event => Object.hasOwn(event, 'event_properties') && !isObject(event.event_properties))) {
+ throw new Error('--events event_properties must be a JSON object')
+ }
result = await ingestApi('POST', '/batch', {
api_key: API_KEY,
events,