Compare commits
96 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d8decdb3e5 | |||
| 03cfee2003 | |||
| f6a3e71f0a | |||
| 6436370abc | |||
| eb1c48bee4 | |||
| 05417ed4c3 | |||
| 1d74a7f465 | |||
| 81ca32cdef | |||
| 07bfbfd393 | |||
| aa411072f2 | |||
| 02575e8baf | |||
| 09fc53aaff | |||
| bcb58dd012 | |||
| f0064bd94b | |||
| e9c527a9dc | |||
| a47d8bb3c7 | |||
| aa6766ef36 | |||
| b0442e1227 | |||
| 0f1eb6eb27 | |||
| dd18ef94bd | |||
| a0189921a5 | |||
| b409f1aa55 | |||
| 57553aa7c8 | |||
| c302cbdae4 | |||
| fd6e3ba8b1 | |||
| 8c3a7aa637 | |||
| 8c0125a8c0 | |||
| 40f3ffbdfb | |||
| d4e01a73d3 | |||
| 641e77892a | |||
| 0c1211778b | |||
| 024f7f4f8f | |||
| 8f1cba5078 | |||
| 188f8057bf | |||
| 99cb86258e | |||
| 83976fa3f4 | |||
| fe81307ca6 | |||
| 3a119b50a2 | |||
| d3332ccb3f | |||
| 776eba09e9 | |||
| b41ff5d495 | |||
| 5f5f9db884 | |||
| 876042b446 | |||
| df2924577b | |||
| 4abaea84f8 | |||
| de454b4c8d | |||
| 961685b5bd | |||
| c622396d50 | |||
| d130c1c6fd | |||
| f8a967aeac | |||
| abee699af8 | |||
| a21131eaf6 | |||
| c4b214a308 | |||
| 6db03eee83 | |||
| efc5b54d2e | |||
| 9860e43398 | |||
| 234117c8dd | |||
| 371c6553cd | |||
| b6b738916f | |||
| fad7e0bc6b | |||
| fc4fb911ef | |||
| 7e0dad1c10 | |||
| 0fb50714b9 | |||
| 7e1821f37d | |||
| 592228fc51 | |||
| 431089e23f | |||
| 5b64733d91 | |||
| 2da2a43a09 | |||
| f7887a6663 | |||
| be505ee915 | |||
| 9584f403b1 | |||
| 993a100eae | |||
| 29f0307ef8 | |||
| 9413c5bcdc | |||
| 1d5fb320f4 | |||
| 69e905ad76 | |||
| 7b9ed9ee78 | |||
| f884807f33 | |||
| f167800113 | |||
| c549d06a6b | |||
| 23061c86eb | |||
| 4d0567a95d | |||
| 8524c95440 | |||
| b1fc60fc2e | |||
| 8d296cf08d | |||
| b8d0ec55ad | |||
| 1cf78441e2 | |||
| 0f34c5de55 | |||
| 1bd8f8371b | |||
| ef263a85b4 | |||
| 315156aac5 | |||
| f90a61b38b | |||
| 71af6f08f3 | |||
| 01e938274d | |||
| c5a3eb63ad | |||
| a4d43456d7 |
66
.gitea/workflows/default_nottags.yaml
Normal file
66
.gitea/workflows/default_nottags.yaml
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
name: Default (not tags)
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags-ignore:
|
||||||
|
- '**'
|
||||||
|
|
||||||
|
env:
|
||||||
|
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
|
||||||
|
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@code.foss.global/${{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 @ship.zone/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
|
||||||
124
.gitea/workflows/default_tags.yaml
Normal file
124
.gitea/workflows/default_tags.yaml
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
name: Default (tags)
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
|
||||||
|
env:
|
||||||
|
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
|
||||||
|
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@code.foss.global/${{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 @ship.zone/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 @ship.zone/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 @ship.zone/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 @ship.zone/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
|
||||||
16
.gitignore
vendored
16
.gitignore
vendored
@@ -1,6 +1,20 @@
|
|||||||
.nogit/
|
.nogit/
|
||||||
node_modules/
|
|
||||||
|
# artifacts
|
||||||
coverage/
|
coverage/
|
||||||
public/
|
public/
|
||||||
pages/
|
pages/
|
||||||
|
|
||||||
|
# installs
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# caches
|
||||||
.yarn/
|
.yarn/
|
||||||
|
.cache/
|
||||||
|
.rpt2_cache
|
||||||
|
|
||||||
|
# builds
|
||||||
|
dist/
|
||||||
|
dist_*/
|
||||||
|
|
||||||
|
# custom
|
||||||
150
.gitlab-ci.yml
150
.gitlab-ci.yml
@@ -1,150 +0,0 @@
|
|||||||
# gitzone standard
|
|
||||||
image: hosttoday/ht-docker-node:npmci
|
|
||||||
|
|
||||||
cache:
|
|
||||||
paths:
|
|
||||||
- .npmci_cache/
|
|
||||||
key: "$CI_BUILD_STAGE"
|
|
||||||
|
|
||||||
stages:
|
|
||||||
- security
|
|
||||||
- test
|
|
||||||
- release
|
|
||||||
- metadata
|
|
||||||
|
|
||||||
# ====================
|
|
||||||
# security stage
|
|
||||||
# ====================
|
|
||||||
mirror:
|
|
||||||
stage: security
|
|
||||||
script:
|
|
||||||
- npmci git mirror
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
|
|
||||||
snyk:
|
|
||||||
stage: security
|
|
||||||
script:
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci command npm install -g snyk
|
|
||||||
- npmci command npm install --ignore-scripts
|
|
||||||
- npmci command snyk test
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
|
|
||||||
sast:
|
|
||||||
stage: security
|
|
||||||
image: registry.gitlab.com/hosttoday/ht-docker-dbase:npmci
|
|
||||||
variables:
|
|
||||||
DOCKER_DRIVER: overlay2
|
|
||||||
allow_failure: true
|
|
||||||
services:
|
|
||||||
- docker:stable-dind
|
|
||||||
script:
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci npm install
|
|
||||||
- npmci command npm run build
|
|
||||||
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
|
|
||||||
- docker run
|
|
||||||
--env SAST_CONFIDENCE_LEVEL="${SAST_CONFIDENCE_LEVEL:-3}"
|
|
||||||
--volume "$PWD:/code"
|
|
||||||
--volume /var/run/docker.sock:/var/run/docker.sock
|
|
||||||
"registry.gitlab.com/gitlab-org/security-products/sast:$SP_VERSION" /app/bin/run /code
|
|
||||||
artifacts:
|
|
||||||
reports:
|
|
||||||
sast: gl-sast-report.json
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
- priv
|
|
||||||
|
|
||||||
# ====================
|
|
||||||
# test stage
|
|
||||||
# ====================
|
|
||||||
|
|
||||||
testLTS:
|
|
||||||
stage: test
|
|
||||||
script:
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci node install lts
|
|
||||||
- npmci npm install
|
|
||||||
- npmci npm test
|
|
||||||
coverage: /\d+.?\d+?\%\s*coverage/
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
|
|
||||||
testSTABLE:
|
|
||||||
stage: test
|
|
||||||
script:
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci node install stable
|
|
||||||
- npmci npm install
|
|
||||||
- npmci npm test
|
|
||||||
coverage: /\d+.?\d+?\%\s*coverage/
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
|
|
||||||
release:
|
|
||||||
stage: release
|
|
||||||
script:
|
|
||||||
- npmci node install stable
|
|
||||||
- npmci npm publish
|
|
||||||
only:
|
|
||||||
- tags
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
|
|
||||||
# ====================
|
|
||||||
# metadata stage
|
|
||||||
# ====================
|
|
||||||
codequality:
|
|
||||||
stage: metadata
|
|
||||||
image: docker:stable
|
|
||||||
allow_failure: true
|
|
||||||
services:
|
|
||||||
- docker:stable-dind
|
|
||||||
script:
|
|
||||||
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
|
|
||||||
- docker run
|
|
||||||
--env SOURCE_CODE="$PWD"
|
|
||||||
--volume "$PWD":/code
|
|
||||||
--volume /var/run/docker.sock:/var/run/docker.sock
|
|
||||||
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
|
|
||||||
artifacts:
|
|
||||||
paths: [codeclimate.json]
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
- priv
|
|
||||||
|
|
||||||
trigger:
|
|
||||||
stage: metadata
|
|
||||||
script:
|
|
||||||
- npmci trigger
|
|
||||||
only:
|
|
||||||
- tags
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
|
|
||||||
pages:
|
|
||||||
image: hosttoday/ht-docker-node:npmci
|
|
||||||
stage: metadata
|
|
||||||
script:
|
|
||||||
- npmci command npm install -g typedoc typescript
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci npm install
|
|
||||||
- npmci command typedoc --module "commonjs" --target "ES2016" --out public/ ts/
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
only:
|
|
||||||
- tags
|
|
||||||
artifacts:
|
|
||||||
expire_in: 1 week
|
|
||||||
paths:
|
|
||||||
- public
|
|
||||||
allow_failure: true
|
|
||||||
11
.vscode/launch.json
vendored
Normal file
11
.vscode/launch.json
vendored
Normal 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
26
.vscode/settings.json
vendored
Normal 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"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
242
changelog.md
Normal file
242
changelog.md
Normal file
@@ -0,0 +1,242 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## 2026-02-02 - 2.0.30 - fix(config)
|
||||||
|
update npmextra configuration and improve README: rename package keys, add release registry config, clarify waitUntilPresent timeout and notification/persistence behavior
|
||||||
|
|
||||||
|
- Renamed npmextra keys: 'gitzone' → '@git.zone/cli' and 'tsdoc' → '@git.zone/tsdoc'
|
||||||
|
- Added release configuration for @git.zone/cli including registries (verdaccio and npm) and accessLevel
|
||||||
|
- Removed top-level 'npmci' section
|
||||||
|
- Added new '@ship.zone/szci' entry with npmGlobalTools
|
||||||
|
- README: added waitUntilPresent timeout example with error handling
|
||||||
|
- README: clarified notifyChangeCumulative is debounced and documented persistence behavior (merge with defaults, atomic writes)
|
||||||
|
- README: documented concurrency/race-condition safety and timeout support for waitUntilPresent
|
||||||
|
|
||||||
|
## 2026-02-02 - 2.0.29 - fix(smartstate)
|
||||||
|
prevent duplicate statepart creation and fix persistence/notification race conditions
|
||||||
|
|
||||||
|
- Add pendingStatePartCreation map to deduplicate concurrent createStatePart calls
|
||||||
|
- Adjust init handling so 'force' falls through to creation and concurrent creations are serialized
|
||||||
|
- Merge persisted state with initial payload in 'persistent' initMode, with persisted values taking precedence
|
||||||
|
- Persist to WebStore before updating in-memory state to ensure atomicity
|
||||||
|
- Debounce cumulative notifications via pendingCumulativeNotification to avoid duplicate notifications
|
||||||
|
- Log selector errors instead of silently swallowing exceptions
|
||||||
|
- Add optional timeout to waitUntilPresent and ensure subscriptions and timeouts are cleaned up to avoid indefinite waits
|
||||||
|
- Await setState when performing chained state updates to ensure ordering and avoid race conditions
|
||||||
|
|
||||||
|
## 2026-02-02 - 2.0.28 - fix(deps)
|
||||||
|
bump devDependencies and dependencies, add tsbundle build config, update docs, and reorganize tests
|
||||||
|
|
||||||
|
- Bumped @git.zone/tsbuild to ^4.1.2, @git.zone/tsbundle to ^2.8.3, @git.zone/tsrun to ^2.0.1, @git.zone/tstest to ^3.1.8, and @types/node to ^25.2.0
|
||||||
|
- Upgraded @push.rocks/smartjson to ^6.0.0
|
||||||
|
- Added @git.zone/tsbundle bundle configuration to npmextra.json for building a dist bundle
|
||||||
|
- Removed pnpm-workspace.yaml entries (cleaned workspace constraints)
|
||||||
|
- Updated readme and readme.hints (docs formatting, version bumped to v2.0.28, issue reporting/security section and dependency list)
|
||||||
|
- Reorganized tests: removed *.both.ts variants and added consolidated test files under test/ (test.ts, test.initialization.ts)
|
||||||
|
|
||||||
|
## 2025-09-12 - 2.0.27 - fix(StatePart)
|
||||||
|
Use stable JSON stringify for state hashing; update dependencies and tooling
|
||||||
|
|
||||||
|
- Replace smartjson.stringify with smartjson.stableOneWayStringify when creating SHA256 state hashes to ensure deterministic hashing and avoid duplicate notifications for semantically identical states.
|
||||||
|
- Bump runtime dependencies: @push.rocks/smarthash -> ^3.2.6, @push.rocks/smartjson -> ^5.2.0.
|
||||||
|
- Bump dev tooling versions: @git.zone/tsbuild -> ^2.6.8, @git.zone/tsbundle -> ^2.5.1, @git.zone/tstest -> ^2.3.8.
|
||||||
|
- Add local .claude/settings.local.json configuration for allowed permissions (local tooling/settings file).
|
||||||
|
|
||||||
|
## 2025-08-16 - 2.0.26 - fix(ci)
|
||||||
|
Add local Claude settings file to allow helper permissions for common local commands
|
||||||
|
|
||||||
|
- Added .claude/settings.local.json to grant local helper permissions for tooling
|
||||||
|
- Allowed commands: Bash(tsx:*), Bash(tstest test:*), Bash(git add:*), Bash(git tag:*)
|
||||||
|
- No changes to source code or runtime behavior; tooling/config only
|
||||||
|
|
||||||
|
## 2025-07-29 - 2.0.25 - fix(core)
|
||||||
|
Major state initialization and validation improvements
|
||||||
|
|
||||||
|
- Fixed state hash bug: Now properly compares hash values instead of storing state objects
|
||||||
|
- Fixed state initialization merge order: Initial state now correctly takes precedence over stored state
|
||||||
|
- Improved type safety: stateStore properly typed as potentially undefined
|
||||||
|
- Simplified init mode logic with clear behavior for 'soft', 'mandatory', 'force', and 'persistent'
|
||||||
|
- Added state validation with extensible validateState() method
|
||||||
|
- Made notifyChange() async to support proper hash comparison
|
||||||
|
- Enhanced select() to filter undefined states automatically
|
||||||
|
- Added comprehensive test suite for state initialization scenarios
|
||||||
|
- Updated documentation with clearer examples and improved readme
|
||||||
|
|
||||||
|
## 2025-07-19 - 2.0.24 - fix(core)
|
||||||
|
Multiple fixes and improvements
|
||||||
|
|
||||||
|
- Fixed StateAction trigger method to properly return Promise<TStateType>
|
||||||
|
- Updated CI workflows to use new container registry and npmci package name
|
||||||
|
- Added pnpm workspace configuration for built-only dependencies
|
||||||
|
|
||||||
|
## 2025-07-19 - 2.0.23 - fix(ci)
|
||||||
|
Update CI workflows to use new container registry and npmci package name
|
||||||
|
|
||||||
|
- Changed CI image from 'registry.gitlab.com/hosttoday/ht-docker-node:npmci' to 'code.foss.global/host.today/ht-docker-node:npmci'
|
||||||
|
- Replaced npmci installation command from '@shipzone/npmci' to '@ship.zone/npmci' in workflow configurations
|
||||||
|
|
||||||
|
## 2025-07-19 - 2.0.22 - fix(smartstate)
|
||||||
|
Fix StateAction trigger method to properly return Promise
|
||||||
|
|
||||||
|
- Fixed StateAction.trigger() to return Promise<TStateType> as expected
|
||||||
|
- Updated readme with improved documentation and examples
|
||||||
|
- Replaced outdated legal information with Task Venture Capital GmbH details
|
||||||
|
- Added implementation notes in readme.hints.md
|
||||||
|
|
||||||
|
## 2025-06-19 - 2.0.21 - maintenance
|
||||||
|
General updates and improvements
|
||||||
|
|
||||||
|
## 2025-06-19 - 2.0.20 - fix(smartstate)
|
||||||
|
Update build scripts and dependency versions; replace isohash with smarthashWeb for state hash generation
|
||||||
|
|
||||||
|
- Adjusted package.json scripts to include verbose testing and modified build command
|
||||||
|
- Bumped development dependencies (tsbuild, tsbundle, tsrun, tstest, tapbundle) to newer versions
|
||||||
|
- Updated production dependencies (lik, smarthash, smartpromise, smartrx) with minor version bumps
|
||||||
|
- Replaced import of isohash with smarthashWeb in state hash generation, ensuring consistency across modules
|
||||||
|
|
||||||
|
## 2024-10-02 - 2.0.19 - fix(dependencies)
|
||||||
|
Update dependencies to latest versions
|
||||||
|
|
||||||
|
- Updated @git.zone/tsbuild to version ^2.1.84
|
||||||
|
- Updated @git.zone/tsbundle to version ^2.0.15
|
||||||
|
- Updated @git.zone/tsrun to version ^1.2.49
|
||||||
|
- Updated @git.zone/tstest to version ^1.0.90
|
||||||
|
- Updated @push.rocks/tapbundle to version ^5.3.0
|
||||||
|
- Updated @types/node to version ^22.7.4
|
||||||
|
- Updated @push.rocks/lik to version ^6.0.15
|
||||||
|
- Updated @push.rocks/smartjson to version ^5.0.20
|
||||||
|
- Updated @push.rocks/smartpromise to version ^4.0.4
|
||||||
|
- Updated @push.rocks/smartrx to version ^3.0.7
|
||||||
|
- Updated @push.rocks/webstore to version ^2.0.20
|
||||||
|
|
||||||
|
## 2024-10-02 - 2.0.18 - fix(core)
|
||||||
|
Fix type errors and typos in Smartstate class
|
||||||
|
|
||||||
|
- Updated type annotation in Smartstate class to ensure StatePartNameType extends string.
|
||||||
|
- Fixed a typo in the JSDoc comment: 'existing' instead of 'exiting'.
|
||||||
|
- Corrected improper type casting in the Smartstate class.
|
||||||
|
|
||||||
|
## 2024-05-29 - 2.0.17 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Updated project description
|
||||||
|
- Multiple updates to `tsconfig`
|
||||||
|
- Updated `npmextra.json` to include `githost`
|
||||||
|
|
||||||
|
## 2023-10-07 - 2.0.16 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2023-10-04 - 2.0.15 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2023-10-03 - 2.0.14 to 2.0.10 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core updates
|
||||||
|
|
||||||
|
## 2023-09-11 - 2.0.9 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2023-09-11 - 2.0.8 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2023-07-27 - 2.0.7 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2023-07-27 - 2.0.6 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2023-04-13 - 2.0.5 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2023-04-12 - 2.0.4 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2023-04-04 - 2.0.3 to 2.0.1 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core updates
|
||||||
|
|
||||||
|
## 2023-03-15 - 2.0.0 - Major Update
|
||||||
|
Core update with significant changes.
|
||||||
|
|
||||||
|
## 2022-03-25 - 1.0.23 - Major Update
|
||||||
|
Breaking changes and major updates.
|
||||||
|
|
||||||
|
- SWITCH TO ESM
|
||||||
|
|
||||||
|
## 2022-01-24 - 1.0.22 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core updates
|
||||||
|
|
||||||
|
## 2020-11-30 - 1.0.21 to 1.0.20 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core updates
|
||||||
|
|
||||||
|
## 2020-11-30 - 1.0.19 to 1.0.18 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core updates
|
||||||
|
|
||||||
|
## 2020-07-27 - 1.0.17 to 1.0.16 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core updates
|
||||||
|
|
||||||
|
## 2020-05-27 - 1.0.15 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2020-05-27 - 1.0.14 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2019-09-25 - 1.0.13 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2019-09-25 - 1.0.12 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core updates
|
||||||
|
|
||||||
|
## 2019-04-30 - 1.0.11 to 1.0.10 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core updates
|
||||||
|
|
||||||
|
## 2019-03-22 - 1.0.9 - Maintenance
|
||||||
|
General updates and improvements.
|
||||||
|
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2019-02-27 - 1.0.8 - Minor Update
|
||||||
|
Minor updates and improvements.
|
||||||
|
|
||||||
|
- Updated action generation
|
||||||
|
- Core update
|
||||||
|
|
||||||
|
## 2019-02-21 - 1.0.7 - Initial Release
|
||||||
|
Initial release of the project.
|
||||||
|
|
||||||
|
- Initial core implementation
|
||||||
2
license
2
license
@@ -1,4 +1,4 @@
|
|||||||
Copyright (c) 2019 Lossless GmbH (hello@lossless.com)
|
Copyright (c) 2019 Task Venture Capital GmbH (hello@task.vc)
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
|||||||
@@ -1,16 +1,49 @@
|
|||||||
{
|
{
|
||||||
"npmci": {
|
"@git.zone/tsbundle": {
|
||||||
"npmGlobalTools": [],
|
"bundles": [
|
||||||
"npmAccessLevel": "public"
|
{
|
||||||
|
"from": "./ts/index.ts",
|
||||||
|
"to": "./dist_bundle/bundle.js",
|
||||||
|
"outputMode": "bundle",
|
||||||
|
"bundler": "esbuild",
|
||||||
|
"production": true
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"gitzone": {
|
"@git.zone/cli": {
|
||||||
|
"projectType": "npm",
|
||||||
"module": {
|
"module": {
|
||||||
"githost": "gitlab.com",
|
"githost": "code.foss.global",
|
||||||
"gitscope": "pushrocks",
|
"gitscope": "push.rocks",
|
||||||
"gitrepo": "smartstate",
|
"gitrepo": "smartstate",
|
||||||
"shortDescription": "a package that handles state in a good way",
|
"description": "A package for handling and managing state in applications.",
|
||||||
"npmPackagename": "@pushrocks/smartstate",
|
"npmPackagename": "@push.rocks/smartstate",
|
||||||
"license": "MIT"
|
"license": "MIT",
|
||||||
|
"keywords": [
|
||||||
|
"state management",
|
||||||
|
"reactive programming",
|
||||||
|
"TypeScript",
|
||||||
|
"observables",
|
||||||
|
"web storage",
|
||||||
|
"state action",
|
||||||
|
"state selection",
|
||||||
|
"state notification",
|
||||||
|
"asynchronous state",
|
||||||
|
"cumulative notification"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"release": {
|
||||||
|
"registries": [
|
||||||
|
"https://verdaccio.lossless.digital",
|
||||||
|
"https://registry.npmjs.org"
|
||||||
|
],
|
||||||
|
"accessLevel": "public"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"@git.zone/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"
|
||||||
|
},
|
||||||
|
"@ship.zone/szci": {
|
||||||
|
"npmGlobalTools": []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
17898
package-lock.json
generated
17898
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
72
package.json
72
package.json
@@ -1,27 +1,65 @@
|
|||||||
{
|
{
|
||||||
"name": "@pushrocks/smartstate",
|
"name": "@push.rocks/smartstate",
|
||||||
"version": "1.0.8",
|
"version": "2.0.30",
|
||||||
"private": false,
|
"private": false,
|
||||||
"description": "a package that handles state in a good way",
|
"description": "A package for handling and managing state in applications.",
|
||||||
"main": "dist/index.js",
|
"main": "dist_ts/index.js",
|
||||||
"typings": "dist/index.d.ts",
|
"typings": "dist_ts/index.d.ts",
|
||||||
|
"type": "module",
|
||||||
"author": "Lossless GmbH",
|
"author": "Lossless GmbH",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "(tstest test/)",
|
"test": "(tstest test/ --verbose)",
|
||||||
"build": "(tsbuild)",
|
"build": "(tsbuild tsfolders --allowimplicitany && tsbundle npm)",
|
||||||
"format": "(gitzone format)"
|
"buildDocs": "tsdoc"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@gitzone/tsbuild": "^2.1.8",
|
"@git.zone/tsbuild": "^4.1.2",
|
||||||
"@gitzone/tstest": "^1.0.15",
|
"@git.zone/tsbundle": "^2.8.3",
|
||||||
"@pushrocks/tapbundle": "^3.0.7",
|
"@git.zone/tsrun": "^2.0.1",
|
||||||
"@types/node": "^11.9.4",
|
"@git.zone/tstest": "^3.1.8",
|
||||||
"tslint": "^5.12.1",
|
"@push.rocks/tapbundle": "^6.0.3",
|
||||||
"tslint-config-prettier": "^1.18.0"
|
"@types/node": "^25.2.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@pushrocks/lik": "^3.0.4",
|
"@push.rocks/lik": "^6.2.2",
|
||||||
"rxjs": "^6.4.0"
|
"@push.rocks/smarthash": "^3.2.6",
|
||||||
}
|
"@push.rocks/smartjson": "^6.0.0",
|
||||||
|
"@push.rocks/smartpromise": "^4.2.3",
|
||||||
|
"@push.rocks/smartrx": "^3.0.10",
|
||||||
|
"@push.rocks/webstore": "^2.0.20"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"ts/**/*",
|
||||||
|
"ts_web/**/*",
|
||||||
|
"dist/**/*",
|
||||||
|
"dist_*/**/*",
|
||||||
|
"dist_ts/**/*",
|
||||||
|
"dist_ts_web/**/*",
|
||||||
|
"assets/**/*",
|
||||||
|
"cli.js",
|
||||||
|
"npmextra.json",
|
||||||
|
"readme.md"
|
||||||
|
],
|
||||||
|
"browserslist": [
|
||||||
|
"last 1 chrome versions"
|
||||||
|
],
|
||||||
|
"keywords": [
|
||||||
|
"state management",
|
||||||
|
"reactive programming",
|
||||||
|
"TypeScript",
|
||||||
|
"observables",
|
||||||
|
"web storage",
|
||||||
|
"state action",
|
||||||
|
"state selection",
|
||||||
|
"state notification",
|
||||||
|
"asynchronous state",
|
||||||
|
"cumulative notification"
|
||||||
|
],
|
||||||
|
"homepage": "https://code.foss.global/push.rocks/smartstate",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://code.foss.global/push.rocks/smartstate.git"
|
||||||
|
},
|
||||||
|
"packageManager": "pnpm@10.11.0+sha512.6540583f41cc5f628eb3d9773ecee802f4f9ef9923cc45b69890fb47991d4b092964694ec3a4f738a420c918a333062c8b925d312f42e4f0c263eb603551f977"
|
||||||
}
|
}
|
||||||
|
|||||||
60
readme.hints.md
Normal file
60
readme.hints.md
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
# Smartstate Implementation Notes
|
||||||
|
|
||||||
|
## Current API (as of v2.0.28+)
|
||||||
|
|
||||||
|
### State Part Initialization
|
||||||
|
- State parts can be created with different init modes: 'soft' (default), 'mandatory', 'force', 'persistent'
|
||||||
|
- 'soft' - returns existing state part if exists, creates new if not
|
||||||
|
- 'mandatory' - requires state part to not exist, fails if it does
|
||||||
|
- 'force' - always creates new state part, overwriting any existing
|
||||||
|
- 'persistent' - like 'soft' but with WebStore persistence (IndexedDB)
|
||||||
|
- Persistent mode automatically calls init() internally - no need to call it manually
|
||||||
|
- State merge order fixed: initial state takes precedence over stored state
|
||||||
|
|
||||||
|
### Actions
|
||||||
|
- Actions are created with `createAction()` method
|
||||||
|
- Two ways to dispatch actions:
|
||||||
|
1. `stateAction.trigger(payload)` - returns Promise<TStatePayload>
|
||||||
|
2. `await statePart.dispatchAction(stateAction, payload)` - returns Promise<TStatePayload>
|
||||||
|
- Both methods return the same Promise, providing flexibility in usage
|
||||||
|
|
||||||
|
### State Management Methods
|
||||||
|
- `select()` - returns Observable with startWith current state, filters undefined states
|
||||||
|
- `waitUntilPresent()` - waits for specific state condition
|
||||||
|
- `stateSetup()` - async state initialization with cumulative defer
|
||||||
|
- `notifyChangeCumulative()` - defers notification to end of call stack
|
||||||
|
- `getState()` - returns current state or undefined
|
||||||
|
- `setState()` - validates state before setting, notifies only on actual changes
|
||||||
|
|
||||||
|
### State Hash Detection
|
||||||
|
- Uses SHA256 hash to detect actual state changes
|
||||||
|
- Fixed: Hash comparison now properly awaits async hash calculation
|
||||||
|
- Prevents duplicate notifications for identical state values
|
||||||
|
- `notifyChange()` is now async to support proper hash comparison
|
||||||
|
|
||||||
|
### State Validation
|
||||||
|
- Basic validation ensures state is not null/undefined
|
||||||
|
- `validateState()` method can be overridden in subclasses for custom validation
|
||||||
|
- Validation runs on both setState() and when loading from persistent storage
|
||||||
|
|
||||||
|
### Type System
|
||||||
|
- Can use either enums or string literal types for state part names
|
||||||
|
- Test uses simple string types: `type TMyStateParts = 'testStatePart'`
|
||||||
|
- State can be undefined initially, handled properly in select() and other methods
|
||||||
|
|
||||||
|
## Recent Fixes (v2.0.24+)
|
||||||
|
1. Fixed state hash bug - now properly compares hash values instead of promises
|
||||||
|
2. Fixed state initialization merge order - initial state now takes precedence
|
||||||
|
3. Ensured stateStore is properly typed as potentially undefined
|
||||||
|
4. Simplified init mode logic with clear behavior for each mode
|
||||||
|
5. Added state validation with extensible validateState() method
|
||||||
|
6. Made notifyChange() async to support proper hash comparison
|
||||||
|
7. Updated select() to filter undefined states
|
||||||
|
|
||||||
|
## Dependency Versions (v2.0.28)
|
||||||
|
- @git.zone/tsbuild: ^4.1.2
|
||||||
|
- @git.zone/tsbundle: ^2.8.3
|
||||||
|
- @git.zone/tsrun: ^2.0.1
|
||||||
|
- @git.zone/tstest: ^3.1.8
|
||||||
|
- @push.rocks/smartjson: ^6.0.0
|
||||||
|
- @types/node: ^25.2.0
|
||||||
343
readme.md
343
readme.md
@@ -1,26 +1,331 @@
|
|||||||
# @pushrocks/smartstate
|
# @push.rocks/smartstate
|
||||||
a package that handles state in a good way
|
|
||||||
|
|
||||||
## Availabililty and Links
|
A powerful TypeScript library for elegant state management using RxJS and reactive programming patterns 🚀
|
||||||
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartstate)
|
|
||||||
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartstate)
|
|
||||||
* [github.com (source mirror)](https://github.com/pushrocks/smartstate)
|
|
||||||
* [docs (typedoc)](https://pushrocks.gitlab.io/smartstate/)
|
|
||||||
|
|
||||||
## Status for master
|
## Issue Reporting and Security
|
||||||
[](https://gitlab.com/pushrocks/smartstate/commits/master)
|
|
||||||
[](https://gitlab.com/pushrocks/smartstate/commits/master)
|
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||||
[](https://www.npmjs.com/package/@pushrocks/smartstate)
|
|
||||||
[](https://snyk.io/test/npm/@pushrocks/smartstate)
|
## Install
|
||||||
[](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
|
||||||
[](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
To install `@push.rocks/smartstate`, you can use pnpm, npm, or yarn:
|
||||||
[](https://prettier.io/)
|
|
||||||
|
```bash
|
||||||
|
# Using pnpm (recommended)
|
||||||
|
pnpm install @push.rocks/smartstate --save
|
||||||
|
|
||||||
|
# Using npm
|
||||||
|
npm install @push.rocks/smartstate --save
|
||||||
|
|
||||||
|
# Using yarn
|
||||||
|
yarn add @push.rocks/smartstate
|
||||||
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
For further information read the linked docs at the top of this readme.
|
The `@push.rocks/smartstate` library provides an elegant way to handle state within your JavaScript or TypeScript projects, leveraging the power of Reactive Extensions (RxJS) and a structured state management strategy.
|
||||||
|
|
||||||
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
|
### Getting Started
|
||||||
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)
|
|
||||||
|
|
||||||
[](https://maintainedby.lossless.com)
|
Import the necessary components from the library:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Smartstate, StatePart, StateAction } from '@push.rocks/smartstate';
|
||||||
|
```
|
||||||
|
|
||||||
|
### Creating a SmartState Instance
|
||||||
|
|
||||||
|
`Smartstate` acts as the container for your state parts. Think of it as the root of your state management structure:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const myAppSmartState = new Smartstate<YourStatePartNamesEnum>();
|
||||||
|
```
|
||||||
|
|
||||||
|
### Understanding Init Modes
|
||||||
|
|
||||||
|
When creating state parts, you can specify different initialization modes:
|
||||||
|
|
||||||
|
| Mode | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| `'soft'` | Default. Returns existing state part if it exists, creates new if not |
|
||||||
|
| `'mandatory'` | Requires state part to not exist, throws error if it does |
|
||||||
|
| `'force'` | Always creates new state part, overwriting any existing one |
|
||||||
|
| `'persistent'` | Like 'soft' but with WebStore persistence using IndexedDB |
|
||||||
|
|
||||||
|
### Defining State Parts
|
||||||
|
|
||||||
|
State parts represent separable sections of your state, making it easier to manage and modularize. Define state part names using either enums or string literal types:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Option 1: Using enums
|
||||||
|
enum AppStateParts {
|
||||||
|
UserState = 'UserState',
|
||||||
|
SettingsState = 'SettingsState'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Option 2: Using string literal types (simpler approach)
|
||||||
|
type AppStateParts = 'UserState' | 'SettingsState';
|
||||||
|
```
|
||||||
|
|
||||||
|
Create a state part within your `Smartstate` instance:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface IUserState {
|
||||||
|
isLoggedIn: boolean;
|
||||||
|
username?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userStatePart = await myAppSmartState.getStatePart<IUserState>(
|
||||||
|
AppStateParts.UserState,
|
||||||
|
{ isLoggedIn: false }, // Initial state
|
||||||
|
'soft' // Init mode (optional, defaults to 'soft')
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Subscribing to State Changes
|
||||||
|
|
||||||
|
Subscribe to changes in a state part to perform actions accordingly:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// The select() method automatically filters out undefined states
|
||||||
|
userStatePart.select().subscribe((currentState) => {
|
||||||
|
console.log(`User Logged In: ${currentState.isLoggedIn}`);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Select a specific part of your state with a selector function:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
userStatePart.select(state => state.username).subscribe((username) => {
|
||||||
|
if (username) {
|
||||||
|
console.log(`Current user: ${username}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Modifying State with Actions
|
||||||
|
|
||||||
|
Create actions to modify the state in a controlled manner:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface ILoginPayload {
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const loginUserAction = userStatePart.createAction<ILoginPayload>(async (statePart, payload) => {
|
||||||
|
return { ...statePart.getState(), isLoggedIn: true, username: payload.username };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Dispatch the action to update the state
|
||||||
|
const newState = await loginUserAction.trigger({ username: 'johnDoe' });
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dispatching Actions
|
||||||
|
|
||||||
|
There are two ways to dispatch actions:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Method 1: Using trigger on the action (returns promise)
|
||||||
|
const newState = await loginUserAction.trigger({ username: 'johnDoe' });
|
||||||
|
|
||||||
|
// Method 2: Using dispatchAction on the state part (returns promise)
|
||||||
|
const newState = await userStatePart.dispatchAction(loginUserAction, { username: 'johnDoe' });
|
||||||
|
```
|
||||||
|
|
||||||
|
Both methods return a Promise with the new state payload.
|
||||||
|
|
||||||
|
### Additional State Methods
|
||||||
|
|
||||||
|
`StatePart` provides several useful methods for state management:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Get current state (may be undefined initially)
|
||||||
|
const currentState = userStatePart.getState();
|
||||||
|
if (currentState) {
|
||||||
|
console.log('Current user:', currentState.username);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for state to be present
|
||||||
|
await userStatePart.waitUntilPresent();
|
||||||
|
|
||||||
|
// Wait for a specific property to be present
|
||||||
|
await userStatePart.waitUntilPresent(state => state.username);
|
||||||
|
|
||||||
|
// Wait with a timeout (throws error if condition not met within timeout)
|
||||||
|
try {
|
||||||
|
await userStatePart.waitUntilPresent(state => state.username, 5000); // 5 second timeout
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Timed out waiting for username');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup initial state with async operations
|
||||||
|
await userStatePart.stateSetup(async (statePart) => {
|
||||||
|
const userData = await fetchUserData();
|
||||||
|
return { ...statePart.getState(), ...userData };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Defer notification to end of call stack (debounced)
|
||||||
|
userStatePart.notifyChangeCumulative();
|
||||||
|
```
|
||||||
|
|
||||||
|
### Persistent State with WebStore
|
||||||
|
|
||||||
|
`Smartstate` supports persistent states using WebStore (IndexedDB-based storage), allowing you to maintain state across sessions:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const settingsStatePart = await myAppSmartState.getStatePart<ISettingsState>(
|
||||||
|
AppStateParts.SettingsState,
|
||||||
|
{ theme: 'light' }, // Initial/default state
|
||||||
|
'persistent' // Mode
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
Persistent state automatically:
|
||||||
|
- Saves state changes to IndexedDB
|
||||||
|
- Restores state on application restart
|
||||||
|
- Merges persisted values with defaults (persisted values take precedence)
|
||||||
|
- Ensures atomic writes (persistence happens before memory update)
|
||||||
|
|
||||||
|
### State Validation
|
||||||
|
|
||||||
|
`Smartstate` includes built-in state validation to ensure data integrity:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Basic validation (built-in) ensures state is not null or undefined
|
||||||
|
await userStatePart.setState(null); // Throws error: Invalid state structure
|
||||||
|
|
||||||
|
// Custom validation by extending StatePart
|
||||||
|
class ValidatedStatePart<T> extends StatePart<string, T> {
|
||||||
|
protected validateState(stateArg: any): stateArg is T {
|
||||||
|
return super.validateState(stateArg) && /* your validation */;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Performance Optimization
|
||||||
|
|
||||||
|
`Smartstate` includes advanced performance optimizations:
|
||||||
|
|
||||||
|
- **🔒 Async State Hash Detection**: Uses SHA256 hashing to detect actual state changes, preventing unnecessary notifications when state values haven't truly changed
|
||||||
|
- **🚫 Duplicate Prevention**: Identical state updates are automatically filtered out
|
||||||
|
- **📦 Cumulative Notifications**: Batch multiple state changes into a single notification using `notifyChangeCumulative()` with automatic debouncing
|
||||||
|
- **🎯 Selective Subscriptions**: Use selectors to subscribe only to specific state properties
|
||||||
|
- **✨ Undefined State Filtering**: The `select()` method automatically filters out undefined states
|
||||||
|
- **⚡ Concurrent Access Safety**: Prevents race conditions when multiple calls request the same state part simultaneously
|
||||||
|
|
||||||
|
### RxJS Integration
|
||||||
|
|
||||||
|
`Smartstate` leverages RxJS for reactive state management:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// State is exposed as an RxJS Subject
|
||||||
|
const stateObservable = userStatePart.select();
|
||||||
|
|
||||||
|
// Automatically starts with current state value
|
||||||
|
stateObservable.subscribe((state) => {
|
||||||
|
console.log('Current state:', state);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Use selectors for specific properties
|
||||||
|
userStatePart.select(state => state.username)
|
||||||
|
.pipe(
|
||||||
|
distinctUntilChanged(),
|
||||||
|
filter(username => username !== undefined)
|
||||||
|
)
|
||||||
|
.subscribe(username => {
|
||||||
|
console.log('Username changed:', username);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Complete Example
|
||||||
|
|
||||||
|
Here's a comprehensive example showcasing the power of `@push.rocks/smartstate`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Smartstate, StatePart, StateAction } from '@push.rocks/smartstate';
|
||||||
|
|
||||||
|
// Define your state structure
|
||||||
|
type AppStateParts = 'user' | 'settings' | 'cart';
|
||||||
|
|
||||||
|
interface IUserState {
|
||||||
|
isLoggedIn: boolean;
|
||||||
|
username?: string;
|
||||||
|
email?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ICartState {
|
||||||
|
items: Array<{ id: string; quantity: number }>;
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create the smartstate instance
|
||||||
|
const appState = new Smartstate<AppStateParts>();
|
||||||
|
|
||||||
|
// Initialize state parts
|
||||||
|
const userState = await appState.getStatePart<IUserState>('user', {
|
||||||
|
isLoggedIn: false
|
||||||
|
});
|
||||||
|
|
||||||
|
const cartState = await appState.getStatePart<ICartState>('cart', {
|
||||||
|
items: [],
|
||||||
|
total: 0
|
||||||
|
}, 'persistent'); // Persists across sessions
|
||||||
|
|
||||||
|
// Create actions
|
||||||
|
const loginAction = userState.createAction<{ username: string; email: string }>(
|
||||||
|
async (statePart, payload) => {
|
||||||
|
// Simulate API call
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||||
|
|
||||||
|
return {
|
||||||
|
isLoggedIn: true,
|
||||||
|
username: payload.username,
|
||||||
|
email: payload.email
|
||||||
|
};
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Subscribe to changes
|
||||||
|
userState.select(state => state.isLoggedIn).subscribe(isLoggedIn => {
|
||||||
|
console.log('Login status changed:', isLoggedIn);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Dispatch actions
|
||||||
|
await loginAction.trigger({ username: 'john', email: 'john@example.com' });
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Features
|
||||||
|
|
||||||
|
| Feature | Description |
|
||||||
|
|---------|-------------|
|
||||||
|
| 🎯 **Type-safe** | Full TypeScript support with intelligent type inference |
|
||||||
|
| ⚡ **Performance optimized** | Async state hash detection prevents unnecessary re-renders |
|
||||||
|
| 💾 **Persistent state** | Built-in IndexedDB support for state persistence |
|
||||||
|
| 🔄 **Reactive** | Powered by RxJS for elegant async handling |
|
||||||
|
| 🧩 **Modular** | Organize state into logical, reusable parts |
|
||||||
|
| ✅ **Validated** | Built-in state validation with extensible validation logic |
|
||||||
|
| 🎭 **Flexible init modes** | Choose how state parts are initialized |
|
||||||
|
| 📦 **Zero config** | Works out of the box with sensible defaults |
|
||||||
|
| 🛡️ **Race condition safe** | Concurrent state part creation is handled safely |
|
||||||
|
| ⏱️ **Timeout support** | `waitUntilPresent` supports optional timeouts |
|
||||||
|
|
||||||
|
## License and Legal Information
|
||||||
|
|
||||||
|
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
|
||||||
|
|
||||||
|
**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 or third parties, 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 or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||||||
|
|
||||||
|
### Company Information
|
||||||
|
|
||||||
|
Task Venture Capital GmbH
|
||||||
|
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||||
|
|
||||||
|
For any legal inquiries or 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.
|
||||||
|
|||||||
157
test/test.initialization.ts
Normal file
157
test/test.initialization.ts
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
import { expect, tap } from '@push.rocks/tapbundle';
|
||||||
|
import * as smartstate from '../ts/index.js';
|
||||||
|
|
||||||
|
type TTestStateParts = 'initTest' | 'persistTest' | 'forceTest';
|
||||||
|
|
||||||
|
interface ITestState {
|
||||||
|
value: number;
|
||||||
|
nested: {
|
||||||
|
data: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
tap.test('should handle soft init mode (default)', async () => {
|
||||||
|
const state = new smartstate.Smartstate<TTestStateParts>();
|
||||||
|
|
||||||
|
// First creation
|
||||||
|
const statePart1 = await state.getStatePart<ITestState>('initTest', {
|
||||||
|
value: 1,
|
||||||
|
nested: { data: 'initial' }
|
||||||
|
});
|
||||||
|
expect(statePart1.getState()).toEqual({
|
||||||
|
value: 1,
|
||||||
|
nested: { data: 'initial' }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Second call should return existing
|
||||||
|
const statePart2 = await state.getStatePart<ITestState>('initTest');
|
||||||
|
expect(statePart1).toEqual(statePart2);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('should handle mandatory init mode', async () => {
|
||||||
|
const state = new smartstate.Smartstate<TTestStateParts>();
|
||||||
|
|
||||||
|
// First creation should succeed
|
||||||
|
const statePart1 = await state.getStatePart<ITestState>('initTest', {
|
||||||
|
value: 1,
|
||||||
|
nested: { data: 'initial' }
|
||||||
|
}, 'mandatory');
|
||||||
|
expect(statePart1).toBeInstanceOf(smartstate.StatePart);
|
||||||
|
|
||||||
|
// Second call with mandatory should fail
|
||||||
|
let error: Error | null = null;
|
||||||
|
try {
|
||||||
|
await state.getStatePart<ITestState>('initTest', {
|
||||||
|
value: 2,
|
||||||
|
nested: { data: 'second' }
|
||||||
|
}, 'mandatory');
|
||||||
|
} catch (e) {
|
||||||
|
error = e as Error;
|
||||||
|
}
|
||||||
|
expect(error).not.toBeNull();
|
||||||
|
expect(error?.message).toMatch(/already exists.*mandatory/);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('should handle force init mode', async () => {
|
||||||
|
const state = new smartstate.Smartstate<TTestStateParts>();
|
||||||
|
|
||||||
|
// First creation
|
||||||
|
const statePart1 = await state.getStatePart<ITestState>('forceTest', {
|
||||||
|
value: 1,
|
||||||
|
nested: { data: 'initial' }
|
||||||
|
});
|
||||||
|
expect(statePart1.getState()?.value).toEqual(1);
|
||||||
|
|
||||||
|
// Force should create new state part
|
||||||
|
const statePart2 = await state.getStatePart<ITestState>('forceTest', {
|
||||||
|
value: 2,
|
||||||
|
nested: { data: 'forced' }
|
||||||
|
}, 'force');
|
||||||
|
expect(statePart2.getState()?.value).toEqual(2);
|
||||||
|
expect(statePart1).not.toEqual(statePart2);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('should handle missing initial state error', async () => {
|
||||||
|
const state = new smartstate.Smartstate<TTestStateParts>();
|
||||||
|
|
||||||
|
let error: Error | null = null;
|
||||||
|
try {
|
||||||
|
await state.getStatePart<ITestState>('initTest');
|
||||||
|
} catch (e) {
|
||||||
|
error = e as Error;
|
||||||
|
}
|
||||||
|
expect(error).not.toBeNull();
|
||||||
|
expect(error?.message).toMatch(/does not exist.*no initial state/);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('should handle state validation', async () => {
|
||||||
|
const state = new smartstate.Smartstate<TTestStateParts>();
|
||||||
|
|
||||||
|
const statePart = await state.getStatePart<ITestState>('initTest', {
|
||||||
|
value: 1,
|
||||||
|
nested: { data: 'initial' }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Setting null should fail validation
|
||||||
|
let error: Error | null = null;
|
||||||
|
try {
|
||||||
|
await statePart.setState(null as any);
|
||||||
|
} catch (e) {
|
||||||
|
error = e as Error;
|
||||||
|
}
|
||||||
|
expect(error).not.toBeNull();
|
||||||
|
expect(error?.message).toMatch(/Invalid state structure/);
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('should handle undefined state in select', async () => {
|
||||||
|
const state = new smartstate.Smartstate<TTestStateParts>();
|
||||||
|
const statePart = new smartstate.StatePart<TTestStateParts, ITestState>('initTest');
|
||||||
|
|
||||||
|
// Select should filter out undefined states
|
||||||
|
const values: (ITestState | undefined)[] = [];
|
||||||
|
statePart.select().subscribe(val => values.push(val));
|
||||||
|
|
||||||
|
// Initially undefined, should not emit
|
||||||
|
expect(values).toHaveLength(0);
|
||||||
|
|
||||||
|
// After setting state, should emit
|
||||||
|
await statePart.setState({
|
||||||
|
value: 1,
|
||||||
|
nested: { data: 'test' }
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(values).toHaveLength(1);
|
||||||
|
expect(values[0]).toEqual({
|
||||||
|
value: 1,
|
||||||
|
nested: { data: 'test' }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
tap.test('should not notify on duplicate state', async () => {
|
||||||
|
const state = new smartstate.Smartstate<TTestStateParts>();
|
||||||
|
const statePart = await state.getStatePart<ITestState>('initTest', {
|
||||||
|
value: 1,
|
||||||
|
nested: { data: 'initial' }
|
||||||
|
});
|
||||||
|
|
||||||
|
let notificationCount = 0;
|
||||||
|
// Use select() to get initial value + changes
|
||||||
|
statePart.select().subscribe(() => notificationCount++);
|
||||||
|
|
||||||
|
// Should have received initial state
|
||||||
|
expect(notificationCount).toEqual(1);
|
||||||
|
|
||||||
|
// Set same state multiple times
|
||||||
|
await statePart.setState({ value: 1, nested: { data: 'initial' } });
|
||||||
|
await statePart.setState({ value: 1, nested: { data: 'initial' } });
|
||||||
|
await statePart.setState({ value: 1, nested: { data: 'initial' } });
|
||||||
|
|
||||||
|
// Should still be 1 (no new notifications for duplicate state)
|
||||||
|
expect(notificationCount).toEqual(1);
|
||||||
|
|
||||||
|
// Change state should notify
|
||||||
|
await statePart.setState({ value: 2, nested: { data: 'changed' } });
|
||||||
|
expect(notificationCount).toEqual(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default tap.start();
|
||||||
41
test/test.ts
41
test/test.ts
@@ -1,5 +1,5 @@
|
|||||||
import { expect, tap } from '@pushrocks/tapbundle';
|
import { expect, tap } from '@push.rocks/tapbundle';
|
||||||
import * as smartstate from '../ts/index';
|
import * as smartstate from '../ts/index.js';
|
||||||
|
|
||||||
type TMyStateParts = 'testStatePart';
|
type TMyStateParts = 'testStatePart';
|
||||||
interface TStatePartPayload {
|
interface TStatePartPayload {
|
||||||
@@ -14,28 +14,45 @@ let testStatePart: smartstate.StatePart<TMyStateParts, TStatePartPayload>;
|
|||||||
|
|
||||||
tap.test('should create a new SmartState', async () => {
|
tap.test('should create a new SmartState', async () => {
|
||||||
testState = new smartstate.Smartstate<TMyStateParts>();
|
testState = new smartstate.Smartstate<TMyStateParts>();
|
||||||
expect(testState).to.be.instanceOf(smartstate.Smartstate);
|
expect(testState).toBeInstanceOf(smartstate.Smartstate);
|
||||||
});
|
});
|
||||||
|
|
||||||
tap.test('should create a new StatePart', async () => {
|
tap.test('should create a new StatePart', async () => {
|
||||||
testStatePart = testState.getStatePart<TStatePartPayload>('testStatePart', {
|
testStatePart = await testState.getStatePart<TStatePartPayload>('testStatePart', {
|
||||||
currentFavorites: [],
|
currentFavorites: [],
|
||||||
deep: {
|
deep: {
|
||||||
hi: 2
|
hi: 2,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
expect(testStatePart).to.be.instanceOf(smartstate.StatePart);
|
expect(testStatePart).toBeInstanceOf(smartstate.StatePart);
|
||||||
console.log(testStatePart);
|
console.log(testStatePart);
|
||||||
});
|
});
|
||||||
|
|
||||||
tap.test('should select something', async () => {
|
tap.test('should select something', async () => {
|
||||||
testStatePart
|
testStatePart
|
||||||
.select(state => state.deep)
|
.select((state) => state.deep.hi)
|
||||||
.subscribe(substate => {
|
.subscribe((substate) => {
|
||||||
console.log(substate);
|
expect(substate).toEqual(2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
tap.test('should dispatch a state action', async () => {});
|
tap.test('should dispatch a state action', async (tools) => {
|
||||||
|
const done = tools.defer();
|
||||||
|
const addFavourite = testStatePart.createAction<string>(async (statePart, payload) => {
|
||||||
|
const currentState = statePart.getState();
|
||||||
|
currentState.currentFavorites.push(payload);
|
||||||
|
return currentState;
|
||||||
|
});
|
||||||
|
testStatePart
|
||||||
|
.waitUntilPresent((state) => {
|
||||||
|
return state.currentFavorites[0];
|
||||||
|
})
|
||||||
|
.then(() => {
|
||||||
|
done.resolve();
|
||||||
|
});
|
||||||
|
await testStatePart.dispatchAction(addFavourite, 'my favourite things');
|
||||||
|
expect(testStatePart.getState().currentFavorites).toContain('my favourite things');
|
||||||
|
await done.promise;
|
||||||
|
});
|
||||||
|
|
||||||
tap.start();
|
export default tap.start();
|
||||||
|
|||||||
8
ts/00_commitinfo_data.ts
Normal file
8
ts/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* autocreated commitinfo by @push.rocks/commitinfo
|
||||||
|
*/
|
||||||
|
export const commitinfo = {
|
||||||
|
name: '@push.rocks/smartstate',
|
||||||
|
version: '2.0.30',
|
||||||
|
description: 'A package for handling and managing state in applications.'
|
||||||
|
}
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
export * from './smartstate.classes.smartstate';
|
export * from './smartstate.classes.smartstate.js';
|
||||||
export * from './smartstate.classes.statepart';
|
export * from './smartstate.classes.statepart.js';
|
||||||
export * from './smartstate.classes.statecollection';
|
export * from './smartstate.classes.stateaction.js';
|
||||||
export * from './smartstate.classes.stateaction';
|
|
||||||
export * from './smartstate.classes.stateobservable';
|
|
||||||
|
|||||||
@@ -1,47 +1,111 @@
|
|||||||
import * as plugins from './smartstate.plugins';
|
import * as plugins from './smartstate.plugins.js';
|
||||||
import { StatePart } from './smartstate.classes.statepart';
|
import { StatePart } from './smartstate.classes.statepart.js';
|
||||||
|
|
||||||
|
export type TInitMode = 'soft' | 'mandatory' | 'force' | 'persistent';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Smartstate takes care of providing state
|
* Smartstate takes care of providing state
|
||||||
*/
|
*/
|
||||||
export class Smartstate<StatePartNameType> {
|
export class Smartstate<StatePartNameType extends string> {
|
||||||
statePartMap: { [key: string]: StatePart<StatePartNameType, any> } = {};
|
public statePartMap: { [key in StatePartNameType]?: StatePart<StatePartNameType, any> } = {};
|
||||||
|
|
||||||
|
private pendingStatePartCreation: Map<string, Promise<StatePart<StatePartNameType, any>>> = new Map();
|
||||||
|
|
||||||
constructor() {}
|
constructor() {}
|
||||||
|
|
||||||
getStatePart<PayloadType>(
|
/**
|
||||||
|
* Allows getting and initializing a new statepart
|
||||||
|
* initMode === 'soft' (default) - returns existing statepart if exists, creates new if not
|
||||||
|
* initMode === 'mandatory' - requires statepart to not exist, fails if it does
|
||||||
|
* initMode === 'force' - always creates new statepart, overwriting any existing
|
||||||
|
* initMode === 'persistent' - like 'soft' but with webstore persistence
|
||||||
|
* @param statePartNameArg
|
||||||
|
* @param initialArg
|
||||||
|
* @param initMode
|
||||||
|
*/
|
||||||
|
public async getStatePart<PayloadType>(
|
||||||
statePartNameArg: StatePartNameType,
|
statePartNameArg: StatePartNameType,
|
||||||
initialArg?: PayloadType
|
initialArg?: PayloadType,
|
||||||
): StatePart<StatePartNameType, PayloadType> {
|
initMode: TInitMode = 'soft'
|
||||||
if (this.statePartMap[statePartNameArg as any]) {
|
): Promise<StatePart<StatePartNameType, PayloadType>> {
|
||||||
if (initialArg) {
|
// Return pending creation if one exists to prevent duplicate state parts
|
||||||
throw new Error(
|
const pending = this.pendingStatePartCreation.get(statePartNameArg);
|
||||||
`${statePartNameArg} already exists, yet you try to set an initial state again`
|
if (pending) {
|
||||||
);
|
return pending as Promise<StatePart<StatePartNameType, PayloadType>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingStatePart = this.statePartMap[statePartNameArg];
|
||||||
|
|
||||||
|
if (existingStatePart) {
|
||||||
|
switch (initMode) {
|
||||||
|
case 'mandatory':
|
||||||
|
throw new Error(
|
||||||
|
`State part '${statePartNameArg}' already exists, but initMode is 'mandatory'`
|
||||||
|
);
|
||||||
|
case 'force':
|
||||||
|
// Force mode: create new state part
|
||||||
|
break; // Fall through to creation
|
||||||
|
case 'soft':
|
||||||
|
case 'persistent':
|
||||||
|
default:
|
||||||
|
// Return existing state part
|
||||||
|
return existingStatePart as StatePart<StatePartNameType, PayloadType>;
|
||||||
}
|
}
|
||||||
return this.statePartMap[statePartNameArg as any];
|
|
||||||
} else {
|
} else {
|
||||||
|
// State part doesn't exist
|
||||||
if (!initialArg) {
|
if (!initialArg) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`${statePartNameArg} does not yet exist, yet you don't provide an initial state`
|
`State part '${statePartNameArg}' does not exist and no initial state provided`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return this.createStatePart<PayloadType>(statePartNameArg, initialArg);
|
}
|
||||||
|
|
||||||
|
const creationPromise = this.createStatePart<PayloadType>(statePartNameArg, initialArg, initMode);
|
||||||
|
this.pendingStatePartCreation.set(statePartNameArg, creationPromise);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await creationPromise;
|
||||||
|
return result;
|
||||||
|
} finally {
|
||||||
|
this.pendingStatePartCreation.delete(statePartNameArg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private createStatePart<PayloadType>(
|
/**
|
||||||
|
* Creates a statepart
|
||||||
|
* @param statePartName
|
||||||
|
* @param initialPayloadArg
|
||||||
|
* @param initMode
|
||||||
|
*/
|
||||||
|
private async createStatePart<PayloadType>(
|
||||||
statePartName: StatePartNameType,
|
statePartName: StatePartNameType,
|
||||||
initialPayloadArg: PayloadType
|
initialPayloadArg: PayloadType,
|
||||||
): StatePart<StatePartNameType, PayloadType> {
|
initMode: TInitMode = 'soft'
|
||||||
const newState = new StatePart<StatePartNameType, PayloadType>(statePartName);
|
): Promise<StatePart<StatePartNameType, PayloadType>> {
|
||||||
newState.setState(initialPayloadArg);
|
const newState = new StatePart<StatePartNameType, PayloadType>(
|
||||||
this.statePartMap[statePartName as any] = newState;
|
statePartName,
|
||||||
|
initMode === 'persistent'
|
||||||
|
? {
|
||||||
|
dbName: 'smartstate',
|
||||||
|
storeName: statePartName,
|
||||||
|
}
|
||||||
|
: null
|
||||||
|
);
|
||||||
|
await newState.init();
|
||||||
|
const currentState = newState.getState();
|
||||||
|
|
||||||
|
if (initMode === 'persistent' && currentState !== undefined) {
|
||||||
|
// Persisted state exists - merge with defaults, persisted values take precedence
|
||||||
|
await newState.setState({
|
||||||
|
...initialPayloadArg,
|
||||||
|
...currentState,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// No persisted state or non-persistent mode
|
||||||
|
await newState.setState(initialPayloadArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.statePartMap[statePartName] = newState;
|
||||||
return newState;
|
return newState;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* dispatches an action on the main level
|
|
||||||
*/
|
|
||||||
dispatch() {}
|
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,20 @@
|
|||||||
import * as plugins from './smartstate.plugins';
|
import * as plugins from './smartstate.plugins.js';
|
||||||
|
import { StatePart } from './smartstate.classes.statepart.js';
|
||||||
|
|
||||||
|
export interface IActionDef<TStateType, TActionPayloadType> {
|
||||||
|
(stateArg: StatePart<any, TStateType>, actionPayload: TActionPayloadType): Promise<TStateType>;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* an actionmodifier for the state
|
* an actionmodifier for the state
|
||||||
*/
|
*/
|
||||||
export class StateAction<StatePayload> {
|
export class StateAction<TStateType, TActionPayloadType> {
|
||||||
constructor(public actionDef: (stateArg: StatePayload) => StatePayload) {}
|
constructor(
|
||||||
|
public statePartRef: StatePart<any, any>,
|
||||||
|
public actionDef: IActionDef<TStateType, TActionPayloadType>
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public trigger(payload: TActionPayloadType): Promise<TStateType> {
|
||||||
|
return this.statePartRef.dispatchAction(this, payload);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
import * as plugins from './smartstate.plugins';
|
|
||||||
import { StatePart } from './smartstate.classes.statepart';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A StatePartCollection is a collection of StateParts.
|
|
||||||
* It can be used for expressing interest in a certain set of StateParts.
|
|
||||||
*/
|
|
||||||
export class StatePartCollection<StatePartNameType, T> extends StatePart<StatePartNameType, T> {
|
|
||||||
constructor(nameArg: StatePartNameType) {
|
|
||||||
super(nameArg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import * as plugins from './smartstate.plugins';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* State observable observes a StatePart and notifies everyone interested
|
|
||||||
*/
|
|
||||||
export class StateObservable {
|
|
||||||
/**
|
|
||||||
* creates an observable from a StateCollection
|
|
||||||
*/
|
|
||||||
public static fromStatePartCollection(filterArg?: () => any) {}
|
|
||||||
|
|
||||||
constructor() {}
|
|
||||||
}
|
|
||||||
@@ -1,23 +1,45 @@
|
|||||||
import * as plugins from './smartstate.plugins';
|
import * as plugins from './smartstate.plugins.js';
|
||||||
|
import { StateAction, type IActionDef } from './smartstate.classes.stateaction.js';
|
||||||
|
|
||||||
import { Observable, Subject } from 'rxjs';
|
export class StatePart<TStatePartName, TStatePayload> {
|
||||||
import { startWith, takeUntil, map } from 'rxjs/operators';
|
public name: TStatePartName;
|
||||||
|
public state = new plugins.smartrx.rxjs.Subject<TStatePayload>();
|
||||||
|
public stateStore: TStatePayload | undefined;
|
||||||
|
private cumulativeDeferred = plugins.smartpromise.cumulativeDefer();
|
||||||
|
|
||||||
import { StateAction } from './smartstate.classes.stateaction';
|
private pendingCumulativeNotification: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
export class StatePart<StatePartNameType, PayloadType> {
|
private webStoreOptions: plugins.webstore.IWebStoreOptions;
|
||||||
name: StatePartNameType;
|
private webStore: plugins.webstore.WebStore<TStatePayload> | null = null; // Add WebStore instance
|
||||||
state = new Subject<PayloadType>();
|
|
||||||
stateStore: PayloadType;
|
|
||||||
|
|
||||||
constructor(nameArg: StatePartNameType) {
|
constructor(nameArg: TStatePartName, webStoreOptionsArg?: plugins.webstore.IWebStoreOptions) {
|
||||||
this.name = nameArg;
|
this.name = nameArg;
|
||||||
|
|
||||||
|
// Initialize WebStore if webStoreOptions are provided
|
||||||
|
if (webStoreOptionsArg) {
|
||||||
|
this.webStoreOptions = webStoreOptionsArg;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* initializes the webstore
|
||||||
|
*/
|
||||||
|
public async init() {
|
||||||
|
if (this.webStoreOptions) {
|
||||||
|
this.webStore = new plugins.webstore.WebStore<TStatePayload>(this.webStoreOptions);
|
||||||
|
await this.webStore.init();
|
||||||
|
const storedState = await this.webStore.get(String(this.name));
|
||||||
|
if (storedState && this.validateState(storedState)) {
|
||||||
|
this.stateStore = storedState;
|
||||||
|
await this.notifyChange();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* gets the state from the state store
|
* gets the state from the state store
|
||||||
*/
|
*/
|
||||||
getState(): PayloadType {
|
public getState(): TStatePayload | undefined {
|
||||||
return this.stateStore;
|
return this.stateStore;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,39 +47,165 @@ export class StatePart<StatePartNameType, PayloadType> {
|
|||||||
* sets the stateStore to the new state
|
* sets the stateStore to the new state
|
||||||
* @param newStateArg
|
* @param newStateArg
|
||||||
*/
|
*/
|
||||||
setState(newStateArg: PayloadType) {
|
public async setState(newStateArg: TStatePayload) {
|
||||||
|
// Validate state structure
|
||||||
|
if (!this.validateState(newStateArg)) {
|
||||||
|
throw new Error(`Invalid state structure for state part '${this.name}'`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save to WebStore first to ensure atomicity - if save fails, memory state remains unchanged
|
||||||
|
if (this.webStore) {
|
||||||
|
await this.webStore.set(String(this.name), newStateArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update in-memory state after successful persistence
|
||||||
this.stateStore = newStateArg;
|
this.stateStore = newStateArg;
|
||||||
this.notifyChange();
|
await this.notifyChange();
|
||||||
|
|
||||||
|
return this.stateStore;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates state structure - can be overridden for custom validation
|
||||||
|
* @param stateArg
|
||||||
|
*/
|
||||||
|
protected validateState(stateArg: any): stateArg is TStatePayload {
|
||||||
|
// Basic validation - ensure state is not null/undefined
|
||||||
|
// Subclasses can override for more specific validation
|
||||||
|
return stateArg !== null && stateArg !== undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* notifies of a change on the state
|
* notifies of a change on the state
|
||||||
*/
|
*/
|
||||||
notifyChange() {
|
public async notifyChange() {
|
||||||
|
if (!this.stateStore) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const createStateHash = async (stateArg: any) => {
|
||||||
|
return await plugins.smarthashWeb.sha256FromString(plugins.smartjson.stableOneWayStringify(stateArg));
|
||||||
|
};
|
||||||
|
const currentHash = await createStateHash(this.stateStore);
|
||||||
|
if (
|
||||||
|
this.lastStateNotificationPayloadHash &&
|
||||||
|
currentHash === this.lastStateNotificationPayloadHash
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.lastStateNotificationPayloadHash = currentHash;
|
||||||
|
}
|
||||||
this.state.next(this.stateStore);
|
this.state.next(this.stateStore);
|
||||||
}
|
}
|
||||||
|
private lastStateNotificationPayloadHash: any;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* creates a cumulative notification by adding a change notification at the end of the call stack;
|
||||||
|
*/
|
||||||
|
public notifyChangeCumulative() {
|
||||||
|
// Debounce: clear any pending notification
|
||||||
|
if (this.pendingCumulativeNotification) {
|
||||||
|
clearTimeout(this.pendingCumulativeNotification);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.pendingCumulativeNotification = setTimeout(async () => {
|
||||||
|
this.pendingCumulativeNotification = null;
|
||||||
|
if (this.stateStore) {
|
||||||
|
await this.notifyChange();
|
||||||
|
}
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* selects a state or a substate
|
* selects a state or a substate
|
||||||
*/
|
*/
|
||||||
select<T = PayloadType>(selectorFn?: (state: PayloadType) => T): Observable<T> {
|
public select<T = TStatePayload>(
|
||||||
|
selectorFn?: (state: TStatePayload) => T
|
||||||
|
): plugins.smartrx.rxjs.Observable<T> {
|
||||||
if (!selectorFn) {
|
if (!selectorFn) {
|
||||||
selectorFn = (state: PayloadType) => <T>(<any>state);
|
selectorFn = (state: TStatePayload) => <T>(<any>state);
|
||||||
}
|
}
|
||||||
|
|
||||||
const mapped = this.state.pipe(
|
const mapped = this.state.pipe(
|
||||||
startWith(this.getState()),
|
plugins.smartrx.rxjs.ops.startWith(this.getState()),
|
||||||
map(selectorFn)
|
plugins.smartrx.rxjs.ops.filter((stateArg): stateArg is TStatePayload => stateArg !== undefined),
|
||||||
|
plugins.smartrx.rxjs.ops.map((stateArg) => {
|
||||||
|
try {
|
||||||
|
return selectorFn(stateArg);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`Selector error in state part '${this.name}':`, e);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
return mapped;
|
return mapped;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* creates an action capable of modifying the state
|
||||||
|
*/
|
||||||
|
public createAction<TActionPayload>(
|
||||||
|
actionDef: IActionDef<TStatePayload, TActionPayload>
|
||||||
|
): StateAction<TStatePayload, TActionPayload> {
|
||||||
|
return new StateAction(this, actionDef);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* dispatches an action on the statepart level
|
* dispatches an action on the statepart level
|
||||||
*/
|
*/
|
||||||
async dispatch(stateAction: StateAction<PayloadType>) {
|
public async dispatchAction<T>(stateAction: StateAction<TStatePayload, T>, actionPayload: T): Promise<TStatePayload> {
|
||||||
const newState = stateAction.actionDef(this.getState());
|
await this.cumulativeDeferred.promise;
|
||||||
this.setState(newState);
|
const newState = await stateAction.actionDef(this, actionPayload);
|
||||||
|
await this.setState(newState);
|
||||||
|
return this.getState();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* waits until a certain part of the state becomes available
|
||||||
|
* @param selectorFn
|
||||||
|
* @param timeoutMs - optional timeout in milliseconds to prevent indefinite waiting
|
||||||
|
*/
|
||||||
|
public async waitUntilPresent<T = TStatePayload>(
|
||||||
|
selectorFn?: (state: TStatePayload) => T,
|
||||||
|
timeoutMs?: number
|
||||||
|
): Promise<T> {
|
||||||
|
const done = plugins.smartpromise.defer<T>();
|
||||||
|
const selectedObservable = this.select(selectorFn);
|
||||||
|
let resolved = false;
|
||||||
|
|
||||||
|
const subscription = selectedObservable.subscribe((value) => {
|
||||||
|
if (value && !resolved) {
|
||||||
|
resolved = true;
|
||||||
|
done.resolve(value);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
if (timeoutMs) {
|
||||||
|
timeoutId = setTimeout(() => {
|
||||||
|
if (!resolved) {
|
||||||
|
resolved = true;
|
||||||
|
subscription.unsubscribe();
|
||||||
|
done.reject(new Error(`waitUntilPresent timed out after ${timeoutMs}ms`));
|
||||||
|
}
|
||||||
|
}, timeoutMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await done.promise;
|
||||||
|
return result;
|
||||||
|
} finally {
|
||||||
|
subscription.unsubscribe();
|
||||||
|
if (timeoutId) clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* is executed
|
||||||
|
*/
|
||||||
|
public async stateSetup(
|
||||||
|
funcArg: (statePartArg?: StatePart<any, TStatePayload>) => Promise<TStatePayload>
|
||||||
|
) {
|
||||||
|
const resultPromise = funcArg(this);
|
||||||
|
this.cumulativeDeferred.addPromise(resultPromise);
|
||||||
|
await this.setState(await resultPromise);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Observable } from 'rxjs';
|
import * as smarthashWeb from '@push.rocks/smarthash/web';
|
||||||
|
import * as smartjson from '@push.rocks/smartjson';
|
||||||
|
import * as smartpromise from '@push.rocks/smartpromise';
|
||||||
|
import * as smartrx from '@push.rocks/smartrx';
|
||||||
|
import * as webstore from '@push.rocks/webstore';
|
||||||
|
|
||||||
const rxjsPart = {
|
export { smarthashWeb, smartjson, smartpromise, smartrx, webstore };
|
||||||
Observable
|
|
||||||
};
|
|
||||||
|
|
||||||
export { rxjsPart };
|
|
||||||
|
|||||||
14
tsconfig.json
Normal file
14
tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"useDefineForClassFields": false,
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"verbatimModuleSyntax": true
|
||||||
|
},
|
||||||
|
"exclude": [
|
||||||
|
"dist_*/**/*.d.ts"
|
||||||
|
]
|
||||||
|
}
|
||||||
17
tslint.json
17
tslint.json
@@ -1,17 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": ["tslint:latest", "tslint-config-prettier"],
|
|
||||||
"rules": {
|
|
||||||
"semicolon": [true, "always"],
|
|
||||||
"no-console": false,
|
|
||||||
"ordered-imports": false,
|
|
||||||
"object-literal-sort-keys": false,
|
|
||||||
"member-ordering": {
|
|
||||||
"options":{
|
|
||||||
"order": [
|
|
||||||
"static-method"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"defaultSeverity": "warning"
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user