npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@alpinehealthcare/pdos

v0.0.99

Published

``` .----------------------------------------------------------------------------------. |__/\\\\\\\\\\\\\____/\\\\\\\\\\\\__________/\\\\\__________/\\\\\\\\\\\___ | | _\/\\\/////////\\\_\/\\\////////\\\______/\\\///\\\______/\\\/////////\\\_

Readme

.----------------------------------------------------------------------------------.
|__/\\\\\\\\\\\\\____/\\\\\\\\\\\\__________/\\\\\__________/\\\\\\\\\\\___        |
| _\/\\\/////////\\\_\/\\\////////\\\______/\\\///\\\______/\\\/////////\\\_       |
|  _\/\\\_______\/\\\_\/\\\______\//\\\___/\\\/__\///\\\___\//\\\______\///__      |
|   _\/\\\\\\\\\\\\\/__\/\\\_______\/\\\__/\\\______\//\\\___\////\\\_________     |
|    _\/\\\/////////____\/\\\_______\/\\\_\/\\\_______\/\\\______\////\\\______    |
|     _\/\\\_____________\/\\\_______\/\\\_\//\\\______/\\\__________\////\\\___   |
|      _\/\\\_____________\/\\\_______/\\\___\///\\\__/\\\_____/\\\______\//\\\__  |
|       _\/\\\_____________\/\\\\\\\\\\\\/______\///\\\\\/_____\///\\\\\\\\\\\/___ |
|        _\///______________\////////////__________\/////_________\///////////_____|
'----------------------------------------------------------------------------------'

NPM Version License: MIT

A cross-platform library for managing and interacting with patient health data with privacy, security, and interoperability at its core.

Overview

PDOS (Patient Data Operating System) is a library that provides a secure framework for handling patient health data. It includes features for managing treatments, messages, and synchronizing health records while maintaining privacy and security.

Networks

🏵️ Marigold - Testnet - Live 🟢

Features

  • Data Management: Secure handling of patient health records
  • Treatment Management: Track active treatments and treatment instances
  • Messaging System: Secure communication for healthcare providers
  • Privacy-First Architecture: Built with patient data privacy as a core principle
  • Modular Design: Extensible architecture through a module system

Modules

PDOS is built on a modular architecture and includes the following:

Auth

The Auth module provides robust authentication, supporting multiple authentication methods:

  • Wallet Authentication: Connect using Web3 wallets via EIP-1193 providers
  • Private Key Authentication: Initialize by passing in a private key

The authentication process includes:

  1. User authentication verification
  2. On-chain verification of user status
  3. Access to PDOS root hash and compute node information
  4. Integration with the Alpine Healthcare smart contracts
// Initialize with wallet authentication
await pdos().auth.initializeWalletUser(provider);

// Check if user is active
const isActive = await pdos().auth.checkIsActive();

// Get PDOS root hash
const rootHash = await pdos().auth.getPDOSRoot();

Encryption

The Encryption module provides end-to-end encryption for patient data using a combination of symmetric and asymmetric cryptography:

  • Lit Protocol Integration: Decentralized encryption using Lit Protocol
  • Access Control Conditions: Smart contract-based access control for data
  • Data Key Management: Secure management of encryption keys
  • Access Packages: Encrypted packages containing necessary decryption keys
// Generate an access package
const accessPackage = await pdos().encryption.generateAccessPackage();

// Encrypt data
const encryptedData = await pdos().encryption.encryptNode(data);

// Decrypt data
const decryptedData = await pdos().encryption.decryptNode(encryptedData);

Storage

The Storage module provides a flexible storage solution for persistent data:

  • Cross-Platform Compatibility: Works across web and mobile platforms
  • Secure Storage: Securely store sensitive information
  • Platform-Specific Adaptations: Automatically adapts to the current platform
// Store data
await pdos().storage.addItem("user_preferences", JSON.stringify(preferences));

// Retrieve data
const preferences = JSON.parse(
  await pdos().storage.getItem("user_preferences"),
);

AppManager

The AppManager module handles application lifecycle management:

  • Platform Detection: Automatically detects and adapts to different platforms
  • Lifecycle Events: Manages application lifecycle events (startup, foreground, background)
  • Platform-Specific Optimizations: Implements optimizations for different platforms
// The AppManager is automatically initialized with the core system
// Lifecycle events are handled internally

Notification

The Notification module manages user notifications across platforms:

  • Cross-Platform Notifications: Supports web and mobile notification systems
  • Permission Management: Handles notification permission requests
  • Custom Notification Channels: Configurable notification channels for Android
  • Event Listeners: Register callbacks for notification events
// Add a notification listener
await pdos().notification.addListener((notification) => {
  console.log("New notification received:", notification);
});

DataRequest

The DataRequest module provides access to health data from various sources:

  • HealthKit Integration: Seamless integration with Apple HealthKit
  • Permission Management: Handles health data access permissions
  • Metrics Collection: Collects and normalizes health metrics
  • Data Aggregation: Aggregates health data for analysis
// Check access to health metrics
await pdos().dataRequest.checkAccess(["step_count", "heart_rate"]);

// Get today's health data
const todaysSteps = await pdos().dataRequest.getTodaysValue("step_count");

Actions

PDOS provides a high-level actions API for common operations across different domains. Actions are pre-defined functions that abstract complex operations, making it easier to interact with the PDOS system without deep knowledge of its internal architecture.

Data Actions

Data actions handle synchronization and retrieval of health data:

  • Sync: Synchronizes treatment binaries and updates the Merkle tree root hash
  • GetAllRecords: Retrieves all health data records from the data manifest
// Synchronize data
await actions.data.sync();

// Get all health records
const healthRecords = actions.data.getAllRecords();

Inbox Actions

Inbox actions manage message operations within the system:

  • GetMessages: Retrieves unread messages from the inbox
  • ClearMessages: Clears all messages from the inbox
  • AddMessage: Adds a new message to the inbox
// Get all unread messages
const messages = await actions.inbox.getMessages();

// Clear all messages
await actions.inbox.clearMessages();

Treatments Actions

Treatments actions handle operations related to medical treatments:

  • AddTreatment: Adds a new treatment to the treatment manifest
  • GetActiveTreatments: Retrieves all active treatments
  • GetTreatment: Finds a specific treatment by name
  • GetTreatmentInstances: Retrieves all instances of a specific treatment
  • GetTreatmentBinaryForTreatment: Retrieves the binary data associated with a treatment
// Get all active treatments
const treatments = actions.treatments.getActiveTreatments();

// Add a new treatment
await actions.treatments.addTreatment("Medication A", "med-hash-123", {
  dosage: "10mg",
  frequency: "twice daily",
});

// Get instances of a treatment
const instances = actions.treatments.getTreatmentInstances("Medication A");

Core

The PDOS Core is the central management system that coordinates all components of the PDOS ecosystem. It handles module initialization, configuration, and lifecycle management.

Configuration

The Core is initialized with a configuration object that defines its behavior:

new Core({
  // Environment setting - currently only 'marigold' is supported
  env: "marigold",

  // Context for the PDOS instance
  context: {
    // Gateway URL for API communication
    gatewayURL: "https://your-gateway-url.com",
    // Whether this instance is running as a compute node
    isComputeNode: false,
  },

  // Optional test configuration
  test: {
    initCredentialId: "test-credential-id",
  },

  // Module configuration
  modules: {
    auth: {},
    encryption: {
      enabled: true,
    },
    storage: {},
    appManager: {},
    notification: {},
    dataRequest: {},
  },
});

Initialization

After configuring the Core, you need to start it to initialize all modules and stores:

// Start PDOS with default configuration
await pdos().start();

// Start PDOS with dependency injection for specific modules
await pdos().start({
  storage: {
    storageLib: customStorageImplementation,
  },
  notification: {
    Notifications: customNotificationSystem,
    Permissions: customPermissionsSystem,
  },
});

During initialization, the Core:

  1. Validates the configuration
  2. Loads and initializes requested modules
  3. Checks module dependencies
  4. Starts each module in the correct order
  5. Initializes the store system
  6. Calls post-start methods on all modules

Accessing Core Services

The singleton pattern allows easy access to Core services:

import pdos from "@alpinehealthcare/pdos";

// Access modules
const authModule = pdos().modules?.auth;
const encryptionModule = pdos().modules?.encryption;

// Access stores
const userAccount = pdos().stores?.userAccount;

// Access the Merkle tree
const rootNode = pdos().tree?.root;

Reset and Lifecycle Management

The Core provides methods to manage the lifecycle of the PDOS system:

// Reset the PDOS system
await pdos().reset();

// Check if PDOS has started
const isStarted = pdos().started;

// Access environment information
const gatewayURL = pdos().gatewayURL;
const isComputeNode = pdos().isComputeNode;

The reset method calls the restart method on all active modules, allowing them to clear state and reinitialize as needed.

PDOS Merkle Tree

PDOS implements a specialized file system for patient data using a Merkle tree structure:

PDOSNode

The PDOSNode class is the foundation of the PDOS Merkle tree, representing nodes in the tree:

  • Node Types: Different node types represent different data structures
  • Tree Path Tracking: Each node maintains its path in the tree
  • Edge Management: Connections between nodes in the tree
  • Node Updates: Mechanism for updating node data securely

Merkle Tree Implementation

The PDOS Merkle tree provides:

  • Verifiable Data Integrity: Cryptographic proof of data integrity
  • Efficient Updates: Only changed parts of the tree need to be updated
  • Hierarchical Data Organization: Logical organization of patient data
  • Tree Path Navigation: Easy navigation through the tree structure
  • Automatic Tree Construction: The tree builds itself automatically when provided with a root hash
  • Root Hash Synchronization: Change propagation throughout the tree with automatic blockchain sync

Core Concepts

NetworkMapper and Child Node Registration

Store classes like UserAccount, TreatmentManifest, etc. register their child node types in the NetworkMapper during their constructor initialization. This registration is crucial for the automatic tree building process:

// Example from UserAccount.ts constructor
constructor(core: Core) {
  super(core, [], "N_UserAccount")

  // Register child node types in the NetworkMapper
  addNode("TreatmentManifest", TreatmentManifest)
  addNode("DataManifest", DataManifest)
  addNode("Inbox", Inbox)
}

The NetworkMapper maintains a registry of node types to their corresponding classes, enabling nodes to construct child instances of the correct type when traversing the tree.

Automatic Tree Building

When initializing the PDOS system with a root hash, the tree automatically builds itself by:

  1. Loading the root node data using the provided hash
  2. Detecting child nodes from the edge information in the node data
  3. Creating instances of the appropriate node classes (using the NetworkMapper registry)
  4. Recursively loading child nodes and their children
// Initializing with a root hash
await userAccount.init(rootHash);

// Under the hood, the node getter loads data and builds the tree
public get node() {
  return (async () => {
    if (this._hash) {
      // Load existing node data from storage
      this._rawNode = await getFromPdfs(this._hash)
      // Process node data, decrypt if needed
      // ...

      // Set node properties based on loaded data
      this._nodeType = this._rawNode.type
      this._treePathInclusive = [...this._treePath, this._hash]
    } else {
      // Create a new node if no hash exists
      // ...
    }

    // Process loaded node
    this.onNodeLoad()
  })()
}
Root PDOS Hash and Blockchain Synchronization

The root hash of the PDOS Merkle tree represents the state of the entire patient data structure. This hash is stored on-chain to provide a tamper-proof reference point for the data.

The push method synchronizes the local root hash with the blockchain when changes are made:

// Synchronizing the local root hash with the blockchain
public async push(addressToUpdate?: string) {
  if (this.core.modules.auth?.authType === AuthType.WALLET) {
    // Get the current on-chain root hash
    const hashId = await this.core.modules.auth?.getPDOSRoot(addressToUpdate)

    // If local hash differs from on-chain hash, update it
    if (this._hash !== hashId) {
      await this.core.modules.auth.updatePDOSRoot(
        this._hash,
        addressToUpdate ?? this.core.modules.auth.publicKey
      )
      console.log("# pdos : synced new root - " + this._hash)
    }
  }
}

This synchronization happens automatically after update operations.

Exports

PDOS provides the following main exports:

  • pdos: Singleton accessor for the current PDOS core instance.
  • Core: Class for configuring and initializing the PDOS system.
  • PDOSNode: The base class for Merkle tree nodes.
  • actions: High-level API for common operations (see below).
  • Types: Various TypeScript types for strong typing (see TypeScript section).

Actions API

PDOS exposes a high-level actions API for common operations. These are grouped by domain:

Inbox Actions

  • actions.inbox.get() – Get all unread messages
  • actions.inbox.clear() – Clear all messages
  • actions.inbox.add(message) – Add a new message
  • actions.inbox.remove(id) – Remove a message by ID

Treatments Actions

  • actions.treatments.add(name, hash, options) – Add a new treatment
  • actions.treatments.delete(id) – Delete a treatment
  • actions.treatments.enable(id) – Enable a treatment
  • actions.treatments.disable(id) – Disable a treatment
  • actions.treatments.get() – Get all treatments
  • actions.treatments.encounters.add(encounter) – Add a treatment encounter
  • actions.treatments.encounters.get() – Get all treatment encounters
  • actions.treatments.encounters.onResponse(response) – Respond to an encounter

Data Actions

  • actions.data.sync() – Synchronize treatment binaries and update the Merkle tree root hash
  • actions.data.availableMetrics() – List available health metrics
  • actions.data.addValueForMetric(metric, value) – Add a value for a health metric
  • actions.data.get() – Get all health data records

User Actions

  • actions.user.get() – Get user information
  • actions.user.update(data) – Update user information

Agents Actions

  • actions.agents.create(agentData) – Create a new agent
  • actions.agents.get() – Get all agents
  • actions.agents.update(agentId, data) – Update an agent
  • actions.agents.delete(agentId) – Delete an agent

Usage Examples

import pdos, { Core, actions } from "@alpinehealthcare/pdos";

// Initialize PDOS
new Core({
  env: "marigold",
  context: { gatewayURL: "https://your-gateway-url.com" },
});
await pdos().start();

// Treatments
const treatments = await actions.treatments.get();
await actions.treatments.add("Medication A", "med-hash-123", {
  dosage: "10mg",
});

// Data
const metrics = await actions.data.availableMetrics();
await actions.data.addValueForMetric("step_count", 10000);

// Inbox
const messages = await actions.inbox.get();
await actions.inbox.clear();

// User
const user = await actions.user.get();
await actions.user.update({ name: "Alice" });

// Agents
const agents = await actions.agents.get();
await actions.agents.create({ name: "Dr. Smith" });

TypeScript Support

PDOS exports useful types for TypeScript users:

  • User – User account type
  • Treatment, TreatmentInstance – Treatment types
  • TreatmentEncounter – Treatment encounter type
  • Inbox – Inbox/message type
  • Agent, AgentBinary – Agent types
  • DataGroup, MetricRecords – Health data types
  • PDOSNode – Merkle tree node base class

Import them as needed:

import { User, Treatment, Agent, PDOSNode } from "@alpinehealthcare/pdos";

Architecture

PDOS is built on a modular architecture with the following components:

  • Core: Central management system for modules, configuration, and user accounts
  • Modules: Pluggable components that extend functionality
  • Actions: Pre-defined functions for common operations
  • Store: Data persistence layer using MobX for state management

Development

Prerequisites

  • Node.js (v14+)
  • Yarn or npm

Setup

  1. Clone the repository
  2. Install dependencies:
yarn install
# or
npm install

Build

yarn build
# or
npm run build

Test

yarn test
# or
npm test