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

zone4code-sdk

v2.8.1

Published

Official TypeScript & JavaScript Client SDK for the Zone4Code Platform

Readme

zone4code-sdk

Official TypeScript & JavaScript Client SDK for the Zone4Code Platform & Singulary.

Provides a unified, type-safe client for all core backend capabilities routed through the Unified API Gateway (https://api.zone4build.com):

  1. 🔐 Authentication (client.auth) — User auth, JWT decode, auto-renewal, profile management, OAuth login.
  2. 📁 Document Management (client.doc) — Cloud file uploads, folders, metadata, presigned URLs.
  3. 🔔 Notifications (client.notification) — Multi-channel SMS, rich HTML/template emails, mobile push alerts.
  4. 📊 Dynamic Entity CRUD (client.from(), client.generic) — Custom schemas, chainable filtering, i18n multilingual translations, audit revisions, and graph relations.
  5. 🔄 State Machine & Workflows (client.workflow) — Generic state machines, transition validation, role gating, order lifecycle tracking, and workflow documentation.
  6. ⚖️ Compliance & Policy DSL (client.compliance) — Business rule evaluation, decision auditing, turnkey sector domain packs (NURSEL, FinTech, Logistics), and policy matrix simulation.
  7. 🛡️ Licensing & Configuration (client.licensing, client.config) — Multi-tier entitlement gating (FREE, STARTER, PRO, ENTERPRISE), dynamic feature flags, and microservice config management.

📦 Installation

npm install zone4code-sdk
# or
pnpm add zone4code-sdk
# or
yarn add zone4code-sdk

🚀 Quick Start & 0-Config Initialization

The SDK automatically detects ZONE4BUILD_GATEWAY_URL or VITE_ZONE4BUILD_GATEWAY_URL from the environment if omitted.

import { createClient } from 'zone4code-sdk';

export const client = createClient({
  gatewayUrl: process.env.ZONE4BUILD_GATEWAY_URL || 'https://api.zone4build.com',
  tenantId: process.env.ZONE4BUILD_WORKSPACE_ID || 'my-workspace-id',
  defaultLanguage: 'en'
});

// Check Gateway Health & License Tier
const health = await client.health();
console.log('Gateway status:', health.status, health.licenseTier);

🔐 1. Authentication (client.auth)

Registration & Login

// Register new user (automatically sets session token)
const { token, user } = await client.auth.register({
  email: '[email protected]',
  password: 'SecurePassword123!',
  name: 'Alice Smith'
});

// Login with email or username
const { token: sessionToken, refreshToken, user: loggedUser } = await client.auth.login({
  email: '[email protected]',
  password: 'SecurePassword123!'
});

// Synchronous decoded user inspection (no network overhead)
const currentUser = client.auth.getUser();
console.log(currentUser?.id, currentUser?.email, currentUser?.roles);

// Logout
client.auth.logout();

📁 2. Document Storage & Media (client.doc)

// Upload a file to cloud storage
const result = await client.doc.upload(myFile);
console.log('File uploaded:', result[0].original);

🔔 3. Notifications (client.notification)

// Send transactional SMS
await client.notification.sendSms({
  phone: '+21620123456',
  text: 'Your order #1024 has been confirmed!',
  senderId: 'Zone4Store'
});

📊 4. Dynamic Entity CRUD (client.from())

// Query products with filters, sorting and pagination
const { data, total } = await client.from('product')
  .eq('status', 'active')
  .gte('price', 100)
  .orderBy('price', 'desc')
  .page(1, 20);

🧩 Data model first (client.models, zone4code-sdk/model)

The app's data model (src/data/model.ts) is the source of every rule. client.models sends it to the platform, which plans and applies schema changes, status transitions, computed fields, and role access on the server.

import { createClient, defineModel } from 'zone4code-sdk';
import type { EntityMap } from './data/types'; // npx zone4code gen types --model src/data/model.ts --out src/data/types.ts

export const model = defineModel({ version: 2, entities: [/* ... */], lists: [/* ... */] });
const client = createClient<EntityMap>({ model });

const plan = await client.models.plan(model);  // { changes, breaking, unsupported, define }
await client.models.apply(model);              // defines only changed entities; throws on breaking changes
await client.models.apply(model, { confirmBreaking: true });
client.from('order');                          // typed by EntityMap
  • Breaking changes (apply refuses them without confirmBreaking): a removed field, a type change, a new required field without a default, a field made required without a default, a removed choice code (or a free field limited to choices), a field newly made unique.
  • validateModel(value) lists what's wrong with a model (names, types, references, rights, limits); plan/apply call it first.
  • upgradeModel(v1) returns the same model as version 2 (lossless). client.schema.define is deprecated in favor of client.models.apply.
  • Business logic goes in the model (flow lists with next/setBy, computed fields, checks), and what they can't express in project plugins (below), never in actions/*.js scripts.

🔌 Project plugins (definePlugin, zone4code-sdk/plugin)

Logic that flow lists, checks and computed fields can't express (stock taken when an order is confirmed, a total read from other records, a rule across entities) goes in a plugin of the project, written in TypeScript with definePlugin.

import { definePlugin, PluginError } from 'zone4code-sdk/plugin';

export default definePlugin({
  name: 'stock',                 // listed in the model: plugins: ['stock']
  entities: ['order'],
  hooks: {
    async onTransition({ field, to, data, db }) {
      if (field !== 'status' || to !== 'confirmed') return;
      const product = await db.get('product', data.product);
      if (!product || product.stock < data.quantity) throw new PluginError('Not enough stock', { code: 'OUT_OF_STOCK', status: 409 });
      await db.update('product', product.id, { stock: product.stock - data.quantity });
    }
  },
  actions: {
    async restock({ input, db }) { /* POST …/order/actions/restock */ }
  }
});
  • Hooks: beforeCreate, afterCreate, beforeUpdate, afterUpdate, beforeDelete, afterDelete, onTransition (once per flow field that moves). Each gets { entity, id, data, previous, user: { id, roles }, db }; actions get { entity, id, record, input, user, db } and return JSON.
  • db reads and writes records of the project only (get, find, create, update), in the same transaction as the write: when a hook throws, everything is rolled back.
  • Refusing: throw new PluginError(message, { code, status }) (400, 403, 404, 409 or 422); any other error refuses with 422 PLUGIN_ERROR.
  • Testing & uploading: plugin tests run on the platform's test engine; upload the compiled bundle with await client.plugins.upload(bundleCode).

🔄 5. State Machine & Workflows (client.workflow)

The Workflow client connects directly to the generic workflow engine and order lifecycle manager:

Check Status & Next Allowed Transitions

// Check workflow status for any entity type (e.g. order, delivery, task)
const status = await client.workflow.check('order', 'order-uuid-123', {
  roles: ['delivery']
});

console.log('Current state:', status.data.currentState.name);
console.log('Allowed transitions:', status.data.nextAllowedTransitions);

Validate Transition Before Execution

const validation = await client.workflow.validateTransition({
  typeName: 'order',
  entityId: 'order-uuid-123',
  fromSerial: 1,
  toSerial: 2
});

if (validation.valid) {
  console.log('Transition is allowed:', validation.message);
}

Order Lifecycle Checker

// Dedicated helper for multi-stage orders (User → Admin → Delivery → Client)
const orderStatus = await client.workflow.checkOrder('order-uuid-123', ['admin']);
console.log('Stage:', orderStatus.data.stage);
console.log('Issues / Blockers:', orderStatus.data.issues);

Introspect Workflow Documentation & Reports

// Get state machine definition (states, transitions, terminal states)
const doc = await client.workflow.getDocumentation('delivery');

// Get human-readable lifecycle report
const report = await client.workflow.getReport('delivery');
console.log(report.data);

⚖️ 6. Compliance & Policy DSL (client.compliance)

The Compliance client connects to the turnkey compliance and rule evaluation engine:

Real-Time Policy Evaluation

const result = await client.compliance.evaluate({
  domain: 'fintech',
  facts: {
    amountUsd: 12000,
    kycVerified: false,
    countryCode: 'TN'
  }
});

console.log('Decision:', result.decision); // 'PASS', 'FLAG', 'FAIL'
console.log('Reasons:', result.reasons);
console.log('Trace details:', result.trace);

Turnkey Sector Domain Packs

// List available turnkey sector packs (NURSEL, FinTech, Logistics)
const packs = await client.compliance.listDomainPacks();

// Get domain details, benchmarks, and test cases
const nurselPack = await client.compliance.getDomainPack('nursel');

Register Custom Policy DSL

const policy = await client.compliance.createOrUpdatePolicy({
  id: 'shipping-safety-v1',
  name: 'Hazardous Materials Transport Rule',
  domain: 'logistics',
  rules: [
    {
      id: 'rule-flammable-refrigerated',
      conditions: {
        all: [
          { fact: 'isFlammable', operator: 'equal', value: true },
          { fact: 'tempControlled', operator: 'equal', value: false }
        ]
      },
      event: {
        type: 'FLAG_SHIPMENT',
        params: { reason: 'Flammable materials require temperature controlled vehicle' }
      }
    }
  ]
});

Policy Matrix Simulation

const simulation = await client.compliance.simulate({
  candidatePolicy: policy,
  testCases: [
    { name: 'Standard parcel', facts: { isFlammable: false }, expectedDecision: 'PASS' },
    { name: 'Unrefrigerated chemical', facts: { isFlammable: true, tempControlled: false }, expectedDecision: 'FLAG' }
  ]
});

console.log('Simulation Summary:', simulation.summary);

🛡️ 7. Licensing, Plans & Configuration (client.licensing, client.config)

Manage access tiers, rate limits, and microservice configurations:

// Check current tier
const tier = await client.getLicenseTier(); // 'FREE' | 'STARTER' | 'PRO' | 'ENTERPRISE'

// Check feature entitlement
if (await client.canAccess('compliance')) {
  console.log('Compliance module is enabled for this license');
}

// Proactive assertion (throws if tier insufficient)
await client.licensing.assertAccess('workflow');

// Read microservice public configuration
const authConfig = await client.config.getPublicConfig('auth-api', 'production');

📨 8. Events (client.events)

client.events delivers the events recorded for your tenant. The SDK polls them over HTTP; it does not open a streaming connection.

// Subscribe to one topic, or '*' for all topics of this tenant
const unsubscribe = client.events.subscribe('order.events', (evt) => {
  console.log(evt.id, evt.payload);
});

// Stop receiving events
unsubscribe();

// Read the most recent events once
const recent = await client.events.listRecent({ topic: 'order.events', limit: 20 });
  • Polling: the first subscription starts polling every 3 seconds (pollIntervalMs to change it). autoStart: false skips starting it. client.events.stopPolling() stops it.
  • Delivery: each event reaches a handler once per client instance. A new client (for example one from withOptions) starts with an empty history and may receive recent events again.
  • Topics: a topic only receives the events recorded for it. Platform events reach your app only when they are recorded for your tenant.
  • Errors: polling failures are ignored and retried on the next tick. listRecent returns an empty list when the request fails, so check the connection separately if you need to tell "no events" from "error".

🛡️ 9. Role-Based Permissions & Access Control (client.permissions)

Manage entity permissions, role grants, and view security audit logs:

// 1. List all cataloged permissions and active role grants for this tenant
const { data: rules } = await client.permissions.list({ page: 1, limit: 50 });
for (const rule of rules) {
  console.log(`${rule.entity}#${rule.scope} -> roles:`, rule.roles.join(', '));
}

// 2. Grant a role access to an entity scope
await client.permissions.grant({
  entity: 'cmsaccount',
  scope: 'view',
  role: 'agency_operator'
});

// 3. Revoke a role from an entity scope (protected: cannot revoke last admin on define)
await client.permissions.revoke({
  entity: 'cmsaccount',
  scope: 'create',
  role: 'agency_operator'
});

// 4. Inspect permission audit history
const { data: audits } = await client.permissions.getAudit({
  entity: 'cmsaccount',
  limit: 20
});
console.log('Recent grant/revoke actions:', audits);

📚 Runnable Code Examples

Check the examples/ directory for complete scenarios:


📄 License

MIT © Zone4Code