Compare commits

...

15 Commits

Author SHA1 Message Date
2a15423c1d update description 2024-05-29 14:17:32 +02:00
d3e854ccc7 update tsconfig 2024-04-14 18:39:02 +02:00
45b0b5d011 update tsconfig 2024-04-01 21:42:34 +02:00
5f370bce10 update npmextra.json: githost 2024-04-01 20:00:14 +02:00
32f1eb7c3c update npmextra.json: githost 2024-03-30 21:49:15 +01:00
d24352a289 2.0.3 2023-06-11 16:09:07 +02:00
e6c15b2d81 fix(core): update 2023-06-11 16:09:06 +02:00
4d6ae3ba87 2.0.2 2023-06-10 16:43:21 +02:00
68ac5e6ec2 fix(core): update 2023-06-10 16:43:20 +02:00
d4401172e6 2.0.1 2023-06-10 16:38:25 +02:00
1887645625 fix(core): update 2023-06-10 16:38:25 +02:00
9e8b30391a 2.0.0 2023-06-10 13:47:30 +02:00
817a660662 BREAKING CHANGE(core): update 2023-06-10 13:47:29 +02:00
5a037699b5 1.0.6 2023-06-10 13:46:58 +02:00
9552cb9de6 fix(core): update 2023-06-10 13:46:58 +02:00
21 changed files with 4904 additions and 8474 deletions

16
.gitignore vendored
View File

@ -1,8 +1,20 @@
.nogit/
node_modules/
# artifacts
coverage/
public/
pages/
# installs
node_modules/
# caches
.yarn/
dist/
.cache/
.rpt2_cache
# builds
dist/
dist_*/
# custom

View File

@ -1,10 +1,10 @@
# gitzone standard
image: hosttoday/ht-docker-node:npmci
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: "$CI_BUILD_STAGE"
key: '$CI_BUILD_STAGE'
stages:
- security
@ -12,55 +12,62 @@ stages:
- release
- metadata
before_script:
- pnpm install -g pnpm
- pnpm install -g @shipzone/npmci
- npmci npm prepare
# ====================
# security stage
# ====================
mirror:
# ====================
# security stage
# ====================
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci git mirror
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --prod
tags:
- lossless
- docker
- notpriv
allow_failure: true
snyk:
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install -g snyk
- npmci command npm install --ignore-scripts
- npmci command snyk test
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --dev
tags:
- lossless
- docker
- notpriv
allow_failure: true
# ====================
# test stage
# ====================
testLTS:
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install lts
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
testSTABLE:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
testBuild:
stage: test
script:
- npmci node install stable
- npmci npm install
- npmci npm build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
@ -70,6 +77,7 @@ release:
only:
- tags
tags:
- lossless
- docker
- notpriv
@ -78,20 +86,15 @@ release:
# ====================
codequality:
stage: metadata
image: docker:stable
allow_failure: true
services:
- docker:stable-dind
only:
- tags
script:
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SOURCE_CODE="$PWD"
--volume "$PWD":/code
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
artifacts:
paths: [codeclimate.json]
- npmci command npm install -g typescript
- npmci npm prepare
- npmci npm install
tags:
- lossless
- docker
- priv
@ -102,18 +105,18 @@ trigger:
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata
script:
- npmci command npm install -g typedoc typescript
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command typedoc --module "commonjs" --target "ES2016" --out public/ ts/
- npmci command npm run buildDocs
tags:
- lossless
- docker
- notpriv
only:

11
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}

26
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

View File

@ -1,6 +1,28 @@
{
"gitzone": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "webdetector",
"description": "A library to detect web environments and PWA installation status within a browser.",
"npmPackagename": "@push.rocks/webdetector",
"license": "MIT",
"keywords": [
"web environment detection",
"PWA status",
"online status check",
"platform detection",
"network status",
"browser detection"
]
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
}
}

8291
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,31 +1,56 @@
{
"name": "@pushrocks/webdetector",
"version": "1.0.5",
"name": "@push.rocks/webdetector",
"version": "2.0.3",
"private": false,
"description": "detect different environments within the browser",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"description": "A library to detect web environments and PWA installation status within a browser.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(parcel build test/index.html --out-dir ./test/dist)",
"test": "(tstest test/)",
"build": "(tsbuild --web)",
"format": "(gitzone format)"
"format": "(gitzone format)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.0.22",
"@gitzone/tstest": "^1.0.15",
"@pushrocks/tapbundle": "^3.0.7",
"@types/node": "^10.11.7",
"parcel-bundler": "^1.11.0",
"tslint": "^5.11.0",
"tslint-config-prettier": "^1.15.0"
"@gitzone/tsbuild": "^2.1.66",
"@gitzone/tsrun": "^1.2.42",
"@gitzone/tstest": "^1.0.74",
"@pushrocks/tapbundle": "^5.0.4",
"@types/node": "^20.2.6"
},
"dependencies": {
"@pushrocks/smartdelay": "^2.0.2",
"@pushrocks/smartrx": "^2.0.3"
"@pushrocks/smartdelay": "^3.0.1",
"@pushrocks/smartrx": "^3.0.1"
},
"browserslist": [
"last 1 version"
]
],
"type": "module",
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"keywords": [
"web environment detection",
"PWA status",
"online status check",
"platform detection",
"network status",
"browser detection"
],
"homepage": "https://code.foss.global/push.rocks/webdetector",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/webdetector.git"
}
}

4450
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

103
readme.md Normal file
View File

@ -0,0 +1,103 @@
# @push.rocks/webdetector
detect different environments within the browser
## Install
To install `@push.rocks/webdetector`, you can use npm or yarn. Run the following command in your terminal:
```bash
npm install @push.rocks/webdetector --save
```
or if you prefer using yarn:
```bash
yarn add @push.rocks/webdetector
```
This package is designed to work in a browser environment.
## Usage
The `@push.rocks/webdetector` module provides a powerful toolset to detect various aspects of the user's browser environment, such as online status, platform type, and PWA (Progressive Web App) installation status. It leverages modern web technologies and observables for real-time detection and updates.
### Importing the Module
First, you need to import the module in your project using ESM syntax:
```typescript
import { WebDetector } from '@push.rocks/webdetector';
```
### Initializing WebDetector
To start utilizing WebDetector, you need to create an instance of it by passing configuration options. The most crucial option is the `checkOnlineUrl`, which is used to verify internet connectivity.
```typescript
const webDetector = new WebDetector({
checkOnlineUrl: 'https://example.com', // URL to check online status
});
```
### Checking Online Status
WebDetector can check if the browser can reach the internet. This is not a mere online/offline status provided by the browser but a more reliable check that attempts to fetch a predetermined URL.
```typescript
async function checkOnlineStatus() {
const isOnline = await webDetector.isOnline();
console.log(`Online status: ${isOnline}`);
}
checkOnlineStatus();
```
### Observing Real-Time Online Status
WebDetector allows you to observe changes in online status in real-time, which is useful for applications that need to react to connectivity changes promptly.
```typescript
webDetector.startPeriodicChecks();
webDetector.onlineObservable.subscribe((state) => {
console.log(`Current state: ${state}`);
});
// Remember to stop the periodic checks when they are no longer needed
webDetector.stopPeriodicChecks();
```
### Detecting the Platform
You can easily detect the user's platform (e.g., iOS, Android, Windows, etc.) using WebDetector.
```typescript
const platform = webDetector.platform.detectPlatform();
console.log(`Platform detected: ${platform}`);
```
### Checking PWA Installation Status
For Progressive Web Apps, it's vital to know if the user has installed the app. WebDetector provides a straightforward way to check this.
```typescript
const isPwaInstalled = webDetector.pwa.isInstalled();
console.log(`Is PWA Installed: ${isPwaInstalled}`);
```
### Comprehensive Observables Integration
`@push.rocks/webdetector` integrates seamlessly with observables provided by RxJS through `@pushrocks/smartrx`, making it easy to integrate with frameworks that use observables for state management.
### Conclusion
`@push.rocks/webdetector` is a versatile module that helps detect various aspects of the browser environment, offering tools for checking connectivity, platform type, and PWA installation status. By utilizing observables for real-time updates, it fits well into modern web application architectures.
Remember, the accurate detection and reaction to the user's environment enhance the user experience significantly, making `@push.rocks/webdetector` a valuable addition to your web development toolkit.
For more advanced use cases, refer to the official documentation and source code available on GitHub and GitLab. Your contributions and feedback are welcome to help improve this project further.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@ -1,7 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<script src="./test.ts"></script>
</head>
<body></body>
</html>

37
test/test.both.ts Normal file
View File

@ -0,0 +1,37 @@
import { tap, expect } from '@pushrocks/tapbundle';
import * as webdetector from '../ts/webdetector.classes.webdetector.js';
let testWebDetector: webdetector.WebDetector;
tap.test('first test', async () => {
testWebDetector = new webdetector.WebDetector({
checkOnlineUrl: 'https://pubapi.lossless.one',
});
expect(testWebDetector).toBeInstanceOf(webdetector.WebDetector);
});
tap.test('should be online', async () => {
const onlineResultBoolean = await testWebDetector.isOnline();
console.log('browser is online:');
console.log(onlineResultBoolean);
testWebDetector.startPeriodicChecks();
testWebDetector.onlineObservable.subscribe((state) => {
console.log(state);
});
testWebDetector.stopPeriodicChecks();
});
tap.test('should detect the platform', async () => {
const platform = testWebDetector.platform.detectPlatform();
console.log(platform);
});
tap.test('should detect if the app is installed', async () => {
const isInstalled = testWebDetector.pwa.isInstalled();
expect(isInstalled).toBeFalse();
});
console.log('hi');
tap.start();

View File

@ -1,17 +0,0 @@
import * as webdetector from '../ts/index'
console.log('hi');
const run = async () => {
const testWebDetector = new webdetector.WebDetector({
checkOnlineUrl: 'https://pubapi.lossless.one'
});
const onlineResultBoolean = await testWebDetector.isOnline();
console.log('browser is online:')
console.log(onlineResultBoolean);
testWebDetector.startPeriodicChecks();
testWebDetector.onlineObservable.subscribe((state) => {
console.log(state);
})
}
run();

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@pushrocks/webdetector',
version: '2.0.3',
description: 'detect different environments within the browser'
}

View File

@ -1,56 +1 @@
import * as plugins from './webdetector.plugins';
import {throttleTime } from 'rxjs/operators';
export interface IWebDetectorOptions {
checkOnlineUrl: string;
}
export class WebDetector {
options: IWebDetectorOptions;
private onlineObservableIntake = new plugins.smartrx.ObservableIntake();
onlineObservable = this.onlineObservableIntake.observable.pipe(throttleTime(10000));
latestState: 'online' | 'offline' = 'online';
constructor(optionsArg: IWebDetectorOptions) {
this.options = optionsArg;
}
/**
*
*/
async isOnline() {
let reachesInternet: boolean = false;
const controller = new AbortController();
const fetchPromise = fetch(this.options.checkOnlineUrl, { signal: controller.signal });
const timeout = setTimeout(() => {
controller.abort();
}, 1000);
await fetchPromise.then(async response => {
reachesInternet = true
}).catch(err => {
// console.log(`request to ${this.options.checkOnlineUrl} failed}`)
});
const latestLocalState = (() => {
if(reachesInternet) {
return 'online'
} else {
return 'offline'
}
})();
if(latestLocalState !== this.latestState) {
this.onlineObservableIntake.push(this.latestState);
}
this.latestState = latestLocalState;
return reachesInternet;
}
async startPeriodicChecks() {
while (true) {
await this.isOnline();
await plugins.smartdelay.delayFor(3000);
}
}
}
export * from './webdetector.classes.webdetector.js';

View File

@ -0,0 +1,25 @@
export type TWebPlatform = 'android' | 'ios' | 'windows' | 'mac' | 'linux' | 'unknown';
export class Platform {
public detectPlatform(): TWebPlatform {
const userAgent = globalThis?.navigator?.userAgent?.toLowerCase();
if (!userAgent) {
return 'unknown';
}
if (/android/.test(userAgent)) {
return 'android';
} else if (/iphone|ipad|ipod/.test(userAgent)) {
return 'ios';
} else if (/win/.test(userAgent)) {
return 'windows';
} else if (/mac/.test(userAgent)) {
return 'mac';
} else if (/linux/.test(userAgent)) {
return 'linux';
}
return 'unknown';
}
}

View File

@ -0,0 +1,12 @@
export class Pwa {
public isInstalled(): boolean {
let isInstalled: boolean;
if (globalThis?.matchMedia?.('(display-mode: standalone)').matches) {
isInstalled = true;
console.log('PWA installed');
} else {
isInstalled = false;
}
return isInstalled;
}
}

View File

@ -0,0 +1,71 @@
import * as plugins from './webdetector.plugins.js';
import { Platform } from './webdetector.classes.platform.js';
import { Pwa } from './webdetector.classes.pwa.js';
export interface IWebDetectorOptions {
checkOnlineUrl: string;
}
export class WebDetector {
// subclasses
public platform = new Platform();
public pwa = new Pwa();
options: IWebDetectorOptions;
private onlineObservableIntake = new plugins.smartrx.ObservableIntake();
public onlineObservable = this.onlineObservableIntake.observable.pipe(
plugins.smartrx.rxjs.ops.throttleTime(10000)
);
latestState: 'online' | 'offline' = 'online';
constructor(optionsArg: IWebDetectorOptions) {
this.options = optionsArg;
}
/**
*
*/
async isOnline() {
let reachesInternet: boolean = false;
const controller = new AbortController();
const fetchPromise = fetch(this.options.checkOnlineUrl, { signal: controller.signal });
const timeout = setTimeout(() => {
controller.abort();
}, 1000);
await fetchPromise
.then(async (response) => {
reachesInternet = true;
})
.catch((err) => {
// console.log(`request to ${this.options.checkOnlineUrl} failed}`)
});
const latestLocalState = (() => {
if (reachesInternet) {
return 'online';
} else {
return 'offline';
}
})();
if (latestLocalState !== this.latestState) {
this.onlineObservableIntake.push(this.latestState);
}
this.latestState = latestLocalState;
return reachesInternet;
}
private periodicChecksRunning = false;
public async startPeriodicChecks() {
this.periodicChecksRunning = true;
while (this.periodicChecksRunning) {
await this.isOnline();
await plugins.smartdelay.delayFor(3000);
}
}
public async stopPeriodicChecks() {
this.periodicChecksRunning = false;
}
}

View File

@ -1,7 +1,4 @@
import * as smartdelay from '@pushrocks/smartdelay';
import * as smartrx from '@pushrocks/smartrx';
export {
smartdelay,
smartrx
}
export { smartdelay, smartrx };

14
tsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}