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

@techery/zod-dynamic-schema

v0.1.1

Published

Type-safe factory functions for creating dynamic Zod schemas with TypeScript inference

Readme

@techery/zod-dynamic-schema

npm version CI Status

Type-safe factory functions for creating dynamic Zod schemas with TypeScript inference.

Developed by Techery.

Motivation

This package was created to solve a specific challenge when working with LLM (Large Language Model) structured outputs. When building LLM applications, we often need to:

  • Define structured output schemas that are mostly fixed but need certain parts to vary based on runtime state
  • Maintain type safety while allowing dynamic schema modifications
  • Create reusable schema templates that can be adjusted based on external data or application state

This helper provides a clean, type-safe way to create schema factories that can generate different variations of a base schema while maintaining consistent structure and type inference.

Features

  • Create reusable Zod schema factories with full TypeScript type inference
  • Support for both parameterized and static schema generation
  • Zero runtime overhead
  • Lightweight with minimal dependencies
  • Perfect for LLM structured output validation

Installation

npm install @techery/zod-dynamic-schema zod

Usage

Real-World Example: Dynamic Form Widget

This example shows how to create a schema for a form widget where the options and validation rules can be dynamically configured based on the context:

import { z } from 'zod';
import { schemaFactory } from '@techery/zod-dynamic-schema';

interface DynamicOptions {
  minItems?: number;
  maxItems?: number;
  instructions?: string;
}

const dynamicOptionsWidgetSchemaFactory = schemaFactory((dynamicOptions: DynamicOptions) => {
  return z.object({
    type: z.literal("options").describe("Options widget type"),
    options: z
      .array(
        z.object({
          name: z.string().describe("Name of the option"),
        })
      )
      .min(dynamicOptions.minItems ?? 2)
      .max(dynamicOptions.maxItems ?? 10)
      .describe(dynamicOptions.instructions),
    multiSelect: z.boolean().describe("Whether the user can select multiple options"),
  });
});

// Create different variants based on context
const singleChoiceQuestion = dynamicOptionsWidgetSchemaFactory({
  minItems: 2,
  maxItems: 4,
  instructions: "Please provide 2-4 options for single choice question"
});

const multipleChoiceQuestion = dynamicOptionsWidgetSchemaFactory({
  minItems: 3,
  maxItems: 6,
  instructions: "Please provide 3-6 options for multiple choice question"
});

// Get the schema type directly from the factory
type DynamicOptions = typeof dynamicOptionsWidgetSchemaFactory.$type;
// Or from the instance
type SingleChoiceWidget = z.infer<typeof singleChoiceQuestion>;
// Both will give you:
// {
//   type: "options";
//   options: { name: string }[];  // with min(2) and max(4) constraints
//   multiSelect: boolean;
// }

LLM Output Schema Example

import { z } from 'zod';
import { schemaFactory } from '@techery/zod-dynamic-schema';

// Define a factory for LLM response schema that varies based on allowed actions
interface ActionSchemaParams {
  allowedActions: string[];
  requireReasoning: boolean;
}

const llmResponseSchema = schemaFactory((params: ActionSchemaParams) => {
  const actionEnum = z.enum(params.allowedActions as [string, ...string[]]);
  
  return z.object({
    action: actionEnum,
    parameters: z.record(z.string(), z.any()),
    confidence: z.number().min(0).max(1),
    reasoning: params.requireReasoning 
      ? z.string().min(1)
      : z.string().optional(),
  });
});

// Create different variants based on context
const chatbotResponse = llmResponseSchema({
  allowedActions: ['reply', 'ask_clarification', 'end_conversation'],
  requireReasoning: true,
});

const dataAnalysisResponse = llmResponseSchema({
  allowedActions: ['analyze_data', 'request_more_data', 'provide_insights'],
  requireReasoning: false,
});

Field Extraction Example

import { z } from 'zod';
import { schemaFactory } from '@techery/zod-dynamic-schema';

// Create a schema factory for structured field extraction
const fieldExtractionSchema = schemaFactory((fields: string[]) =>
  z.object({
    extracted_fields: z.object(
      fields.reduce((acc, field) => ({
        ...acc,
        [field]: z.string(),
      }), {})
    ),
    confidence_scores: z.object(
      fields.reduce((acc, field) => ({
        ...acc,
        [field]: z.number().min(0).max(1),
      }), {})
    ),
  })
);

// Use with different field sets
const nameExtractor = fieldExtractionSchema(['firstName', 'lastName']);
const addressExtractor = fieldExtractionSchema([
  'street',
  'city',
  'state',
  'zipCode'
]);

Type Information

The package exports the following types:

type SchemaFactory<I, Z extends z.ZodTypeAny> = {
  $type: z.infer<Z>;
  (input: I): Z;
  (): Z;
};

The $type property allows you to get the inferred type directly from the factory, without creating an instance. This is useful when you need the type but don't have the runtime parameters yet.

Authors

License

MIT