Compare commits

..

91 Commits

Author SHA1 Message Date
8514c4def0 6.0.0
Some checks failed
Default (tags) / security (push) Failing after 21s
Default (tags) / test (push) Failing after 13s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-11-01 15:26:26 +00:00
aeac92f3fd BREAKING CHANGE(Smartenv): Add Deno and Bun runtime detection, introduce getSafeModuleFor API, update docs and tests, and make isNode semantics Node-only (breaking change) 2025-11-01 15:26:26 +00:00
ce338e27ea fix(documentation): update readme with comprehensive API documentation and hints file
- Updated readme.md with complete API reference and usage examples
- Added readme.hints.md with architecture and implementation details
- Improved documentation structure and clarity
- Version bump to 5.0.13
2025-07-28 12:00:51 +00:00
b4897d238f update description 2024-05-29 14:12:50 +02:00
df69e46697 update tsconfig 2024-04-14 17:32:19 +02:00
1493430d9f update npmextra.json: githost 2024-04-01 21:34:47 +02:00
78afde963b update npmextra.json: githost 2024-04-01 19:58:07 +02:00
a4a633e936 update npmextra.json: githost 2024-03-30 21:47:05 +01:00
27fbe00cb0 5.0.12 2023-11-09 16:37:53 +01:00
f3cc468eda fix(core): update 2023-11-09 16:37:52 +01:00
b303799b8d 5.0.11 2023-11-09 16:20:20 +01:00
590ed5b180 fix(core): update 2023-11-09 16:20:20 +01:00
ddcf52de19 5.0.10 2023-10-03 23:40:15 +02:00
c1b3af09ef fix(core): update 2023-10-03 23:40:15 +02:00
a1e2cda010 5.0.9 2023-10-03 18:55:37 +02:00
d409d3a532 fix(core): update 2023-10-03 18:55:36 +02:00
b4dae84835 5.0.8 2023-10-03 18:55:17 +02:00
20e27c93d9 fix(core): update 2023-10-03 18:55:16 +02:00
117dc6013c 5.0.7 2023-10-03 18:54:52 +02:00
c6bc433a73 fix(core): update 2023-10-03 18:54:51 +02:00
299815838c switch to new org scheme 2023-07-11 00:36:49 +02:00
e8318cbf2f switch to new org scheme 2023-07-10 02:48:52 +02:00
ae60053cff 5.0.6 2023-02-12 19:08:40 +01:00
dca3cf1f08 fix(core): update 2023-02-12 19:08:40 +01:00
eaf379b119 5.0.5 2023-01-03 16:46:41 +01:00
0074938e57 fix(core): update 2023-01-03 16:46:41 +01:00
eed1c75aba 5.0.4 2022-12-28 19:43:49 +01:00
6de2f36964 fix(core): update 2022-12-28 19:43:48 +01:00
76e777a3ac 5.0.3 2022-08-07 01:17:45 +02:00
165cd3737e fix(core): update 2022-08-07 01:17:45 +02:00
2f11d1ba0f 5.0.2 2022-05-28 23:22:31 +02:00
33692ff417 fix(core): update 2022-05-28 23:22:31 +02:00
f408337186 5.0.1 2022-03-25 13:22:43 +01:00
bd6d574226 fix(core): update 2022-03-25 13:22:42 +01:00
d5c2d167ec 5.0.0 2022-03-16 16:10:47 +01:00
2af6d5a974 4.0.18 2022-03-16 16:10:09 +01:00
fdba21d60d 4.0.17 2022-03-16 16:09:25 +01:00
c17ebca309 fix(core): update 2022-03-16 16:09:24 +01:00
a014dcf1ab 4.0.16 2020-10-13 20:09:15 +00:00
44bee7bf6f fix(core): update 2020-10-13 20:09:15 +00:00
7841917058 4.0.15 2020-09-29 19:29:51 +00:00
f5a674f98d fix(core): update 2020-09-29 19:29:50 +00:00
80ece7c093 4.0.14 2020-09-29 19:10:00 +00:00
39250b3d47 fix(core): update 2020-09-29 19:10:00 +00:00
ed78c0becf 4.0.13 2020-09-29 18:38:22 +00:00
63c103fde5 fix(core): update 2020-09-29 18:38:21 +00:00
88003bde0f 4.0.12 2020-09-29 17:49:34 +00:00
276a0641e8 fix(core): update 2020-09-29 17:49:33 +00:00
b166269cb4 4.0.11 2020-09-29 10:23:08 +00:00
3ca1b425bf fix(core): update 2020-09-29 10:23:07 +00:00
ffc07da665 4.0.10 2020-06-25 23:00:33 +00:00
be2adaf259 fix(core): update 2020-06-25 23:00:32 +00:00
7aa9637826 4.0.9 2020-06-25 22:26:05 +00:00
a3c4f87741 fix(core): update 2020-06-25 22:26:04 +00:00
f005f57764 4.0.8 2020-06-25 22:23:10 +00:00
6e418cdbf8 fix(core): update 2020-06-25 22:23:10 +00:00
87155900e1 4.0.8 2019-11-15 20:59:04 +01:00
d24b11f737 fix(core): update 2019-11-15 20:59:02 +01:00
17ebd58951 4.0.7 2019-08-22 00:20:11 +02:00
32bd229f91 fix(core): update 2019-08-22 00:20:10 +02:00
4e5ddf8411 4.0.6 2019-06-17 08:54:47 +02:00
701c7c1b8b fix(core): update 2019-06-17 08:54:46 +02:00
9a272def16 4.0.5 2019-06-17 08:51:04 +02:00
0213950aae fix(core): update 2019-06-17 08:51:03 +02:00
b7342dbf05 4.0.4 2019-06-17 08:46:28 +02:00
677c8d33b9 fix(core): update 2019-06-17 08:46:28 +02:00
ffc781011d 4.0.3 2018-02-14 00:29:00 +01:00
aeec1b36a3 fix CI 2018-02-14 00:28:56 +01:00
4c2e7f9446 4.0.2 2018-02-14 00:15:51 +01:00
dddad457f3 update npmextra 2018-02-14 00:15:47 +01:00
4f110c6e64 4.0.1 2018-02-14 00:13:16 +01:00
12d971c470 update ci 2018-02-14 00:13:12 +01:00
886c245e8d 4.0.0 2018-02-14 00:12:25 +01:00
50d610e5df update smartenv to support os information on nodejs 2018-02-14 00:12:21 +01:00
5edb62c134 3.0.0 2017-05-25 01:33:20 +02:00
38f22a6d95 remove npmts.json 2017-05-25 01:33:15 +02:00
Phil Kunz
91cdb71388 Merge branch 'master' into 'master'
Update to latest standards

See merge request !1
2017-05-24 23:28:41 +00:00
ab33e97c8d streamline package 2017-05-17 15:59:10 +02:00
47f840841c 2.0.6 2017-04-21 00:11:11 +02:00
fe2210dc9f update readme 2017-04-21 00:11:06 +02:00
489ebab6ee 2.0.5 2017-04-21 00:04:31 +02:00
46baf07551 now has a env vars feature 2017-04-21 00:04:28 +02:00
cf0aabfbfc 2.0.4 2017-04-19 20:18:19 +02:00
a5005aeb96 2.0.3 2017-04-19 20:06:25 +02:00
a7e9f1303d update ci 2017-04-19 20:06:21 +02:00
92a6508c6a 2.0.2 2017-04-19 20:05:11 +02:00
32f6b5cbf8 update 2017-04-19 20:05:05 +02:00
bdfbcead8d 2.0.1 2017-04-19 20:02:46 +02:00
e73e704886 update dependencies to latest standards 2017-04-19 20:02:43 +02:00
efa818680a 2.0.0 2016-11-21 18:29:08 +01:00
572d85b3d3 prepare new major version 2016-11-21 18:29:02 +01:00
47 changed files with 18273 additions and 549 deletions

View File

@@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

26
.gitignore vendored
View File

@@ -1,14 +1,20 @@
node_modules/
.settings/
.idea/
.nogit/
# artifacts
coverage/
docs/
public/
pages/
#npm devug
npm-debug.log
# installs
node_modules/
ts/*.js
ts/*.js.map
ts/typings/
# caches
.yarn/
.cache/
.rpt2_cache
test/browser/browserified/
# builds
dist/
dist_*/
# custom

View File

@@ -1,59 +0,0 @@
image: hosttoday/ht-docker-node:npmts
stages:
- test
- release
- trigger
- pages
testLEGACY:
stage: test
script:
- npmci test legacy
tags:
- docker
allow_failure: true
testLTS:
stage: test
script:
- npmci test lts
tags:
- docker
testSTABLE:
stage: test
script:
- npmci test stable
tags:
- docker
release:
stage: release
script:
- npmci publish
only:
- tags
tags:
- docker
trigger:
stage: trigger
script:
- npmci trigger
only:
- tags
tags:
- docker
pages:
image: hosttoday/ht-docker-node:npmpage
stage: pages
script:
- npmci command npmpage --host gitlab
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public

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,6 @@
The MIT License (MIT)
Copyright (c) 2015 Push.Rocks
Copyright (c) 2015 Task Venture Capital GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -1,39 +0,0 @@
# smartenv
store things about your environment and let them travel across modules
## Availabililty
[![npm](https://push.rocks/assets/repo-button-npm.svg)](https://www.npmjs.com/package/smartenv)
[![git](https://push.rocks/assets/repo-button-git.svg)](https://gitlab.com/pushrocks/smartenv)
[![git](https://push.rocks/assets/repo-button-mirror.svg)](https://github.com/pushrocks/smartenv)
[![docs](https://push.rocks/assets/repo-button-docs.svg)](https://pushrocks.gitlab.io/smartenv/)
## Status for master
[![build status](https://gitlab.com/pushrocks/smartenv/badges/master/build.svg)](https://gitlab.com/pushrocks/smartenv/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smartenv/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartenv/commits/master)
[![Dependency Status](https://david-dm.org/pushrocks/smartenv.svg)](https://david-dm.org/pushrocks/smartenv)
[![bitHound Dependencies](https://www.bithound.io/github/pushrocks/smartenv/badges/dependencies.svg)](https://www.bithound.io/github/pushrocks/smartenv/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/pushrocks/smartenv/badges/code.svg)](https://www.bithound.io/github/pushrocks/smartenv)
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Install
Install the package through npm
```
npm install smartenv
```
## Usage
```javascript
var smartenv = require("smartenv");
smartenv.info(); //prints an output about your current environment and registered objects
smartenv.register({akey:"a text"},"somevalue"); // register a new object
smartenv.makeGlobal() // make smartenv available from gobal.smartenv
smartenv.get("somevalue").akey; // returns "a text"
smartenv.items.somevalue.akey; // also returns "a text"
```
[![npm](https://push.rocks/assets/repo-header.svg)](https://push.rocks)

19
changelog.md Normal file
View File

@@ -0,0 +1,19 @@
# Changelog
## 2025-11-01 - 6.0.0 - BREAKING CHANGE(Smartenv)
Add Deno and Bun runtime detection, introduce getSafeModuleFor API, update docs and tests, and make isNode semantics Node-only (breaking change)
- Implement runtime detection for Deno and Bun; runtimeEnv now returns one of 'node' | 'deno' | 'bun' | 'browser'.
- Change isNode to be true only for Node.js; add isDeno and isBun accessors. This is a breaking change in behavior for code that relied on isNode including Deno/Bun.
- Add getSafeModuleFor(target, moduleNameOrUrl, getFunction?) API to load modules conditionally for single, multiple or 'server' runtimes. Existing helpers getSafeNodeModule and getSafeWebModule updated to work with wider runtimes.
- Add runtime-specific version getters (nodeVersion, denoVersion, bunVersion) and update printEnv output accordingly.
- Expand and add tests for Node, Deno, Bun and Browser environments (tests/* files).
- Update documentation (readme.md and readme.hints.md) to describe detection order, new API and migration notes from 4.x to 5.x/6.x.
- Bump devDependencies (tsbuild, tsrun, tstest) and include an updated deno.lock.
## [5.0.13] - 2025-07-28
### Fixed
- Updated readme.md with comprehensive documentation including API reference, core features, and usage examples
- Added readme.hints.md with architecture and implementation details for future reference
- Improved documentation structure and clarity

7175
deno.lock generated Normal file

File diff suppressed because it is too large Load Diff

4
dist/index.d.ts vendored
View File

@@ -1,4 +0,0 @@
import * as classes from './smartenv.classes';
export declare let getEnv: () => classes.Environment;
export declare let printEnv: () => void;
export declare let obs: any;

7
dist/index.js vendored
View File

@@ -1,7 +0,0 @@
"use strict";
const SmartenvEnvironment = require("./smartenv.environment");
const SmartenvObjectstorage = require("./smartenv.objectstorage");
exports.getEnv = SmartenvEnvironment.getEnv;
exports.printEnv = SmartenvEnvironment.printEnv;
exports.obs = SmartenvObjectstorage.obs;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBRUEsOERBQTZEO0FBQzdELGtFQUFpRTtBQUV0RCxRQUFBLE1BQU0sR0FBRyxtQkFBbUIsQ0FBQyxNQUFNLENBQUE7QUFDbkMsUUFBQSxRQUFRLEdBQUcsbUJBQW1CLENBQUMsUUFBUSxDQUFBO0FBQ3ZDLFFBQUEsR0FBRyxHQUFHLHFCQUFxQixDQUFDLEdBQUcsQ0FBQSJ9

View File

@@ -1,11 +0,0 @@
export declare class Environment {
runtimeEnv: string;
isBrowser: boolean;
userAgent: string;
isNode: boolean;
nodeVersion: string;
isCI: boolean;
isTravis: boolean;
isC9: boolean;
constructor();
}

View File

@@ -1,8 +0,0 @@
export declare var getEnvString: () => string;
export declare var getUserAgentString: () => string;
export declare var isNode: () => boolean;
export declare var getNodeVersion: () => string;
export declare var isBrowser: () => boolean;
export declare var isCI: () => boolean;
export declare var isC9: () => boolean;
export declare var isTravis: () => boolean;

View File

@@ -1,53 +0,0 @@
"use strict";
exports.getEnvString = function () {
if (typeof window !== 'undefined') {
return 'browser';
}
else if (typeof process !== 'undefined') {
return 'node';
}
};
exports.getUserAgentString = function () {
if (exports.isBrowser()) {
return navigator.userAgent;
}
else {
return undefined;
}
};
exports.isNode = function () {
return exports.getEnvString() === 'node';
};
exports.getNodeVersion = function () {
return process.version;
};
exports.isBrowser = function () {
return !exports.isNode();
};
exports.isCI = function () {
if (process.env.CI) {
return true;
}
else {
return false;
}
;
};
exports.isC9 = function () {
if (process.env.C9_HOSTNAME) {
return true;
}
else {
return false;
}
};
exports.isTravis = function () {
if (process.env.TRAVIS) {
return true;
}
else {
return false;
}
;
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRlbnYuY2xhc3Nlcy5oZWxwZXJzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvc21hcnRlbnYuY2xhc3Nlcy5oZWxwZXJzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBVyxRQUFBLFlBQVksR0FBRztJQUN0QixFQUFFLENBQUMsQ0FBQyxPQUFPLE1BQU0sS0FBSyxXQUFXLENBQUMsQ0FBQyxDQUFDO1FBQ2hDLE1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QUc7SUFDZCxFQUFFLENBQUMsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLFdBQVcsQ0FBQyxDQUFDLENBQUM7UUFDMUIsTUFBTSxDQUFDLElBQUksQ0FBQTtJQUNmLENBQUM7SUFBQyxJQUFJLENBQUMsQ0FBQztRQUNKLE1BQU0sQ0FBQyxLQUFLLENBQUE7SUFDaEIsQ0FBQztBQUNMLENBQUMsQ0FBQTtBQUVVLFFBQUEsUUFBUSxHQUFHO0lBQ2xCLEVBQUUsQ0FBQyxDQUFDLE9BQU8sQ0FBQyxHQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQztRQUNyQixNQUFNLENBQUMsSUFBSSxDQUFBO0lBQ2YsQ0FBQztJQUFDLElBQUksQ0FBQyxDQUFDO1FBQ0osTUFBTSxDQUFDLEtBQUssQ0FBQTtJQUNoQixDQUFDO0lBQUEsQ0FBQztBQUNOLENBQUMsQ0FBQSJ9

View File

@@ -1,17 +0,0 @@
"use strict";
const helpers = require("./smartenv.classes.helpers");
class Environment {
constructor() {
this.runtimeEnv = helpers.getEnvString();
this.isBrowser = helpers.isBrowser();
this.userAgent = helpers.getUserAgentString();
this.isNode = helpers.isNode();
this.nodeVersion = helpers.getNodeVersion();
this.isCI = helpers.isCI();
this.isTravis = helpers.isTravis();
this.isC9 = helpers.isC9();
}
;
}
exports.Environment = Environment;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRlbnYuY2xhc3Nlcy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3RzL3NtYXJ0ZW52LmNsYXNzZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLHNEQUFzRDtBQUV0RDtJQVNJO1FBQ0ksSUFBSSxDQUFDLFVBQVUsR0FBRyxPQUFPLENBQUMsWUFBWSxFQUFFLENBQUE7UUFDeEMsSUFBSSxDQUFDLFNBQVMsR0FBRyxPQUFPLENBQUMsU0FBUyxFQUFFLENBQUE7UUFDcEMsSUFBSSxDQUFDLFNBQVMsR0FBRyxPQUFPLENBQUMsa0JBQWtCLEVBQUUsQ0FBQTtRQUM3QyxJQUFJLENBQUMsTUFBTSxHQUFHLE9BQU8sQ0FBQyxNQUFNLEVBQUUsQ0FBQTtRQUM5QixJQUFJLENBQUMsV0FBVyxHQUFHLE9BQU8sQ0FBQyxjQUFjLEVBQUUsQ0FBQTtRQUMzQyxJQUFJLENBQUMsSUFBSSxHQUFHLE9BQU8sQ0FBQyxJQUFJLEVBQUUsQ0FBQTtRQUMxQixJQUFJLENBQUMsUUFBUSxHQUFHLE9BQU8sQ0FBQyxRQUFRLEVBQUUsQ0FBQTtRQUNsQyxJQUFJLENBQUMsSUFBSSxHQUFHLE9BQU8sQ0FBQyxJQUFJLEVBQUUsQ0FBQTtJQUM5QixDQUFDO0lBQUEsQ0FBQztDQUNMO0FBbkJELGtDQW1CQyJ9

View File

@@ -1,10 +0,0 @@
import * as classes from './smartenv.classes';
/**
* returns the environment
* @returns {Environment}
*/
export declare var getEnv: () => classes.Environment;
/**
* prints the environment to console
*/
export declare var printEnv: () => void;

View File

@@ -1,34 +0,0 @@
"use strict";
const classes = require("./smartenv.classes");
const objectStorage = require("./smartenv.objectstorage");
let environment;
let envDetermined = false;
/**
* returns the environment
* @returns {Environment}
*/
exports.getEnv = function () {
if (!envDetermined) {
environment = new classes.Environment();
envDetermined = true; // ensure code above only runs once
}
;
return environment;
};
/**
* prints the environment to console
*/
exports.printEnv = function () {
if (this.getEnv().isNode) {
console.log('running on NODE');
let smartenvVersion = require('../package.json').version;
console.log('node version is ' + this.getEnv().nodeVersion + ' and smartenv version is ' + smartenvVersion);
}
else {
console.log('running on BROWSER');
console.log('browser is ' + this.getEnv().userAgent);
}
console.log('the smartenv registration store currently holds the following properties:');
console.log(Object.getOwnPropertyNames(objectStorage.obs.getAll()));
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJ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BTyxDQUFDLEdBQUcsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sRUFBRSxDQUFDLFNBQVMsQ0FBQyxDQUFBO0lBQ3hELENBQUM7SUFDRCxPQUFPLENBQUMsR0FBRyxDQUFDLDJFQUEyRSxDQUFDLENBQUE7SUFDeEYsT0FBTyxDQUFDLEdBQUcsQ0FBQyxNQUFNLENBQUMsbUJBQW1CLENBQUMsYUFBYSxDQUFDLEdBQUcsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxDQUFDLENBQUE7QUFDdkUsQ0FBQyxDQUFBIn0=

View File

@@ -1,2 +0,0 @@
export declare var obs: any;
export declare var obsItems: any;

View File

@@ -1,43 +0,0 @@
"use strict";
const plugins = require("./smartenv.plugins");
exports.obs = {
add: function (paramNameArg = 'undefined', objectArg = 'undefined') {
if (paramNameArg === 'undefined') {
console.log('paramName is undefined');
return;
}
if (objectArg === 'undefined') {
console.log('objectArg is undefined');
}
if (typeof exports.obsItems[paramNameArg] === 'undefined') {
exports.obsItems[paramNameArg] = objectArg;
}
else {
console.log('object is already present, so add operation has failed.');
}
return exports.obsItems[paramNameArg];
},
replace: function (paramNameArg, objectArg) {
exports.obsItems[paramNameArg] = objectArg;
},
merge: function (paramNameArg, objectArg) {
if (!(typeof exports.obsItems[paramNameArg] === 'undefined')) {
exports.obsItems[paramNameArg] = plugins._.assign(exports.obsItems[paramNameArg], objectArg);
}
else {
console.log('object is not present, so there is nothing to merge');
}
},
get: function (keyName) {
return exports.obsItems[keyName];
},
getAll: function () {
return exports.obsItems;
},
addComplete: function (itemsArg) {
exports.obsItems = plugins._.assign(exports.obsItems, itemsArg);
return exports.obsItems;
}
};
exports.obsItems = {};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRlbnYub2JqZWN0c3RvcmFnZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3RzL3NtYXJ0ZW52Lm9iamV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ZLENBQUMsS0FBSyxXQUFXLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFDbkQsZ0JBQVEsQ0FBQyxZQUFZLENBQUMsR0FBRyxPQUFPLENBQUMsQ0FBQyxDQUFDLE1BQU0sQ0FBQyxnQkFBUSxDQUFDLFlBQVksQ0FBQyxFQUFDLFNBQVMsQ0FBQyxDQUFBO1FBQy9FLENBQUM7UUFBQyxJQUFJLENBQUMsQ0FBQztZQUNKLE9BQU8sQ0FBQyxHQUFHLENBQUMscURBQXFELENBQUMsQ0FBQTtRQUN0RSxDQUFDO0lBQ0wsQ0FBQztJQUNELEdBQUcsRUFBRSxVQUFTLE9BQU87UUFDakIsTUFBTSxDQUFDLGdCQUFRLENBQUMsT0FBTyxDQUFDLENBQUE7SUFDNUIsQ0FBQztJQUNELE1BQU0sRUFBRTtRQUNKLE1BQU0sQ0FBQyxnQkFBUSxDQUFBO0lBQ25CLENBQUM7SUFDRCxXQUFXLEVBQUUsVUFBUyxRQUFRO1FBQzFCLGdCQUFRLEdBQUcsT0FBTyxDQUFDLENBQUMsQ0FBQyxNQUFNLENBQUMsZ0JBQVEsRUFBQyxRQUFRLENBQUMsQ0FBQTtRQUM5QyxNQUFNLENBQUMsZ0JBQVEsQ0FBQTtJQUNuQixDQUFDO0NBQ0osQ0FBQTtBQUNVLFFBQUEsUUFBUSxHQUFRLEVBQUUsQ0FBQSJ9

View File

@@ -1,4 +0,0 @@
import 'typings-global';
import * as Q from 'q';
import * as _ from 'lodash';
export { Q, _ };

View File

@@ -1,7 +0,0 @@
"use strict";
require("typings-global");
const Q = require("q");
exports.Q = Q;
const _ = require("lodash");
exports._ = _;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRlbnYucGx1Z2lucy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3RzL3NtYXJ0ZW52LnBsdWdpbnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLDBCQUF1QjtBQUN2Qix1QkFBc0I7QUFJbEIsY0FBQztBQUhMLDRCQUEyQjtBQUl2QixjQUFDIn0=

32
npmextra.json Normal file
View File

@@ -0,0 +1,32 @@
{
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"gitzone": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartenv",
"description": "A module for storing and accessing environment details across different platforms.",
"npmPackagename": "@push.rocks/smartenv",
"license": "MIT",
"keywords": [
"environment detection",
"cross-platform",
"node.js",
"browser",
"module loading",
"CI detection",
"OS detection",
"runtime environment",
"typescript",
"async"
]
}
},
"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"
}
}

View File

@@ -1,7 +0,0 @@
{
"mode":"default",
"coverageTreshold":75,
"tsOptions": {
"target": "ES5"
}
}

View File

@@ -1,35 +1,63 @@
{
"name": "smartenv",
"version": "1.2.11",
"description": "store things about your environment and let them travel across modules",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"name": "@push.rocks/smartenv",
"version": "6.0.0",
"description": "A module for storing and accessing environment details across different platforms.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
"scripts": {
"test": "(npmts)",
"testbrowser": "(npm test) && (node testbrowser.js)"
"test": "(tstest test/ --web)",
"build": "(tsbuild --web --allowimplicitany && tsbundle npm)",
"testbrowser": "(npm test) && (node testbrowser.js)",
"buildDocs": "tsdoc"
},
"repository": {
"type": "git",
"url": "https://gitlab.com/pushrocks/smartenv.git"
"url": "https://code.foss.global/push.rocks/smartenv.git"
},
"keywords": [
"environment"
"environment detection",
"cross-platform",
"node.js",
"browser",
"module loading",
"CI detection",
"OS detection",
"runtime environment",
"typescript",
"async"
],
"author": "Smart Coordination GmbH <office@push.rocks> (https://push.rocks)",
"author": "Lossless GmbH <hello@lossless.support> (https://lossless.com)",
"license": "MIT",
"bugs": {
"url": "https://gitlab.com/pushrocks/smartenv/issues"
},
"homepage": "https://gitlab.com/pushrocks/smartenv",
"homepage": "https://code.foss.global/push.rocks/smartenv",
"dependencies": {
"@types/q": "0.x.x",
"lodash": "^4.17.2",
"q": "^1.4.1",
"typings-global": "^1.0.14"
"@push.rocks/smartpromise": "^4.0.2"
},
"devDependencies": {
"@types/should": "^8.1.30",
"beautylog": "^6.0.0",
"should": "^11.1.1"
}
"@git.zone/tsbuild": "^2.6.8",
"@git.zone/tsbundle": "^2.0.15",
"@git.zone/tsrun": "^1.6.2",
"@git.zone/tstest": "^2.7.0",
"@types/node": "^22.0.0"
},
"private": false,
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
],
"packageManager": "pnpm@10.11.0+sha512.6540583f41cc5f628eb3d9773ecee802f4f9ef9923cc45b69890fb47991d4b092964694ec3a4f738a420c918a333062c8b925d312f42e4f0c263eb603551f977"
}

9479
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

79
readme.hints.md Normal file
View File

@@ -0,0 +1,79 @@
# SmartEnv Hints
## Architecture Overview
- Single main class `Smartenv` that provides all functionality
- Uses dependency injection pattern with plugins imported from smartenv.plugins.ts
- Utilizes @push.rocks/smartpromise for async operations
- **BREAKING CHANGE**: `runtimeEnv` now returns `'node' | 'deno' | 'bun' | 'browser'` (previously only 'node' | 'browser')
## Runtime Detection System
### Detection Order (Critical!)
The order matters to avoid false positives:
1. **Deno** - Check `globalThis.Deno?.version` first (Deno has a `process` object for compatibility)
2. **Bun** - Check `globalThis.Bun?.version` second (Bun also has a `process` object)
3. **Node.js** - Check `globalThis.process?.versions?.node` third (must be specific to avoid Deno/Bun)
4. **Browser** - Check `globalThis.window && globalThis.document` as fallback
### Runtime Properties
- `runtimeEnv: TRuntimeType` - Returns 'node' | 'deno' | 'bun' | 'browser'
- `isNode: boolean` - True only for Node.js (excludes Deno and Bun)
- `isDeno: boolean` - True only for Deno runtime
- `isBun: boolean` - True only for Bun runtime
- `isBrowser: boolean` - True only for browser environment
### Version Getters
- `nodeVersion: string` - Node.js version (returns 'undefined' in other runtimes)
- `denoVersion: string` - Deno version (returns 'undefined' in other runtimes)
- `bunVersion: string` - Bun version (returns 'undefined' in other runtimes)
## Module Loading API
### New: getSafeModuleFor()
Flexible module loading that supports runtime targeting:
```typescript
// Load for specific runtime
await env.getSafeModuleFor('node', 'path')
// Load for multiple runtimes
await env.getSafeModuleFor(['node', 'deno'], 'path')
// Load for all server-side runtimes (shorthand for ['node', 'deno', 'bun'])
await env.getSafeModuleFor('server', 'path')
// Browser loading requires getFunction
await env.getSafeModuleFor('browser', 'url', () => window.someLibrary)
```
**Parameters:**
- `target: TRuntimeTarget | TRuntimeTarget[]` - Runtime(s) to load for
- `moduleNameOrUrl: string` - Module name or URL
- `getFunction?: () => any` - Required for browser module loading
**Returns:** Module or `undefined` if runtime doesn't match
### Legacy Methods (Still Supported)
- `getSafeNodeModule()` - Now works for Node.js, Deno, and Bun
- `getSafeWebModule()` - Browser-only module loading
## Key Implementation Details
- Dynamic module loading using Function constructor for server-side modules
- Script tag injection for browser module loading with duplicate prevention
- OS detection uses the native 'os' module loaded dynamically (works in Node.js, Deno, Bun)
- All detection uses `globalThis` for robustness across environments
## Testing Approach
- Tests use @git.zone/tstest with tap-based testing across all runtimes
- `test.node.ts` - Node.js specific tests, verifies it's not confused with Deno/Bun
- `test.deno.ts` - Deno runtime tests
- `test.bun.ts` - Bun runtime tests
- `test.chrome.ts` - Browser environment tests
- Each test file verifies proper runtime detection and module loading
## Important Notes
- The `getSafeNodeModule` uses dynamic import via Function constructor to avoid bundler issues
- Browser module loading tracks loaded scripts to prevent duplicate loads
- All OS detection methods are async and return false in browser environments
- The package is isomorphic and designed for use in all four runtime contexts
- Runtime detection checks globals in specific order to avoid false positives from compatibility layers

615
readme.md Normal file
View File

@@ -0,0 +1,615 @@
# @push.rocks/smartenv
> 🚀 **Universal JavaScript Runtime Detection** - One library for Node.js, Deno, Bun, and Browser
A powerful TypeScript library that provides comprehensive runtime environment detection and safe module loading across **all major JavaScript runtimes**. Write once, run everywhere with confidence.
## Why smartenv?
Modern JavaScript runs in many environments - Node.js, Deno, Bun, and browsers. Writing isomorphic code that works everywhere is challenging. **smartenv** solves this by providing:
-**Accurate runtime detection** - Distinguishes Node.js from Deno, Bun, and browsers without false positives
-**Smart module loading** - Load the right modules for each runtime automatically
-**Platform detection** - Detect macOS, Linux, Windows, and CI environments
-**Zero dependencies** (except @push.rocks/smartpromise)
-**Full TypeScript support** with complete type definitions
-**Battle-tested** - Comprehensive test suite across all runtimes
## Install
```bash
pnpm install @push.rocks/smartenv --save
```
```bash
npm install @push.rocks/smartenv --save
```
## Quick Start
```typescript
import { Smartenv } from '@push.rocks/smartenv';
const env = new Smartenv();
// Detect the runtime
console.log(env.runtimeEnv); // 'node' | 'deno' | 'bun' | 'browser'
// Load modules safely for your runtime
const pathModule = await env.getSafeModuleFor('server', 'path');
if (pathModule) {
console.log('Path module loaded!');
}
// Check specific runtimes
if (env.isNode) {
console.log(`Running on Node.js ${env.nodeVersion}`);
} else if (env.isDeno) {
console.log(`Running on Deno ${env.denoVersion}`);
} else if (env.isBun) {
console.log(`Running on Bun ${env.bunVersion}`);
} else {
console.log(`Running in ${env.userAgent}`);
}
```
## Core Features
### 🎯 Multi-Runtime Detection
Accurately detects all major JavaScript runtimes using proper detection order to avoid false positives:
```typescript
const env = new Smartenv();
// Runtime type - returns one of: 'node' | 'deno' | 'bun' | 'browser'
console.log(env.runtimeEnv);
// Boolean checks for each runtime
env.isNode; // true only in Node.js
env.isDeno; // true only in Deno
env.isBun; // true only in Bun
env.isBrowser; // true only in browser
```
**Why detection order matters:** Deno and Bun provide `process` objects for Node.js compatibility. smartenv checks for `Deno` and `Bun` globals first, then `process.versions.node`, ensuring accurate detection.
### 📦 Smart Module Loading
The new `getSafeModuleFor()` API lets you target specific runtimes or groups:
```typescript
// Load for a specific runtime
const fsNode = await env.getSafeModuleFor('node', 'fs');
// Load for Deno (requires 'node:' prefix for Node.js built-ins)
const fsDeno = await env.getSafeModuleFor('deno', 'node:path');
// Load for all server-side runtimes (Node.js + Deno + Bun)
const pathModule = await env.getSafeModuleFor('server', 'path');
// Load for multiple specific runtimes
const crypto = await env.getSafeModuleFor(['node', 'bun'], 'crypto');
// Browser module loading
const jQuery = await env.getSafeModuleFor(
'browser',
'https://code.jquery.com/jquery-3.6.0.min.js',
() => window.jQuery
);
```
**Target options:**
- `'node'` - Node.js only
- `'deno'` - Deno only
- `'bun'` - Bun only
- `'browser'` - Browser only
- `'server'` - Shorthand for `['node', 'deno', 'bun']`
- `['node', 'deno']` - Array of specific runtimes
If the current runtime doesn't match the target, the method returns `undefined` and logs a warning.
### 🖥️ Platform Detection
Detect operating systems in server-side runtimes (Node.js, Deno, Bun):
```typescript
const env = new Smartenv();
// Async OS detection
const isMac = await env.isMacAsync(); // macOS
const isLinux = await env.isLinuxAsync(); // Linux
const isWindows = await env.isWindowsAsync(); // Windows
if (isMac) {
console.log('Running on macOS');
}
```
### 🔢 Version Information
Get version strings for each runtime:
```typescript
const env = new Smartenv();
// Returns version string or 'undefined' if not in that runtime
env.nodeVersion; // e.g., 'v20.10.0'
env.denoVersion; // e.g., '1.40.0'
env.bunVersion; // e.g., '1.0.20'
env.userAgent; // Browser user agent string
```
### 🏗️ CI Detection
Detect if running in a continuous integration environment:
```typescript
const env = new Smartenv();
if (env.isCI) {
console.log('Running in CI environment');
// Enable extended test suite, different build config, etc.
}
```
## API Reference
### Runtime Detection Properties
#### `runtimeEnv: TRuntimeType`
Returns the detected runtime as a string.
**Type:** `'node' | 'deno' | 'bun' | 'browser'`
```typescript
const env = new Smartenv();
console.log(env.runtimeEnv); // 'node', 'deno', 'bun', or 'browser'
```
#### `isNode: boolean`
`true` if running in Node.js (specifically checks for `process.versions.node`).
```typescript
if (env.isNode) {
console.log('Node.js environment');
}
```
#### `isDeno: boolean`
`true` if running in Deno (checks for `Deno` global).
```typescript
if (env.isDeno) {
console.log('Deno environment');
}
```
#### `isBun: boolean`
`true` if running in Bun (checks for `Bun` global).
```typescript
if (env.isBun) {
console.log('Bun environment');
}
```
#### `isBrowser: boolean`
`true` if running in a browser environment.
```typescript
if (env.isBrowser) {
console.log('Browser environment');
}
```
#### `isCI: boolean`
`true` if running in a CI environment (checks `process.env.CI` in server runtimes).
```typescript
if (env.isCI) {
// CI-specific logic
}
```
### Version Properties
#### `nodeVersion: string`
Node.js version string. Returns `'undefined'` if not in Node.js.
```typescript
console.log(env.nodeVersion); // 'v20.10.0'
```
#### `denoVersion: string`
Deno version string. Returns `'undefined'` if not in Deno.
```typescript
console.log(env.denoVersion); // '1.40.0'
```
#### `bunVersion: string`
Bun version string. Returns `'undefined'` if not in Bun.
```typescript
console.log(env.bunVersion); // '1.0.20'
```
#### `userAgent: string`
Browser user agent string. Returns `'undefined'` if not in browser.
```typescript
console.log(env.userAgent); // 'Mozilla/5.0...'
```
### Platform Detection Methods
#### `isMacAsync(): Promise<boolean>`
Asynchronously checks if running on macOS. Works in Node.js, Deno, and Bun.
```typescript
const isMac = await env.isMacAsync();
if (isMac) {
console.log('Running on macOS');
}
```
#### `isLinuxAsync(): Promise<boolean>`
Asynchronously checks if running on Linux. Works in Node.js, Deno, and Bun.
```typescript
const isLinux = await env.isLinuxAsync();
if (isLinux) {
console.log('Running on Linux');
}
```
#### `isWindowsAsync(): Promise<boolean>`
Asynchronously checks if running on Windows. Works in Node.js, Deno, and Bun.
```typescript
const isWindows = await env.isWindowsAsync();
if (isWindows) {
console.log('Running on Windows');
}
```
### Module Loading Methods
#### `getSafeModuleFor<T>(target, moduleNameOrUrl, getFunction?): Promise<T | undefined>`
**The recommended way to load modules** - supports runtime targeting with flexible options.
**Parameters:**
- `target: TRuntimeTarget | TRuntimeTarget[]` - Runtime(s) to load for
- `moduleNameOrUrl: string` - Module name (server runtimes) or URL (browser)
- `getFunction?: () => any` - Function to retrieve module (required for browser)
**Returns:** `Promise<T | undefined>` - Loaded module or undefined if runtime doesn't match
**Examples:**
```typescript
// Node.js only
const fs = await env.getSafeModuleFor('node', 'fs');
// Deno only (note: use 'node:' prefix for Node.js built-ins)
const path = await env.getSafeModuleFor('deno', 'node:path');
// All server runtimes
const crypto = await env.getSafeModuleFor('server', 'crypto');
// Multiple specific runtimes
const util = await env.getSafeModuleFor(['node', 'bun'], 'util');
// Browser
const lib = await env.getSafeModuleFor(
'browser',
'https://cdn.example.com/lib.js',
() => window.MyLib
);
```
#### `getSafeNodeModule<T>(moduleName, runAfterFunc?): Promise<T>`
**Legacy method** - Loads modules in server-side runtimes (Node.js, Deno, Bun).
```typescript
const fs = await env.getSafeNodeModule('fs');
// With post-load callback
const express = await env.getSafeNodeModule('express', async (mod) => {
console.log('Express loaded');
});
```
#### `getSafeWebModule(url, getFunction): Promise<any>`
**Legacy method** - Loads web modules via script tag in browser. Prevents duplicate loading.
```typescript
const jQuery = await env.getSafeWebModule(
'https://code.jquery.com/jquery-3.6.0.min.js',
() => window.jQuery
);
```
#### `getEnvAwareModule(options): Promise<any>`
**Legacy method** - Loads environment-appropriate modules.
```typescript
const module = await env.getEnvAwareModule({
nodeModuleName: 'node-fetch',
webUrlArg: 'https://unpkg.com/whatwg-fetch@3.6.2/dist/fetch.umd.js',
getFunction: () => window.fetch
});
```
### Utility Methods
#### `printEnv(): Promise<void>`
Prints environment information to console for debugging.
```typescript
await env.printEnv();
// Node.js: "running on NODE" + version
// Deno: "running on DENO" + version
// Bun: "running on BUN" + version
// Browser: "running on BROWSER" + user agent
```
## Real-World Examples
### 🌍 Isomorphic Cryptography
```typescript
import { Smartenv } from '@push.rocks/smartenv';
const env = new Smartenv();
// Load crypto for any server runtime
const crypto = await env.getSafeModuleFor('server', 'crypto');
if (crypto) {
const hash = crypto.createHash('sha256');
hash.update('hello world');
console.log(hash.digest('hex'));
} else if (env.isBrowser) {
// Use Web Crypto API
const encoder = new TextEncoder();
const data = encoder.encode('hello world');
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
console.log(Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join(''));
}
```
### 📁 Cross-Runtime File System
```typescript
const env = new Smartenv();
async function readConfig() {
if (env.isNode) {
const fs = await env.getSafeModuleFor('node', 'fs/promises');
return JSON.parse(await fs.readFile('config.json', 'utf-8'));
} else if (env.isDeno) {
const content = await Deno.readTextFile('config.json');
return JSON.parse(content);
} else if (env.isBun) {
const file = Bun.file('config.json');
return await file.json();
} else {
// Browser: fetch from server
const response = await fetch('/config.json');
return response.json();
}
}
```
### 🔧 Development vs Production
```typescript
const env = new Smartenv();
async function setupEnvironment() {
// Different behavior in CI
if (env.isCI) {
console.log('CI Environment detected');
// Skip interactive prompts, use default values
return { mode: 'ci', verbose: true };
}
// Platform-specific paths
if (await env.isMacAsync()) {
return { configPath: '/Users/username/.config' };
} else if (await env.isLinuxAsync()) {
return { configPath: '/home/username/.config' };
} else if (await env.isWindowsAsync()) {
return { configPath: 'C:\\Users\\username\\AppData\\Local' };
}
}
```
### 🎨 Conditional Analytics Loading
```typescript
const env = new Smartenv();
async function initializeAnalytics() {
if (!env.isBrowser) {
console.log('Analytics skipped - not in browser');
return;
}
// Only load analytics in browser
const analytics = await env.getSafeModuleFor(
'browser',
'https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID',
() => window.gtag
);
if (analytics) {
analytics('config', 'GA_MEASUREMENT_ID');
}
}
```
### 🧪 Runtime-Specific Testing
```typescript
const env = new Smartenv();
async function runTests() {
console.log(`Testing in ${env.runtimeEnv}`);
// Load test utilities for current runtime
const testLib = await env.getSafeModuleFor(
['node', 'deno', 'bun'],
'@git.zone/tstest'
);
if (testLib) {
// Run server-side tests
await runServerTests(testLib);
} else {
// Run browser tests
await runBrowserTests();
}
}
```
## TypeScript Support
smartenv is written in TypeScript and provides complete type definitions:
```typescript
import {
Smartenv,
TRuntimeType, // 'node' | 'deno' | 'bun' | 'browser'
TRuntimeTarget, // TRuntimeType | 'server'
IEnvObject
} from '@push.rocks/smartenv';
const env: Smartenv = new Smartenv();
const runtime: TRuntimeType = env.runtimeEnv;
// Type-safe module loading
const fs = await env.getSafeModuleFor<typeof import('fs')>('node', 'fs');
if (fs) {
fs.readFileSync('./file.txt', 'utf-8'); // Full type support
}
```
## How Runtime Detection Works
smartenv uses a careful detection order to avoid false positives:
1. **Check for Deno** - `globalThis.Deno?.version` (Deno has `process` for compatibility)
2. **Check for Bun** - `globalThis.Bun?.version` (Bun also has `process`)
3. **Check for Node.js** - `globalThis.process?.versions?.node` (must be specific)
4. **Check for Browser** - `globalThis.window && globalThis.document` (fallback)
This order is critical because Deno and Bun provide `process` objects for Node.js compatibility, which would cause false Node.js detection if checked first.
## Migration from 4.x to 5.x
**Breaking Changes:**
1. **`runtimeEnv` return type changed:**
- **Before:** `'node' | 'browser'`
- **After:** `'node' | 'deno' | 'bun' | 'browser'`
2. **`isNode` is now more specific:**
- **Before:** Returns `true` for Node.js, Deno, and Bun
- **After:** Returns `true` only for Node.js
**Migration guide:**
```typescript
// Before (4.x)
if (env.isNode) {
// This ran in Node.js, Deno, and Bun
}
// After (5.x) - Option 1: Check all server runtimes
if (env.isNode || env.isDeno || env.isBun) {
// Works in Node.js, Deno, and Bun
}
// After (5.x) - Option 2: Use the new module loading API
const module = await env.getSafeModuleFor('server', 'path');
if (module) {
// Module loaded successfully in any server runtime
}
```
## Performance
-**Lightweight** - Minimal overhead with lazy evaluation
- 🚀 **Fast detection** - Simple boolean checks, no heavy operations
- 💾 **Cached results** - Detection runs once, results are cached
- 📦 **Small bundle** - ~5KB minified, tree-shakeable
## Browser Compatibility
Tested and working in:
- ✅ Chrome/Chromium (latest)
- ✅ Firefox (latest)
- ✅ Safari (latest)
- ✅ Edge (latest)
## Node.js Compatibility
- ✅ Node.js 18.x
- ✅ Node.js 20.x (LTS)
- ✅ Node.js 22.x
## Deno Compatibility
- ✅ Deno 1.40+
**Note:** When using Deno, use the `node:` prefix for Node.js built-in modules:
```typescript
const path = await env.getSafeModuleFor('deno', 'node:path');
```
## Bun Compatibility
- ✅ Bun 1.0+
## 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.

81
test/test.bun.ts Normal file
View File

@@ -0,0 +1,81 @@
import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as smartenv from '../ts/index.js';
let testEnv: smartenv.Smartenv;
tap.test('should create smartenv instance', async () => {
testEnv = new smartenv.Smartenv();
});
tap.test('should detect Bun runtime correctly', async () => {
expect(testEnv.runtimeEnv).toEqual('bun');
expect(testEnv.isBun).toBeTrue();
expect(testEnv.isNode).toBeFalse();
expect(testEnv.isDeno).toBeFalse();
expect(testEnv.isBrowser).toBeFalse();
console.log(' Bun runtime detected correctly');
});
tap.test('should get Bun version', async () => {
const version = testEnv.bunVersion;
expect(version).not.toEqual('undefined');
expect(typeof version).toEqual('string');
console.log('Bun version is ' + version);
});
tap.test('should print environment', async () => {
testEnv.printEnv();
});
tap.test('should load modules for Bun', async () => {
const pathModule = await testEnv.getSafeModuleFor('bun', 'path');
expect(pathModule).not.toBeUndefined();
expect(typeof pathModule.join).toEqual('function');
console.log(' Successfully loaded module for Bun');
});
tap.test('should load modules for server runtimes', async () => {
const pathModule = await testEnv.getSafeModuleFor('server', 'path');
expect(pathModule).not.toBeUndefined();
expect(typeof pathModule.join).toEqual('function');
console.log(' Successfully loaded module with server target');
});
tap.test('should load modules for array of runtimes', async () => {
const pathModule = await testEnv.getSafeModuleFor(['bun', 'node'], 'path');
expect(pathModule).not.toBeUndefined();
expect(typeof pathModule.join).toEqual('function');
console.log(' Successfully loaded module with array target');
});
tap.test('should not load modules for wrong runtime', async () => {
const result = await testEnv.getSafeModuleFor('node', 'path');
expect(result).toBeUndefined();
console.log(' Correctly rejected Node.js-only module in Bun');
});
tap.test('should detect OS', async () => {
const resultMac = await testEnv.isMacAsync();
const resultLinux = await testEnv.isLinuxAsync();
const resultWindows = await testEnv.isWindowsAsync();
const osModule = await import('os');
if (resultMac) {
expect(osModule.platform()).toEqual('darwin');
console.log('platform is Mac!');
} else if (resultLinux) {
expect(osModule.platform()).toEqual('linux');
console.log('platform is Linux!');
} else {
expect(osModule.platform()).toEqual('win32');
console.log('platform is Windows!');
}
});
tap.test('should detect CI environment if present', async () => {
if (process.env.CI) {
expect(testEnv.isCI).toBeTrue();
}
console.log('CI detection: ' + testEnv.isCI);
});
tap.start();

58
test/test.chrome.ts Normal file
View File

@@ -0,0 +1,58 @@
import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as smartenv from '../ts/index.js';
let testEnv: smartenv.Smartenv;
tap.test('should create smartenv instance', async () => {
testEnv = new smartenv.Smartenv();
});
tap.test('should detect browser runtime correctly', async () => {
expect(testEnv.runtimeEnv).toEqual('browser');
expect(testEnv.isBrowser).toBeTrue();
expect(testEnv.isNode).toBeFalse();
expect(testEnv.isDeno).toBeFalse();
expect(testEnv.isBun).toBeFalse();
console.log(' Browser runtime detected correctly');
});
tap.test('should get user agent', async () => {
const userAgent = testEnv.userAgent;
expect(userAgent).not.toEqual('undefined');
expect(typeof userAgent).toEqual('string');
console.log('User agent: ' + userAgent);
});
tap.test('should print environment', async () => {
testEnv.printEnv();
});
tap.test('should not get server runtime versions', async () => {
expect(testEnv.nodeVersion).toEqual('undefined');
expect(testEnv.denoVersion).toEqual('undefined');
expect(testEnv.bunVersion).toEqual('undefined');
console.log(' Server runtime versions correctly return undefined in browser');
});
tap.test('should not load server modules', async () => {
const result = await testEnv.getSafeModuleFor('server', 'path');
expect(result).toBeUndefined();
console.log(' Correctly rejected server module in browser');
});
tap.test('should not detect as CI', async () => {
expect(testEnv.isCI).toBeFalse();
console.log(' CI detection correctly false in browser');
});
tap.test('OS detection should return false in browser', async () => {
const resultMac = await testEnv.isMacAsync();
const resultLinux = await testEnv.isLinuxAsync();
const resultWindows = await testEnv.isWindowsAsync();
expect(resultMac).toBeFalse();
expect(resultLinux).toBeFalse();
expect(resultWindows).toBeFalse();
console.log(' OS detection correctly returns false in browser');
});
tap.start();

0
test/test.d.ts vendored
View File

59
test/test.deno.ts Normal file
View File

@@ -0,0 +1,59 @@
import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as smartenv from '../ts/index.js';
let testEnv: smartenv.Smartenv;
tap.test('should create smartenv instance', async () => {
testEnv = new smartenv.Smartenv();
});
tap.test('should detect Deno runtime correctly', async () => {
expect(testEnv.runtimeEnv).toEqual('deno');
expect(testEnv.isDeno).toBeTrue();
expect(testEnv.isNode).toBeFalse();
expect(testEnv.isBun).toBeFalse();
expect(testEnv.isBrowser).toBeFalse();
console.log(' Deno runtime detected correctly');
});
tap.test('should get Deno version', async () => {
const version = testEnv.denoVersion;
expect(version).not.toEqual('undefined');
expect(typeof version).toEqual('string');
console.log('Deno version is ' + version);
});
tap.test('should print environment', async () => {
testEnv.printEnv();
});
tap.test('should load modules for Deno', async () => {
// Deno requires 'node:' prefix for Node.js built-in modules
const pathModule = await testEnv.getSafeModuleFor('deno', 'node:path');
expect(pathModule).not.toBeUndefined();
expect(typeof pathModule.join).toEqual('function');
console.log(' Successfully loaded module for Deno');
});
tap.test('should load modules for server runtimes', async () => {
// Deno requires 'node:' prefix for Node.js built-in modules
const pathModule = await testEnv.getSafeModuleFor('server', 'node:path');
expect(pathModule).not.toBeUndefined();
expect(typeof pathModule.join).toEqual('function');
console.log(' Successfully loaded module with server target');
});
tap.test('should not load modules for wrong runtime', async () => {
const result = await testEnv.getSafeModuleFor('node', 'node:path');
expect(result).toBeUndefined();
console.log(' Correctly rejected Node.js-only module in Deno');
});
tap.test('should detect CI environment if present', async () => {
// CI detection relies on Node.js process.env, which may not work in Deno
// This test documents expected behavior
const isCI = testEnv.isCI;
console.log('CI detection in Deno: ' + isCI);
});
tap.start();

View File

@@ -1,21 +0,0 @@
"use strict";
const smartenv = require("../dist/index.js");
const beautylog = require("beautylog");
smartenv.printEnv();
// test smartenv.obs.add
smartenv.obs.add('myTestObject', { key1: 'Peter' });
smartenv.obs.add('myTestObject', { key1: 'Klaus' }); // now trying to add a second
smartenv.printEnv();
beautylog.log(smartenv.obs.get('myTestObject').key1); // this should be Peter
// test smartenv.obs.replace
smartenv.obs.replace('myTestObject', { key1: 'Klaus' });
beautylog.log(smartenv.obs.get('myTestObject').key1); // this should be Klaus
// test smartenv.obs.merge
smartenv.obs.merge('myTestObject', { key2: 'Peter' });
beautylog.log(smartenv.obs.get('myTestObject').key1 + smartenv.obs.get('myTestObject').key2);
// this should be KlausPeter
let key2 = 'hello';
smartenv.obs.get('myTestObject').key2 = key2;
beautylog.log(smartenv.obs.get('myTestObject').key2);
beautylog.success('Success!');
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVzdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInRlc3QudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLDZDQUE0QztBQUM1Qyx1Q0FBc0M7QUFDdEMsUUFBUSxDQUFDLFFBQVEsRUFBRSxDQUFBO0FBRW5CLHdCQUF3QjtBQUN4QixRQUFRLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxjQUFjLEVBQUMsRUFBQyxJQUFJLEVBQUMsT0FBTyxFQUFDLENBQUMsQ0FBQTtBQUMvQyxRQUFRLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxjQUFjLEVBQUMsRUFBQyxJQUFJLEVBQUMsT0FBTyxFQUFDLENBQUMsQ0FBQSxDQUFDLDZCQUE2QjtBQUM3RSxRQUFRLENBQUMsUUFBUSxFQUFFLENBQUE7QUFDbkIsU0FBUyxDQUFDLEdBQUcsQ0FBQyxRQUFRLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxjQUFjLENBQUMsQ0FBQyxJQUFJLENBQUMsQ0FBQSxDQUFDLHVCQUF1QjtBQUU1RSw0QkFBNEI7QUFDNUIsUUFBUSxDQUFDLEdBQUcsQ0FBQyxPQUFPLENBQUMsY0FBYyxFQUFDLEVBQUMsSUFBSSxFQUFDLE9BQU8sRUFBQyxDQUFDLENBQUE7QUFDbkQsU0FBUyxDQUFDLEdBQUcsQ0FBQyxRQUFRLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxjQUFjLENBQUMsQ0FBQyxJQUFJLENBQUMsQ0FBQSxDQUF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4BAA4B;AAC7E,QAAQ,CAAC,QAAQ,EAAE,CAAC;AACpB,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,uBAAuB;AAE7E,2BAA2B;AAC3B,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,cAAc,EAAC,EAAC,IAAI,EAAC,OAAO,EAAC,CAAC,CAAC;AACpD,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,uBAAuB;AAE7E,yBAAyB;AACzB,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,cAAc,EAAC,EAAC,IAAI,EAAC,OAAO,EAAC,CAAC,CAAC;AAClD,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,4BAA4B;AAE1H,IAAI,IAAI,GAAG,OAAO,CAAC;AACnB,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC;AAC7C,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC;AAErD,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC"}

81
test/test.node.ts Normal file
View File

@@ -0,0 +1,81 @@
import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as smartenv from '../ts/index.js';
let testEnv: smartenv.Smartenv;
tap.test('should create smartenv instance', async () => {
testEnv = new smartenv.Smartenv();
});
tap.test('should detect Node.js runtime correctly', async () => {
expect(testEnv.runtimeEnv).toEqual('node');
expect(testEnv.isNode).toBeTrue();
expect(testEnv.isDeno).toBeFalse();
expect(testEnv.isBun).toBeFalse();
expect(testEnv.isBrowser).toBeFalse();
console.log('✓ Node.js runtime detected correctly (not confused with Deno or Bun)');
});
tap.test('should get Node.js version', async () => {
const version = testEnv.nodeVersion;
expect(version).not.toEqual('undefined');
expect(typeof version).toEqual('string');
expect(version).toMatch(/^v\d+\.\d+\.\d+/);
console.log('Node.js version is ' + version);
});
tap.test('should print environment', async () => {
testEnv.printEnv();
});
tap.test('should load modules for Node.js', async () => {
const pathModule = await testEnv.getSafeModuleFor('node', 'path');
expect(pathModule).not.toBeUndefined();
expect(typeof pathModule.join).toEqual('function');
console.log('✓ Successfully loaded module for Node.js');
});
tap.test('should load modules for server runtimes', async () => {
const pathModule = await testEnv.getSafeModuleFor('server', 'path');
expect(pathModule).not.toBeUndefined();
expect(typeof pathModule.join).toEqual('function');
console.log('✓ Successfully loaded module with server target');
});
tap.test('should load modules for array of runtimes', async () => {
const pathModule = await testEnv.getSafeModuleFor(['node', 'deno'], 'path');
expect(pathModule).not.toBeUndefined();
expect(typeof pathModule.join).toEqual('function');
console.log('✓ Successfully loaded module with array target');
});
tap.test('should not load modules for wrong runtime', async () => {
const result = await testEnv.getSafeModuleFor('browser', 'path');
expect(result).toBeUndefined();
console.log('✓ Correctly rejected browser-only module in Node.js');
});
tap.test('should get os', async () => {
const resultMac = await testEnv.isMacAsync();
const resultLinux = await testEnv.isLinuxAsync();
const resultWindows = await testEnv.isWindowsAsync();
const osModule = await import('os');
if (resultMac) {
expect(osModule.platform()).toEqual('darwin');
console.log('platform is Mac!');
} else if (resultLinux) {
expect(osModule.platform()).toEqual('linux');
console.log('platform is Linux!');
} else {
expect(osModule.platform()).toEqual('win32');
console.log('platform is Windows!');
}
});
tap.test('should state wether we are in CI', async () => {
if (process.env.CI) {
expect(testEnv.isCI).toBeTrue();
}
});
tap.start();

View File

@@ -1,24 +0,0 @@
import * as smartenv from '../dist/index.js'
import * as beautylog from 'beautylog'
smartenv.printEnv()
// test smartenv.obs.add
smartenv.obs.add('myTestObject',{key1:'Peter'})
smartenv.obs.add('myTestObject',{key1:'Klaus'}) // now trying to add a second
smartenv.printEnv()
beautylog.log(smartenv.obs.get('myTestObject').key1) // this should be Peter
// test smartenv.obs.replace
smartenv.obs.replace('myTestObject',{key1:'Klaus'})
beautylog.log(smartenv.obs.get('myTestObject').key1) // this should be Klaus
// test smartenv.obs.merge
smartenv.obs.merge('myTestObject',{key2:'Peter'})
beautylog.log(smartenv.obs.get('myTestObject').key1 + smartenv.obs.get('myTestObject').key2)
// this should be KlausPeter
let key2 = 'hello'
smartenv.obs.get('myTestObject').key2 = key2
beautylog.log(smartenv.obs.get('myTestObject').key2)
beautylog.success('Success!')

8
ts/00_commitinfo_data.ts Normal file
View File

@@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartenv',
version: '6.0.0',
description: 'A module for storing and accessing environment details across different platforms.'
}

View File

@@ -1,8 +1 @@
import * as plugins from './smartenv.plugins'
import * as classes from './smartenv.classes'
import * as SmartenvEnvironment from './smartenv.environment'
import * as SmartenvObjectstorage from './smartenv.objectstorage'
export let getEnv = SmartenvEnvironment.getEnv
export let printEnv = SmartenvEnvironment.printEnv
export let obs = SmartenvObjectstorage.obs
export * from './smartenv.classes.smartenv.js';

20
ts/interfaces/index.ts Normal file
View File

@@ -0,0 +1,20 @@
export let defaultme = null;
/**
* Runtime type representing the detected JavaScript runtime environment
*/
export type TRuntimeType = 'node' | 'deno' | 'bun' | 'browser';
/**
* Runtime target for module loading - can be a specific runtime or 'server' for all server-side runtimes
*/
export type TRuntimeTarget = TRuntimeType | 'server';
declare global {
namespace NodeJS {
interface Global {
window: any;
navigator: any;
}
}
}

View File

@@ -1,51 +0,0 @@
export var getEnvString = function(): string {
if (typeof window !== 'undefined') {
return 'browser'
} else if (typeof process !== 'undefined') {
return 'node'
}
}
export var getUserAgentString = function(): string{
if (isBrowser()) {
return navigator.userAgent
} else {
return undefined
}
}
export var isNode = function(): boolean {
return getEnvString() === 'node'
}
export var getNodeVersion = function(): string {
return process.version
}
export var isBrowser = function(): boolean {
return !isNode()
}
export var isCI = function(){
if (process.env.CI) {
return true
} else {
return false
};
}
export var isC9 = function(){
if (process.env.C9_HOSTNAME) {
return true
} else {
return false
}
}
export var isTravis = function(){
if (process.env.TRAVIS) {
return true
} else {
return false
};
}

View File

@@ -0,0 +1,259 @@
import * as plugins from './smartenv.plugins.js';
import * as interfaces from './interfaces/index.js';
// interfaces
export interface IEnvObject {
name: string;
value: string;
}
/**
* Smartenv class that makes it easy
*/
export class Smartenv {
public async getEnvAwareModule(optionsArg: {
nodeModuleName: string;
webUrlArg: string;
getFunction: () => any;
}) {
if (this.isNode) {
const moduleResult = await this.getSafeNodeModule(optionsArg.nodeModuleName);
return moduleResult;
} else if (this.isBrowser) {
const moduleResult = await this.getSafeWebModule(
optionsArg.webUrlArg,
optionsArg.getFunction
);
return moduleResult;
} else {
console.error('platform for loading not supported by smartenv');
}
}
public async getSafeNodeModule<T = any>(moduleNameArg: string, runAfterFunc?: (moduleArg: T) => Promise<any>): Promise<T> {
if (!this.isNode && !this.isDeno && !this.isBun) {
console.error(`You tried to load a server module in a wrong context: ${moduleNameArg}. This does not throw.`);
return;
}
// tslint:disable-next-line: function-constructor
const returnValue: T = await (new Function(`return import('${moduleNameArg}')`)() as Promise<T>);
if (runAfterFunc) {
await runAfterFunc(returnValue);
}
return returnValue;
}
public loadedScripts: string[] = [];
public async getSafeWebModule(urlArg: string, getFunctionArg: () => any) {
if (!this.isBrowser) {
console.error('You tried to load a web module in a wrong context');
return;
}
if (this.loadedScripts.includes(urlArg)) {
return getFunctionArg();
} else {
this.loadedScripts.push(urlArg);
}
const done = plugins.smartpromise.defer();
if (globalThis.importScripts) {
globalThis.importScripts(urlArg);
done.resolve();
} else {
const script = document.createElement('script');
script.onload = () => {
done.resolve();
};
script.src = urlArg;
document.head.appendChild(script);
}
await done.promise;
return getFunctionArg();
}
public get runtimeEnv(): interfaces.TRuntimeType {
// Check Deno first (most distinctive)
if (typeof globalThis.Deno !== 'undefined' &&
typeof (globalThis as any).Deno?.version !== 'undefined') {
return 'deno';
}
// Check Bun second (most distinctive)
if (typeof globalThis.Bun !== 'undefined' &&
typeof (globalThis as any).Bun?.version !== 'undefined') {
return 'bun';
}
// Check Node.js (be explicit about versions to avoid Deno/Bun false positives)
if (typeof globalThis.process !== 'undefined' &&
typeof (globalThis as any).process?.versions?.node !== 'undefined') {
return 'node';
}
// Check Browser (default fallback)
if (typeof globalThis.window !== 'undefined' &&
typeof (globalThis as any).document !== 'undefined') {
return 'browser';
}
// Safe fallback
return 'browser';
}
public get isBrowser(): boolean {
return this.runtimeEnv === 'browser';
}
public get isNode(): boolean {
return this.runtimeEnv === 'node';
}
public get isDeno(): boolean {
return this.runtimeEnv === 'deno';
}
public get isBun(): boolean {
return this.runtimeEnv === 'bun';
}
public get userAgent(): string {
if (this.isBrowser) {
// make sure we are in Browser
return navigator.userAgent;
} else {
return 'undefined';
}
}
public get nodeVersion(): string {
if (this.isNode) {
return process.version;
}
return 'undefined';
}
public get denoVersion(): string {
if (this.isDeno) {
return (globalThis as any).Deno.version.deno;
}
return 'undefined';
}
public get bunVersion(): string {
if (this.isBun) {
return (globalThis as any).Bun.version;
}
return 'undefined';
}
/**
* Load a module only if the current runtime matches the target runtime(s)
* @param target - Single runtime, array of runtimes, or 'server' for all server-side runtimes
* @param moduleNameOrUrl - Module name (for Node/Deno/Bun) or URL (for browser)
* @param getFunction - Optional function to retrieve the module in browser context
* @returns The loaded module or undefined if runtime doesn't match
*/
public async getSafeModuleFor<T = any>(
target: interfaces.TRuntimeTarget | interfaces.TRuntimeTarget[],
moduleNameOrUrl: string,
getFunction?: () => any
): Promise<T | undefined> {
// Normalize target to array
let targetRuntimes: interfaces.TRuntimeType[];
if (Array.isArray(target)) {
// Expand 'server' if present in array
targetRuntimes = target.flatMap(t =>
t === 'server' ? ['node', 'deno', 'bun'] as interfaces.TRuntimeType[] : [t as interfaces.TRuntimeType]
);
} else if (target === 'server') {
targetRuntimes = ['node', 'deno', 'bun'];
} else {
targetRuntimes = [target];
}
// Check if current runtime matches any target
if (!targetRuntimes.includes(this.runtimeEnv)) {
console.warn(
`Module "${moduleNameOrUrl}" requested for runtime(s) [${targetRuntimes.join(', ')}] ` +
`but current runtime is "${this.runtimeEnv}". Skipping load.`
);
return undefined;
}
// Load based on current runtime
if (this.isNode || this.isDeno || this.isBun) {
// Server-side runtimes use dynamic import
const moduleResult = await this.getSafeNodeModule<T>(moduleNameOrUrl);
return moduleResult;
} else if (this.isBrowser) {
if (!getFunction) {
console.error(`Browser module load requires getFunction parameter for "${moduleNameOrUrl}"`);
return undefined;
}
const moduleResult = await this.getSafeWebModule(moduleNameOrUrl, getFunction);
return moduleResult as T;
}
return undefined;
}
public get isCI(): boolean {
if (this.isNode) {
if (process.env.CI) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public async isMacAsync(): Promise<boolean> {
if (this.isNode) {
const os = await this.getSafeNodeModule('os');
return os.platform() === 'darwin';
} else {
return false;
}
}
public async isWindowsAsync(): Promise<boolean> {
if (this.isNode) {
const os = await this.getSafeNodeModule('os');
return os.platform() === 'win32';
} else {
return false;
}
}
public async isLinuxAsync(): Promise<boolean> {
if (this.isNode) {
const os = await this.getSafeNodeModule('os');
return os.platform() === 'linux';
} else {
return false;
}
}
/**
* prints the environment to console
*/
public async printEnv() {
if (this.isNode) {
console.log('running on NODE');
console.log('node version is ' + this.nodeVersion);
} else if (this.isDeno) {
console.log('running on DENO');
console.log('deno version is ' + this.denoVersion);
} else if (this.isBun) {
console.log('running on BUN');
console.log('bun version is ' + this.bunVersion);
} else {
console.log('running on BROWSER');
console.log('browser is ' + this.userAgent);
}
}
}

View File

@@ -1,22 +0,0 @@
import helpers = require('./smartenv.classes.helpers')
export class Environment {
runtimeEnv: string
isBrowser: boolean
userAgent: string
isNode: boolean
nodeVersion: string
isCI: boolean
isTravis: boolean
isC9: boolean
constructor() {
this.runtimeEnv = helpers.getEnvString()
this.isBrowser = helpers.isBrowser()
this.userAgent = helpers.getUserAgentString()
this.isNode = helpers.isNode()
this.nodeVersion = helpers.getNodeVersion()
this.isCI = helpers.isCI()
this.isTravis = helpers.isTravis()
this.isC9 = helpers.isC9()
};
}

View File

@@ -1,38 +0,0 @@
/**
* Deals with the environment the current JS script is running in.
*/
import * as plugins from './smartenv.plugins'
import * as classes from './smartenv.classes'
import * as objectStorage from './smartenv.objectstorage'
let environment: classes.Environment
let envDetermined: boolean = false
/**
* returns the environment
* @returns {Environment}
*/
export var getEnv = function(){
if (!envDetermined) {
environment = new classes.Environment()
envDetermined = true // ensure code above only runs once
};
return environment
}
/**
* prints the environment to console
*/
export var printEnv = function() {
if (this.getEnv().isNode) {
console.log('running on NODE')
let smartenvVersion = require('../package.json').version
console.log('node version is ' + this.getEnv().nodeVersion + ' and smartenv version is ' + smartenvVersion)
} else {
console.log('running on BROWSER')
console.log('browser is ' + this.getEnv().userAgent)
}
console.log('the smartenv registration store currently holds the following properties:')
console.log(Object.getOwnPropertyNames(objectStorage.obs.getAll()))
}

View File

@@ -1,39 +0,0 @@
import plugins = require('./smartenv.plugins')
export var obs: any = {
add: function(paramNameArg = 'undefined',objectArg = 'undefined') {
if (paramNameArg === 'undefined') {
console.log('paramName is undefined')
return
}
if (objectArg === 'undefined') {
console.log('objectArg is undefined')
}
if (typeof obsItems[paramNameArg] === 'undefined') {
obsItems[paramNameArg] = objectArg
} else {
console.log('object is already present, so add operation has failed.')
}
return obsItems[paramNameArg]
},
replace: function(paramNameArg,objectArg){
obsItems[paramNameArg] = objectArg
},
merge: function(paramNameArg,objectArg){
if (!(typeof obsItems[paramNameArg] === 'undefined')) {
obsItems[paramNameArg] = plugins._.assign(obsItems[paramNameArg],objectArg)
} else {
console.log('object is not present, so there is nothing to merge')
}
},
get: function(keyName) {
return obsItems[keyName]
},
getAll: function () {
return obsItems
},
addComplete: function(itemsArg) {
obsItems = plugins._.assign(obsItems,itemsArg)
return obsItems
}
}
export var obsItems: any = {}

View File

@@ -1,8 +1,3 @@
import 'typings-global'
import * as Q from 'q'
import * as _ from 'lodash'
import * as smartpromise from '@push.rocks/smartpromise';
export {
Q,
_
}
export { smartpromise };

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,3 +0,0 @@
{
"extends": "tslint-config-standard"
}