From 9914dc9d5a8d3f78f3877fe053757bb185c1f723 Mon Sep 17 00:00:00 2001 From: Kam Lasater Date: Mon, 8 Aug 2022 20:37:37 -0400 Subject: [PATCH] First cut at esm and commonjs --- index.cjs | 57 +++++++++++++++++++++++++++++++++++++++++++ index.mjs => index.js | 0 package.json | 7 +++++- 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 index.cjs rename index.mjs => index.js (100%) diff --git a/index.cjs b/index.cjs new file mode 100644 index 0000000..d02a9fe --- /dev/null +++ b/index.cjs @@ -0,0 +1,57 @@ +const axios = require('axios') +const { v4: uuid } = require('uuid'); +const md5 = require('md5') + +const LIBRARY_VERSION = process.env.npm_package_version || 'unknown' +const LIBRARY_NAME = process.env.npm_package_name || 'analytics-async' + +export async function track(msg) { + return call('track', msg) +} + +export async function identify(msg) { + return call('identify', msg) +} + +async function call(type, message) { + + message = Object.assign({}, message) + message.context = Object.assign({ + library: { + name: LIBRARY_NAME, + version: LIBRARY_VERSION + } + }, message.context) + + message._metadata = Object.assign({ + nodeVersion: process.versions.node + }, message._metadata) + + if (!message.timestamp) { + message.timestamp = new Date() + } + + if (!message.messageId) { + // We md5 the messaage to add more randomness. This is primarily meant + // for use in the browser where the uuid package falls back to Math.random() + // which is not a great source of randomness. + // Borrowed from analytics.js (https://github.com/segment-integrations/analytics.js-integration-segmentio/blob/a20d2a2d222aeb3ab2a8c7e72280f1df2618440e/lib/index.js#L255-L256). + message.messageId = `node-${md5(JSON.stringify(message))}-${uuid()}` + } + + const headers = { + 'content-type': 'application/json', + 'user-agent': `${LIBRARY_NAME}/${LIBRARY_VERSION}` + } + + const req = { + auth: { + username: process.env.SEGMENT_WRITE_KEY || 'Unset process.env.SEGMENT_WRITE_KEY' + }, + headers + } + + let p = axios.post(`https://api.segment.io/v1/${type}`, message, req) + console.log(`${type} => ${message.userId}`) + return p +} diff --git a/index.mjs b/index.js similarity index 100% rename from index.mjs rename to index.js diff --git a/package.json b/package.json index 208fbca..5b82a54 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,12 @@ "name": "analytics-async", "version": "0.0.4", "description": "The hassle-free way to integrate analytics into any node application w/o dropping API calls.", - "main": "index.mjs", + "main": "index.js", + "type": "module", + "exports": { + "import": "./main.js", + "require": "./main.cjs" + }, "scripts": { "start": "node index.mjs", "test": "echo \"Error: no test specified\" && exit 1"