Skip to content

Commit

Permalink
even more types
Browse files Browse the repository at this point in the history
  • Loading branch information
mariusandra committed Jul 14, 2022
1 parent 30ddeee commit c1e44bf
Show file tree
Hide file tree
Showing 12 changed files with 174 additions and 190 deletions.
6 changes: 3 additions & 3 deletions src/base-request-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ export class RequestQueueScaffold {
isPolling: boolean // flag to continue to recursively poll or not
_event_queue: any[]
_empty_queue_count: number // to track empty polls
_poller: () => void // to become interval for reference to clear later
_poller: NodeJS.Timeout | undefined // to become interval for reference to clear later
_pollInterval: number

constructor(pollInterval = 3000) {
this.isPolling = true // flag to continue to recursively poll or not
this._event_queue = []
this._empty_queue_count = 0 // to track empty polls
this._poller = function () {} // to become interval for reference to clear later
this._poller = undefined // to become interval for reference to clear later
this._pollInterval = pollInterval
}

Expand All @@ -21,7 +21,7 @@ export class RequestQueueScaffold {
}
}

enqueue(): void {
enqueue(requestData): void {
return
}

Expand Down
25 changes: 13 additions & 12 deletions src/compression.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
import { LZString } from './lz-string'
import { strToU8, gzipSync } from 'fflate'
import { gzipSync, strToU8 } from 'fflate'
import { _base64Encode } from './utils'
import { Compression } from './types'

export function decideCompression(compressionSupport) {
if (compressionSupport['gzip-js']) {
return 'gzip-js'
} else if (compressionSupport['lz64']) {
return 'lz64'
export function decideCompression(compressionSupport: Record<Compression, boolean>): Compression {
if (compressionSupport[Compression.GZipJS]) {
return Compression.GZipJS
} else if (compressionSupport[Compression.LZ64]) {
return Compression.LZ64
} else {
return 'base64'
return Compression.Base64
}
}

export function compressData(compression, jsonData, options) {
if (compression === 'lz64') {
return [{ data: LZString.compressToBase64(jsonData), compression: 'lz64' }, options]
} else if (compression === 'gzip-js') {
export function compressData(compression: Compression, jsonData: string, options) {
if (compression === Compression.LZ64) {
return [{ data: LZString.compressToBase64(jsonData), compression: Compression.LZ64 }, options]
} else if (compression === Compression.GZipJS) {
// :TRICKY: This returns an UInt8Array. We don't encode this to a string - returning a blob will do this for us.
return [
gzipSync(strToU8(jsonData), { mtime: 0 }),
{ ...options, blob: true, urlQueryArgs: { compression: 'gzip-js' } },
{ ...options, blob: true, urlQueryArgs: { compression: Compression.GZipJS } },
]
} else {
return [{ data: _base64Encode(jsonData) }, options]
Expand Down
2 changes: 1 addition & 1 deletion src/extensions/toolbar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class Toolbar {
* 1. In the URL hash params if the customer is using an old snippet
* 2. From session storage under the key `editorParams` if the editor was initialized on a previous page
*/
maybeLoadEditor(location = window.location, localStorage, history = window.history) {
maybeLoadEditor(location = window.location, localStorage = undefined, history = window.history) {
try {
// Before running the code we check if we can access localStorage, if not we opt-out
if (!localStorage) {
Expand Down
10 changes: 5 additions & 5 deletions src/lz-string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
const f = String.fromCharCode
const keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
const keyStrUriSafe = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$'
const baseReverseDic = {}
const baseReverseDic: Record<string, Record<string, number>> = {}

function getBaseValue(alphabet, character) {
function getBaseValue(alphabet: string, character: string) {
if (!baseReverseDic[alphabet]) {
baseReverseDic[alphabet] = {}
for (let i = 0; i < alphabet.length; i++) {
Expand All @@ -25,7 +25,7 @@ function getBaseValue(alphabet, character) {
}

export const LZString = {
compressToBase64: function (input) {
compressToBase64: function (input: null | string) {
if (input == null) return ''
const res = LZString._compress(input, 6, function (a) {
return keyStrBase64.charAt(a)
Expand Down Expand Up @@ -341,15 +341,15 @@ export const LZString = {
return context_data.join('')
},

decompress: function (compressed) {
decompress: function (compressed: string | null) {
if (compressed == null) return ''
if (compressed == '') return null
return LZString._decompress(compressed.length, 32768, function (index) {
return compressed.charCodeAt(index)
})
},

_decompress: function (length, resetValue, getNextValue) {
_decompress: function (length: string, resetValue, getNextValue) {
let dictionary = [],
enlargeIn = 4,
dictSize = 4,
Expand Down
78 changes: 37 additions & 41 deletions src/posthog-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,17 @@ import { getPerformanceData } from './apm'
import {
CaptureResult,
ClearOptInOutCapturingOptions,
FeatureFlagsClass,
Compression,
HasOptedInOutCapturingOptions,
isFeatureEnabledOptions,
OptInOutCapturingOptions,
PersistenceClass,
PostHogConfig,
Properties,
Property,
XHROptions,
} from './types'
import { FeatureFlags } from '../react'

/*
SIMPLE STYLE GUIDE:
Expand Down Expand Up @@ -158,7 +160,7 @@ const defaultConfig = (): PostHogConfig => ({
* initializes document.posthog as well as any additional instances
* declared before this file has loaded).
*/
const create_mplib = function (token: string, config?: PostHogConfig, name: string) {
const create_mplib = function (token: string, config: Partial<PostHogConfig>, name: string): PostHogLib {
let instance: PostHogLib
const target = name === PRIMARY_INSTANCE_NAME || !posthog_master ? posthog_master : posthog_master[name]

Expand Down Expand Up @@ -227,8 +229,8 @@ export class PostHogLib {

people: PostHogPeople
persistence: PersistenceClass
featureFlags: FeatureFlagsClass
feature_flags: FeatureFlagsClass
featureFlags: FeatureFlags
feature_flags: FeatureFlags
sessionManager: SessionIdManager
toolbar: Toolbar
sessionRecording: SessionRecording
Expand All @@ -238,12 +240,17 @@ export class PostHogLib {
_retryQueue: RetryQueue

_triggered_notifs: any
compression: any
compression: Partial<Record<Compression, boolean>>
_jsc: any
__captureHooks: any
__request_queue: any
__autocapture_enabled: any
// decideEndpointWasHit = false
__autocapture_enabled: boolean
decideEndpointWasHit: boolean

constructor() {
this.compression = {}
this.decideEndpointWasHit = false
}

// Initialization methods

Expand All @@ -263,7 +270,7 @@ export class PostHogLib {
* @param {Object} [config] A dictionary of config options to override. <a href="https://github.com/posthog/posthog-js/blob/6e0e873/src/posthog-core.js#L57-L91">See a list of default config options</a>.
* @param {String} [name] The name for the new posthog instance that you want created
*/
init(token: string, config: Partial<PostHogConfig>, name: string) {
init(token: string, config: Partial<PostHogConfig>, name: string): PostHogLib | void {
if (_isUndefined(name)) {
console.error('You must name your new library: init(token, config, name)')
return
Expand All @@ -287,11 +294,10 @@ export class PostHogLib {
// method is this one initializes the actual instance, whereas the
// init(...) method sets up a new library and calls _init on it.
//
_init(token: string, config: Partial<PostHogConfig>, name: string) {
_init(token: string, config: Partial<PostHogConfig>, name: string): void {
this.__loaded = true
this.config = {} as PostHogConfig // will be set right below
this._triggered_notifs = []
this.compression = {}

this.set_config(
_extend({}, defaultConfig(), config, {
Expand Down Expand Up @@ -398,7 +404,7 @@ export class PostHogLib {
* If we are going to use script tags, this returns a string to use as the
* callback GET param.
*/
_prepare_callback(callback, data) {
_prepare_callback(callback, data?) {
if (_isUndefined(callback)) {
return null
}
Expand Down Expand Up @@ -447,22 +453,12 @@ export class PostHogLib {
this.__compress_and_send_json_request(url, jsonData, options || __NOOPTIONS, __NOOP)
}

__compress_and_send_json_request(
url: string,
jsonData: Record<string, any>,
options?: { transport: 'XHR' | 'sendBeacon' },
callback
): void {
__compress_and_send_json_request(url: string, jsonData: string, options?: XHROptions, callback): void {
const [data, _options] = compressData(decideCompression(this.compression), jsonData, options)
this._send_request(url, data, _options, callback)
}

_send_request(
url: string,
data: Record<string, any>,
options?: { transport: 'XHR' | 'sendBeacon' },
callback
): void {
_send_request(url: string, data: Record<string, any>, options: Partial<XHROptions>, callback): void {
if (ENQUEUE_REQUESTS) {
this.__request_queue.push(arguments)
return
Expand All @@ -479,7 +475,7 @@ export class PostHogLib {
options.method = 'GET'
}

const useSendBeacon = window.navigator.sendBeacon && options.transport.toLowerCase() === 'sendbeacon'
const useSendBeacon = 'sendBeacon' in window.navigator && options.transport.toLowerCase() === 'sendbeacon'
url = addParamsToURL(url, options.urlQueryArgs, {
ip: this.get_config('ip'),
})
Expand Down Expand Up @@ -539,7 +535,7 @@ export class PostHogLib {
*
* @param {Array} array
*/
_execute_array(array) {
_execute_array(array): void {
let fn_name
const alias_calls = []
const other_calls = []
Expand Down Expand Up @@ -604,7 +600,7 @@ export class PostHogLib {
*
* @param {Array} item A [function_name, args...] array to be executed
*/
push(item) {
push(item): void {
this._execute_array([item])
}

Expand Down Expand Up @@ -706,16 +702,16 @@ export class PostHogLib {
return data
}

_addCaptureHook(callback) {
_addCaptureHook(callback): void {
this.__captureHooks.push(callback)
}

_invokeCaptureHooks(eventName, eventData) {
_invokeCaptureHooks(eventName: string, eventData: CaptureResult): void {
this.config._onCapture(eventName, eventData)
_each(this.__captureHooks, (callback) => callback(eventName))
}

_calculate_event_properties(event_name: string, event_properties: Properties, start_timestamp) {
_calculate_event_properties(event_name: string, event_properties: Properties, start_timestamp: number): Properties {
// set defaults
let properties = { ...event_properties }
properties['token'] = this.get_config('token')
Expand Down Expand Up @@ -820,7 +816,7 @@ export class PostHogLib {
this.persistence.unregister(property)
}

_register_single(prop, value) {
_register_single(prop: string, value: Property) {
this.register({ [prop]: value })
}

Expand Down Expand Up @@ -1473,15 +1469,15 @@ export class PostHogLib {
* @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this PostHog instance's config)
*/
opt_out_capturing(options?: OptInOutCapturingOptions): void {
options = _extend(
const _options = _extend(
{
clear_persistence: true,
},
options
options || {}
)

this._gdpr_call_func(optOut, options)
this._gdpr_update_persistence(options)
this._gdpr_call_func(optOut, _options)
this._gdpr_update_persistence(_options)
}

/**
Expand Down Expand Up @@ -1542,15 +1538,15 @@ export class PostHogLib {
* @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this PostHog instance's config)
*/
clear_opt_in_out_capturing(options?: ClearOptInOutCapturingOptions): void {
options = _extend(
const _options = _extend(
{
enable_persistence: true,
},
options
options ?? {}
)

this._gdpr_call_func(clearOptInOut, options)
this._gdpr_update_persistence(options)
this._gdpr_call_func(clearOptInOut, _options)
this._gdpr_update_persistence(_options)
}

/**
Expand Down Expand Up @@ -1602,10 +1598,10 @@ export class PostHogLib {
}
}

debug(debug): void {
if (debug === false) {
debug(debug: boolean): void {
if (!debug) {
window.console.log("You've disabled debug mode.")
localStorage && localStorage.setItem('ph_debug', undefined)
localStorage && localStorage.removeItem('ph_debug')
this.set_config({ debug: false })
} else {
window.console.log(
Expand Down
Loading

0 comments on commit c1e44bf

Please sign in to comment.