Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.
JavaScript agent-skillsai-agentsai-seoclaudeclaude-codeclaude-code-pluginclaude-skillscodexcontent-marketingconversion-rate-optimizationcopywritingcursoremail-marketinggenerative-engine-optimizationgrowth-marketingmarketingmarketing-automationsaas-marketingseoskill-md
feat(segment): retain single-event delivery metadata
Rudy Celeklib8b46b7a2640
diff --git a/tests/clis/segment-delivery-metadata.test.cjs b/tests/clis/segment-delivery-metadata.test.cjsnew file mode 100644index 0000000..938c9b7--- /dev/null+++ b/tests/clis/segment-delivery-metadata.test.cjs@@ -0,0 +1,49 @@+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/segment.js')+function run(command, extra = [], allowFetch = true) {+ const args = [...command, '--user-id', 'customer-1', ...extra]+ const code = `global.fetch=async(url,options)=>{if(!${allowFetch})throw new Error('unexpected fetch');return {status:200,text:async()=>JSON.stringify({url,body:JSON.parse(options.body)})}};process.argv=['node',${JSON.stringify(cli)},...${JSON.stringify(args)}];require(${JSON.stringify(cli)});`+ return spawnSync(process.execPath, ['-e', code], { encoding: 'utf8', env: { ...process.env, SEGMENT_WRITE_KEY: 'fixture-only' } })+}+for (const [command, endpoint] of [[['track', 'event', '--event', 'Order Completed'], '/track'], [['identify', 'user', '--traits', '{"tier":"Gold"}'], '/identify'], [['page', 'view', '--name', 'Pricing'], '/page']]) {+ test(`${command.slice(0, 2).join(' ')} retains occurrence time and retry identity`, () => {+ const timestamp = '2024-04-12T10:15:30.123+02:00'+ const r = run(command, ['--timestamp', timestamp, '--message-id', 'source-event:123'])+ assert.equal(r.status, 0, r.stderr)+ const out = JSON.parse(r.stdout)+ assert.equal(out.url, `https://api.segment.io/v1${endpoint}`)+ assert.equal(out.body.timestamp, timestamp)+ assert.equal(out.body.messageId, 'source-event:123')+ assert.equal(out.body.userId, 'customer-1')+ })+}+test('without metadata flags the provider defaults remain untouched', () => {+ const out = JSON.parse(run(['track', 'event', '--event', 'Signup']).stdout)+ assert.equal(Object.hasOwn(out.body, 'timestamp'), false)+ assert.equal(Object.hasOwn(out.body, 'messageId'), false)+})+test('preview keeps metadata and masks credentials', () => {+ const r = run(['page', 'view'], ['--timestamp', '2024-04-12T10:15:30Z', '--message-id', 'x'.repeat(100), '--dry-run'], false)+ assert.equal(r.status, 0, r.stderr)+ const out = JSON.parse(r.stdout)+ assert.equal(out.body.messageId.length, 100)+ assert.equal(out.headers.Authorization, '***')+})+for (const extra of [['--timestamp'], ['--timestamp', 'yesterday'], ['--timestamp', '2024-04-12'], ['--timestamp', '2024-04-12T10:15:30'], ['--timestamp', '2024-13-12T10:15:30Z'], ['--timestamp', '2024-02-30T10:15:30Z'], ['--timestamp', '2024-02-31T10:15:30Z'], ['--timestamp', '2023-02-29T10:15:30Z'], ['--timestamp', '2024-04-31T10:15:30Z'], ['--timestamp', '2024-04-12T24:00:00Z'], ['--message-id'], ['--message-id', ''], ['--message-id', 'x'.repeat(101)]]) {+ test(`invalid delivery metadata ${extra[0]} ${String(extra[1]).slice(0, 20)} fails before request`, () => {+ const r = run(['track', 'event', '--event', 'Signup'], extra, false)+ assert.equal(r.status, 1)+ assert.match(JSON.parse(r.stderr).error, /timestamp|message-id/)+ })+}++test('valid leap days and timezone offsets preserve literal occurrence time', () => {+ for (const timestamp of ['2024-02-29T10:15:30Z', '2000-02-29T10:15:30.123-05:30', '2024-12-31T23:59:59+02:00']) {+ const r = run(['track', 'event', '--event', 'Signup'], ['--timestamp', timestamp])+ assert.equal(r.status, 0, r.stderr)+ assert.equal(JSON.parse(r.stdout).body.timestamp, timestamp)+ }+})diff --git a/tools/clis/segment.js b/tools/clis/segment.jsindex ea2efed..fbecf71 100755--- a/tools/clis/segment.js+++ b/tools/clis/segment.js@@ -81,6 +81,26 @@ function parseArgs(args) {const args = parseArgs(rawArgs)const [cmd, sub, ...rest] = args._+function withDeliveryMetadata(body) {+ if (args.timestamp !== undefined) {+ const value = args.timestamp+ const parts = typeof value === 'string' ? /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.exec(value) : null+ const [year, month, day, hour, minute, second] = parts ? parts.slice(1).map(Number) : []+ const leap = year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]+ if (!parts || month < 1 || month > 12 || day < 1 || day > days[month - 1] || hour > 23 || minute > 59 || second > 59 || !Number.isFinite(Date.parse(value))) {+ throw new Error('--timestamp must be a valid ISO-8601 datetime with a timezone')+ }+ body.timestamp = value+ }+ if (args['message-id'] !== undefined) {+ const value = args['message-id']+ if (typeof value !== 'string' || value.length < 1 || value.length > 100) throw new Error('--message-id must contain 1 to 100 characters')+ body.messageId = value+ }+ return body+}+async function main() {let result@@ -97,7 +117,7 @@ async function main() {if (args.properties) {try { body.properties = JSON.parse(args.properties) } catch { result = { error: 'Invalid JSON in --properties' }; break }}- result = await trackApi('POST', '/track', body)+ result = await trackApi('POST', '/track', withDeliveryMetadata(body))break}default:@@ -113,7 +133,7 @@ async function main() {if (args.traits) {try { body.traits = JSON.parse(args.traits) } catch { result = { error: 'Invalid JSON in --traits' }; break }}- result = await trackApi('POST', '/identify', body)+ result = await trackApi('POST', '/identify', withDeliveryMetadata(body))break}default:@@ -130,7 +150,7 @@ async function main() {if (args.properties) {try { body.properties = JSON.parse(args.properties) } catch { result = { error: 'Invalid JSON in --properties' }; break }}- result = await trackApi('POST', '/page', body)+ result = await trackApi('POST', '/page', withDeliveryMetadata(body))break}default:@@ -179,6 +199,7 @@ async function main() {identify: 'identify user --user-id <id> [--traits <json>]',page: 'page view --user-id <id> [--name <name>] [--properties <json>]',batch: 'batch send --events <json_array>',+ metadata: 'Single track/identify/page calls: [--timestamp <ISO_datetime>] [--message-id <1_to_100_characters>]',profiles: 'profiles [traits|events] --space-id <id> --user-id <id>',}}diff --git a/tools/integrations/segment.md b/tools/integrations/segment.mdindex 3d5a9be..db62222 100644--- a/tools/integrations/segment.md+++ b/tools/integrations/segment.md@@ -163,3 +163,21 @@ analytics.page('Pricing');Pass the raw user ID to `profiles traits` or `profiles events`. The CLI URL-encodesthe value so characters such as `/`, `+`, `?`, and `#` remain part of the user ID.Do not pre-encode it. See [Profile API identifiers](https://www.twilio.com/docs/segment/unify/profile-api).++## Importing and retrying individual events++Single `track event`, `identify user`, and `page view` calls accept+`--timestamp` and `--message-id`. Use an ISO datetime with a timezone to retain+when a historical event occurred, and reuse the source event's ID when retrying:++```bash+node tools/clis/segment.js track event --user-id customer-1 --event "Order Completed" \+ --timestamp 2024-04-12T10:15:30Z --message-id order-123 --dry-run+```++Both fields are omitted when flags are absent, leaving Segment's defaults+intact. Message IDs must contain 1–100 characters. For `batch send`, place the+metadata on each event in `--events`; these individual-call flags do not rewrite+batches. See [common fields](https://www.twilio.com/docs/segment/connections/spec/common)+and [duplicate handling](https://www.twilio.com/docs/segment/guides/duplicate-data).+Downstream destinations can handle these fields differently.