zone4code-sdk
v2.8.1
Published
Official TypeScript & JavaScript Client SDK for the Zone4Code Platform
Maintainers
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):
- 🔐 Authentication (
client.auth) — User auth, JWT decode, auto-renewal, profile management, OAuth login. - 📁 Document Management (
client.doc) — Cloud file uploads, folders, metadata, presigned URLs. - 🔔 Notifications (
client.notification) — Multi-channel SMS, rich HTML/template emails, mobile push alerts. - 📊 Dynamic Entity CRUD (
client.from(),client.generic) — Custom schemas, chainable filtering, i18n multilingual translations, audit revisions, and graph relations. - 🔄 State Machine & Workflows (
client.workflow) — Generic state machines, transition validation, role gating, order lifecycle tracking, and workflow documentation. - ⚖️ Compliance & Policy DSL (
client.compliance) — Business rule evaluation, decision auditing, turnkey sector domain packs (NURSEL, FinTech, Logistics), and policy matrix simulation. - 🛡️ 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.defineis deprecated in favor ofclient.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 inactions/*.jsscripts.
🔌 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. dbreads 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 422PLUGIN_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 (
pollIntervalMsto change it).autoStart: falseskips 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.
listRecentreturns 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:
examples/01-auth-flow.ts— Authentication & profile lifecycle.examples/03-document-upload.ts— S3 file upload & folder items.examples/04-notifications.ts— SMS & Email messaging.examples/05-generic-crud-i18n.ts— Dynamic entities with multi-language i18n.examples/08-workflow-management.ts— Workflow check, validation & documentation.examples/09-compliance-and-policies.ts— Policy DSL, evaluation, domain packs, simulation.examples/10-licensing-and-plans.ts— Licensing tiers, feature gating & config management.examples/11-model-first-app/— A full app from its data model:model.ts(flows, computed fields, checks, rights), generatedtypes.ts,apply-model.ts(plan/apply) andapp.ts(typed CRUD, defaults, validation, status buttons).
📄 License
MIT © Zone4Code
