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

@litusarchieve18/agricore-utils

v1.0.19

Published

Canonical Backend Utility Library for AgriCore

Downloads

1,715

Readme

@litusarchieve18/agricore-utils

The Canonical Backend Utility Library for the AgriCore ecosystem.

This library provides the foundational "plumbing" for the AgriCore backend, including standardized error handling, data middleware, domain enums, and the core security session contracts. It is specifically optimized to be framework-agnostic and lightweight, with native support for the Base44 / Deno deployment environment.

📦 Installation

Because Base44 Deno functions require module resolution at runtime without private authentication headers, this package is published to the public NPM registry.

For Node.js Environments

npm install @litusarchieve18/agricore-utils

For Base44 / Deno Environments
You do not need a .npmrc or GITHUB_TOKEN to use this library in Base44. Import it directly using the npm: protocol:
import { AgriLogger, AppError, MOD } from 'npm:@litusarchieve18/agricore-utils@^1.0.4';

🏗️ Core Architecture & Features
This library is designed with the "Adapter Pattern" in mind. It defines strict contracts (AgriCoreSession) so that your business logic remains completely isolated from the underlying Base44 database infrastructure.

1. The AgriCore Session (v2)
The universal contract for authenticated users. The v2 upgrade includes injected UI-ready navigation data (availableScopes) and tenant configurations to prevent unnecessary frontend API calls.

TypeScript
import { AgriCoreSession } from 'npm:@litusarchieve18/agricore-utils@^1.0.4';

// Example of the v2 structure:
const session: AgriCoreSession = {
  userId: "69e1a1...",
  companyId: "69e6a3...",
  activeScopeId: "660216...",
  companyConfig: { isMultiEntity: true },
  role: "owner",
  privileges: ["finance", "hr", "auditCompliance", "admin"],
  enabledModules: ["farm_management", "packhouse"],
  readScopes: ["..."],
  writeScopes: ["..."],
  availableScopes: [
    { authScopeId: "...", base44Id: "...",  type: "company", name: "Acme Corp", parentId: null }
  ],
  resourceOverrides: { /* ... */ }
}
2. Security Pillars & Middleware
Pure functions that enforce Row Level Security (RLS) and standardized data preparation without requiring direct database access.

assertCanWrite(session, targetScopeId)

buildRlsFilter(session)

withSaveMiddleware(data)

generateCanonicalId()

3. Error Registry & Handling
Standardized error tracking using Module (MOD), Category (CAT), and Action (ACT) constants.

AppError class

ErrorFactory

4. Domain Enums
The universal vocabulary of the AgriCore platform, ensuring type-safety across all microservices (e.g., UserRole, UserPrivilege, AccessLevel, FacilityType, NotificationMode, TaskStatus, RESOURCE_PATHS).

🔐 Security & Access Control
The library now includes a centralized logic layer to enforce granular permissions across all AgriCore services.

---------------------------------------------------------------------

evaluateBaseAccess: Automatically determines a user's base permission level (NONE, READ, or WRITE) for a specific resource path (e.g., records.financials). It respects the OWNER role "God Mode" bypass and uses ROLE_SECTIONS_BY_KEY to provide sensible defaults for different app sections.

Access Ranking (resolveEffectiveAccess): Implements an additive permission model. By ranking levels (NONE < READ < WRITE), it allows the system to compare base permissions against specific user overrides and resolve the highest authorized access level.

🛡️ Multi-Tenant Boundary Protection (Backend Only)
To ensure absolute data isolation in our multi-tenant environment, the library provides a "Boundary Guard."

assertTenantBoundary: A critical security function that prevents "Cross-Tenant" attacks. It validates that any target userId or authScopeId (Facility/Legal Entity) involved in a request belongs specifically to the requester's companyId. This serves as a final, mandatory check before any database write operations.

🌳 Infrastructure & Hierarchy Resolution
AgriCore data records require a full "Infrastructure Path" (Company ID, Legal Entity ID, and Facility ID). Instead of manual lookups, the library automates tree-walking.

generateInfrastructureFields: This utility takes a user’s activeScope and their availableScopes tree. It recursively walks up the hierarchy—from a specific Facility to the Legal Entity and finally to the Root Company. It resolves all relevant infrastructure IDs and generates a new canonicalId, ensuring that every data record is correctly anchored in the organizational hierarchy.

// Example: Using the new utilities in a Base44 Save Hook
const infrastructure = generateInfrastructureFields(activeScope, session.availableScopes);

// Ensure the user isn't trying to save data into a company they don't belong to
await assertTenantBoundary(db, session.companyId, { authScopeId: infrastructure.authScopeId });

const recordToSave = {
  ...userInput,
  ...infrastructure, // Injects canonicalId, companyId, legalEntityId, etc.
};

To completely eliminate database bottlenecks and solve serverless rate-limiting, AgriCore has migrated to a state-of-the-art, "Zero-DB" authorization architecture. By decoupling our security rules from the database SDK, our backend API endpoints now resolve complex multi-tenant boundaries and granular role-based access controls in roughly 1 millisecond.

---------------------------------------------------------------------

Key Features of the New Security Engine:

One-Time Session Generation: On login, the backend dynamically aggregates a user's full hierarchical profile—including role assignments, availableScopes (Company > Legal Entity > Facility), and granular resourceOverrides—into a single, cryptographically signed JSON Web Token (JWT).

Zero-DB Library Validations: The @litusarchieve18/agricore-utils library has been upgraded to utilize pure, synchronous functions. Deep hierarchical access checks (findSpecificOverride) and tenant isolation (assertTenantBoundary) are now resolved directly against the JWT payload in-memory, completely bypassing the database for routine requests.

Smart Frontend Interceptor: A centralized React hook (useApiClient) acts as an automated API wrapper. It seamlessly injects the user's customJWT and the globally selected activeScopeId into every outbound request. This keeps UI forms completely decoupled from authentication logic.

Instant Context Switching: Because the JWT securely holds the user's entire "VIP List" of permitted scopes, users can instantly switch between farms, legal entities, and facilities in the frontend global dropdown without triggering a new authentication handshake or database query.

---------------------------------------------------------------------

This Document Management Engine provides a standardized, compliant, and migration-ready architecture for handling agricultural records. It ensures that files are stored predictably and matched against audit requirements with high precision.

Document Management & Compliance Engine
This module handles the lifecycle of file assets, from standardized naming and path generation to intelligent metadata matching for compliance audits.

1. Standardized Taxonomy (DocumentType)
The DocumentType enum serves as the single source of truth for the AgriCore document ecosystem. It categorizes every record—from SPRAY_RECORD to MAPPING_FARM_MAPS—ensuring that the database remains searchable and consistent across different farms and legal entities.

2. Smart Routing (generateDocumentPath)
This function enforces the "Core vs. Seasonal" storage architecture. It ensures that permanent files (Fixed Assets) and crop-cycle files (Working Assets) are physically and logically separated:

Static Assets (isStatic: true): Routed to {SiteName}/_CORE/{DocumentType}.

Seasonal Assets: Routed to a strict temporal hierarchy: {SiteName}/_SEASONAL/{Year}/{DocumentType}/{Crop}.

3. Intelligence Engine (calculateFileMetadataMatch)
A 3-tier matching algorithm used to automatically suggest evidence for audit questions. It evaluates the relevance of a file based on three layers:

Static Hard Fails: Strict equality checks for properties like documentType.

Dynamic Hard Fails (mustMatchContext): Ensures files belong to the correct boundaries (e.g., siteId array inclusion) based on the current AuditHeader.

Soft Relevance Scoring (contextMatch): Calculates a percentage score based on environmental tags like seasonId or crop, allowing the UI to surface the "best matches" first.

Quick Example
TypeScript
// 1. Generate a path for a seasonal spray record
const path = generateDocumentPath({
  siteName: "North Farm",
  docType: DocumentType.SPRAY_RECORD,
  year: 2026,
  crop: "Mango"
}); 
// Output: North_Farm/_SEASONAL/2026/SPRAY_RECORD/MANGO

// 2. Score a file against an audit requirement
const score = calculateFileMetadataMatch(
  { 
    mustMatch: { documentType: "SPRAY_RECORD" },
    mustMatchContext: ["siteId"], // Hard fail if wrong farm
    contextMatch: ["seasonId"]    // Soft score for season relevance
  },
  file.metadata,
  auditHeader.context
);

============================================================================

🛠️ Development & Publishing Guide
Zero Dependencies
To keep the package ultra-lightweight (~30KB), this library has zero runtime dependencies. All build tools (tsup, typescript) are strictly kept in devDependencies, and the package.json uses the "files": ["dist"] array to ensure only compiled code is uploaded.

Building Locally
This project uses tsup for rapid, zero-config bundling into both CommonJS and ES Modules.

Bash
npm run build
The "No-PIN" Publishing Workflow (NPM 2FA Workaround)
Due to NPM's deprecation of CLI TOTP apps and Windows Security (Passkey) loop issues, publishing updates requires a Granular Access Token with 2FA Bypass.

To publish a new version:

Bump the "version" in package.json.

Ensure you have your granular token in a local (git-ignored) .npmrc file:

Ini, TOML
//registry.npmjs.org/:_authToken=npm_YOUR_GRANULAR_TOKEN
(Note: This token MUST be generated from the NPM website with the "Bypass Two-Factor Authentication" checkbox enabled for the @litusarchieve18 scope).

Run the publish command:

Bash
npm publish --access public
📝 Version History
V1.0.18 - refactor inventory access in RESOURCE_PATHS 

V1.0.18 - refactor menu structure

V1.0.17 — refactor type and enum

V1.0.16 — BarcodeType, BarcodeNamespace, ProductType, ProductUnit, CatalogSyncStatus, StorageTier

V1.0.15 — add some standardized enum and types for CAR 

V1.0.14 — add DOCUMENT_DISPLAY_INFO do manage the grouping and a little description for UI 

V1.0.13 — add DocumentMenuMap and refactoring library code to export enum

V1.0.12 — add some functionality to add a file tag

V1.0.11 — add userName and userEmail to AgriCoreSession

V1.0.10 — add an explicit exports map

V1.0.9 — added jwt function

v1.0.8 — added temporary RESOURCE_REQUIREMENTS

v1.0.7 — add RESOURCE_MODULE_MAP

v1.0.6 — adding more logic

v1.0.5 — refactor the code and edit readme

v1.0.4 — add generateInfrastructureFields, security access control and multi tenant boundary

v1.0.3 — add the base44Id

v1.0.2 — Breaking Change: Upgraded AgriCoreSession interface. Added companyConfig and UI-ready availableScopes arrays to support the frontend hierarchy dropdown without secondary API calls.

v1.0.1 — Migrated package from private GitHub Registry to public NPM Registry for Base44/Deno compatibility. Removed baseUrl from tsconfig.json for NodeNext compatibility. Cleaned build artifacts from dependencies.

v1.0.0 — Initial release. Core logging, error factory, and validation utilities.


### Analyst Notes on the Process:
This README captures the entire technical journey we just completed:
1. It explains **how** to import the code into Base44 using the `npm:` prefix.
2. It highlights the **Adapter pattern** and the **v2 Session Object** so future developers know *why* the data is shaped that way.
3. Most importantly, it documents the exact **Publishing Workflow** and the **2FA bypas