Skip to content

Commit

Permalink
Bootstrap signals package boilerplate (#1093)
Browse files Browse the repository at this point in the history
  • Loading branch information
silesky authored May 24, 2024
1 parent 9a19a3c commit 0589554
Show file tree
Hide file tree
Showing 27 changed files with 334 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .buildkite/pipeline.yml
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,23 @@ steps:
- yarn turbo run --filter='./packages/consent/*' lint
- echo "+++ Run Tests"
- yarn turbo run --filter='./packages/consent/*' test
plugins:
- ssh://[email protected]/segmentio/cache-buildkite-plugin#v2.0.0:
key: "v1.1-cache-dev-{{ checksum 'yarn.lock' }}"

- label: '[Signals] Lint + Test'
agents:
queue: v1
commands:
- npm config set "//registry.npmjs.org/:_authToken" $${NPM_TOKEN}
- echo "--- Install dependencies"
- PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 HUSKY=0 yarn install --immutable
- echo "--- Build bundles"
- yarn turbo run --filter='./packages/signals/*' build
- echo "+++ Run Lint"
- yarn turbo run --filter='./packages/signals/*' lint
- echo "+++ Run Tests"
- yarn turbo run --filter='./packages/signals/*' test
plugins:
- ssh://[email protected]/segmentio/cache-buildkite-plugin#v2.0.0:
key: "v1.1-cache-dev-{{ checksum 'yarn.lock' }}"
Expand Down
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ module.exports = () =>
'<rootDir>/packages/consent/consent-tools',
'<rootDir>/packages/consent/consent-wrapper-onetrust',
'<rootDir>/scripts',
'<rootDir>/packages/signals/browser-signals',
],
})
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"playgrounds/*",
"packages/*",
"packages/consent/*",
"packages/signals/*",
"scripts"
],
"engines": {
Expand Down
7 changes: 7 additions & 0 deletions packages/signals/browser-signals/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** @type { import('eslint').Linter.Config } */
module.exports = {
extends: ['../../../.eslintrc'],
env: {
browser: true,
},
}
1 change: 1 addition & 0 deletions packages/signals/browser-signals/.lintstagedrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require("@internal/config").lintStagedConfig
21 changes: 21 additions & 0 deletions packages/signals/browser-signals/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright © 2023 Segment

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
1 change: 1 addition & 0 deletions packages/signals/browser-signals/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# @segment/analytics-browser-signals
5 changes: 5 additions & 0 deletions packages/signals/browser-signals/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const { createJestTSConfig } = require('@internal/config')

module.exports = createJestTSConfig(__dirname, {
testEnvironment: 'jsdom',
})
55 changes: 55 additions & 0 deletions packages/signals/browser-signals/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"name": "@segment/analytics-browser-signals",
"version": "0.0.1",
"main": "./dist/cjs/index.js",
"private": true,
"module": "./dist/esm/index.js",
"types": "./dist/types/index.d.ts",
"sideEffects": [
"./dist/umd/analytics-browser-signals.umd.js"
],
"jsdelivr": "./dist/umd/analytics-browser-signals.umd.js",
"unpkg": "./dist/umd/analytics-browser-signals.umd.js",
"files": [
"LICENSE",
"dist/",
"src/",
"!**/__tests__/**",
"!**/test-helpers/**",
"!*.tsbuildinfo"
],
"scripts": {
".": "yarn run -T turbo run --filter=@segment/analytics-browser-signals...",
"test": "yarn jest",
"lint": "yarn concurrently 'yarn:eslint .' 'yarn:tsc --noEmit'",
"build": "rm -rf dist && yarn concurrently 'yarn:build:*'",
"build:esm": "yarn tsc -p tsconfig.build.json",
"build:cjs": "yarn tsc -p tsconfig.build.json --outDir ./dist/cjs --module commonjs",
"build:bundle": "NODE_ENV=production yarn run webpack",
"build:bundle-dev": "NODE_ENV=development yarn run webpack",
"watch": "yarn concurrently 'yarn build:bundle-dev --watch' 'yarn build:esm --watch'",
"version": "sh scripts/version.sh",
"watch:test": "yarn test --watch",
"tsc": "yarn run -T tsc",
"eslint": "yarn run -T eslint",
"concurrently": "yarn run -T concurrently --raw",
"jest": "yarn run -T jest",
"webpack": "yarn run -T webpack"
},
"dependencies": {
"tslib": "^2.4.1"
},
"peerDependencies": {
"@segment/analytics-next": ">=1.70.0"
},
"peerDependenciesMeta": {
"@segment/analytics-next": {
"optional": true
}
},
"packageManager": "[email protected]",
"devDependencies": {
"@internal/config-webpack": "workspace:^",
"@internal/test-helpers": "workspace:^"
}
}
11 changes: 11 additions & 0 deletions packages/signals/browser-signals/scripts/version.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/sh
# Generate a version.ts file from the version in the package.json

PKG_VERSION=$(node --eval="process.stdout.write(require('./package.json').version)")

cat <<EOF >src/generated/version.ts
// This file is generated.
export const version = '$PKG_VERSION'
EOF

git add src/generated/version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { SignalBuffer } from '../index'

describe(SignalBuffer, () => {
let buffer: SignalBuffer

beforeEach(() => {
buffer = new SignalBuffer()
})

it('should exits', () => {
expect(buffer).toBeTruthy()
})
})
1 change: 1 addition & 0 deletions packages/signals/browser-signals/src/core/buffer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class SignalBuffer {}
5 changes: 5 additions & 0 deletions packages/signals/browser-signals/src/core/signals/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { SignalBuffer } from '../buffer'

export class Signals {
buffer = new SignalBuffer()
}
2 changes: 2 additions & 0 deletions packages/signals/browser-signals/src/generated/version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// This file is generated.
export const version = '0.0.1'
6 changes: 6 additions & 0 deletions packages/signals/browser-signals/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* This is the public API for this package.
* We avoid using splat (*) exports so that we can control what is exposed.
*/
export { SignalsPlugin } from './plugin/signals-plugin'
export { Signals } from './core/signals'
9 changes: 9 additions & 0 deletions packages/signals/browser-signals/src/index.umd.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* This is the entry point to a webpack bundle that can be loaded via a <script /> tag
*/
import { SignalsPlugin } from './index'
export { SignalsPlugin } // in case someone wants to use the umd module directly

if (typeof window !== 'undefined') {
;(window as any).SignalsPlugin = SignalsPlugin
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const SignalsPlugin = {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { AnyAnalytics } from '../../types'

export const analyticsMock: jest.Mocked<AnyAnalytics> = {
addSourceMiddleware: jest.fn(),
track: jest.fn(),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './analytics-mock'
75 changes: 75 additions & 0 deletions packages/signals/browser-signals/src/types/analytics-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* Defining stub interface here because we don't want to introduce a prod dependency on the analytics-next package
* Otherwise, we would introduce typescript errors for library consumers (unless they do skipLibCheck: true).
*/

export type EdgeFunctionSettings =
| {
version: number
downloadURL: string
}
| {}

export interface CDNSettings {
integrations: CDNSettingsIntegrations
edgeFunction?: EdgeFunctionSettings
}

export interface SegmentEventStub {
context: {}
}

export interface SourceMiddlewareParams {
payload: {
obj: SegmentEventStub
}
next: (payload: SourceMiddlewareParams['payload'] | null) => void
}

export type SourceMiddlewareFunction = (
middleware: SourceMiddlewareParams
) => null | void | Promise<void | null>

export interface DestinationMiddlewareParams {
payload: SourceMiddlewareParams['payload']
next: SourceMiddlewareParams['next']
/**
* integration name
* @example "Amplitude (Actions)"
*/
integration: string
}

export interface AnyAnalytics {
addSourceMiddleware(
middleware: Function | SourceMiddlewareFunction
): any | this
track(event: string, properties?: unknown, ...args: any[]): void
}

/**
*CDN Settings Integrations object.
* @example
* { "Fullstory": {...}, "Braze Web Mode (Actions)": {...}}
*/
export interface CDNSettingsIntegrations {
[integrationName: string]: { [key: string]: any }
}

export type PluginType = 'before' | 'after' | 'destination'

export interface Plugin<Analytics = AnyAnalytics, Ctx = Record<string, any>> {
name: string
type: PluginType
isLoaded: () => boolean
load: (ctx: Ctx, instance: Analytics) => Promise<unknown>

unload?: (ctx: Ctx, instance: Analytics) => Promise<unknown> | unknown
ready?: () => Promise<unknown>
track?: (ctx: Ctx) => Promise<Ctx> | Ctx
identify?: (ctx: Ctx) => Promise<Ctx> | Ctx
page?: (ctx: Ctx) => Promise<Ctx> | Ctx
group?: (ctx: Ctx) => Promise<Ctx> | Ctx
alias?: (ctx: Ctx) => Promise<Ctx> | Ctx
screen?: (ctx: Ctx) => Promise<Ctx> | Ctx
}
1 change: 1 addition & 0 deletions packages/signals/browser-signals/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './analytics-api'
1 change: 1 addition & 0 deletions packages/signals/browser-signals/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './ts-helpers'
33 changes: 33 additions & 0 deletions packages/signals/browser-signals/src/utils/ts-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Resolve a type to its final form.
*/
type Compute<T> = { [K in keyof T]: T[K] } & {}

/**
* A utility type that makes a specified set of fields optional in a given type.
* @template T - The type to make fields optional in.
* @template K - The keys of the fields to make optional.
* @example
* type MyType = {
* a: string
* b: number
* }
* type MyTypeWithOptionalA = OptionalField<MyType, 'a'>
* // MyTypeWithOptionalA is equivalent to:
* type MyTypeWithOptionalA = {
* a?: string
* b: number
* }
*/
export type OptionalField<T, K extends keyof T> = Compute<
Omit<T, K> & Partial<Pick<T, K>>
>

/**
* Helper function for exhaustive checks of discriminated unions.
*/
export function assertNever(value: never): never {
throw new Error(
`Unhandled discriminated union member: ${JSON.stringify(value)}`
)
}
9 changes: 9 additions & 0 deletions packages/signals/browser-signals/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"include": ["src"],
"exclude": ["**/__tests__/**", "**/test-helpers/**"],
"compilerOptions": {
"outDir": "./dist/esm",
"declarationDir": "./dist/types"
}
}
11 changes: 11 additions & 0 deletions packages/signals/browser-signals/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "../../../tsconfig.json",
"exclude": ["node_modules", "dist"],
"compilerOptions": {
"module": "ESNext", // es6 modules
"target": "ES2020", // don't down-compile *too much* -- if users are using webpack, they can always transpile this library themselves
"lib": ["ES2020", "DOM", "DOM.Iterable"], // assume that consumers will be polyfilling at least down to es2020
"moduleResolution": "node",
"isolatedModules": true // ensure we are friendly to build systems
}
}
25 changes: 25 additions & 0 deletions packages/signals/browser-signals/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const common = require('@internal/config-webpack/webpack.config.common')
const path = require('path')
const { merge } = require('webpack-merge')
const isProd = process.env.NODE_ENV === 'production'
/**
* @type { import('webpack').Configuration }
*/
module.exports = merge(common, {
entry: {
'analytics-browser-signals.umd': {
import: path.resolve(__dirname, 'src/index.umd.ts'),
library: {
name: 'AnalyticsBrowserSignals',
type: 'umd',
},
},
},
output: {
filename: isProd ? '[name].js' : '[name].development.js',
path: path.resolve(__dirname, 'dist/umd'),
chunkFilename: isProd
? '[name].[contenthash].js'
: '[name].chunk.development.js',
},
})
15 changes: 15 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3902,6 +3902,21 @@ __metadata:
languageName: node
linkType: hard

"@segment/analytics-browser-signals@workspace:packages/signals/browser-signals":
version: 0.0.0-use.local
resolution: "@segment/analytics-browser-signals@workspace:packages/signals/browser-signals"
dependencies:
"@internal/config-webpack": "workspace:^"
"@internal/test-helpers": "workspace:^"
tslib: ^2.4.1
peerDependencies:
"@segment/analytics-next": ">=1.70.0"
peerDependenciesMeta:
"@segment/analytics-next":
optional: true
languageName: unknown
linkType: soft

"@segment/[email protected], @segment/analytics-consent-tools@workspace:^, @segment/analytics-consent-tools@workspace:packages/consent/consent-tools":
version: 0.0.0-use.local
resolution: "@segment/analytics-consent-tools@workspace:packages/consent/consent-tools"
Expand Down

0 comments on commit 0589554

Please sign in to comment.