Compare commits

...

137 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
41e1386a8d 1.2.11 2016-11-21 18:28:08 +01:00
98d6f9e483 reverse to ES5 2016-11-21 18:28:06 +01:00
f295776bea 1.2.10 2016-11-21 14:51:39 +01:00
cde63e95a8 update repo links 2016-11-21 14:51:35 +01:00
6e4804a5ad 1.2.9 2016-11-21 14:47:30 +01:00
137592a19b update types 2016-11-21 14:47:24 +01:00
b850bc48cd 1.2.8 2016-11-21 12:11:53 +01:00
e1ce867493 update README 2016-11-21 12:11:49 +01:00
8e94ca9a60 1.2.7 2016-11-21 12:05:00 +01:00
81eaaaca90 update tests 2016-11-21 12:04:57 +01:00
340e7716f0 1.2.6 2016-11-21 11:58:41 +01:00
af7b9c46d2 update to latest standards 2016-11-21 11:58:37 +01:00
56d4432d31 Update README.md 2016-05-19 06:55:05 +02:00
LosslessBot
324abf821e 1.2.5 2016-05-02 01:43:11 +02:00
LosslessBot
fde407a762 update travis.yml 2016-05-02 01:43:07 +02:00
LosslessBot
c9ac84954f update travis.yml 2016-05-02 01:41:57 +02:00
LosslessBot
e0b4a93f1c 1.2.4 2016-05-02 01:30:02 +02:00
LosslessBot
70015b5ffc now bundles typings 2016-05-02 01:29:42 +02:00
5a4d47411a 1.2.3 2016-04-05 15:53:54 +02:00
1730706034 fix package.json 2016-04-05 15:53:51 +02:00
7ecf342548 prepare for npmts-g 2016-04-05 15:13:52 +02:00
7f10392757 update dependencies and add caret to npmts dependency 2016-04-05 12:34:03 +02:00
9e229eee85 1.2.2 2016-04-05 01:07:24 +02:00
74c2c87f22 updated deps 2016-04-05 01:07:24 +02:00
0e0ee89263 1.2.1 2016-04-04 18:24:30 +02:00
a0e8f2f5e2 updated deps 2016-04-04 18:24:22 +02:00
043c5a0c6e 1.2.0 2016-03-03 01:50:17 +01:00
a1d5b4fc4e add isC9 to env 2016-03-03 01:50:13 +01:00
cd0b8f18af 1.1.0 2016-02-23 17:23:39 +01:00
d5387ddc05 1.0.10 2016-02-23 16:33:22 +01:00
3487b348df update deps 2016-02-23 16:31:50 +01:00
81036f8da3 1.0.9 2016-02-23 15:03:19 +01:00
b1464d97bf resolve dependency loop 2016-02-23 15:03:14 +01:00
5636cf330e 1.0.8 2016-02-23 14:36:20 +01:00
2e8b49fa18 update deps 2016-02-23 14:36:03 +01:00
df6036fbf1 1.0.7 2016-02-23 14:33:16 +01:00
8ec33947b6 update deps 2016-02-23 14:33:08 +01:00
50100115a6 1.0.6 2016-02-20 10:55:24 +01:00
8251e878c2 update deps 2016-02-20 10:55:19 +01:00
4a18d648c6 1.0.5 2016-02-20 10:50:38 +01:00
f9b89cc9db update object assignment 2016-02-20 10:50:32 +01:00
190aab3a11 1.0.4 2016-02-20 10:21:12 +01:00
cd26fffaf2 update travis 2016-02-20 10:21:09 +01:00
c2e48fa8b9 1.0.3 2016-02-20 10:11:32 +01:00
0db5ec169a add CI questions to Environment 2016-02-20 10:11:25 +01:00
0a29fafaeb update structure 2016-02-18 13:27:45 +01:00
43 changed files with 18278 additions and 448 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

25
.gitignore vendored
View File

@@ -1,13 +1,20 @@
node_modules/
.settings/
.idea/
.nogit/
# artifacts
coverage/
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

4
.npmignore Normal file
View File

@@ -0,0 +1,4 @@
node_modules/
coverage/
test/
ts/typings/

View File

@@ -1,16 +0,0 @@
language: node_js
node_js:
- 4.2.2
before_install:
- npm install -g tsd
deploy:
provider: npm
email: npm@smart-coordination.com
api_key:
secure: uNjLbNelm8nj9R/tRlwRvcXWLS1QtA0QEbDKPDTWHNo68wAHgdwXIdzkVkNcihZYVasR/LqGuSLfzoD4H8mKmCXD+v85h048VmmtWniZQRp/OVWl0uzRwDDryhiYlhY5U9oOFEQsMO96C8qPqcGchq+DA7Gi3ZnAl7pmeb54xp9H+7jmLyZTyO8Hq00anV5PopBOW23mZEnWHznzYeg83BlWmLdbyfyZKT4W5Urg1BAMgxt9PdtrQoiPy4LP6AHXG88kvY3Iz8OBG+h/06bura8MPfeupGoktodN9krb+sRE/COybATWImMh9Z5gI5TWqUR7tp7XivpgolYY41gaN93oUQ9EOTdJ5kFku1dnPrNFqXO/97slVTMR6fMMgRXwzTz6BiKI1NsAZeW7oLUONw06APZ6VBhVY6Po3Rioun8OE9Q0wXm/BvnRqVHt3sew4MIgmEBwQSQE14gLJGGgNojzmcPstc0czQp+kzV5DpGiW3IWIWZ7MsBJOOJ13RHeb6koFdBR7JZj0QzzBcWD7juJVOS45MlP7hU/sKRDO/fN3nu8TNwHvJab6XYP5/gqlbh/3h2vb7bxyDXiKGi2Ds8hZOHoyWoCrU3sbH3eKKkKo+LFI3J7PbY11T6TkSAdszLsQzcvC2QlsGQRWVywYMm32R6BVfxF3AlLX5a8JsI=
on:
tags: true
repo: pushrocks/smartenv
notifications:
slack:
secure: f5Uss0z9RPl/QcA/DroB8loyE93aOYI6bqCkrsiUscmZtlv/TVQtT4dxqGA6uvcG6iTQDBi3Ul88dQxWkRm4IqbhY35/iMaV2dHW4FVYMAh8GQMbsfL2sALCcufxD9blw47awv3iFcwhV1EeyesscjgL0JIjduk96v/7G/6QIO2838M1lzlgtj+kRUkim8qkaEs1je3gRrhMUIjLuAdscMXyUKYFMjWo9ACSjVUl30R/ZNemb18itIja6i92GotreBgcfEMczvy58ovDC7xdJUsY8LjMI01DwY+WPRnI0tAhsuI8moBwwcdM4e3bAjKjucQRjO33O5bMWRZ6QCiYd0DnCEFyCPQLJ4GSy/tkD00n8ijLHAOSV3AH1zNbdK1EAdSPQXDvlI36KJn/2hyQLoitGHVUPr76ujJWP82ypO2tgIp3XQU0dJVCxDuHnwJO2+hjdI+gCPqxNTpjeujHx3UdkTGNRjuuf9dlZ/D08fApjYxy2fxItTqo3QjP/nrqvBXUOPP8yPHpjIT4H2t5Pr4SJjBGI6X4qhKyFj6s9rA/Xu1rL+45zu1C3uC3z+u3T9UwrbzJ/cZM6r6UQvQmUvIfBNaMlg4I/diQCDIPL+Rhop2nylY3IcHmJnk2itn7kOqj1tohCpFEml5pRuSZy4udWywkdtyBAsHWFLF7oiQ=

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,28 +0,0 @@
# smartenv
store things about your environment and let them travel across modules
## Status
[![Build Status](https://travis-ci.org/pushrocks/smartenv.svg?branch=release)](https://travis-ci.org/pushrocks/smartenv)
[![Dependency Status](https://david-dm.org/pushrocks/smartenv.svg)](https://david-dm.org/pushrocks/smartenv)
[![devDependency Status](https://david-dm.org/pushrocks/smartenv/dev-status.svg)](https://david-dm.org/pushrocks/smartenv#info=devDependencies)
[![bitHound Dependencies](https://www.bithound.io/github/pushrocks/smartenv/badges/dependencies.svg)](https://www.bithound.io/github/pushrocks/smartenv/master/dependencies/npm)
[![bitHound Overalll Score](https://www.bithound.io/github/pushrocks/smartenv/badges/score.svg)](https://www.bithound.io/github/pushrocks/smartenv)
## 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"
```

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

11
dist/index.js vendored
View File

@@ -1,11 +0,0 @@
#!/usr/bin/env node
/// <reference path="typings/main.d.ts" />
var SmartenvEnvironment = require("./smartenv.environment");
var SmartenvObjectStorage = require("./smartenv.objectstorage");
var smartenv = {}; //create smartenv object
SmartenvEnvironment.init(smartenv);
smartenv.obs = SmartenvObjectStorage.obs;
module.exports = smartenv;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLDBDQUEwQztBQUUxQyxJQUFPLG1CQUFtQixXQUFXLHdCQUF3QixDQUFDLENBQUM7QUFDL0QsSUFBTyxxQkFBcUIsV0FBVywwQkFBMEIsQ0FBQyxDQUFDO0FBRW5FLElBQUksUUFBUSxHQUFPLEVBQUUsQ0FBQyxDQUFDLHdCQUF3QjtBQUMvQyxtQkFBbUIsQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLENBQUM7QUFDbkMsUUFBUSxDQUFDLEdBQUcsR0FBRyxxQkFBcUIsQ0FBQyxHQUFHLENBQUM7QUFFekMsaUJBQVMsUUFBUSxDQUFDIiwiZmlsZSI6ImluZGV4LmpzIiwic291cmNlc0NvbnRlbnQiOlsiLy8vIDxyZWZlcmVuY2UgcGF0aD1cInR5cGluZ3MvbWFpbi5kLnRzXCIgLz5cblxuaW1wb3J0IFNtYXJ0ZW52RW52aXJvbm1lbnQgPSByZXF1aXJlKFwiLi9zbWFydGVudi5lbnZpcm9ubWVudFwiKTtcbmltcG9ydCBTbWFydGVudk9iamVjdFN0b3JhZ2UgPSByZXF1aXJlKFwiLi9zbWFydGVudi5vYmplY3RzdG9yYWdlXCIpO1xuXG52YXIgc21hcnRlbnY6YW55ID0ge307IC8vY3JlYXRlIHNtYXJ0ZW52IG9iamVjdFxuU21hcnRlbnZFbnZpcm9ubWVudC5pbml0KHNtYXJ0ZW52KTtcbnNtYXJ0ZW52Lm9icyA9IFNtYXJ0ZW52T2JqZWN0U3RvcmFnZS5vYnM7XG5cbmV4cG9ydCA9IHNtYXJ0ZW52O1xuIl0sInNvdXJjZVJvb3QiOiIvc291cmNlLyJ9

View File

@@ -1,25 +0,0 @@
#!/usr/bin/env node
/// <reference path="typings/main.d.ts" />
var Environment = (function () {
function Environment(runtimeEnvArg, userAgentArg) {
if (userAgentArg === void 0) { userAgentArg = "undefined"; }
this.runtimeEnv = runtimeEnvArg;
this.userAgent = userAgentArg;
if (runtimeEnvArg == "node") {
this.isBrowser = false;
this.isNode = true;
this.nodeVersion = process.version;
}
else if (runtimeEnvArg == "browser") {
this.is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ZWZpbmVkXCI7XG4gICAgICAgIH1cbiAgICB9O1xufVxuIl0sInNvdXJjZVJvb3QiOiIvc291cmNlLyJ9

View File

@@ -1,56 +0,0 @@
#!/usr/bin/env node
/// <reference path="typings/main.d.ts" />
/**
* Deals with the environment the current JS script is running in.
*/
var plugins = require("./smartenv.plugins");
var SmartenvClasses = require("./smartenv.classes");
var SmartenvObjectStorage = require("./smartenv.objectstorage");
var environment;
var envDetermined = false;
/**
* returns the environment
* @returns {Environment}
*/
var getEnv = function () {
if (!envDetermined) {
(function () {
var localRunTimeEnv = "undefined";
var localUserAgent = "undefined";
if (typeof window !== "undefined") {
localRunTimeEnv = 'browser';
localUserAgent = navigator.userAgent;
}
else if (typeof process !== "undefined") {
localRunTimeEnv = 'node';
}
environment = new SmartenvClasses.Environment(localRunTimeEnv, localUserAgent);
})();
envDetermined = true; // ensure code above only runs once
}
;
return environment;
};
/**
* prints the environment to console
*/
var printEnv = function () {
if (this.getEnv().isNode) {
plugins.beautylog.ok("running on NODE");
var smartenvVersion = require("../package.json").version;
plugins.beautylog.log("node version is " + this.getEnv().nodeVersion + " and smartenv version is " + smartenvVersion);
}
else {
plugins.beautylog.ok("running on BROWSER");
plugins.beautylog.log("browser is " + this.getEnv().userAgent);
}
plugins.beautylog.log("the smartenv registration store currently holds the following properties:");
console.log(Object.getOwnPropertyNames(SmartenvObjectStorage.obs.getAll()));
};
exports.init = function (objectArg) {
objectArg.getEnv = getEnv;
objectArg.printEnv = printEnv;
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNtYXJ0ZW52LmVudmlyb25tZW50LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLDBDQUEwQztBQUMxQzs7R0FFRztBQUNILElBQU8sT0FBTyxXQUFXLG9CQUFvQixDQUFDLENBQUM7QUFDL0MsSUFBTyxlQUFlLFdBQVcsb0JBQW9CLENBQUMsQ0FBQztBQUN2RCxJQUFPLHFC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ubG9nKE9iamVjdC5nZXRPd25Qcm9wZXJ0eU5hbWVzKFNtYXJ0ZW52T2JqZWN0U3RvcmFnZS5vYnMuZ2V0QWxsKCkpKTtcbn07XG5cbmV4cG9ydCB2YXIgaW5pdCA9IGZ1bmN0aW9uKG9iamVjdEFyZykge1xuICAgIG9iamVjdEFyZy5nZXRFbnYgPSBnZXRFbnY7XG4gICAgb2JqZWN0QXJnLnByaW50RW52ID0gcHJpbnRFbnY7XG59OyJdLCJzb3VyY2VSb290IjoiL3NvdXJjZS8ifQ==

View File

@@ -1,48 +0,0 @@
#!/usr/bin/env node
/// <reference path="typings/main.d.ts" />
var plugins = require("./smartenv.plugins");
exports.obs = {
add: function (paramNameArg, objectArg) {
if (paramNameArg === void 0) { paramNameArg = "undefined"; }
if (objectArg === void 0) { objectArg = "undefined"; }
if (paramNameArg == "undefined") {
plugins.beautylog.error("paramName is undefined");
return;
}
if (objectArg == "undefined") {
plugins.beautylog.error("objectArg is undefined");
}
if (typeof exports.obsItems[paramNameArg] === "undefined") {
exports.obsItems[paramNameArg] = objectArg;
}
else {
plugins.beautylog.error("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 {
plugins.beautylog.error("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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNtYXJ0ZW52Lm9iamVjdHN0b3JhZ2UudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE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ICAgICAgIG9ic0l0ZW1zW3BhcmFtTmFtZUFyZ10gPSBwbHVnaW5zLl8uYXNzaWduKG9ic0l0ZW1zW3BhcmFtTmFtZUFyZ10sb2JqZWN0QXJnKTtcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIHBsdWdpbnMuYmVhdXR5bG9nLmVycm9yKFwib2JqZWN0IGlzIG5vdCBwcmVzZW50LCBzbyB0aGVyZSBpcyBub3RoaW5nIHRvIG1lcmdlXCIpO1xuICAgICAgICB9XG4gICAgfSxcbiAgICBnZXQ6IGZ1bmN0aW9uKGtleU5hbWUpIHtcbiAgICAgICAgcmV0dXJuIG9ic0l0ZW1zW2tleU5hbWVdO1xuICAgIH0sXG4gICAgZ2V0QWxsOiBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHJldHVybiBvYnNJdGVtcztcbiAgICB9LFxuICAgIGFkZENvbXBsZXRlOiBmdW5jdGlvbihpdGVtc0FyZykge1xuICAgICAgICBvYnNJdGVtcyA9IHBsdWdpbnMuXy5hc3NpZ24ob2JzSXRlbXMsaXRlbXNBcmcpO1xuICAgICAgICByZXR1cm4gb2JzSXRlbXM7XG4gICAgfVxufTtcbmV4cG9ydCB2YXIgb2JzSXRlbXM6YW55ID0ge307Il0sInNvdXJjZVJvb3QiOiIvc291cmNlLyJ9

View File

@@ -1,10 +0,0 @@
#!/usr/bin/env node
/// <reference path="typings/main.d.ts" />
var plugins = {
beautylog: require("beautylog"),
_: require("lodash")
};
module.exports = plugins;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNtYXJ0ZW52LnBsdWdpbnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsMENBQTBDO0FBQzFDLElBQUksT0FBTyxHQUFHO0lBQ1YsU0FBUyxFQUFFLE9BQU8sQ0FBQyxXQUFXLENBQUM7SUFDL0IsQ0FBQyxFQUFFLE9BQU8sQ0FBQyxRQUFRLENBQUM7Q0FDdkIsQ0FBQztBQUVGLGlCQUFTLE9BQU8sQ0FBQyIsImZpbGUiOiJzbWFydGVudi5wbHVnaW5zLmpzIiwic291cmNlc0NvbnRlbnQiOlsiLy8vIDxyZWZlcmVuY2UgcGF0aD1cInR5cGluZ3MvbWFpbi5kLnRzXCIgLz5cbnZhciBwbHVnaW5zID0ge1xuICAgIGJlYXV0eWxvZzogcmVxdWlyZShcImJlYXV0eWxvZ1wiKSxcbiAgICBfOiByZXF1aXJlKFwibG9kYXNoXCIpXG59O1xuXG5leHBvcnQgPSBwbHVnaW5zOyJdLCJzb3VyY2VSb290IjoiL3NvdXJjZS8ifQ==

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,4 +0,0 @@
{
"mode":"default",
"coveralls":true
}

View File

@@ -1,33 +1,63 @@
{
"name": "smartenv",
"version": "1.0.2",
"description": "store things about your environment and let them travel across modules",
"main": "dist/index.js",
"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://github.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://github.com/pushrocks/smartenv/issues"
"url": "https://gitlab.com/pushrocks/smartenv/issues"
},
"homepage": "https://github.com/pushrocks/smartenv",
"homepage": "https://code.foss.global/push.rocks/smartenv",
"dependencies": {
"beautylog": "^2.1.1",
"lodash": "^4.5.0"
"@push.rocks/smartpromise": "^4.0.2"
},
"devDependencies": {
"easyserve": "0.0.5",
"gulp": "^3.9.1",
"gulp-browser": "1.0.10",
"npmts": "^3.0.2"
}
"@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.

View File

@@ -1,6 +0,0 @@
<head>
<script async src="browserified/index.js"></script>
</head>
<body>
</body>

View File

@@ -1,2 +0,0 @@
var smartenv = require("./index.js");
smartenv.printEnv();

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();

4
test/test.d.ts vendored
View File

@@ -1,4 +0,0 @@
/// <reference path="../ts/typings/main.d.ts" />
declare var smartenv: any;
declare var beautylog: any;
declare var key2: string;

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,25 +0,0 @@
#!/usr/bin/env node
/// <reference path="../ts/typings/main.d.ts" />
var smartenv = require("../dist/index.js");
var beautylog = require("beautylog");
beautylog.info("Now testing the smartenv module");
smartenv.printEnv();
beautylog.info("Now testing the smartenv module");
//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
var key2 = "hello";
smartenv.obs.get("myTestObject").key2 = key2;
beautylog.log(smartenv.obs.get("myTestObject").key2);
beautylog.success("Success!");
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInRlc3QudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsZ0RBQWdEO0FBQ2hELElBQUksUUFBUSxHQUFHLE9BQU8sQ0FBQyxrQkFBa0IsQ0FBQyxDQUFDO0FBQzNDLElBQUksU0FBUyxHQUFHLE9BQU8sQ0FBQyxXQUFXLENBQUMsQ0FBQztBQUNyQyxTQUFTLENBQUMsSUFBSSxDQUFDLGlDQUFpQyxDQUFDLENBQUM7QUFDbEQsUUFBUSxDQUFDLFFBQVEsRUFBRSxDQUFDO0FBQ3BCLFNBQVMsQ0FBQyxJQUFJLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUVsRCx1QkFBdUI7QUFDdkIsUUFBUSxDQUFDLEdBQ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,OAAO,EAAC,CAAC,CAAC;AAChD,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,cAAc,EAAC,EAAC,IAAI,EAAC,OAAO,EAAC,CAAC,CAAC,CAAC,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,26 +0,0 @@
/// <reference path="../ts/typings/main.d.ts" />
var smartenv = require("../dist/index.js");
var beautylog = require("beautylog");
beautylog.info("Now testing the smartenv module");
smartenv.printEnv();
beautylog.info("Now testing the smartenv module");
//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
var key2 = "hello";
smartenv.obs.get("myTestObject").key2 = key2;
beautylog.log(smartenv.obs.get("myTestObject").key2);
beautylog.success("Success!");

View File

@@ -1,21 +0,0 @@
/// <reference path="typings/tsd.d.ts" />
var plugins = {
beautylog: require("beautylog")("os"),
gulp: require("gulp"),
gulpBrowser: require("gulp-browser"),
easyserve: require("easyserve")
};
plugins.gulp.task('compileBrowserJS', function() {
var stream = plugins.gulp.src('test/browser/index.js')
.pipe(plugins.gulpBrowser.browserify())
.pipe(plugins.gulp.dest("test/browser/browserified/"));
return stream;
});
plugins.gulp.task('default',['compileBrowserJS'], function() {
plugins.beautylog.success('browserJS has been browserified');
plugins.easyserve("test/browser/");
});
plugins.gulp.start.apply(plugins.gulp, ['default']);

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,10 +1 @@
/// <reference path="typings/main.d.ts" />
import SmartenvEnvironment = require("./smartenv.environment");
import SmartenvObjectStorage = require("./smartenv.objectstorage");
var smartenv:any = {}; //create smartenv object
SmartenvEnvironment.init(smartenv);
smartenv.obs = SmartenvObjectStorage.obs;
export = smartenv;
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

@@ -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,21 +0,0 @@
/// <reference path="typings/main.d.ts" />
export class Environment {
public runtimeEnv:string;
public userAgent:string;
public nodeVersion:string;
public isBrowser:boolean;
public isNode:boolean;
constructor(runtimeEnvArg:string,userAgentArg:string = "undefined") {
this.runtimeEnv = runtimeEnvArg;
this.userAgent = userAgentArg;
if(runtimeEnvArg == "node"){
this.isBrowser = false;
this.isNode = true;
this.nodeVersion = process.version;
} else if (runtimeEnvArg == "browser") {
this.isBrowser = true;
this.isNode = false;
this.nodeVersion = "undefined";
}
};
}

View File

@@ -1,54 +0,0 @@
/// <reference path="typings/main.d.ts" />
/**
* Deals with the environment the current JS script is running in.
*/
import plugins = require("./smartenv.plugins");
import SmartenvClasses = require("./smartenv.classes");
import SmartenvObjectStorage = require("./smartenv.objectstorage");
var environment:SmartenvClasses.Environment;
var envDetermined:boolean = false;
/**
* returns the environment
* @returns {Environment}
*/
var getEnv = function(){
if (!envDetermined) {
(function() {
var localRunTimeEnv = "undefined";
var localUserAgent = "undefined";
if (typeof window !== "undefined") {
localRunTimeEnv = 'browser';
localUserAgent = navigator.userAgent;
} else if (typeof process !== "undefined") {
localRunTimeEnv = 'node';
}
environment = new SmartenvClasses.Environment(localRunTimeEnv,localUserAgent);
})();
envDetermined = true; // ensure code above only runs once
};
return environment;
};
/**
* prints the environment to console
*/
var printEnv = function() {
if (this.getEnv().isNode) {
plugins.beautylog.ok("running on NODE");
var smartenvVersion = require("../package.json").version;
plugins.beautylog.log("node version is " + this.getEnv().nodeVersion + " and smartenv version is " + smartenvVersion);
} else {
plugins.beautylog.ok("running on BROWSER");
plugins.beautylog.log("browser is " + this.getEnv().userAgent);
}
plugins.beautylog.log("the smartenv registration store currently holds the following properties:");
console.log(Object.getOwnPropertyNames(SmartenvObjectStorage.obs.getAll()));
};
export var init = function(objectArg) {
objectArg.getEnv = getEnv;
objectArg.printEnv = printEnv;
};

View File

@@ -1,41 +0,0 @@
/// <reference path="typings/main.d.ts" />
import plugins = require("./smartenv.plugins");
export var obs:any = {
add: function(paramNameArg = "undefined",objectArg = "undefined") {
if (paramNameArg == "undefined"){
plugins.beautylog.error("paramName is undefined");
return;
}
if (objectArg == "undefined"){
plugins.beautylog.error("objectArg is undefined");
}
if (typeof obsItems[paramNameArg] === "undefined"){
obsItems[paramNameArg] = objectArg;
} else {
plugins.beautylog.error("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 {
plugins.beautylog.error("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,7 +1,3 @@
/// <reference path="typings/main.d.ts" />
var plugins = {
beautylog: require("beautylog"),
_: require("lodash")
};
import * as smartpromise from '@push.rocks/smartpromise';
export = plugins;
export { smartpromise };

View File

@@ -1,5 +0,0 @@
{
"ambientDependencies": {
"node": "github:DefinitelyTyped/DefinitelyTyped/node/node.d.ts"
}
}

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"
]
}