first commit
Some checks failed
Release / Release (push) Failing after 1m44s

This commit is contained in:
Lectom C Han
2025-07-07 18:53:25 +09:00
commit 421105f082
102 changed files with 63663 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
## 0.1.2
- Move browser locale and is debug reads from import to first event to better support SSR
## 0.1.1
- Support for custom API path
- use `installType` to determine if the extension is in debug mode
## 0.1.0
- Initial version of the Aptabase SDK for Browser Extensions

21
packages/browser/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Sumbit Labs Ltd.
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.

View File

@@ -0,0 +1,44 @@
![Aptabase](https://aptabase.com/og.png)
# Aptabase SDK for Browser Extensions
A tiny SDK (1 kB) to instrument your Browser/Chrome extensions with Aptabase, an Open Source, Privacy-First and Simple Analytics for Mobile, Desktop and Web Apps.
## Install
Install the SDK using npm or your preferred JavaScript package manager
```bash
npm add @aptabase/browser
```
## Usage
First you need to get your `App Key` from Aptabase, you can find it in the `Instructions` menu on the left side menu.
Initialize the SDK in your `Background Script` using your `App Key`:
```js
import { init } from '@aptabase/browser';
init('<YOUR_APP_KEY>'); // 👈 this is where you enter your App Key
```
The `init` function also supports an optional second parameter, which is an object with the `isDebug`property. Your data is segregated between development and production environments, so it's important to set this value correctly. By default the SDK will check if the extension was installed from an Extension Store, and if it wasn't it'll assume it's in development mode. If you want to override this behavior, you can set the`isDebug` property.
Afterwards you can start tracking events with `trackEvent` from anywhere in your extension:
```js
import { trackEvent } from '@aptabase/browser';
trackEvent('connect_click'); // An event with no properties
trackEvent('play_music', { name: 'Here comes the sun' }); // An event with a custom property
```
A few important notes:
1. The SDK will automatically enhance the event with some useful information, like the OS, the app version, and other things.
2. You're in control of what gets sent to Aptabase. This SDK does not automatically track any events, you need to call `trackEvent` manually.
- Because of this, it's generally recommended to at least track an event at startup
3. You do not need to await the `trackEvent` function, it'll run in the background.
4. Only strings and numeric values are allowed on custom properties

View File

@@ -0,0 +1,36 @@
{
"name": "@aptabase/browser",
"version": "0.1.2",
"type": "module",
"description": "Browser Extension SDK for Aptabase: Open Source, Privacy-First and Simple Analytics for Mobile, Desktop and Web Apps",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"require": "./dist/index.cjs",
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/aptabase/aptabase-js.git",
"directory": "packages/browser"
},
"bugs": {
"url": "https://github.com/aptabase/aptabase-js/issues"
},
"homepage": "https://github.com/aptabase/aptabase-js",
"license": "MIT",
"scripts": {
"build": "tsup",
"prepublishOnly": "npm run build"
},
"files": [
"README.md",
"LICENSE",
"dist",
"package.json"
]
}

4
packages/browser/src/global.d.ts vendored Normal file
View File

@@ -0,0 +1,4 @@
declare var aptabase: {
init: Function;
trackEvent: Function;
};

View File

@@ -0,0 +1,91 @@
import { getApiUrl, newSessionId, sendEvent, validateAppKey, type AptabaseOptions } from '../../shared';
// Session expires after 1 hour of inactivity
const SESSION_TIMEOUT = 1 * 60 * 60;
const sdkVersion = `aptabase-browser@${process.env.PKG_VERSION}`;
const isWebContext = 'document' in globalThis;
let _appKey = '';
let _apiUrl: string | undefined;
let _options: AptabaseOptions | undefined;
globalThis.aptabase = {
init,
trackEvent,
};
export async function init(appKey: string, options?: AptabaseOptions): Promise<void> {
if (isWebContext) {
console.error('@aptabase/browser can only be initialized in your background script.');
return;
}
if (!validateAppKey(appKey)) return;
const ext = await chrome.management.getSelf();
const isDebug = options?.isDebug ?? ext.installType === 'development';
const appVersion = options?.appVersion ?? chrome.runtime.getManifest().version;
_apiUrl = options?.apiUrl ?? getApiUrl(appKey, options);
_appKey = appKey;
_options = { ...options, isDebug, appVersion };
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message && message.type === '__aptabase__trackEvent') {
trackEvent(message.eventName, message.props);
}
});
}
export async function trackEvent(eventName: string, props?: Record<string, string | number | boolean>): Promise<void> {
if (isWebContext) {
return chrome.runtime.sendMessage({ type: '__aptabase__trackEvent', eventName, props });
}
if (!_apiUrl) return;
const sessionId = await getSessionId();
return sendEvent({
apiUrl: _apiUrl,
sessionId,
appKey: _appKey,
isDebug: _options?.isDebug,
appVersion: _options?.appVersion,
sdkVersion,
eventName,
props,
});
}
type CachedItem = {
id: string;
lastTouched: number;
};
let _sessionId = newSessionId();
async function getSessionId(): Promise<string> {
const now = Date.now();
// If storage is not available, return the in memory session id
// This id will be recreated if the extension is reloaded or the service worker becomes inactive
if (!chrome?.storage?.local) return _sessionId;
return new Promise((resolve) => {
chrome.storage.local.get('_ab_session_id', (result) => {
let item = (result['_ab_session_id'] as CachedItem) ?? { id: _sessionId, lastTouched: Date.now() };
const diffInMs = now - item.lastTouched;
const diffInSec = Math.floor(diffInMs / 1000);
if (diffInSec > SESSION_TIMEOUT) {
item.id = newSessionId();
}
item.lastTouched = now;
chrome.storage.local.set({ _ab_session_id: item }, () => {
resolve(item.id);
});
});
});
}

View File

@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "es6",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"jsx": "react-jsx",
"baseUrl": ".",
"paths": {
"types": ["@types"]
},
"declaration": true,
"declarationDir": "./dist"
}
}

View File

@@ -0,0 +1,15 @@
import { defineConfig } from 'tsup';
const { version } = require('./package.json');
export default defineConfig({
entry: ['src/index.ts'],
format: ['cjs', 'esm'],
dts: true,
splitting: false,
minify: true,
sourcemap: true,
clean: true,
env: {
PKG_VERSION: version,
},
});