@treasuredata/web-sdk 1.0.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.
Files changed (50) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +807 -0
  4. package/dist/browser.d.ts +9 -0
  5. package/dist/checksums.txt +8 -0
  6. package/dist/core/config.d.ts +10 -0
  7. package/dist/core/config.template.d.ts +10 -0
  8. package/dist/core/configurator.d.ts +35 -0
  9. package/dist/core/sdk.d.ts +3 -0
  10. package/dist/index.d.ts +37 -0
  11. package/dist/init.d.ts +18 -0
  12. package/dist/loader.d.ts +59 -0
  13. package/dist/loader.js +1 -0
  14. package/dist/loader.min.js +1 -0
  15. package/dist/plugins/clicks.d.ts +21 -0
  16. package/dist/plugins/conversion-api.d.ts +23 -0
  17. package/dist/plugins/global-id.d.ts +17 -0
  18. package/dist/plugins/in-browser-message.d.ts +6 -0
  19. package/dist/plugins/page-personalize/bridge/constants.d.ts +9 -0
  20. package/dist/plugins/page-personalize/bridge/rpc.d.ts +15 -0
  21. package/dist/plugins/page-personalize/index.d.ts +34 -0
  22. package/dist/plugins/page-personalize/injection/inject.d.ts +17 -0
  23. package/dist/plugins/page-personalize/modes/preview.d.ts +3 -0
  24. package/dist/plugins/page-personalize/modes/spot-selection.d.ts +9 -0
  25. package/dist/plugins/page-personalize/offers.d.ts +72 -0
  26. package/dist/plugins/page-personalize/router.d.ts +17 -0
  27. package/dist/plugins/page-personalize/types.d.ts +27 -0
  28. package/dist/plugins/page-personalize/utils/selector-generator.d.ts +6 -0
  29. package/dist/plugins/personalization.d.ts +39 -0
  30. package/dist/plugins/record.d.ts +32 -0
  31. package/dist/plugins/server-cookie.d.ts +14 -0
  32. package/dist/plugins/session.d.ts +25 -0
  33. package/dist/plugins/track.d.ts +16 -0
  34. package/dist/plugins/utm.d.ts +16 -0
  35. package/dist/td-sdk.cjs +3263 -0
  36. package/dist/td-sdk.esm.js +3263 -0
  37. package/dist/td-sdk.esm.min.js +1 -0
  38. package/dist/td-sdk.js +3176 -0
  39. package/dist/td-sdk.min.cjs +1 -0
  40. package/dist/td-sdk.min.js +1 -0
  41. package/dist/treasure.d.ts +198 -0
  42. package/dist/types/index.d.ts +177 -0
  43. package/dist/utils/element.d.ts +20 -0
  44. package/dist/utils/lodash.d.ts +18 -0
  45. package/dist/utils/misc.d.ts +17 -0
  46. package/dist/utils/set-cookie.d.ts +14 -0
  47. package/dist/utils/uuid.d.ts +14 -0
  48. package/dist/utils/xhr.d.ts +58 -0
  49. package/dist/vendor/js-cookies.d.ts +19 -0
  50. package/package.json +90 -0
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Core type definitions for Treasure Data Web SDK
3
+ */
4
+ import type { PersonalizationFetchConfig } from '../plugins/personalization';
5
+ import type { AddRecordOptions } from '../plugins/record';
6
+ import type { PersonalizationPayload } from '../plugins/page-personalize/offers';
7
+ import type { ApplyPersonalizationOptions } from '../plugins/page-personalize';
8
+ export type JSONValue = string | number | boolean | null | {
9
+ [key: string]: JSONValue;
10
+ } | JSONValue[];
11
+ export interface TrackEvent {
12
+ /** Database table name */
13
+ table: string;
14
+ /** Event data payload */
15
+ data: Record<string, JSONValue>;
16
+ /** Success callback */
17
+ success?: ((response: TrackResponse) => void) | undefined;
18
+ /** Error callback */
19
+ error?: ((error: TDError) => void) | undefined;
20
+ }
21
+ export interface PersonalizationOptions {
22
+ endpoint: string;
23
+ token: string;
24
+ database?: string;
25
+ }
26
+ export interface TrackResponse {
27
+ success: boolean;
28
+ message?: string;
29
+ [key: string]: JSONValue | undefined;
30
+ }
31
+ export interface TDError extends Error {
32
+ code?: string;
33
+ status?: number;
34
+ details?: Record<string, JSONValue>;
35
+ }
36
+ export interface TDConfig {
37
+ /** API write key */
38
+ writeKey: string;
39
+ /** Database name */
40
+ database: string;
41
+ /** API endpoint host */
42
+ host?: string;
43
+ /** Development mode flag */
44
+ development?: boolean;
45
+ /** Global ID cookie name */
46
+ globalIdCookie?: string;
47
+ /** Logging flag */
48
+ logging?: boolean;
49
+ /** API pathname */
50
+ pathname?: string;
51
+ /** Request type */
52
+ requestType?: string;
53
+ /** JSONP timeout in milliseconds */
54
+ jsonpTimeout?: number;
55
+ /** Start in signed mode */
56
+ startInSignedMode?: boolean;
57
+ /** Use server-side cookie */
58
+ useServerSideCookie?: boolean;
59
+ /** Server-side cookie domain function */
60
+ sscDomain?: string | (() => string);
61
+ /** Server-side cookie server function */
62
+ sscServer?: (cookieDomain: string) => string;
63
+ /** Store consent by localStorage */
64
+ storeConsentByLocalStorage?: boolean;
65
+ /** Full endpoint URL (computed) */
66
+ endpoint?: string;
67
+ /** Global values storage */
68
+ globals?: Record<string, Record<string, JSONValue>>;
69
+ /** Cookie storage configuration */
70
+ storage?: StorageConfiguration;
71
+ /** CDP host for personalization API (default: 'cdp.in.treasuredata.com') */
72
+ cdpHost?: string;
73
+ /** Personalization config; when set, every tracked event also fetches personalization */
74
+ personalization?: PersonalizationOptions;
75
+ /** Client ID for tracking */
76
+ clientId?: string | number;
77
+ }
78
+ export interface StorageConfiguration {
79
+ name: string;
80
+ domain: string;
81
+ path?: string;
82
+ expires: number;
83
+ }
84
+ export interface Logger {
85
+ debug: (...args: unknown[]) => void;
86
+ warn: (...args: unknown[]) => void;
87
+ error: (...args: unknown[]) => void;
88
+ }
89
+ export interface TreasureCore {
90
+ config: TDConfig;
91
+ log: Logger;
92
+ }
93
+ export interface TreasurePlugin<T = any> {
94
+ name: string;
95
+ setup: (core: TreasureCore, sdk: TreasureSDK) => T;
96
+ }
97
+ export interface TreasureSDK extends TreasureCore {
98
+ use: <T>(plugin: TreasurePlugin<T>) => TreasureSDK & T;
99
+ /** Get the configured write key */
100
+ getWriteKey(): string;
101
+ /** Set the write key */
102
+ setWriteKey(writeKey: string): void;
103
+ inSignedMode(): boolean;
104
+ isGlobalIdEnabled(): boolean;
105
+ setSignedMode(): void;
106
+ setAnonymousMode(keepIdentifier?: boolean): void;
107
+ blockEvents(): void;
108
+ unblockEvents(): void;
109
+ areEventsBlocked(): boolean;
110
+ getUUID(): string;
111
+ resetUUID(suggestedStorage?: StorageConfiguration, suggestedClientId?: string): void;
112
+ set(table: string | Record<string, JSONValue>, property?: string | Record<string, JSONValue>, value?: JSONValue): void;
113
+ get(table?: string, key?: string): JSONValue;
114
+ removeCachedGlobalID(): void;
115
+ removeServerCookie(): void;
116
+ addRecord(table: string, record: Record<string, JSONValue>, success?: (response: TrackResponse) => void, error?: (error: TDError) => void, options?: AddRecordOptions): void;
117
+ trackEvent(table?: string, record?: Record<string, JSONValue>, success?: (result: TrackResponse) => void, failure?: (error: TDError) => void): void;
118
+ trackPageview(table?: string, success?: (result: TrackResponse) => void, failure?: (error: TDError) => void, options?: {
119
+ payload?: Record<string, JSONValue>;
120
+ }): void;
121
+ getTrackValues(): Record<string, JSONValue>;
122
+ getPersonalizationConfig(): PersonalizationOptions | undefined;
123
+ setPersonalizationConfig(options?: PersonalizationOptions): void;
124
+ trackClicks(options?: {
125
+ tableName?: string;
126
+ element?: string | HTMLElement;
127
+ }): void;
128
+ collectUTMParameters(): Record<string, JSONValue>;
129
+ getUTMParameters(): Record<string, JSONValue>;
130
+ fetchUserSegments(options: {
131
+ audienceToken: string | string[];
132
+ keys?: Record<string, JSONValue>;
133
+ }, successCallback?: (segments: {
134
+ key: Record<string, JSONValue>;
135
+ values: string[];
136
+ attributes: Record<string, JSONValue>;
137
+ }[]) => void, errorCallback?: (error: Error) => void): void;
138
+ fetchUserSegments(audienceToken: string | string[], successCallback?: (segments: {
139
+ key: Record<string, JSONValue>;
140
+ values: string[];
141
+ attributes: Record<string, JSONValue>;
142
+ }[]) => void, errorCallback?: (error: Error) => void): void;
143
+ fetchPersonalization(config: {
144
+ endpoint: string;
145
+ database: string;
146
+ table: string;
147
+ token: string;
148
+ }, data?: Record<string, JSONValue> | null, successCallback?: (response: Record<string, JSONValue>) => void, errorCallback?: (error: Error) => void): void;
149
+ applyPersonalization(payload: PersonalizationPayload, options?: ApplyPersonalizationOptions): void;
150
+ personalizePage(config: PersonalizationFetchConfig, data?: Record<string, JSONValue> | null, successCallback?: (payload: PersonalizationPayload) => void, errorCallback?: (error: Error) => void): void;
151
+ collectTags(options?: {
152
+ table?: string;
153
+ success?: (response: TrackResponse) => void;
154
+ error?: (error: TDError) => void;
155
+ }): void;
156
+ fetchServerCookie(success?: (serverSideId: string) => void, error?: (error: string | Error) => void, forceFetch?: boolean): void;
157
+ fetchGlobalID(success?: (globalId: string | null) => void, error?: (error: unknown) => void, forceFetch?: boolean, options?: {
158
+ path?: string;
159
+ domain?: string;
160
+ secure?: boolean;
161
+ maxAge?: number | string | Date;
162
+ sameSite?: 'None' | 'Lax' | 'Strict';
163
+ }): void;
164
+ }
165
+ export interface ElementData {
166
+ tag: string;
167
+ tree: string;
168
+ alt?: string;
169
+ class?: string;
170
+ href?: string;
171
+ id?: string;
172
+ name?: string;
173
+ role?: string;
174
+ title?: string;
175
+ type?: string;
176
+ }
177
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * DOM element utility functions for click tracking
3
+ */
4
+ export declare function getEventTarget(event: Event): Element;
5
+ export declare function addEventListener(el: Element | Document, type: string, fn: (event: Event) => void): () => void;
6
+ /**
7
+ * ORIGINAL SOURCE: https://github.com/getsentry/raven-js/
8
+ * Given a child DOM element, returns a query-selector statement describing that
9
+ * and its ancestors
10
+ * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
11
+ */
12
+ export declare function htmlTreeAsString(elem: Element | null): string;
13
+ /**
14
+ * ORIGINAL SOURCE: https://github.com/getsentry/raven-js/
15
+ * Returns a simple, query-selector representation of a DOM element
16
+ * e.g. [HTMLElement] => input#foo.btn[name=baz]
17
+ */
18
+ export declare function htmlElementAsString(elem: Element | null): string;
19
+ export declare function hasAttribute(element: Element, attrName: string): boolean;
20
+ //# sourceMappingURL=element.d.ts.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Lightweight lodash-like utility functions
3
+ * Modern TypeScript implementations without external dependencies
4
+ */
5
+ export declare function forEach<T>(collection: T[] | Record<string, T>, callback: (value: T, key: string | number) => void): void;
6
+ export declare function isNumber(value: unknown): value is number;
7
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
8
+ export declare function isString(value: unknown): value is string;
9
+ export declare function isArray(value: unknown): value is unknown[];
10
+ export declare function isFunction(value: unknown): value is Function;
11
+ export declare function isEmpty(value: unknown): boolean;
12
+ export declare function keys(obj: Record<string, unknown>): string[];
13
+ export declare function assign<T extends Record<string, unknown>>(target: T, ...sources: Partial<T>[]): T;
14
+ export declare function forIn<T>(obj: Record<string, T>, callback: (value: T, key: string) => void): void;
15
+ export declare function omit<T extends Record<string, unknown>>(obj: T, ...keysToOmit: (keyof T)[]): Partial<T>;
16
+ export declare function cloneDeep<T>(value: T): T;
17
+ export declare function noop(): void;
18
+ //# sourceMappingURL=lodash.d.ts.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Miscellaneous utility functions
3
+ */
4
+ export declare function disposable(action: () => void): () => void;
5
+ export declare function invariant(condition: unknown, text: string): asserts condition;
6
+ export declare function fetchWithTimeout(url: string, milliseconds: number, options?: RequestInit): Promise<Response>;
7
+ export declare function isLocalStorageAccessible(): boolean;
8
+ export declare function camelCase(str?: string): string | undefined;
9
+ export declare const adlHeaders: {
10
+ readonly 'Content-Type': "application/vnd.treasuredata.v1+json";
11
+ readonly Accept: "application/vnd.treasuredata.v1+json";
12
+ };
13
+ export declare const globalIdAdlHeaders: {
14
+ readonly 'Content-Type': "application/vnd.treasuredata.v1.js+json";
15
+ readonly Accept: "application/vnd.treasuredata.v1.js+json";
16
+ };
17
+ //# sourceMappingURL=misc.d.ts.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Set cookie on highest allowed domain utility
3
+ */
4
+ export interface CookieConfig {
5
+ domain: string;
6
+ path?: string;
7
+ expires: number;
8
+ customDomain?: boolean;
9
+ }
10
+ /**
11
+ * Set cookie on highest allowed domain
12
+ */
13
+ export declare function setCookie(storage: CookieConfig, name: string, value?: string): void;
14
+ //# sourceMappingURL=set-cookie.d.ts.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * UUID Generation Utility
3
+ * Generates RFC4122 compliant UUIDs for client identification
4
+ */
5
+ /**
6
+ * Generate a UUID v4 (random)
7
+ * Based on RFC4122 specification
8
+ */
9
+ export declare function generateUUID(): string;
10
+ /**
11
+ * Validate if a string is a valid UUID
12
+ */
13
+ export declare function isValidUUID(uuid: string): boolean;
14
+ //# sourceMappingURL=uuid.d.ts.map
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Modern Fetch API utility functions
3
+ * Using AbortController for all timeout handling (baseline browser support)
4
+ */
5
+ declare const FETCH_CREDENTIALS: {
6
+ readonly 'same-origin': "same-origin";
7
+ readonly include: "include";
8
+ readonly omit: "omit";
9
+ };
10
+ interface RequestOptions {
11
+ headers?: Record<string, string>;
12
+ credentials?: keyof typeof FETCH_CREDENTIALS;
13
+ signal?: AbortSignal;
14
+ }
15
+ /**
16
+ * POST request using fetch API
17
+ */
18
+ declare function post(url: string, body: any, options?: RequestOptions): Promise<any>;
19
+ /**
20
+ * GET request using fetch API
21
+ */
22
+ declare function get(url: string, options?: RequestOptions): Promise<any>;
23
+ /**
24
+ * Add timeout to any promise using AbortController
25
+ */
26
+ declare function withTimeout<T>(promiseFactory: (signal: AbortSignal) => Promise<T>, milliseconds: number, timeoutMessage?: string): Promise<T>;
27
+ /**
28
+ * POST request with timeout using AbortController
29
+ */
30
+ declare function postWithTimeout(url: string, body: any, milliseconds: number, options?: RequestOptions): Promise<any>;
31
+ /**
32
+ * GET request with timeout using AbortController
33
+ */
34
+ declare function getWithTimeout(url: string, milliseconds: number, options?: RequestOptions): Promise<any>;
35
+ /**
36
+ * Generic timeout utility for any promise-returning function
37
+ *
38
+ * @example
39
+ * const result = await timeoutPromise(
40
+ * () => fetch('/api/data'),
41
+ * 5000,
42
+ * 'API call timed out'
43
+ * )
44
+ */
45
+ declare function timeoutPromise<T>(promiseFactory: () => Promise<T>, milliseconds: number, timeoutMessage?: string): Promise<T>;
46
+ /**
47
+ * Modern fetch-only API with AbortController timeout handling
48
+ */
49
+ export declare const api: {
50
+ post: typeof post;
51
+ get: typeof get;
52
+ postWithTimeout: typeof postWithTimeout;
53
+ getWithTimeout: typeof getWithTimeout;
54
+ withTimeout: typeof withTimeout;
55
+ timeoutPromise: typeof timeoutPromise;
56
+ };
57
+ export {};
58
+ //# sourceMappingURL=xhr.d.ts.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Cookie utility functions
3
+ * TypeScript implementation of js-cookies functionality
4
+ */
5
+ export interface CookieOptions {
6
+ expires?: number | string | Date;
7
+ path?: string;
8
+ domain?: string;
9
+ secure?: boolean;
10
+ sameSite?: 'Strict' | 'Lax' | 'None';
11
+ }
12
+ export declare const cookie: {
13
+ getItem(sKey: string): string | null;
14
+ setItem(sKey: string, sValue: string, vEnd?: number | string | Date, sPath?: string, sDomain?: string, bSecure?: boolean, sameSite?: "Strict" | "Lax" | "None"): boolean;
15
+ removeItem(sKey: string, sPath?: string, sDomain?: string): boolean;
16
+ hasItem(sKey: string): boolean;
17
+ keys(): string[];
18
+ };
19
+ //# sourceMappingURL=js-cookies.d.ts.map
package/package.json ADDED
@@ -0,0 +1,90 @@
1
+ {
2
+ "name": "@treasuredata/web-sdk",
3
+ "version": "1.0.0",
4
+ "description": "Modern TypeScript SDK for Treasure Data - Browser event tracking library",
5
+ "main": "dist/td-sdk.cjs",
6
+ "module": "dist/td-sdk.esm.js",
7
+ "browser": "dist/td-sdk.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/td-sdk.esm.js",
13
+ "require": "./dist/td-sdk.cjs",
14
+ "browser": "./dist/td-sdk.js",
15
+ "default": "./dist/td-sdk.esm.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "!dist/**/*.map",
25
+ "NOTICE"
26
+ ],
27
+ "scripts": {
28
+ "build": "./bin/build.sh",
29
+ "build:vite": "vite build && vite build --config vite.iife.config.ts",
30
+ "build:types": "tsc --emitDeclarationOnly --outDir dist",
31
+ "build:dev": "vite build --mode development",
32
+ "dev": "vite",
33
+ "test": "vitest",
34
+ "test:run": "vitest run",
35
+ "test:coverage": "vitest run --coverage",
36
+ "test:ui": "vitest --ui",
37
+ "type-check": "tsc --noEmit",
38
+ "lint": "eslint src/ --ext .ts,.js",
39
+ "lint:fix": "eslint src/ --ext .ts,.js --fix",
40
+ "format": "prettier --write \"src/**/*.{ts,js}\" \"test/**/*.{ts,js}\"",
41
+ "format:check": "prettier --check \"src/**/*.{ts,js}\" \"test/**/*.{ts,js}\"",
42
+ "hooks:install": "git config core.hooksPath .githooks && chmod +x .githooks/pre-commit",
43
+ "clean": "rm -rf dist",
44
+ "prepublishOnly": "npm run clean && npm run build && npm run build:types && node ./scripts/strip-maps-for-publish.cjs",
45
+ "deploy": "./bin/deploy.sh",
46
+ "deploy:prod": "./bin/deploy.sh --prod",
47
+ "deploy:force": "./bin/deploy.sh --force",
48
+ "deploy:prod:force": "./bin/deploy.sh --force --prod --wait",
49
+ "upload": "./bin/upload-version.sh",
50
+ "upload:force": "./bin/upload-version.sh --force",
51
+ "activate": "./bin/activate-version.sh",
52
+ "invalidate": "./bin/invalidate-release.sh"
53
+ },
54
+ "keywords": [
55
+ "treasure-data",
56
+ "analytics",
57
+ "tracking",
58
+ "typescript",
59
+ "browser",
60
+ "web-sdk"
61
+ ],
62
+ "author": "Treasure Data",
63
+ "license": "Apache-2.0",
64
+ "browserslist": [
65
+ "extends browserslist-config-baseline"
66
+ ],
67
+ "engines": {
68
+ "node": ">=18"
69
+ },
70
+ "type": "module",
71
+ "devDependencies": {
72
+ "@types/node": "^25.6.0",
73
+ "@typescript-eslint/eslint-plugin": "^8.59.2",
74
+ "@typescript-eslint/parser": "^8.59.2",
75
+ "@vitest/coverage-v8": "^2.1.9",
76
+ "@vitest/ui": "^2.1.9",
77
+ "browserslist-config-baseline": "^0.5.0",
78
+ "eslint": "^9.39.4",
79
+ "eslint-config-prettier": "^10.1.8",
80
+ "happy-dom": "^20.9.0",
81
+ "prettier": "^3.8.3",
82
+ "terser": "^5.46.2",
83
+ "typescript": "^6.0.3",
84
+ "vite": "^5.4.21",
85
+ "vitest": "^2.1.9"
86
+ },
87
+ "dependencies": {
88
+ "comlink": "^4.4.2"
89
+ }
90
+ }