@leanbase-giangnd/js 0.0.5 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,47 +1,48 @@
1
1
  {
2
- "name": "@leanbase-giangnd/js",
3
- "version": "0.0.5",
4
- "description": "Leanbase browser SDK - event tracking, autocapture, and session replay",
5
- "repository": {
6
- "type": "git",
7
- "directory": "packages/leanbase"
8
- },
9
- "author": "leanbase",
10
- "license": "Copyrighted by Leanflag Limited",
11
- "main": "dist/index.cjs",
12
- "module": "dist/index.mjs",
13
- "types": "dist/index.d.ts",
14
- "unpkg": "dist/leanbase.iife.js",
15
- "jsdelivr": "dist/leanbase.iife.js",
16
- "files": [
17
- "dist",
18
- "src",
19
- "README.md"
20
- ],
21
- "publishConfig": {
22
- "access": "public"
23
- },
24
- "dependencies": {
25
- "@rrweb/record": "2.0.0-alpha.17",
26
- "fflate": "^0.4.8",
27
- "@posthog/core": "1.3.1"
28
- },
29
- "devDependencies": {
30
- "jest": "^29.7.0",
31
- "jest-environment-jsdom": "^29.7.0",
32
- "rollup": "^4.44.1",
33
- "rimraf": "^6.0.1",
34
- "@posthog-tooling/tsconfig-base": "1.0.0",
35
- "@posthog-tooling/rollup-utils": "1.0.0"
36
- },
37
- "scripts": {
38
- "clean": "rimraf dist coverage",
39
- "test:unit": "jest -c jest.config.js",
40
- "lint": "eslint src test",
41
- "lint:fix": "eslint src test --fix",
42
- "prebuild": "node -p \"'export const version = \\'' + require('./package.json').version + '\\''\" > src/version.ts",
43
- "build": "rollup -c",
44
- "dev": "rollup -c -w",
45
- "package": "mkdir -p ../../target && pnpm pack --pack-destination ../../target"
46
- }
47
- }
2
+ "name": "@leanbase-giangnd/js",
3
+ "version": "0.1.0",
4
+ "description": "Leanbase browser SDK - event tracking, autocapture, and session replay",
5
+ "repository": {
6
+ "type": "git",
7
+ "directory": "packages/leanbase"
8
+ },
9
+ "author": "leanbase",
10
+ "license": "Copyrighted by Leanflag Limited",
11
+ "main": "dist/index.cjs",
12
+ "module": "dist/index.mjs",
13
+ "types": "dist/index.d.ts",
14
+ "unpkg": "dist/leanbase.iife.js",
15
+ "jsdelivr": "dist/leanbase.iife.js",
16
+ "scripts": {
17
+ "clean": "rimraf dist coverage",
18
+ "test:unit": "jest -c jest.config.js",
19
+ "lint": "eslint src test",
20
+ "lint:fix": "eslint src test --fix",
21
+ "prebuild": "node -p \"'export const version = \\'' + require('./package.json').version + '\\''\" > src/version.ts",
22
+ "build": "rollup -c",
23
+ "dev": "rollup -c -w",
24
+ "prepublishOnly": "pnpm lint && pnpm test:unit && pnpm build",
25
+ "package": "mkdir -p ../../target && pnpm pack --pack-destination ../../target"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "src",
30
+ "README.md"
31
+ ],
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@posthog/core": "workspace:*",
37
+ "@rrweb/record": "2.0.0-alpha.17",
38
+ "fflate": "^0.4.8"
39
+ },
40
+ "devDependencies": {
41
+ "@posthog-tooling/tsconfig-base": "workspace:*",
42
+ "@posthog-tooling/rollup-utils": "workspace:*",
43
+ "jest": "catalog:",
44
+ "jest-environment-jsdom": "catalog:",
45
+ "rollup": "catalog:",
46
+ "rimraf": "^6.0.1"
47
+ }
48
+ }
@@ -43,7 +43,6 @@ import {
43
43
  SESSION_RECORDING_REMOTE_CONFIG,
44
44
  SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION,
45
45
  } from '../../../constants'
46
- import { sendSnapshotDirect } from './snapshot-transport'
47
46
  import { Leanbase } from '../../../leanbase'
48
47
  import {
49
48
  CaptureResult,
@@ -1020,32 +1019,14 @@ export class LazyLoadedSessionRecording {
1020
1019
  }
1021
1020
  }
1022
1021
 
1023
- private async _captureSnapshot(properties: Properties) {
1024
- // Send snapshots directly to the recorder endpoint to avoid the core
1025
- // analytics batching and persisted queue. The lifecycle gate in
1026
- // SessionRecording ensures this method is only called when recording
1027
- // is allowed.
1028
- try {
1029
- const url = this._snapshotUrl()
1030
- // include minimal metadata expected by /s/ endpoint
1031
- const payload = {
1032
- $snapshot_bytes: properties.$snapshot_bytes,
1033
- $snapshot_data: properties.$snapshot_data,
1034
- $session_id: properties.$session_id,
1035
- $window_id: properties.$window_id,
1036
- $lib: properties.$lib,
1037
- $lib_version: properties.$lib_version,
1038
- // include distinct_id from persistence for server-side association
1039
- distinct_id: this._instance.persistence?.get_property('distinct_id'),
1040
- }
1041
-
1042
- await sendSnapshotDirect(this._instance, url, payload)
1043
- } catch (err) {
1044
- try {
1045
- // eslint-disable-next-line no-console
1046
- console.debug('[SessionRecording] snapshot send failed', err)
1047
- } catch {}
1048
- }
1022
+ private _captureSnapshot(properties: Properties) {
1023
+ // :TRICKY: Make sure we batch these requests, use a custom endpoint and don't truncate the strings.
1024
+ this._instance.capture('$snapshot', properties, {
1025
+ _url: this._snapshotUrl(),
1026
+ _noTruncate: true,
1027
+ _batchKey: SESSION_RECORDING_BATCH_KEY,
1028
+ skip_client_rate_limiting: true,
1029
+ })
1049
1030
  }
1050
1031
 
1051
1032
  private _snapshotUrl(): string {
package/src/leanbase.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  PostHogCore,
3
3
  getFetch,
4
- isArray,
5
4
  isEmptyObject,
6
5
  isEmptyString,
7
6
  isNumber,
@@ -32,11 +31,10 @@ import {
32
31
  navigator,
33
32
  userAgent,
34
33
  } from './utils'
35
- import { decompressSync, strFromU8 } from 'fflate'
36
34
  import Config from './config'
37
35
  import { Autocapture } from './autocapture'
38
36
  import { logger } from './leanbase-logger'
39
- import { COOKIELESS_MODE_FLAG_PROPERTY, USER_STATE, SESSION_RECORDING_REMOTE_CONFIG } from './constants'
37
+ import { COOKIELESS_MODE_FLAG_PROPERTY, USER_STATE } from './constants'
40
38
  import { getEventProperties } from './utils/event-utils'
41
39
  import { SessionIdManager } from './sessionid'
42
40
  import { SessionPropsManager } from './session-props'
@@ -210,132 +208,10 @@ export class Leanbase extends PostHogCore {
210
208
  this.sessionRecording?.onRemoteConfig(config)
211
209
  }
212
210
 
213
- async fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse> {
211
+ fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse> {
214
212
  const fetchFn = getFetch()
215
213
  if (!fetchFn) {
216
- throw new Error('Fetch API is not available in this environment.')
217
- }
218
-
219
- try {
220
- const isPost = !options.method || options.method.toUpperCase() === 'POST'
221
- const isBatchEndpoint = typeof url === 'string' && url.endsWith('/batch/')
222
-
223
- if (isPost && isBatchEndpoint && options && options.body) {
224
- let parsed: any = null
225
- try {
226
- const headers = (options.headers || {}) as Record<string, any>
227
- const contentEncoding = (
228
- headers['Content-Encoding'] ||
229
- headers['content-encoding'] ||
230
- ''
231
- ).toLowerCase()
232
-
233
- const toUint8 = async (body: any): Promise<Uint8Array | null> => {
234
- if (typeof body === 'string') return new TextEncoder().encode(body)
235
- if (typeof Blob !== 'undefined' && body instanceof Blob) {
236
- const ab = await body.arrayBuffer()
237
- return new Uint8Array(ab)
238
- }
239
- if (body instanceof ArrayBuffer) return new Uint8Array(body)
240
- if (ArrayBuffer.isView(body)) return new Uint8Array((body as any).buffer ?? body)
241
- try {
242
- return new TextEncoder().encode(String(body))
243
- } catch {
244
- return null
245
- }
246
- }
247
-
248
- if (contentEncoding === 'gzip' || contentEncoding === 'deflate') {
249
- const u8 = await toUint8(options.body)
250
- if (u8) {
251
- try {
252
- const dec = decompressSync(u8)
253
- const s = strFromU8(dec)
254
- parsed = JSON.parse(s)
255
- } catch {
256
- parsed = null
257
- }
258
- }
259
- } else {
260
- if (typeof options.body === 'string') {
261
- parsed = JSON.parse(options.body)
262
- } else {
263
- const u8 = await toUint8(options.body)
264
- if (u8) {
265
- try {
266
- parsed = JSON.parse(new TextDecoder().decode(u8))
267
- } catch {
268
- parsed = null
269
- }
270
- } else {
271
- try {
272
- parsed = JSON.parse(String(options.body))
273
- } catch {
274
- parsed = null
275
- }
276
- }
277
- }
278
- }
279
- } catch {
280
- parsed = null
281
- }
282
-
283
- if (parsed && isArray(parsed.batch)) {
284
- const hasSnapshot = parsed.batch.some((item: any) => item && item.event === '$snapshot')
285
- // Debug logging to help diagnose routing issues
286
- try {
287
- // eslint-disable-next-line no-console
288
- console.debug(
289
- '[Leanbase.fetch] parsed.batch.length=',
290
- parsed.batch.length,
291
- 'hasSnapshot=',
292
- hasSnapshot
293
- )
294
- } catch {}
295
-
296
- // If remote config has explicitly disabled session recording, drop snapshot events
297
- try {
298
- // Read persisted remote config that SessionRecording stores
299
- const persisted: any = this.get_property(SESSION_RECORDING_REMOTE_CONFIG)
300
- const serverAllowsRecording = !(
301
- (persisted && persisted.enabled === false) ||
302
- this.config.disable_session_recording === true
303
- )
304
-
305
- if (!serverAllowsRecording && hasSnapshot) {
306
- // remove snapshot events from the batch before sending to /batch/
307
- parsed.batch = parsed.batch.filter((item: any) => !(item && item.event === '$snapshot'))
308
- // If no events remain, short-circuit and avoid sending an empty batch
309
- if (!parsed.batch.length) {
310
- try {
311
- // eslint-disable-next-line no-console
312
- console.debug(
313
- '[Leanbase.fetch] sessionRecording disabled, dropping snapshot-only batch'
314
- )
315
- } catch {}
316
- return { status: 200, json: async () => ({}) } as any
317
- }
318
- // re-encode the body so the underlying fetch receives the modified batch
319
- try {
320
- const newBody = JSON.stringify(parsed)
321
- options = { ...options, body: newBody }
322
- } catch {}
323
- }
324
- } catch {}
325
-
326
- if (hasSnapshot) {
327
- const host = (this.config && this.config.host) || ''
328
- const newUrl = host ? `${host.replace(/\/$/, '')}/s/` : url
329
- try {
330
- // eslint-disable-next-line no-console
331
- console.debug('[Leanbase.fetch] routing snapshot batch to', newUrl)
332
- } catch {}
333
- return fetchFn(newUrl, options)
334
- }
335
- }
336
- }
337
- } catch {
338
- return fetchFn(url, options)
214
+ return Promise.reject(new Error('Fetch API is not available in this environment.'))
339
215
  }
340
216
 
341
217
  return fetchFn(url, options)
@@ -1,6 +1,5 @@
1
1
  declare module 'fflate' {
2
2
  export const gzipSync: (...args: any[]) => any
3
3
  export const strFromU8: (...args: any[]) => any
4
- export const decompressSync: (...args: any[]) => any
5
4
  export const strToU8: (...args: any[]) => any
6
5
  }
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = '0.0.5'
1
+ export const version = '0.1.0'
package/LICENSE DELETED
@@ -1,37 +0,0 @@
1
- Copyright 2025 Leanflag Limited
2
- This project is a fork of PostHog/posthog-js.
3
-
4
- All rights reserved. This software is proprietary to Leanflag Limited and may only be used for Leanflag Limited products and internal purposes. Redistribution, modification, or commercial use outside of Leanflag Limited is strictly prohibited without explicit written permission from Leanflag Limited.
5
-
6
-
7
- ---
8
-
9
- Copyright 2020 Posthog / Hiberly, Inc.
10
-
11
- Copyright 2015 Mixpanel, Inc.
12
-
13
-
14
- Some files in this codebase contain code from getsentry/sentry-javascript by Software, Inc. dba Sentry.
15
- In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases.
16
-
17
- MIT License
18
-
19
- Copyright (c) 2012 Functional Software, Inc. dba Sentry
20
-
21
- Permission is hereby granted, free of charge, to any person obtaining a copy of
22
- this software and associated documentation files (the "Software"), to deal in
23
- the Software without restriction, including without limitation the rights to
24
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
25
- of the Software, and to permit persons to whom the Software is furnished to do
26
- so, subject to the following conditions:
27
-
28
- The above copyright notice and this permission notice shall be included in all
29
- copies or substantial portions of the Software.
30
-
31
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
34
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
36
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
37
- SOFTWARE.
@@ -1,50 +0,0 @@
1
- import { gzipSync, strToU8 } from 'fflate'
2
- import { Leanbase } from '../../../leanbase'
3
-
4
- /**
5
- * Leanbase-only SnapshotTransport
6
- * Sends gzip-compressed snapshot payloads directly to the /s/ endpoint.
7
- * This bypasses `posthog.capture()` and the analytics /batch/ queue.
8
- *
9
- * Reasoning: session replay snapshots must not enter the batch/persisted
10
- * queues managed by @posthog/core. This transport posts directly to the
11
- * recorder endpoint and uses the instance.fetch() implementation so it
12
- * runs in the same environment the SDK uses.
13
- */
14
- export async function sendSnapshotDirect(instance: Leanbase, url: string, payload: unknown) {
15
- const fetchFn: any =
16
- instance && (instance as any).fetch ? (instance as any).fetch.bind(instance) : (globalThis as any).fetch
17
-
18
- const body = JSON.stringify(payload)
19
- const compressed = gzipSync(strToU8(body))
20
-
21
- const headers: Record<string, string> = {
22
- 'Content-Encoding': 'gzip',
23
- 'Content-Type': 'application/json',
24
- Accept: 'application/json',
25
- }
26
-
27
- if (!fetchFn) {
28
- // best-effort: if no fetch available, fail silently (recorder should not crash app)
29
- try {
30
- // eslint-disable-next-line no-console
31
- console.debug('[SnapshotTransport] no fetch available, dropping snapshot')
32
- } catch {}
33
- return { status: 0 }
34
- }
35
-
36
- try {
37
- // Use the instance.fetch wrapper so environment-specific shims are used.
38
- return await fetchFn(url, {
39
- method: 'POST',
40
- body: compressed,
41
- headers,
42
- })
43
- } catch (err) {
44
- try {
45
- // eslint-disable-next-line no-console
46
- console.debug('[SnapshotTransport] send failed', err)
47
- } catch {}
48
- return { status: 0 }
49
- }
50
- }