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

@major-tech/resource-client

v0.2.76

Published

TypeScript client library for invoking Major resources (PostgreSQL, Custom APIs, HubSpot, S3)

Readme

@major-tech/resource-client

TS client: PostgreSQL/DynamoDB/CosmosDB/Snowflake/CustomAPI/HubSpot/S3. Type-safe, 0-dep, universal (Node/browser/edge), ESM+CJS.

Install

pnpm add @major-tech/resource-client

Config (All Clients)

{ baseUrl: string; applicationId: string; resourceId: string; majorJwtToken?: string; fetch?: typeof fetch }

Response Format

{ ok: true; requestId: string; result: T } | { ok: false; requestId: string; error: { message: string; httpStatus?: number } }

PostgresResourceClient

Constructor: new PostgresResourceClient(config: BaseClientConfig)

Method: invoke(sql: string, params: DbParamPrimitive[] | undefined, invocationKey: string, timeoutMs?: number): Promise<DatabaseInvokeResponse>

Params:

  • sql: SQL query string
  • params: (string | number | boolean | null)[] - positional params ($1, $2, etc)
  • invocationKey: unique operation ID (regex: [a-zA-Z0-9][a-zA-Z0-9._:-]*)
  • timeoutMs: optional timeout

Result (ok=true):

{ kind: "database"; rows: Record<string, unknown>[]; rowsAffected?: number }

Example:

import { PostgresResourceClient } from "@major-tech/resource-client";
const c = new PostgresResourceClient({
  baseUrl,
  applicationId,
  resourceId,
  majorJwtToken,
});
const r = await c.invoke(
  "SELECT * FROM users WHERE id = $1",
  [123],
  "fetch-user"
);
// r.ok ? r.result.rows : r.error.message

DynamoDBResourceClient

Constructor: new DynamoDBResourceClient(config: BaseClientConfig)

Method: invoke(command: DbDynamoDBPayload["command"], params: Record<string, unknown>, invocationKey: string, timeoutMs?: number): Promise<DatabaseInvokeResponse>

Params:

  • command: "GetItem" | "PutItem" | "UpdateItem" | "DeleteItem" | "Query" | "Scan" | ...
  • params: Command parameters (e.g., { TableName: 'users', Key: { id: { S: '123' } } })
  • invocationKey: unique operation ID
  • timeoutMs: optional timeout

Result (ok=true):

{
  kind: "database";
  command: string;
  data: unknown;
}

Example:

import { DynamoDBResourceClient } from "@major-tech/resource-client";
const c = new DynamoDBResourceClient({ baseUrl, applicationId, resourceId });
const r = await c.invoke(
  "GetItem",
  { TableName: "users", Key: { id: { S: "123" } } },
  "get-user"
);
// r.ok ? r.result.data : r.error

CustomApiResourceClient

Constructor: new CustomApiResourceClient(config: BaseClientConfig)

Method: invoke(method: HttpMethod, path: string, invocationKey: string, options?: { query?: QueryParams; headers?: Record<string, string>; body?: BodyPayload; timeoutMs?: number }): Promise<ApiInvokeResponse>

Params:

  • method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
  • path: URL path (appended to resource baseUrl)
  • invocationKey: unique operation ID
  • options.query: Record<string, string | string[]> - query params
  • options.headers: Record<string, string> - additional headers
  • options.body: { type: "json"; value: unknown } | { type: "text"; value: string } | { type: "bytes"; base64: string; contentType: string }
  • options.timeoutMs: timeout (default: 30000)

Result (ok=true):

{ kind: "api"; status: number; body: { kind: "json"; value: unknown } | { kind: "text"; value: string } | { kind: "bytes"; base64: string; contentType: string } }

Example:

import { CustomApiResourceClient } from "@major-tech/resource-client";
const c = new CustomApiResourceClient({ baseUrl, applicationId, resourceId });
const r = await c.invoke("POST", "/v1/pay", "create-pay", {
  query: { currency: "USD" },
  headers: { "X-Key": "val" },
  body: { type: "json", value: { amt: 100 } },
  timeoutMs: 5000,
});
// r.ok ? r.result.status : r.error

HubSpotResourceClient

Constructor: new HubSpotResourceClient(config: BaseClientConfig)

Method: invoke(method: HttpMethod, path: string, invocationKey: string, options?: { query?: QueryParams; body?: { type: "json"; value: unknown }; timeoutMs?: number }): Promise<ApiInvokeResponse>

Params:

  • method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
  • path: HubSpot API path
  • invocationKey: unique operation ID
  • options.query: Record<string, string | string[]>
  • options.body: { type: "json"; value: unknown } - JSON only
  • options.timeoutMs: timeout (default: 30000)

Result: Same as CustomApiResourceClient

Example:

import { HubSpotResourceClient } from "@major-tech/resource-client";
const c = new HubSpotResourceClient({ baseUrl, applicationId, resourceId });
const r = await c.invoke("GET", "/crm/v3/objects/contacts", "fetch-contacts", {
  query: { limit: "10" },
});
// r.ok && r.result.body.kind === 'json' ? r.result.body.value : r.error

SnowflakeResourceClient

Constructor: new SnowflakeResourceClient(config: BaseClientConfig)

Methods:

  • execute(statement: string, invocationKey: string, options?: SnowflakeExecuteOptions): Promise<SnowflakeInvokeResponse>
  • status(statementHandle: string, invocationKey: string, options?: { partition?: number }): Promise<SnowflakeInvokeResponse>
  • cancel(statementHandle: string, invocationKey: string): Promise<SnowflakeInvokeResponse>
  • invoke(payload: DbSnowflakePayload, invocationKey: string): Promise<SnowflakeInvokeResponse> - raw payload

Execute Options:

{
  bindings?: Record<string, { type: SnowflakeBindingType; value: string | number | boolean | null }>;
  database?: string;      // Override default database
  schema?: string;        // Override default schema
  warehouse?: string;     // Override default warehouse
  role?: string;          // Override default role
  timeout?: number;       // Timeout in seconds (max 604800 = 7 days)
  async?: boolean;        // Execute asynchronously
  parameters?: SnowflakeSessionParameters;  // Session params (timezone, query_tag, etc.)
  nullable?: boolean;     // Return NULL as "null" string
  requestId?: string;     // Idempotency key
}

Binding Types: "TEXT" | "FIXED" | "REAL" | "BOOLEAN" | "DATE" | "TIME" | "TIMESTAMP_LTZ" | "TIMESTAMP_NTZ" | "TIMESTAMP_TZ" | "BINARY" | "ARRAY" | "OBJECT" | "VARIANT"

Result (ok=true):

{
  kind: "snowflake";
  code?: string;                    // Snowflake response code
  message: string;                  // Response message
  statementHandle?: string;         // Handle for async operations
  statementHandles?: string[];      // Multi-statement handles
  statementStatusUrl?: string;      // URL to check status
  createdOn?: number;               // Timestamp
  resultSetMetaData?: {             // Column metadata
    numRows: number;
    format: string;
    rowType: SnowflakeColumnMetadata[];
    partitionInfo?: SnowflakePartitionInfo[];
  };
  data?: (string | null)[][];       // Result rows
  stats?: {                         // DML stats
    numRowsInserted?: number;
    numRowsUpdated?: number;
    numRowsDeleted?: number;
  };
}

Example:

import { SnowflakeResourceClient } from "@major-tech/resource-client";
const c = new SnowflakeResourceClient({ baseUrl, applicationId, resourceId, majorJwtToken });

// Execute a query
const r = await c.execute(
  "SELECT * FROM users WHERE region = ?",
  "fetch-users",
  {
    bindings: { "1": { type: "TEXT", value: "US-WEST" } },
    warehouse: "COMPUTE_WH",
  }
);
// r.ok ? r.result.data : r.error.message

// Async execution for long-running queries
const async = await c.execute(
  "INSERT INTO large_table SELECT * FROM source",
  "bulk-insert",
  { async: true }
);
// async.ok ? async.result.statementHandle : async.error

// Check status of async query
const status = await c.status(async.result.statementHandle!, "check-status");
// status.result.code === "090001" means completed

// Cancel a running query
const cancel = await c.cancel(statementHandle, "cancel-query");

S3ResourceClient

Constructor: new S3ResourceClient(config: BaseClientConfig)

Method: invoke(command: S3Command, params: Record<string, unknown>, invocationKey: string, options?: { timeoutMs?: number }): Promise<StorageInvokeResponse>

Params:

  • command: "ListObjectsV2" | "HeadObject" | "GetObjectTagging" | "PutObjectTagging" | "DeleteObject" | "DeleteObjects" | "CopyObject" | "ListBuckets" | "GetBucketLocation" | "GeneratePresignedUrl"
  • params: Command-specific params (e.g., { Bucket, Prefix, Key, expiresIn })
  • invocationKey: unique operation ID
  • options.timeoutMs: optional timeout

Result (ok=true):

{ kind: "storage"; command: string; data: unknown } | { kind: "storage"; presignedUrl: string; expiresAt: string }
  • Standard commands return { kind: "storage"; command; data }
  • GeneratePresignedUrl returns { kind: "storage"; presignedUrl; expiresAt }

Example:

import { S3ResourceClient } from "@major-tech/resource-client";
const c = new S3ResourceClient({ baseUrl, applicationId, resourceId });
const r = await c.invoke(
  "ListObjectsV2",
  { Bucket: "my-bucket", Prefix: "uploads/" },
  "list-uploads"
);
// r.ok ? r.result.data : r.error
const u = await c.invoke(
  "GeneratePresignedUrl",
  { Bucket: "my-bucket", Key: "file.pdf", expiresIn: 3600 },
  "presigned"
);
// u.ok && 'presignedUrl' in u.result ? u.result.presignedUrl : u.error

createProxyFetch (Next.js)

Subpath: @major-tech/resource-client/next. Returns a fetch-compatible function that routes every request through the Major HTTP proxy. Drop into any SDK that accepts a custom fetch (Stripe, OpenAI, etc.) to inherit Major's auth, secrets, and routing. The helper auto-forwards x-major-user-jwt from the incoming Next request via next/headers.

Install:

pnpm add @major-tech/resource-client

next is declared as an optional peer dependency (>=14.0.0). It's only required when you import from the /next subpath; the main entry stays 0-dep.

Config:

| Field | Type | Required | Notes | | --------------- | -------------- | -------- | --------------------------------------------------------------------------------------------- | | baseUrl | string | yes | e.g. "https://go-api.prod.major.build" | | resourceId | string | yes | UUID of the resource to proxy through | | majorJwtToken | string | yes | App-level JWT; sent as x-major-jwt | | fetch | typeof fetch | no | Override runtime fetch (defaults to globalThis.fetch) | | timeoutMs | number | no | Default X-Major-Timeout-Ms (server-clamped to 60_000); only set if caller didn't supply one |

x-major-user-jwt is auto-forwarded on every call by reading headers().get("x-major-user-jwt") from the incoming Next request — no config needed. Outside a request scope (e.g. background jobs) the lookup is skipped.

Notes:

  • The proxy injects upstream auth, so callers must NOT set Authorization.
  • Reserved request headers (Authorization, Cookie, Host, Forwarded, X-Forwarded-*, X-Real-Ip) and the X-Major-* / X-Pd-* namespaces are silently stripped by the proxy.
  • Body and X-Major-Max-Response-Bytes are clamped to 50 MB by the proxy.

Example - Stripe SDK:

import Stripe from "stripe";
import { createProxyFetch } from "@major-tech/resource-client/next";

const proxyFetch = createProxyFetch({
  baseUrl: process.env.MAJOR_API_BASE_URL!,
  resourceId: process.env.STRIPE_RESOURCE_ID!,
  majorJwtToken: process.env.MAJOR_JWT_TOKEN!,
});

const stripe = new Stripe("sk_unused_proxy_injects_real_key", {
  httpClient: Stripe.createFetchHttpClient(proxyFetch),
});

const customers = await stripe.customers.list({ limit: 10 });

Example - plain fetch:

import { createProxyFetch } from "@major-tech/resource-client/next";

const proxyFetch = createProxyFetch({ baseUrl, resourceId, majorJwtToken });

const res = await proxyFetch("https://api.example.com/v1/foo", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ x: 1 }),
});

Error Handling

import { ResourceInvokeError } from '@major-tech/resource-client';
try { await client.invoke(...); }
catch (e) { if (e instanceof ResourceInvokeError) { e.message, e.httpStatus, e.requestId } }

CLI - Singleton Generator

Commands:

  • npx major-client add <resourceId> <name> <type> <desc> <appId> - Add resource, generate singleton (app mode)
  • npx major-client add <resourceId> <name> <type> <desc> --mode skill - Add resource for a skill script (see Skill mode)
  • npx major-client list - List all resources
  • npx major-client remove <name> - Remove resource
  • npx major-client regenerate - Regenerate all clients

Types: postgresql | dynamodb | cosmosdb | snowflake | custom | hubspot | googlesheets | s3

Generated Files:

  • resources.json - Resource registry
  • src/clients/<name>.ts - Singleton client
  • src/clients/index.ts - Exports

Env Vars: MAJOR_API_BASE_URL, MAJOR_JWT_TOKEN

Example:

npx major-client add "res_123" "orders-db" "postgresql" "Orders DB" "app_456"
import { ordersDbClient } from "./clients";
const r = await ordersDbClient.invoke(
  "SELECT * FROM orders",
  [],
  "list-orders"
);

Skill mode

Use --mode skill to generate clients for scripts that run inside a Major deployment (an agent or orchestrator session) — e.g. scripts created by a skill. The generated client embeds only the resourceId: there is no application_id or tool_id. Identity is resolved entirely from the deployment-identity JWT, and the client posts to /internal/skills/v1/resource/:resourceId/invoke.

Add command (no application_id):

npx major-client add "res_123" "orders-db" "postgresql" "Orders DB" --mode skill

Env Vars: MAJOR_API_BASE_URL (the go-api base URL; defaults to the prod URL) and MAJOR_JWT_TOKEN (the deployment-identity JWT). Both are injected into the Major agent/session runtime, so generated skill clients work with no extra wiring.

Usage is identical to app mode:

import { ordersDbClient } from "./clients";
const r = await ordersDbClient.invoke("SELECT * FROM orders", [], "list-orders");

Access is authorized server-side against the deployment identity: for orchestrator sessions the user needs resource:build on the resource; for agent sessions the resource must additionally be scoped to the agent (in agent_resources).

MIT License