Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Move to uuidv7 #160

Merged
merged 22 commits into from
Feb 6, 2024
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
15 changes: 15 additions & 0 deletions .github/workflows/bundle-size.yml
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice 🙌

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: Bundled Size

on: [pull_request]

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- uses: preactjs/compressed-size-action@v2
with:
pattern: './**/lib/**/*.{js}'
# Always ignore SourceMaps and node_modules:
exclude: '{**/*.map,**/node_modules/**}'
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
node-version: 16

- run: yarn install
- run: yarn compile
- run: yarn build
- run: yarn lint
- run: yarn prettier:check

Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@
"private": true,
"license": "MIT",
"scripts": {
"build": "yarn compile",
"build": "yarn build-rollup && yarn build-react-native",
"lint": "eslint -c .eslintrc.js --fix posthog-*",
"prettier": "prettier --write \"./**/*.{ts,tsx}\"",
"prettier:check": "prettier --check \"./**/*.{ts,tsx}\"",
"test": "jest posthog-core posthog-node posthog-web",
"test:all": "jest posthog-core posthog-node posthog-web && yarn test:rn",
"test:rn": "cd posthog-react-native && yarn test",
"compile": "rollup -c && cd posthog-react-native && yarn build"
"build-rollup": "rollup -c",
"build-react-native": "cd posthog-react-native && yarn build"
},
"devDependencies": {
"@babel/core": "^7.18.6",
Expand Down
7 changes: 5 additions & 2 deletions posthog-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
"version": "2.1.0",
"main": "src/index.ts",
"repository": {
"type" : "git",
"url" : "https://github.com/PostHog/posthog-js-lite.git",
"type": "git",
"url": "https://github.com/PostHog/posthog-js-lite.git",
"directory": "posthog-core"
},
"dependencies": {
"uuidv7": "^0.6.3"
}
}
10 changes: 5 additions & 5 deletions posthog-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
assert,
currentISOTime,
currentTimestamp,
generateUUID,
removeTrailingSlash,
retriable,
RetriableOptions,
Expand All @@ -23,6 +22,7 @@ import {
export * as utils from './utils'
import { LZString } from './lz-string'
import { SimpleEventEmitter } from './eventemitter'
import { uuidv7 } from 'uuidv7'

class PostHogFetchHttpError extends Error {
name = 'PostHogFetchHttpError'
Expand Down Expand Up @@ -142,7 +142,7 @@ export abstract class PostHogCoreStateless {
}

protected addPendingPromise(promise: Promise<any>): void {
const promiseUUID = generateUUID()
const promiseUUID = uuidv7()
this.pendingPromises[promiseUUID] = promise
promise.finally(() => {
delete this.pendingPromises[promiseUUID]
Expand Down Expand Up @@ -414,7 +414,7 @@ export abstract class PostHogCoreStateless {
library: this.getLibraryId(),
library_version: this.getLibraryVersion(),
timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
uuid: options?.uuid ? options.uuid : generateUUID(globalThis),
uuid: options?.uuid ? options.uuid : uuidv7(),
}

const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip
Expand Down Expand Up @@ -696,7 +696,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
let sessionId = this.getPersistedProperty<string>(PostHogPersistedProperty.SessionId)
const sessionTimestamp = this.getPersistedProperty<number>(PostHogPersistedProperty.SessionLastTimestamp) || 0
if (!sessionId || Date.now() - sessionTimestamp > this._sessionExpirationTimeSeconds * 1000) {
sessionId = generateUUID(globalThis)
sessionId = uuidv7()
this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId)
}
this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, Date.now())
Expand All @@ -711,7 +711,7 @@ export abstract class PostHogCore extends PostHogCoreStateless {
getAnonymousId(): string {
let anonId = this.getPersistedProperty<string>(PostHogPersistedProperty.AnonymousId)
if (!anonId) {
anonId = generateUUID(globalThis)
anonId = uuidv7()
this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId)
}
return anonId
Expand Down
21 changes: 0 additions & 21 deletions posthog-core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,27 +38,6 @@ export async function retriable<T>(fn: () => Promise<T>, props: RetriableOptions
throw lastError
}

// https://stackoverflow.com/a/8809472
export function generateUUID(globalThis?: any): string {
// Public Domain/MIT
let d = new Date().getTime() //Timestamp
let d2 =
(globalThis && globalThis.performance && globalThis.performance.now && globalThis.performance.now() * 1000) || 0 //Time in microseconds since page-load or 0 if unsupported
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16 //random number between 0 and 16
if (d > 0) {
//Use timestamp until depleted
r = (d + r) % 16 | 0
d = Math.floor(d / 16)
} else {
//Use microseconds since page-load if supported
r = (d2 + r) % 16 | 0
d2 = Math.floor(d2 / 16)
}
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
})
}

export function currentTimestamp(): number {
return new Date().getTime()
}
Expand Down
4 changes: 2 additions & 2 deletions posthog-core/test/posthog.capture.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { parseBody } from './test-utils/test-utils'
import { createTestClient, PostHogCoreTestClient, PostHogCoreTestClientMocks } from './test-utils/PostHogCoreTestClient'
import { generateUUID } from '../src/utils'
import { uuidv7 } from 'uuidv7'

describe('PostHog Core', () => {
let posthog: PostHogCoreTestClient
Expand Down Expand Up @@ -67,7 +67,7 @@ describe('PostHog Core', () => {
it('should allow overriding the uuid', async () => {
jest.setSystemTime(new Date('2022-01-01'))

const id = generateUUID()
const id = uuidv7()

posthog.capture('custom-event', { foo: 'bar' }, { uuid: id })
const body = parseBody(mocks.fetch.mock.calls[0])
Expand Down
11 changes: 1 addition & 10 deletions posthog-core/test/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assert, removeTrailingSlash, generateUUID, currentISOTime, currentTimestamp } from '../src/utils'
import { assert, removeTrailingSlash, currentISOTime, currentTimestamp } from '../src/utils'

describe('utils', () => {
describe('assert', () => {
Expand All @@ -24,15 +24,6 @@ describe('utils', () => {
describe.skip('retriable', () => {
it('should do something', () => {})
})
describe('generateUUID', () => {
it('should generate something that looks like a UUID', () => {
const REGEX = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/

for (let i = 0; i < 1000; i++) {
expect(generateUUID(globalThis)).toMatch(REGEX)
}
})
})
describe('currentTimestamp', () => {
it('should get the timestamp', () => {
expect(currentTimestamp()).toEqual(Date.now())
Expand Down
6 changes: 5 additions & 1 deletion posthog-node/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
## 3.6.1 - 2024-01-26
# 3.6.2 - 2024-02-06

1. Swapped to `uuidv7` for unique ID generation

# 3.6.1 - 2024-01-26

1. Remove new relative date operators, combine into regular date operators

Expand Down
2 changes: 1 addition & 1 deletion posthog-node/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "posthog-node",
"version": "3.6.1",
"version": "3.6.2",
"description": "PostHog Node.js integration",
"repository": {
"type": "git",
Expand Down
4 changes: 2 additions & 2 deletions posthog-node/test/posthog-node.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ jest.mock('../src/fetch')
import fetch from '../src/fetch'
import { anyDecideCall, anyLocalEvalCall, apiImplementation } from './feature-flags.spec'
import { waitForPromises, wait } from '../../posthog-core/test/test-utils/test-utils'
import { generateUUID } from 'posthog-core/src/utils'
import { randomUUID } from 'crypto'

jest.mock('../package.json', () => ({ version: '1.2.3' }))

Expand Down Expand Up @@ -194,7 +194,7 @@ describe('PostHog Node.js', () => {

it('should allow overriding uuid', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
const uuid = generateUUID()
const uuid = randomUUID()
posthog.capture({ event: 'custom-time', distinctId: '123', uuid })
await waitForPromises()
jest.runOnlyPendingTimers()
Expand Down
4 changes: 4 additions & 0 deletions posthog-react-native/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 2.11.2 - 2024-02-06

1. Swapped to `uuidv7` for unique ID generation

# 2.11.1 - 2024-01-25

1. Do not try to load packages on the macOS target that are not supported.
Expand Down
2 changes: 1 addition & 1 deletion posthog-react-native/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "posthog-react-native",
"version": "2.11.1",
"version": "2.11.2",
"main": "lib/posthog-react-native/index.js",
"files": [
"lib/"
Expand Down
4 changes: 4 additions & 0 deletions posthog-web/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 2.6.1 - 2024-02-06

1. Swapped to `uuidv7` for unique ID generation

# 2.6.0 - 2024-01-18

1. Adds support for overriding the event `uuid` via capture options
Expand Down
2 changes: 1 addition & 1 deletion posthog-web/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "posthog-js-lite",
"version": "2.6.0",
"version": "2.6.1",
"main": "lib/index.cjs.js",
"module": "lib/index.esm.js",
"types": "lib/index.d.ts",
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -9697,6 +9697,11 @@ uuid@^8.0.0, uuid@^8.3.2:
resolved "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz"
integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==

uuidv7@^0.6.3:
version "0.6.3"
resolved "https://registry.yarnpkg.com/uuidv7/-/uuidv7-0.6.3.tgz#2abcfa683b4ad4a0cbbbaedffc3ef940c110cf10"
integrity sha512-zV3eW2NlXTsun/aJ7AixxZjH/byQcH/r3J99MI0dDEkU2cJIBJxhEWUHDTpOaLPRNhebPZoeHuykYREkI9HafA==

v8-compile-cache-lib@^3.0.1:
version "3.0.1"
resolved "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz"
Expand Down
Loading